Async/ResultSet.pm

filter: Statementstmt 85.5% 769 / 899 Branchbran 61.7% 278 / 450 Conditioncond 52.1% 197 / 378 MC/DCmcdc 29.2% 64 / 219 Subroutinesub 87.7% 100 / 114 Podpod 100% 61 / 61 totaltotal 69.2% 1469 / 2121 CC 399 SCAR 33.9
CC
399
Cov
72%
_inflate_row
223.6
_has_dynamic_sql
99.7
_build_payload
75.3
CRAP 29.6
« Async/Row.pm ↑ Summary Async/Exception/Factory.pm »
1 package DBIx::Class::Async::ResultSet;
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 =head1 NAME
11  
12 DBIx::Class::Async::ResultSet - Non-blocking resultset proxy with Future-based execution
13  
14 =head1 VERSION
15  
16 Version v1.0.9
17  
18 =head1 SYNOPSIS
19  
20 my $rs = $schema->resultset('User')->search({ active => 1 });
21  
22 # Async execution using Futures
23 $rs->all->then(sub {
24 my $users = shift; # Arrayref of DBIx::Class::Async::Row objects
25 foreach my $user (@$users) {
26 print "Found: " . $user->username . "\n";
27 }
28 })->retain;
29  
30 # Using the await helper
31 my $count = $schema->await( $rs->count );
32  
33 =head1 DESCRIPTION
34  
35 This class provides an asynchronous interface to L<DBIx::Class::ResultSet>. Most
36 methods that would normally perform I/O (like C<all>, C<count>, or C<create>)
37 return a L<Future> object instead of raw data.
38  
39 =cut
40  
41 99 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
42 99 ▶use v5.14;
Subroutine BEGIN: called CC=1 SCAR=0.0
43  
44 99 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
45 99 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
46 99 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
47 99 ▶use Scalar::Util 'blessed';
Subroutine BEGIN: called CC=1 SCAR=0.0
48 99 ▶use DBIx::Class::Async;
Subroutine BEGIN: called CC=1 SCAR=0.0
49 99 ▶use DBIx::Class::Async::Row;
Subroutine BEGIN: called CC=1 SCAR=0.0
50 99 ▶use DBIx::Class::Async::ResultSetColumn;
Subroutine BEGIN: called CC=1 SCAR=0.0
51 99 ▶use DBIx::Class::Async::SelectNormaliser;
Subroutine BEGIN: called CC=1 SCAR=0.0
52  
53 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
54  
55 99 my %ACCUMULATING_ATTRS = map { $_ => 1 } qw(
56 join
57 prefetch
58 columns
59 +columns
60 select
61 as
62 order_by
63 group_by
64 having
65 );
66  
67 99 my %DATETIME_COLUMN_TYPES = map { $_ => 1 } qw(
68 datetime timestamp timestamptz
69 timestamp\ with\ time\ zone
70 timestamp\ without\ time\ zone
71 date time
72 );
73  
74 =head1 METHODS
75  
76 =head2 new
77  
78 my $rs = DBIx::Class::Async::ResultSet->new(
79 schema_instance => $schema,
80 source_name => 'User',
81 cond => { is_active => 1 },
82 attrs => { order_by => 'created_at' },
83 );
84  
85 Instantiates a new asynchronous ResultSet. While typically called internally
86 by C<< $schema->resultset('Source') >>, it can be used to manually construct
87 a result set with a specific state.
88  
89 =over 4
90  
91 =item * Required Arguments
92  
93 =over 4
94  
95 =item * C<schema_instance>: The L<DBIx::Class::Async::Schema> object.
96  
97 =item * C<source_name>: The string name of the ResultSource (e.g., 'User').
98  
99 =back
100  
101 =item * Optional Arguments
102  
103 =over 4
104  
105 =item * C<async_db>: The worker bridge. If omitted, it defaults to the bridge
106 associated with the C<schema_instance>.
107  
108 =item * C<cond>: A hashref of search conditions (the C<WHERE> clause).
109  
110 =item * C<attrs>: A hashref of query attributes (C<join>, C<prefetch>, C<rows>, etc.).
111  
112 =item * C<result_class>: The class used to inflate rows. Defaults to C<DBIx::Class::Core>.
113  
114 =back
115  
116 =item * Internal State
117  
118 The constructor initialises buffers for rows (C<_rows>) and iteration
119 cursors (C<_pos>), ensuring that newly created ResultSets are always
120 in a "clean" state ready for fresh execution.
121  
122 =back
123  
124 =cut
125  
126 sub new {
127 1615 ▶ my ($class, %args) = @_;
Subroutine new: called CC=10 SCAR=24.0
Pod documented
128  
129 # 1. Validation
130 1615 ▶ croak "Missing required argument: schema_instance" unless $args{schema_instance};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"schema_instance"} 0 1615 1615
131 1615 ▶ croak "Missing required argument: source_name" unless $args{source_name};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"source_name"} 0 1615 1615
132  
133 # 2. Blessing the unified state
134 return bless {
135 # Core Infrastructure
136 _schema_instance => $args{schema_instance},
137 _async_db => $args{async_db} // $args{_schema_instance}->{_async_db},
138  
139 # Source Metadata
140 _source_name => $args{source_name},
141 _result_class => $args{result_class} // 'DBIx::Class::Core',
142  
143 # Query State
144 _cond => $args{cond} // {},
145 _attrs => $args{attrs} // {},
146  
147 # Result State (Usually reset on clone)
148 _rows => $args{rows} // undef,
149 _pos => $args{pos} // 0,
150  
151 # Prefetch/Pager logic
152 _is_prefetched => $args{is_prefetched} // 0,
153 _pager => $args{pager},
154 1615 ▶ }, $class;
Condition80%12/15
$args{"async_db"} // $args{"_schema_instance"}{"_async_db"}
l!l&&r!l&&!r
161500
$args{"result_class"} // "DBIx::Class::Core"
l!l
158827
$args{"cond"} // {}
l!l
663952
$args{"attrs"} // {}
l!l
661954
$args{"rows"} // undef
l!l
01615
$args{"pos"} // 0
l!l
618997
$args{"is_prefetched"} // 0
l!l
618997
MC/DC0%0/2
$args{"async_db"} // $args{"_schema_instance"}{"_async_db"}
$args{"async_db"} $args{"_schema_instance"}{"_async_db"}
MC/DC100%1/1
$args{"result_class"} // "DBIx::Class::Core"
$args{"result_class"}
MC/DC100%1/1
$args{"cond"} // {}
$args{"cond"}
MC/DC100%1/1
$args{"attrs"} // {}
$args{"attrs"}
MC/DC0%0/1
$args{"rows"} // undef
$args{"rows"}
MC/DC100%1/1
$args{"pos"} // 0
$args{"pos"}
MC/DC100%1/1
$args{"is_prefetched"} // 0
$args{"is_prefetched"}
Truth table33%1/3
A // B
A= $args{"async_db"}B= $args{"_schema_instance"}{"_async_db"}
ABresult
1X1
011
000
Truth table100%2/2
A
A= $args{"result_class"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"cond"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"attrs"}
Aresult
11
00
Truth table50%1/2
A
A= $args{"rows"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"pos"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"is_prefetched"}
Aresult
11
00
155 }
156  
157 =head2 new_result
158  
159 Internal method used to turn a raw database hashref into a L<DBIx::Class::Async::Row> object. It handles:
160  
161 =over 4
162  
163 =item * Dotted Key Expansion
164  
165 Expands C<< {'user.name' => 'Bob'} >> into nested hashes for prefetched relationships.
166  
167 =item * Relationship Inflation
168  
169 Automatically turns prefetched relationship data into nested Row objects.
170  
171 =item * Class Hijacking
172  
173 If a custom C<result_class> is used, it dynamically creates an anonymous class
174 inheriting from both the async row and your custom class.
175  
176 =back
177  
178 =cut
179  
180 sub new_result {
181 1138 ▶ my ($self, $data, $attrs) = @_;
Subroutine new_result: called CC=23 SCAR=35.6
Pod documented
182 1138 ▶ return unless defined $data;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $data 0 1138 1138
183  
184 my $in_storage = (ref $attrs eq 'HASH' && exists $attrs->{in_storage})
185 ? $attrs->{in_storage}
186 1138 ▶ : 0; # Default to NOT in storage
Branch: 1 branch
BranchTrueFalseTotal
ref $attrs eq 'HASH' && exists $attrs->{'in_storage'} ? : 521 617 1138
Condition66%2/3
ref $attrs eq "HASH" and exists $attrs->{"in_storage"}
!ll&&!rl&&r
6170521
MC/DC50%1/2
ref $attrs eq "HASH" and exists $attrs->{"in_storage"}
ref $attrs eq "HASH" exists $attrs->{"in_storage"}
Truth table66%2/3
A and B
A= ref $attrs eq "HASH"B= exists $attrs->{"in_storage"}
ABresult
0X0
100
111
187  
188 # Ensure we are working with a hash copy
189 1138 ▶ my %raw_data = ref $data eq 'HASH' ? %$data : ();
Branch: 1 branch
BranchTrueFalseTotal
ref $data eq 'HASH' ? : 1138 0 1138
190 1138 my %col_data;
191 my %rel_data;
192  
193 # It converts {'user.id' => 2, 'user.name' => 'Bob'}
194 # into { user => { id => 2, name => 'Bob' } }
195 1138 my @all_keys = keys %raw_data;
196  
197 1138 foreach my $key (@all_keys) {
198 # Check for dots (e.g., 'user.name')
199 7235 ▶ if ($key =~ /^(.+)\.(.+)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($key =~ /^(.+)\.(.+)$/u) 0 7235 7235
200 0 my ($rel, $subcol) = ($1, $2);
201  
202 # Initialise the nested hash if it doesn't exist
203 0 ▶ $raw_data{$rel} //= {};
Condition0%0/2
$raw_data{$rel} //= {}
l!l
00
MC/DC0%0/1
$raw_data{$rel} //= {}
$raw_data{$rel}
Truth table0%0/2
A
A= $raw_data{$rel}
Aresult
11
00
204  
205 # Move the value into the nested hash
206 0 $raw_data{$rel}{$subcol} = $raw_data{$key};
207  
208 # Delete the original dotted key safely
209 0 delete $raw_data{$key};
210 }
211 }
212  
213 1138 foreach my $key (keys %raw_data) {
214 7235 my $val = $raw_data{$key};
215  
216 # Only treat as a relationship if the source explicitly says it is
217 7235 ▶ if ($self->result_source->has_relationship($key) &&
Branch: 1 branch
BranchTrueFalseTotal
if ($self->result_source->has_relationship($key) and not $self->result_source->has_column($key)) { } 14 7221 7235
Condition66%2/3
$self->result_source->has_relationship($key) and not $self->result_source->has_column($key)
!ll&&!rl&&r
7221014
MC/DC50%1/2
$self->result_source->has_relationship($key) and not $self->result_source->has_column($key)
$self->result_source->has_relationship($key) not $self->result_source->has_column($key)
Truth table66%2/3
A and not(B)
A= $self->result_source->has_relationship($key)B= not $self->result_source->has_column($key)
ABresult
0X0
100
111
218 !$self->result_source->has_column($key)) {
219  
220 14 my $rel_info = $self->result_source->relationship_info($key);
221 14 ▶ if (defined $val) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $val) 14 0 14
222 14 ▶ if ($rel_info->{attrs}{accessor} eq 'multi') {
Branch: 1 branch
BranchTrueFalseTotal
if ($rel_info->{'attrs'}{'accessor'} eq 'multi') { } 8 6 14
223 8 $rel_data{$key} = $self->_new_prefetched_dataset($val, $key);
224 }
225 else {
226 # belongs_to / might_have: Inflate into a Row object immediately
227 6 ▶ if (ref $val eq 'HASH' && grep { defined } values %$val) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $val eq 'HASH' and grep {defined $_;} values %$val) { } 6 0 6
Condition33%1/3
ref $val eq "HASH" and grep {defined $_;} values %$val
!ll&&!rl&&r
006
MC/DC0%0/2
ref $val eq "HASH" and grep {defined $_;} values %$val
ref $val eq "HASH" grep {defined $_;} values %$val
Truth table33%1/3
A and B
A= ref $val eq "HASH"B= grep {defined $_;} values %$val
ABresult
0X0
100
111
228 6 my $rel_rs = $self->result_source->schema->resultset($rel_info->{source});
229 6 $rel_data{$key} = $rel_rs->new_result($val);
230 }
231 else {
232 0 $rel_data{$key} = undef;
233 }
234 }
235 }
236 }
237 else {
238 # Regular database column
239 7221 $col_data{$key} = $val;
240 }
241 }
242  
243 # Create Row using the proper constructor
244 my $new_row = DBIx::Class::Async::Row->new(
245 schema_instance => $self->{_schema_instance},
246 async_db => $self->{_async_db},
247 source_name => $self->{_source_name},
248 1138 result_source => $self->result_source,
249 row_data => \%col_data,
250 in_storage => $in_storage,
251 );
252  
253 # Set the relationship data
254 1138 $new_row->{_relationship_data} = { %rel_data };
255  
256 # Dynamic Class Hijacking - handle custom result_class
257 1138 ▶ my $target_class = $self->{_attrs}->{result_class} || $self->result_class;
Condition66%2/3
$self->{'_attrs'}{'result_class'} || $self->result_class
l!l&&r!l&&!r
211360
MC/DC0%0/2
$self->{'_attrs'}{'result_class'} || $self->result_class
$self->{'_attrs'}{'result_class'} $self->result_class
Truth table66%2/3
A || B
A= $self->{'_attrs'}{'result_class'}B= $self->result_class
ABresult
1X1
011
000
258 1138 my $base_row_class = ref($new_row);
259  
260 1138 ▶ if ($target_class && $target_class ne $base_row_class) {
Branch: 1 branch
BranchTrueFalseTotal
if ($target_class and $target_class ne $base_row_class) 1138 0 1138
Condition33%1/3
$target_class and $target_class ne $base_row_class
!ll&&!rl&&r
001138
MC/DC0%0/2
$target_class and $target_class ne $base_row_class
$target_class $target_class ne $base_row_class
Truth table33%1/3
A and B
A= $target_classB= $target_class ne $base_row_class
ABresult
0X0
100
111
261 # Create anonymous class name
262 1138 my $safe_target = $target_class =~ s/::/_/gr;
263 1138 my $anon_class = "DBIx::Class::Async::Anon::${safe_target}";
264  
265 99 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
266 1138 ▶ unless (@{"${anon_class}::ISA"}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@{"${anon_class}::ISA";}) 111 1027 1138
267 # Load the custom class if not already loaded
268 111 ▶ unless ($target_class->can('can')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($target_class->can("can")) 0 111 111
269 0 ▶ eval "require $target_class" or die "Could not load $target_class: $@";
Branch: 1 branch
BranchTrueFalseTotal
eval "require $target_class" or die "Could not load ${target_class}: $@" 0 0 0
270 }
271  
272 # Set up inheritance: Anon -> AsyncRow -> CustomClass
273 111 @{"${anon_class}::ISA"} = ($base_row_class, $target_class);
274 }
275  
276 # Re-bless into the anonymous class
277 1138 bless $new_row, $anon_class;
278  
279 # Ensure accessors are created
280 1138 ▶ $new_row->_ensure_accessors if $new_row->can('_ensure_accessors');
Branch: 1 branch
BranchTrueFalseTotal
if $new_row->can("_ensure_accessors") 1138 0 1138
281 }
282  
283 # ACTIVATE the accessors in Row.pm
284 1138 ▶ if ($new_row->can('_install_prefetch_accessors')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($new_row->can("_install_prefetch_accessors")) 1138 0 1138
285 1138 $new_row->_install_prefetch_accessors;
286 }
287  
288 1138 return $new_row;
289 }
290  
291 =head2 new_result_set
292  
293 my $new_rs = $rs->new_result_set({ cond => { active => 1 } });
294  
295 An internal but critical factory method used to spawn new instances of the
296 ResultSet while preserving the asynchronous execution context.
297  
298 This method performs a "smart clone" of the current object's state, ensuring
299 that the background worker pool and metadata links are carried over to the
300 derived ResultSet.
301  
302 =over 4
303  
304 =item * State Mapping
305  
306 It automatically maps internal underscored attributes
307 (e.g., C<_source_name>) to clean constructor arguments (C<source_name>).
308  
309 =item * Infrastructure Persistence
310  
311 Explicitly carries over the C<async_db> (the worker bridge) and the C<schema_instance>.
312  
313 =item * Override Injection
314  
315 Accepts a hashref of overrides to modify the state of the new instance (commonly
316 used for merging new search conditions or attributes).
317  
318 =back
319  
320 Example: Manual ResultSet Cloning
321  
322 If you were extending this library and needed to create a specialised ResultSet
323 that shares the same worker pool:
324  
325 sub specialised_search {
326 my ($self, $extra_logic) = @_;
327  
328 # This ensures the new RS knows how to talk to the workers
329 return $self->new_result_set({
330 cond => { %{$self->{_cond}}, %$extra_logic },
331 attrs => { %{$self->{_attrs}}, cache_for => '1 hour' }
332 });
333 }
334  
335 =cut
336  
337 sub new_result_set {
338 618 ▶ my ($self, $overrides) = @_;
Subroutine new_result_set: called CC=4 SCAR=13.9
Pod documented
339  
340 618 my %args;
341 618 foreach my $internal_key (keys %$self) {
342 # 1. Only process keys starting with an underscore
343 6267 ▶ next unless $internal_key =~ /^_/;
Branch: 1 branch
BranchTrueFalseTotal
unless $internal_key =~ /^_/u 0 6267 6267
344  
345 # 2. Strip leading underscore for the "clean" argument name
346 6267 my $clean_key = $internal_key;
347 6267 $clean_key =~ s/^_//;
348  
349 6267 $args{$clean_key} = $self->{$internal_key};
350 }
351  
352 618 $args{async_db} = $self->{_async_db};
353 618 $args{schema_instance} = $self->{_schema_instance};
354  
355 # 3. Apply overrides
356 618 ▶ if ($overrides) {
Branch: 1 branch
BranchTrueFalseTotal
if ($overrides) 618 0 618
357 618 @args{keys %$overrides} = values %$overrides;
358 }
359  
360 # 4. Call new() with a flat list (%args)
361 618 return (ref $self)->new(%args);
362 }
363  
364 =head2 all
365  
366 my $future = $rs->all;
367 $future->on_done(sub {
368 my $rows = shift; # Arrayref of row objects
369 say $_->name for @$rows;
370 });
371  
372 The primary method for retrieving all results from the ResultSet. It returns a
373 L<Future> that resolves to an arrayref of L<DBIx::Class::Async::Row> objects.
374  
375 =over 4
376  
377 =item * Tier 1: Prefetched/Injected Data
378  
379 If data was manually injected via C<set_cache> or arrived as raw hashrefs,
380 C<all> automatically inflates them into full Row objects, injecting the necessary
381 C<async_db> bridge and metadata into each.
382  
383 =item * Tier 2: Local Buffer
384  
385 If the ResultSet has already been executed and the rows are held in memory
386 (C<_rows>), it returns them immediately wrapped in a resolved Future.
387  
388 =item * Tier 3: Shared Query Cache
389  
390 Before hitting the database, it consults the C<_query_cache> using a surgical
391 lookup based on the source name and query signature.
392  
393 =item * Tier 4: Non-Blocking Fetch
394  
395 On a cache miss, it dispatches the request to the worker pool via C<all_future>.
396 Once results return, they are indexed in the cache for future requests.
397  
398 =back
399  
400 B<Efficiency Note:> This method is highly optimised to prevent redundant IPC
401 (Inter-Process Communication). Multiple calls to C<all> on the same ResultSet
402 will only ever trigger a single network request.
403  
404 =cut
405  
406 sub all {
407 337 ▶ my ($self) = @_;
Subroutine all: called CC=20 SCAR=31.6
Pod documented
408 337 my $db = $self->{_async_db};
409  
410 # 1. Check if caching is explicitly disabled for this query
411 337 ▶ if (exists $self->{_attrs}{cache} && !$self->{_attrs}{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $self->{"_attrs"}{"cache"} and not $self->{"_attrs"}{"cache"}) 3 334 337
Condition100%3/3
exists $self->{"_attrs"}{"cache"} and not $self->{"_attrs"}{"cache"}
!ll&&!rl&&r
33223
MC/DC100%2/2
exists $self->{"_attrs"}{"cache"} and not $self->{"_attrs"}{"cache"}
exists $self->{"_attrs"}{"cache"} not $self->{"_attrs"}{"cache"}
Truth table100%3/3
A and not(B)
A= exists $self->{"_attrs"}{"cache"}B= not $self->{"_attrs"}{"cache"}
ABresult
0X0
100
111
412 3 return $self->all_future;
413 }
414  
415 334 ▶ if ($self->can('_has_dynamic_sql') && $self->_has_dynamic_sql) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->can("_has_dynamic_sql") and $self->_has_dynamic_sql) 0 334 334
Condition33%1/3
$self->can("_has_dynamic_sql") and $self->_has_dynamic_sql
!ll&&!rl&&r
03340
MC/DC0%0/2
$self->can("_has_dynamic_sql") and $self->_has_dynamic_sql
$self->can("_has_dynamic_sql") $self->_has_dynamic_sql
Truth table33%1/3
A and B
A= $self->can("_has_dynamic_sql")B= $self->_has_dynamic_sql
ABresult
0X0
100
111
416 0 return $self->all_future;
417 }
418  
419 # 2. Check cache_ttl (use both _cache_ttl and cache_ttl for compatibility)
420 my $cache_ttl = $self->{_attrs}{cache_ttl}
421 // $db->{_cache_ttl}
422 334 ▶ // 0;
Condition60%3/5
($self->{"_attrs"}{"cache_ttl"} // $db->{"_cache_ttl"}) // 0
l!l
3340
$self->{"_attrs"}{"cache_ttl"} // $db->{"_cache_ttl"}
l!l&&r!l&&!r
13330
MC/DC0%0/2
($self->{"_attrs"}{"cache_ttl"} // $db->{"_cache_ttl"}) // 0
$self->{"_attrs"}{"cache_ttl"} $db->{"_cache_ttl"}
Truth table66%2/3
A // B
A= $self->{"_attrs"}{"cache_ttl"}B= $db->{"_cache_ttl"}
ABresult
1X1
011
000
423  
424 # 3. If no caching, skip to query
425 334 ▶ if (!$cache_ttl) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($cache_ttl) 91 243 334
426 91 return $self->all_future;
427 }
428  
429 # 4. Check for dynamic SQL
430 243 ▶ if ($self->can('_has_dynamic_sql') && $self->_has_dynamic_sql) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->can("_has_dynamic_sql") and $self->_has_dynamic_sql) 0 243 243
Condition33%1/3
$self->can("_has_dynamic_sql") and $self->_has_dynamic_sql
!ll&&!rl&&r
02430
MC/DC0%0/2
$self->can("_has_dynamic_sql") and $self->_has_dynamic_sql
$self->can("_has_dynamic_sql") $self->_has_dynamic_sql
Truth table33%1/3
A and B
A= $self->can("_has_dynamic_sql")B= $self->_has_dynamic_sql
ABresult
0X0
100
111
431 0 return $self->all_future;
432 }
433  
434 # 5. Check for prefetched data first
435 243 ▶ if ($self->{_is_prefetched} && $self->{_entries}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_is_prefetched"} and $self->{"_entries"}) 8 235 243
Condition66%2/3
$self->{"_is_prefetched"} and $self->{"_entries"}
!ll&&!rl&&r
23508
MC/DC50%1/2
$self->{"_is_prefetched"} and $self->{"_entries"}
$self->{"_is_prefetched"} $self->{"_entries"}
Truth table66%2/3
A and B
A= $self->{"_is_prefetched"}B= $self->{"_entries"}
ABresult
0X0
100
111
436 my @blessed_rows = map {
437 12 ▶ if (ref($_) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_ eq 'HASH') { } 8 4 12
438 8 $self->_inflate_row($_, { in_storage => 1 })
439 }
440 else {
441 4 $_; # Already a Row object
442 }
443 8 } @{$self->{_entries}};
444  
445 8 $self->{_entries} = \@blessed_rows;
446 8 $self->{_rows} = \@blessed_rows;
447 8 return Future->done($self->{_entries});
448 }
449  
450 # 6. Check in-memory cache (_rows)
451 235 ▶ if ($self->{_rows} && ref($self->{_rows}) eq 'ARRAY' && @{$self->{_rows}}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_rows"} and ref $self->{"_rows"} eq "ARRAY" and @{$self->{"_rows"};}) 2 233 235
Condition66%4/6
$self->{"_rows"} and ref $self->{"_rows"} eq "ARRAY" and @{$self->{"_rows"};}
!ll&&!rl&&r
23302
$self->{"_rows"} and ref $self->{"_rows"} eq "ARRAY"
!ll&&!rl&&r
23302
MC/DC33%1/3
$self->{"_rows"} and ref $self->{"_rows"} eq "ARRAY" and @{$self->{"_rows"};}
$self->{"_rows"} ref $self->{"_rows"} eq "ARRAY" @{$self->{"_rows"};}
Truth table50%2/4
A and B and C
A= $self->{"_rows"}B= ref $self->{"_rows"} eq "ARRAY"C= @{$self->{"_rows"};}
ABCresult
0XX0
10X0
1100
1111
452 2 return Future->done($self->{_rows});
453 }
454  
455 # 7. Generate cache key
456 233 my $cache_key = $self->_generate_cache_key(0);
457  
458 233 ▶ if ($db->{_cache} && defined $cache_key) {
Branch: 1 branch
BranchTrueFalseTotal
if ($db->{"_cache"} and defined $cache_key) 233 0 233
Condition33%1/3
$db->{"_cache"} and defined $cache_key
!ll&&!rl&&r
00233
MC/DC0%0/2
$db->{"_cache"} and defined $cache_key
$db->{"_cache"} defined $cache_key
Truth table33%1/3
A and B
A= $db->{"_cache"}B= defined $cache_key
ABresult
0X0
100
111
459 233 my $cached_data = eval { $db->{_cache}->get($cache_key) };
460 233 ▶ if (defined $cached_data && ref($cached_data) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $cached_data and ref $cached_data eq "ARRAY") 31 202 233
Condition66%2/3
defined $cached_data and ref $cached_data eq "ARRAY"
!ll&&!rl&&r
202031
MC/DC50%1/2
defined $cached_data and ref $cached_data eq "ARRAY"
defined $cached_data ref $cached_data eq "ARRAY"
Truth table66%2/3
A and B
A= defined $cached_dataB= ref $cached_data eq "ARRAY"
ABresult
0X0
100
111
461 31 $db->{_stats}{_cache_hits}++;
462  
463 my @rows = map {
464 31 $self->new_result($_, { in_storage => 1 })
465 } @$cached_data;
466  
467 31 $self->{_rows} = \@rows;
468 31 return Future->done(\@rows);
469 }
470 }
471  
472 # 9. Cache miss - increment counter and fetch from database
473 202 $db->{_stats}{_cache_misses}++;
474  
475 return $self->all_future->on_done(sub {
476 202 ▶ my $rows = shift;
Subroutine __ANON__: called CC=7 SCAR=20.1
477  
478 # Store UNBLESSED data in CHI
479 202 ▶ if ($db->{_cache} && defined $cache_key && $cache_ttl) {
Branch: 1 branch
BranchTrueFalseTotal
if ($db->{"_cache"} and defined $cache_key and $cache_ttl) 202 0 202
Condition33%2/6
$db->{"_cache"} and defined $cache_key and $cache_ttl
!ll&&!rl&&r
00202
$db->{"_cache"} and defined $cache_key
!ll&&!rl&&r
00202
MC/DC0%0/3
$db->{"_cache"} and defined $cache_key and $cache_ttl
$db->{"_cache"} defined $cache_key $cache_ttl
Truth table25%1/4
A and B and C
A= $db->{"_cache"}B= defined $cache_keyC= $cache_ttl
ABCresult
0XX0
10X0
1100
1111
480 202 my @cache_data;
481  
482 # Check if rows are already hashrefs (from HashRefInflator)
483 202 ▶ if (@$rows && ref($rows->[0]) eq 'HASH' && !blessed($rows->[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$rows and ref $rows->[0] eq 'HASH' and not builtin::blessed($rows->[0])) { } 1 201 202
Condition83%5/6
@$rows and ref $rows->[0] eq "HASH" and not builtin::blessed($rows->[0])
!ll&&!rl&&r
20101
@$rows and ref $rows->[0] eq "HASH"
!ll&&!rl&&r
381631
MC/DC66%2/3
@$rows and ref $rows->[0] eq "HASH" and not builtin::blessed($rows->[0])
@$rows ref $rows->[0] eq "HASH" not builtin::blessed($rows->[0])
Truth table75%3/4
A and B and not(C)
A= @$rowsB= ref $rows->[0] eq "HASH"C= not builtin::blessed($rows->[0])
ABCresult
0XX0
10X0
1100
1111
484 # Already hashrefs, use directly
485 1 @cache_data = @$rows;
486 }
487 else {
488 # Blessed Row objects, extract columns
489 @cache_data = map {
490 201 my %cols = $_->get_columns;
491 312 \%cols;
492 } @$rows;
493 }
494  
495 202 eval { $db->{_cache}->set($cache_key, \@cache_data) };
496 }
497  
498  
499 202 $self->{_rows} = $rows;
500 202 return $rows;
501 202 });
502 }
503  
504 =head2 all_future
505  
506 my $future = $rs->all_future($cond?, \%attrs?);
507  
508 The low-level execution engine for searches. Dispatches a search request to the
509 background worker and returns a L<Future>.
510  
511 =over 4
512  
513 =item * Payload Construction
514  
515 Merges the ResultSet's internal state (C<cond> and C<attrs>) with any temporary
516 overrides passed to the method. It uses C<_build_payload> to ensure the data
517 is serialisable for IPC.
518  
519 =item * Worker Dispatch
520  
521 Calls the C<search> method on the background worker pool via the internal C<_call_worker>
522 bridge.
523  
524 =item * Post-Fetch Inflation (Tier 1)
525  
526 Before creating objects, it runs custom column inflators. This is where database
527 strings (like JSON or custom types) are converted back into Perl structures.
528  
529 =item * Inflation Logic (Tier 2)
530  
531 =over 4
532  
533 =item * If C<HashRefInflator> is requested, it returns the raw data structures
534 for maximum performance.
535  
536 =item * Otherwise, it maps the data through C<_inflate_row> to produce fully
537 functional L<DBIx::Class::Async::Row> objects.
538  
539 =back
540  
541 =back
542  
543 =cut
544  
545 sub all_future {
546 321 ▶ my ($self, $cond, $attrs) = @_;
Subroutine all_future: called CC=5 SCAR=16.4
Pod documented
547  
548 321 my $db = $self->{_async_db};
549 321 my $payload = $self->_build_payload();
550 321 $payload->{source_name} = $self->{_source_name};
551  
552 321 ▶ $payload->{cond} = $cond // $self->{_cond} // {};
Condition60%3/5
($cond // $self->{"_cond"}) // {}
l!l
3210
$cond // $self->{"_cond"}
l!l&&r!l&&!r
83130
MC/DC0%0/2
($cond // $self->{"_cond"}) // {}
$cond $self->{"_cond"}
Truth table66%2/3
A // B
A= $condB= $self->{"_cond"}
ABresult
1X1
011
000
553 321 ▶ $payload->{attrs} = $attrs // $self->{_attrs} // {};
Condition40%2/5
($attrs // $self->{"_attrs"}) // {}
l!l
3210
$attrs // $self->{"_attrs"}
l!l&&r!l&&!r
03210
MC/DC0%0/2
($attrs // $self->{"_attrs"}) // {}
$attrs $self->{"_attrs"}
Truth table33%1/3
A // B
A= $attrsB= $self->{"_attrs"}
ABresult
1X1
011
000
554  
555 return DBIx::Class::Async::_call_worker(
556 $db,
557 'search',
558 $payload,
559 )->then(sub {
560 319 ▶ my $rows_data = shift;
Subroutine __ANON__: called CC=13 SCAR=26.0
561  
562 319 ▶ if (!ref($rows_data) || ref($rows_data) ne 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (not ref $rows_data or ref $rows_data ne "ARRAY") 0 319 319
Condition33%1/3
not ref $rows_data or ref $rows_data ne "ARRAY"
l!l&&r!l&&!r
00319
MC/DC0%0/2
not ref $rows_data or ref $rows_data ne "ARRAY"
not ref $rows_data ref $rows_data ne "ARRAY"
Truth table33%1/3
not(A) or B
A= not ref $rows_dataB= ref $rows_data ne "ARRAY"
ABresult
1X1
011
000
563 0 return [];
564 }
565  
566 # 1. Apply Column Inflators (JSON -> HASH) to the raw data first
567 319 my $moniker = $self->{_source_name};
568 319 my $source_class = $self->result_source->result_class;
569  
570 my $inflators = $db->{_custom_inflators}{$moniker}
571 319 ▶ || $db->{_custom_inflators}{$source_class}
Condition80%4/5
$db->{'_custom_inflators'}{$moniker} || $db->{'_custom_inflators'}{$source_class} || {}
l!l
25663
$db->{"_custom_inflators"}{$moniker} or $db->{"_custom_inflators"}{$source_class}
l!l&&r!l&&!r
256063
MC/DC50%1/2
$db->{'_custom_inflators'}{$moniker} || $db->{'_custom_inflators'}{$source_class} || {}
$db->{"_custom_inflators"}{$moniker} $db->{"_custom_inflators"}{$source_class}
Truth table66%2/3
A or B
A= $db->{"_custom_inflators"}{$moniker}B= $db->{"_custom_inflators"}{$source_class}
ABresult
1X1
011
000
572 || {};
573  
574 319 ▶ if (keys %$inflators) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %$inflators) 256 63 319
575 256 foreach my $row (@$rows_data) {
576 415 foreach my $col (keys %$inflators) {
577 415 ▶ if (exists $row->{$col} && defined $row->{$col} && !ref $row->{$col}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $row->{$col} and defined $row->{$col} and not ref $row->{$col}) 4 411 415
Condition83%5/6
exists $row->{$col} and defined $row->{$col} and not ref $row->{$col}
!ll&&!rl&&r
41104
exists $row->{$col} and defined $row->{$col}
!ll&&!rl&&r
34084
MC/DC66%2/3
exists $row->{$col} and defined $row->{$col} and not ref $row->{$col}
exists $row->{$col} defined $row->{$col} not ref $row->{$col}
Truth table75%3/4
A and B and not(C)
A= exists $row->{$col}B= defined $row->{$col}C= not ref $row->{$col}
ABCresult
0XX0
10X0
1100
1111
578 4 $row->{$col} = $inflators->{$col}{inflate}->($row->{$col});
579 }
580 }
581 }
582 }
583  
584 # 2. Decide based on result_class
585 319 ▶ my $result_class = $self->{_attrs}{result_class} || '';
Condition100%2/2
$self->{'_attrs'}{'result_class'} || ''
l!l
6313
MC/DC100%1/1
$self->{'_attrs'}{'result_class'} || ''
$self->{'_attrs'}{'result_class'}
Truth table100%2/2
A
A= $self->{'_attrs'}{'result_class'}
Aresult
11
00
586  
587 319 ▶ if ($result_class eq 'DBIx::Class::ResultClass::HashRefInflator') {
Branch: 1 branch
BranchTrueFalseTotal
if ($result_class eq "DBIx::Class::ResultClass::HashRefInflator") 6 313 319
588 6 $self->{_rows} = $rows_data;
589 6 return $rows_data;
590 }
591  
592 # 3. Otherwise, turn into Row objects
593 313 my @objects = map { $self->_inflate_row($_, { in_storage => 1 }) } @$rows_data;
594 313 $self->{_rows} = \@objects;
595 313 return \@objects;
596 321 });
597 }
598  
599 =head2 as_query
600  
601 my ($sql, @bind) = @{ $rs->as_query };
602  
603 Returns a representation of the SQL query and its bind parameters that would be
604 executed by this ResultSet.
605  
606 Unlike most other methods in this package, C<as_query> is B<synchronous> and
607 returns a standard DBIC query arrayref immediately. It does not communicate
608 with the worker pool.
609  
610 =over 4
611  
612 =item * Shadow Schema Execution
613  
614 Internally, it maintains a C<dbi:NullP:> (Null Proxy) connection. This allows
615 the L<DBIx::Class> SQL generator to function in the parent process without
616 requiring a real database socket.
617  
618 =item * Metadata Awareness
619  
620 It automatically loads your C<schema_class> if it isn't already in memory to
621 ensure relationships and column types are correctly mapped to SQL.
622  
623 =item * Warning Suppression
624  
625 It intelligently silences "Generic Driver" warnings (like C<undetermined_driver>)
626 that typically occur when generating SQL without an active database handle, keeping
627 your logs clean while preserving actual errors if C<ASYNC_TRACE> is enabled.
628  
629 =back
630  
631 Example: Debugging a complex join
632  
633 my $rs = $schema->resultset('User')->search(
634 { 'orders.status' => 'shipped' },
635 { join => 'orders' }
636 );
637  
638 my ($sql, @bind) = @{ $rs->as_query };
639 print "Generated SQL: $sql\n";
640  
641 =cut
642  
643 sub as_query {
644 61 ▶ my $self = shift;
Subroutine as_query: called CC=7 SCAR=19.8
Pod documented
645  
646 61 my $bridge = $self->{_async_db};
647 61 my $schema_class = $bridge->{_schema_class};
648  
649 61 ▶ unless ($schema_class->can('resultset')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($schema_class->can("resultset")) 0 61 61
650 0 ▶ eval "require $schema_class" or die "as_query: $@";
Branch: 1 branch
BranchTrueFalseTotal
eval "require $schema_class" or die "as_query: $@" 0 0 0
651 }
652  
653 # Silence the "Generic Driver" warnings for the duration of this method
654 local $SIG{__WARN__} = sub {
655 10 ▶ if (ASYNC_TRACE) {
Subroutine __ANON__: called CC=1 SCAR=0.0
656 warn @_ unless $_[0] =~ /undetermined_driver|sql_limit_dialect|GenericSubQ/
657 }
658 61 };
659  
660 61 ▶ unless ($bridge->{_metadata_schema}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($bridge->{"_metadata_schema"}) 4 57 61
661 4 $bridge->{_metadata_schema} = $schema_class->connect('dbi:NullP:');
662 }
663  
664 # Handle empty select => [] by generating SQL manually
665 61 ▶ if (exists $self->{_attrs}{select} &&
Branch: 1 branch
BranchTrueFalseTotal
if (exists $self->{"_attrs"}{"select"} and ref $self->{"_attrs"}{"select"} eq "ARRAY" and @{$self->{"_attrs"}{"select"};} == 0) 2 59 61
Condition83%5/6
exists $self->{"_attrs"}{"select"} and ref $self->{"_attrs"}{"select"} eq "ARRAY" and @{$self->{"_attrs"}{"select"};} == 0
!ll&&!rl&&r
5812
exists $self->{"_attrs"}{"select"} and ref $self->{"_attrs"}{"select"} eq "ARRAY"
!ll&&!rl&&r
5803
MC/DC66%2/3
exists $self->{"_attrs"}{"select"} and ref $self->{"_attrs"}{"select"} eq "ARRAY" and @{$self->{"_attrs"}{"select"};} == 0
exists $self->{"_attrs"}{"select"} ref $self->{"_attrs"}{"select"} eq "ARRAY" @{$self->{"_attrs"}{"select"};} == 0
Truth table75%3/4
A and B and C
A= exists $self->{"_attrs"}{"select"}B= ref $self->{"_attrs"}{"select"} eq "ARRAY"C= @{$self->{"_attrs"}{"select"};} == 0
ABCresult
0XX0
10X0
1100
1111
666 ref $self->{_attrs}{select} eq 'ARRAY' &&
667 3 @{$self->{_attrs}{select}} == 0) {
668  
669 2 return $self->_generate_empty_select_query();
670 }
671  
672 # SQL is generated lazily; warnings often trigger here or at as_query()
673 my $real_rs = $bridge->{_metadata_schema}
674 ->resultset($self->{_source_name})
675 59 ->search($self->{_cond}, $self->{_attrs});
676  
677 59 return $real_rs->as_query;
678 }
679  
680 =head2 as_subselect_rs
681  
682 my $subquery_rs = $rs->as_subselect_rs;
683  
684 Returns a new ResultSet with the current query wrapped as a subselect in
685 the FROM clause. This is useful for applying further operations on top of
686 an already-filtered or aggregated result set.
687  
688 # Get active users, then find those over 18 in the subquery
689 my $active_users = $schema->resultset('User')->search({ active => 1 });
690 my $adult_active = $active_users->as_subselect_rs->search({ age => { '>' => 18 }});
691  
692 B<Note:> Unlike upstream L<DBIx::Class::ResultSet>, this implementation
693 correctly preserves the column list from the original ResultSet.
694 When you select a subset of columns, the subselect will only include those
695 columns, not all columns from the table.
696  
697 # This works correctly - subselect only has id and name
698 my $rs = $schema->resultset('User')
699 ->search({}, { columns => ['id', 'name'] })
700 ->as_subselect_rs;
701  
702 # Further searches on the subselect can only reference id and name
703 my $filtered = $rs->search({ name => { -like => 'A%' }});
704  
705 This is particularly useful for:
706  
707 =over 4
708  
709 =item * Creating derived tables for complex queries
710  
711 =item * Applying LIMIT in a subquery before joining
712  
713 =item * Building multi-stage aggregations
714  
715 =item * Optimising queries with window functions
716  
717 =back
718  
719 =cut
720  
721 sub as_subselect_rs {
722 4 ▶ my $self = shift;
Subroutine as_subselect_rs: called CC=3 SCAR=11.0
Pod documented
723  
724 4 my $subquery = $self->as_query;
725 4 ▶ my $columns = $self->{_attrs}{columns} || $self->{_attrs}{select};
Condition66%2/3
$self->{'_attrs'}{'columns'} || $self->{'_attrs'}{'select'}
l!l&&r!l&&!r
301
MC/DC50%1/2
$self->{'_attrs'}{'columns'} || $self->{'_attrs'}{'select'}
$self->{'_attrs'}{'columns'} $self->{'_attrs'}{'select'}
Truth table66%2/3
A || B
A= $self->{'_attrs'}{'columns'}B= $self->{'_attrs'}{'select'}
ABresult
1X1
011
000
726  
727 4 my %new_attrs = (
728 alias => 'me',
729 from => { me => $subquery }, # Key: alias the subquery
730 );
731  
732 4 ▶ if ($columns) {
Branch: 1 branch
BranchTrueFalseTotal
if ($columns) 3 1 4
733 3 $new_attrs{columns} = $columns; # Key: preserve columns
734 }
735  
736 return bless({
737 _schema_instance => $self->{_schema_instance},
738 _async_db => $self->{_async_db},
739 _source_name => $self->{_source_name},
740 _result_class => $self->{_result_class},
741 4 _cond => {},
742 _attrs => \%new_attrs,
743 _rows => undef,
744 _pos => 0,
745 _is_prefetched => 0,
746 _pager => undef,
747 }, ref($self));
748 }
749  
750 =head2 clear_cache
751  
752 Clears both the local ResultSet buffer and the central query cache for this
753 specific source.
754  
755 =cut
756  
757 sub clear_cache {
758 582 ▶ my ($self, $cache_key) = @_;
Subroutine clear_cache: called CC=4 SCAR=14.1
Pod documented
759 582 my $db = $self->{_async_db};
760  
761 # Clear local in-memory cache
762 582 delete $self->{_rows};
763  
764 # Clear surgical query cache
765 582 ▶ if ($db->{_query_cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($db->{"_query_cache"}) 582 0 582
766 582 my $source = $self->{_source_name};
767 582 delete $db->{_query_cache}->{$source};
768 }
769  
770 582 ▶ if ($db->{_cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($db->{"_cache"}) 478 104 582
771 478 ▶ if (defined $cache_key) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $cache_key) { } 0 478 478
772 0 $db->{_cache}->remove($cache_key);
773 }
774 else {
775 478 $db->{_cache}->clear();
776 }
777 }
778  
779 582 return $self;
780 }
781  
782 =head2 cursor
783  
784 my $cursor = $rs->cursor;
785  
786 Returns a storage-level cursor object for the current ResultSet.
787  
788 This is a low-level method typically used when you need to handle extremely
789 large result sets that would exceed memory limits if fetched all at once via
790 C<all>.
791  
792 =over 4
793  
794 =item * Async Integration
795  
796 The returned cursor is not a standard DBI cursor; it is wrapped by
797 C<DBIx::Class::Async::Storage>, ensuring that calls to C<next> or C<all>
798 on the cursor itself are still routed through the non-blocking worker pool.
799  
800 =item * Efficiency
801  
802 Use this when you intend to process thousands of rows and want to maintain a
803 constant memory footprint.
804  
805 =back
806  
807 Example: Manual Cursor Iteration
808  
809 my $cursor = $rs->search({ type => 'heavy_report' })->cursor;
810  
811 # While this looks synchronous, the underlying storage handle
812 # manages the async state transitions.
813 while (my @row = $cursor->next) {
814 process_data(@row);
815 }
816  
817 =cut
818  
819 sub cursor {
820 1 ▶ my $self = shift;
Subroutine cursor: called CC=1 SCAR=0.0
Pod documented
821  
822 1 return $self->{_schema_instance}->storage->cursor($self);
823 }
824  
825 =head2 create
826  
827 my $future = $rs->create({
828 username => 'jdoe',
829 profile => { theme => 'dark' } # Automatically deflated if configured
830 });
831  
832 Asynchronously inserts a new record into the database. Returns a L<Future>
833 that resolves to a L<DBIx::Class::Async::Row> object representing the
834 persisted data (including database-generated defaults and IDs).
835  
836 =over 4
837  
838 =item * Auto-Deflation
839  
840 Before sending data to the worker pool, the method strips table aliases (C<me.>,
841 C<self.>) and applies custom deflation logic (e.g., serialising a hashref to
842 a JSON string).
843  
844 =item * Cache Invalidation
845  
846 Calling C<create> automatically clears the ResultSet's internal cache via
847 L</clear_cache> to ensure subsequent queries reflect the new state of the
848 database.
849  
850 =item * Lifecycle Management
851  
852 Upon a successful insert, the worker returns the raw record data. The parent process then:
853  
854 =over 4
855  
856 =item 1. Re-inflates complex types (e.g., strings back to objects).
857  
858 =item 2. Instantiates a Row object via L</new_result>.
859  
860 =item 3. Marks the object as C<in_storage>, making it ready for immediate updates or deletions.
861  
862 =back
863  
864 =back
865  
866 Example: Handling a New User Signup
867  
868 $schema->resultset('User')->create({ email => 'new@user.com' })
869 ->then(sub {
870 my $user = shift;
871 say "Created user with ID: " . $user->id;
872 })
873 ->catch(sub {
874 warn "Failed to create user: " . shift;
875 });
876  
877 =cut
878  
879 sub create {
880 479 ▶ my ($self, $raw_data) = @_;
Subroutine create: called CC=9 SCAR=22.1
Pod documented
881  
882 479 my $db = $self->{_async_db};
883 479 my $source_name = $self->{_source_name};
884  
885 479 $self->clear_cache;
886  
887 # Guard against scalar-ref values on primary key columns.
888 # Scalar refs are used to embed raw SQL expressions (e.g. \'UUID()'),
889 # but these cannot cross the async worker IPC boundary -- they are
890 # stringified during serialisation and the SQL expression is lost.
891 # DBIC then falls back to last_insert_id() on a non-autoincrement
892 # char column, returning a wrong value ('1' on SQLite, undef on MySQL).
893 # Generate the PK value in Perl instead:
894 # e.g. Data::UUID->new->create_str instead of \'UUID()'
895  
896 479 my @pk_cols = $self->result_source->primary_columns;
897 479 for my $pk (@pk_cols) {
898 481 ▶ if (exists $raw_data->{$pk} && ref($raw_data->{$pk}) eq 'SCALAR') {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $raw_data->{$pk} and ref $raw_data->{$pk} eq "SCALAR") 1 480 481
Condition100%3/3
exists $raw_data->{$pk} and ref $raw_data->{$pk} eq "SCALAR"
!ll&&!rl&&r
434461
MC/DC100%2/2
exists $raw_data->{$pk} and ref $raw_data->{$pk} eq "SCALAR"
exists $raw_data->{$pk} ref $raw_data->{$pk} eq "SCALAR"
Truth table100%3/3
A and B
A= exists $raw_data->{$pk}B= ref $raw_data->{$pk} eq "SCALAR"
ABresult
0X0
100
111
899 1 Carp::croak(
900 "DBIx::Class::Async: Cannot use a scalar-ref (inline SQL) "
901 . "for primary key column '$pk' on source '$source_name'. "
902 . "Scalar references cannot be serialised across the async "
903 . "worker IPC boundary. "
904 . "Generate the value in Perl before calling create() -- "
905 . "e.g. use Data::UUID->new->create_str instead of \\'UUID()'."
906 );
907 }
908 }
909  
910 # 1. Fetch inflators
911 478 ▶ my $inflators = $db->{_custom_inflators}{$source_name} || {};
Condition100%2/2
$db->{'_custom_inflators'}{$source_name} || {}
l!l
40672
MC/DC100%1/1
$db->{'_custom_inflators'}{$source_name} || {}
$db->{'_custom_inflators'}{$source_name}
Truth table100%2/2
A
A= $db->{'_custom_inflators'}{$source_name}
Aresult
11
00
912  
913 # 2. Deflate the incoming data (Parent Side)
914 478 my %deflated_data;
915 478 ▶ while (my ($k, $v) = each %$raw_data) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %$raw_data) 1398 478 1876
916 1398 my $clean_key = $k;
917 1398 $clean_key =~ s/^(?:foreign|self|me)\.//;
918 1398 ▶ if ($inflators->{$clean_key} && $inflators->{$clean_key}{deflate}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($inflators->{$clean_key} and $inflators->{$clean_key}{"deflate"}) 8 1390 1398
Condition66%2/3
$inflators->{$clean_key} and $inflators->{$clean_key}{"deflate"}
!ll&&!rl&&r
139008
MC/DC50%1/2
$inflators->{$clean_key} and $inflators->{$clean_key}{"deflate"}
$inflators->{$clean_key} $inflators->{$clean_key}{"deflate"}
Truth table66%2/3
A and B
A= $inflators->{$clean_key}B= $inflators->{$clean_key}{"deflate"}
ABresult
0X0
100
111
919 8 $v = $inflators->{$clean_key}{deflate}->($v);
920 }
921 1398 $deflated_data{$clean_key} = $v;
922 }
923  
924 # 3. Leverage specialised payload builder
925 my $payload = {
926 source_name => $self->{_source_name},
927 data => \%deflated_data,
928 attrs => $self->{_attrs} || {},
929 478 ▶ };
Condition50%1/2
$self->{'_attrs'} || {}
l!l
4780
MC/DC0%0/1
$self->{'_attrs'} || {}
$self->{'_attrs'}
Truth table50%1/2
A
A= $self->{'_attrs'}
Aresult
11
00
930  
931 # 4. Dispatch with correct signature
932 return DBIx::Class::Async::_call_worker(
933 $db,
934 'create',
935 $payload
936 )->then(sub {
937 478 ▶ my $db_row = shift;
Subroutine __ANON__: called CC=5 SCAR=17.2
938 478 ▶ return Future->done(undef) unless $db_row;
Branch: 1 branch
BranchTrueFalseTotal
unless $db_row 0 478 478
939  
940 # 5. Inflation of return data
941 478 for my $col (keys %$inflators) {
942 406 ▶ if (exists $db_row->{$col} && $inflators->{$col}{inflate}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $db_row->{$col} and $inflators->{$col}{"inflate"}) 406 0 406
Condition33%1/3
exists $db_row->{$col} and $inflators->{$col}{"inflate"}
!ll&&!rl&&r
00406
MC/DC0%0/2
exists $db_row->{$col} and $inflators->{$col}{"inflate"}
exists $db_row->{$col} $inflators->{$col}{"inflate"}
Truth table33%1/3
A and B
A= exists $db_row->{$col}B= $inflators->{$col}{"inflate"}
ABresult
0X0
100
111
943 406 $db_row->{$col} = $inflators->{$col}{inflate}->($db_row->{$col});
944 }
945 }
946  
947 # 6. Use new_result to create new row
948 478 my $obj = $self->new_result($db_row, { in_storage => 1 });
949 478 return Future->done($obj);
950 478 });
951 }
952  
953 =head2 count
954  
955 my $future = $rs->count({ status => 'active' });
956 $future->on_done(sub {
957 my $count = shift;
958 say "Found $count active records.";
959 });
960  
961 Executes a C<SELECT COUNT(*)> query against the database asynchronously. Returns
962 a L<Future> resolving to the integer count.
963  
964 =over 4
965  
966 =item * Optimisation - Row Limit
967  
968 If the ResultSet has a fixed number of C<rows> defined in its attributes and
969 no additional conditions are passed to C<count>, the method returns the C<rows>
970 value immediately without hitting the database.
971  
972 =item * Caching
973  
974 Uses a specialised cache key (suffix C<:count>) to store results in the
975 C<async_db> cache. Aggregate queries are often expensive; this ensures that
976 multiple count requests for the same criteria are served from memory.
977  
978 =item * Worker Dispatch
979  
980 Dispatches the C<count> command to the background worker pool, keeping the
981 parent process non-blocking.
982  
983 =back
984  
985 Example: Conditional Counting
986  
987 $rs->count({ category_id => 5 })->then(sub {
988 my $count = shift;
989 return $count > 0 ? $rs->all : Future->done([]);
990 });
991  
992 =cut
993  
994 sub count {
995 51 ▶ my ($self, $cond, $attrs) = @_;
Subroutine count: called CC=3 SCAR=11.0
Pod documented
996  
997 51 ▶ if (!defined $cond && exists $self->{_attrs}{rows}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $cond and exists $self->{"_attrs"}{"rows"}) 5 46 51
Condition100%3/3
not defined $cond and exists $self->{"_attrs"}{"rows"}
!ll&&!rl&&r
2445
MC/DC100%2/2
not defined $cond and exists $self->{"_attrs"}{"rows"}
not defined $cond exists $self->{"_attrs"}{"rows"}
Truth table100%3/3
not(A) and B
A= not defined $condB= exists $self->{"_attrs"}{"rows"}
ABresult
0X0
100
111
998 5 return Future->done($self->{_attrs}{rows});
999 }
1000  
1001 46 my $db = $self->{_async_db};
1002  
1003 46 my $payload = $self->_build_payload($cond, $attrs);
1004  
1005 46 warn "[PID $$] STAGE 1 (Parent): Dispatching count" if ASYNC_TRACE;
1006  
1007 # This returns a Future that will be resolved by the worker
1008 46 return DBIx::Class::Async::_call_worker(
1009 $db, 'count', $payload);
1010 }
1011  
1012 =head2 count_future
1013  
1014 my $future = $rs->count_future;
1015  
1016 Returns a L<Future> that resolves to the row count, bypassing all parent-process
1017 caching mechanisms.
1018  
1019 Unlike the standard L</count> method, which may return a cached result or an
1020 in-memory attribute value, C<count_future> always dispatches a C<SELECT COUNT(*)>
1021 request directly to the worker pool.
1022  
1023 =over 4
1024  
1025 =item * Bypasses Cache
1026  
1027 Ignores any data stored in the C<_query_cache> or the shared C<_cache> bucket.
1028  
1029 =item * Stateless
1030  
1031 Does not inspect C<$rs->{_attrs}->{rows}>. It forces the database to perform
1032 the calculation.
1033  
1034 =item * Direct Dispatch
1035  
1036 Uses the low-level C<_call_worker> interface to ensure the smallest possible
1037 overhead between the method call and the IPC (Inter-Process Communication) layer.
1038  
1039 =back
1040  
1041 Example: Forcing a fresh count in a high-concurrency environment
1042  
1043 # count() might return a cached value from 2 seconds ago
1044 # count_future() hits the metal
1045  
1046 $rs->count_future->on_done(sub {
1047 my $exact_count = shift;
1048 print "Live DB Count: $exact_count\n";
1049 });
1050  
1051 =cut
1052  
1053 sub count_future {
1054 14 ▶ my $self = shift;
Subroutine count_future: called CC=1 SCAR=0.0
Pod documented
1055 14 my $db = $self->{_async_db};
1056  
1057 return DBIx::Class::Async::_call_worker(
1058 $db, 'count', {
1059 source_name => $self->{_source_name},
1060 cond => $self->{_cond},
1061 attrs => $self->{_attrs},
1062 14 });
1063 }
1064  
1065 =head2 count_literal
1066  
1067 my $future = $rs->count_literal('age > ? AND status = "active"', 21);
1068  
1069 Performs a count operation using a raw SQL fragment. This is useful for complex
1070 filtering that is difficult to express via standard L<SQL::Abstract> syntax.
1071  
1072 Returns a L<Future> resolving to the integer count.
1073  
1074 =over 4
1075  
1076 =item * Fluent Chaining
1077  
1078 Internally, this method calls C<search_literal> to generate a transient, specialised
1079 ResultSet and then immediately calls C<count> on it.
1080  
1081 =item * Infrastructure Inheritance
1082  
1083 The transient ResultSet automatically inherits the C<_async_db> worker bridge
1084 and C<_schema_instance> from the parent, ensuring the raw SQL is executed in
1085 the correct worker process.
1086  
1087 =item * Security
1088  
1089 Always pass parameters as a bind list (e.g., C<@bind>) rather than interpolating
1090 variables directly into the SQL string to prevent SQL injection.
1091  
1092 =back
1093  
1094 Example: Using Database-Specific Functions
1095  
1096 # Using Postgres-specific ILIKE for case-insensitive counting
1097 my $future = $rs->count_literal('email ILIKE ?', '%@GMAIL.COM');
1098  
1099 $future->on_done(sub {
1100 my $gmail_users = shift;
1101 print "Found $gmail_users Gmail accounts.\n";
1102 });
1103  
1104 =cut
1105  
1106 sub count_literal {
1107 2 ▶ my ($self, $sql_fragment, @bind) = @_;
Subroutine count_literal: called CC=1 SCAR=0.0
Pod documented
1108  
1109 # 1. search_literal() creates a NEW ResultSet instance.
1110 # 2. Because we fixed search_literal/new_result_set, this new RS
1111 # already shares the same _async_db and _schema_instance.
1112 # 3. We then chain the count() call which returns the Future.
1113  
1114 2 return $self->search_literal($sql_fragment, @bind)->count;
1115 }
1116  
1117 =head2 count_rs
1118  
1119 my $count_rs = $rs->count_rs($cond?, \%attrs?);
1120  
1121 Returns a new L<DBIx::Class::Async::ResultSet> specifically configured to
1122 perform a C<COUNT(*)> operation.
1123  
1124 Unlike L</count>, which returns a B<Future> that executes immediately,
1125 C<count_rs> is synchronous and returns a B<ResultSet>. This allows you to
1126 pre-define a count query and pass it around your application or combine it with
1127 further search modifiers before execution.
1128  
1129 =over 4
1130  
1131 =item * Chainability
1132  
1133 Because it returns a ResultSet, you can continue chaining methods like C<search>
1134 or C<attr> before eventually calling C<all> or C<next> to get the value.
1135  
1136 =item * Infrastructure Guarantee
1137  
1138 Internally calls C<search>, ensuring the newly created ResultSet remains pinned to
1139 the same C<async_db> worker bridge and parent C<schema_instance>.
1140  
1141 =item * Automatic Projection
1142  
1143 Automatically sets the C<select> attribute to C<{ count => '*' }> and the
1144 C<as> alias to C<'count'>.
1145  
1146 =back
1147  
1148 Example: Defining a count query for later execution
1149  
1150 # Create the count-specific ResultSet
1151 my $pending_count_rs = $rs->count_rs({ status => 'pending' });
1152  
1153 # ... later in the code ...
1154  
1155 # Execute it via the standard async 'all' or 'next'
1156 $pending_count_rs->next->then(sub {
1157 my $row = shift;
1158 print "Pending count: " . $row->get_column('count') . "\n";
1159 });
1160  
1161 =cut
1162  
1163 sub count_rs {
1164 2 ▶ my ($self, $cond, $attrs) = @_;
Subroutine count_rs: called CC=2 SCAR=7.1
Pod documented
1165  
1166 # By calling $self->search, we guarantee the new RS
1167 # inherits the pinned _async_db and _schema_instance.
1168 return $self->search($cond, {
1169 2 ▶ %{ $attrs || {} },
Branch: 1 branch
BranchTrueFalseTotal
$attrs or {} 2 0 2
1170 select => [ { count => '*' } ],
1171 as => [ 'count' ],
1172 });
1173 }
1174  
1175 =head2 count_total
1176  
1177 my $total_future = $rs->count_total($extra_cond?, \%extra_attrs?);
1178  
1179 Returns a L<Future> resolving to the total number of records matching the current
1180 filter, specifically ignoring any pagination or sorting attributes.
1181  
1182 This is primarily used to calculate the "Total Pages" in a paginated UI, where
1183 the current ResultSet might be sliced to only 20 rows, but you need to know
1184 that 5,000 total records match the criteria.
1185  
1186 =over 4
1187  
1188 =item * Attribute Stripping
1189  
1190 Automatically removes C<rows>, C<offset>, C<page>, and C<order_by> from the
1191 query. This ensures the database doesn't perform unnecessary sorting or slicing,
1192 resulting in a much faster count.
1193  
1194 =item * Parameter Merging
1195  
1196 Allows passing in C<$cond> and C<$attrs> which are merged with the existing
1197 ResultSet state before execution.
1198  
1199 =item * Direct Execution
1200  
1201 Like L</count_future>, this bypasses any local result buffers and asks the
1202 worker to perform a fresh C<COUNT(*)> on the un-sliced dataset.
1203  
1204 =back
1205  
1206 Example: Implementing Pagination Metadata
1207  
1208 my $paged_rs = $rs->search({ category => 'electronics' })
1209 ->page(1)
1210 ->rows(10);
1211  
1212 # This resolves to 10 (the current page size)
1213 my $current_count_f = $paged_rs->count;
1214  
1215 # This resolves to the absolute total (e.g., 450)
1216 my $grand_total_f = $paged_rs->count_total;
1217  
1218 Future->needs_all($current_count_f, $grand_total_f)->then(sub {
1219 my ($current, $total) = @_;
1220 print "Showing $current of $total total items.\n";
1221 });
1222  
1223 =cut
1224  
1225 sub count_total {
1226 7 ▶ my ($self, $cond, $attrs) = @_;
Subroutine count_total: called CC=5 SCAR=16.7
Pod documented
1227  
1228 # 1. Merge incoming parameters with existing ResultSet state
1229 7 ▶ my %merged_cond = ( %{ $self->{_cond} || {} }, %{ $cond || {} } );
Branch: 2 branches
BranchTrueFalseTotal
$self->{"_cond"} or {} 0 7 7
$cond or {} 7 0 7
1230 7 ▶ my %merged_attrs = ( %{ $self->{_attrs} || {} }, %{ $attrs || {} } );
Branch: 2 branches
BranchTrueFalseTotal
$self->{"_attrs"} or {} 0 7 7
$attrs or {} 7 0 7
1231  
1232 # 2. Strip slicing/ordering attributes to get the absolute total
1233 7 delete @merged_attrs{qw(rows offset page order_by)};
1234  
1235 # 3. Use the static call exactly like your other count() implementations
1236 return DBIx::Class::Async::_call_worker(
1237 $self->{_async_db},
1238 'count',
1239 {
1240 source_name => $self->{_source_name},
1241 7 cond => \%merged_cond,
1242 attrs => \%merged_attrs,
1243 });
1244 }
1245  
1246 =head2 delete
1247  
1248 my $future = $rs->search({ status => 'obsolete' })->delete;
1249  
1250 Asynchronously removes records matching the ResultSet's criteria from the database.
1251 Returns a L<Future> resolving to the number of rows deleted.
1252  
1253 =over 4
1254  
1255 =item * Auto-Routing Logic
1256  
1257 =over 4
1258  
1259 =item * Direct Path
1260  
1261 If the query is a simple attribute-free HASH (e.g., C<< { id => 5 } >>), it
1262 dispatches a single C<DELETE> command directly to the worker.
1263  
1264 =item * Safe Path (delete_all)
1265  
1266 If the ResultSet contains complex logic (joins, limits, or offsets), it automatically
1267 delegates to L</delete_all> to avoid database-specific restrictions on
1268 multi-table deletes.
1269  
1270 =back
1271  
1272 =item * Cache Invalidation
1273  
1274 Immediately calls L</clear_cache> on the ResultSet to prevent the application
1275 from reading stale data that has been removed from the physical storage.
1276  
1277 =item * Non-Blocking
1278  
1279 Like all write operations in this library, the process is handed off to the
1280 worker pool, allowing your main application to continue processing other
1281 requests.
1282  
1283 =back
1284  
1285 Example: Safe Deletion of Limited Sets
1286  
1287 # This uses the 'Safe Path' because of the 'rows' attribute
1288 $rs->search({ type => 'log' }, { rows => 100 })->delete
1289 ->on_done(sub {
1290 my $count = shift;
1291 say "Cleaned up $count log entries.";
1292 });
1293  
1294 =cut
1295  
1296 sub delete {
1297 50 ▶ my $self = shift;
Subroutine delete: called CC=10 SCAR=23.2
Pod documented
1298  
1299 50 $self->clear_cache;
1300  
1301 50 ▶ my $attrs = $self->{_attrs} || {};
Condition50%1/2
$self->{'_attrs'} || {}
l!l
500
MC/DC0%0/1
$self->{'_attrs'} || {}
$self->{'_attrs'}
Truth table50%1/2
A
A= $self->{'_attrs'}
Aresult
11
00
1302 50 my $cond = $self->{_cond};
1303  
1304 # Attributes that make a direct single-query DELETE unsafe.
1305 # For each of these we must take the two-step path: fetch matching PKs
1306 # via a clean search, then DELETE WHERE pk IN (...).
1307 #
1308 # - rows / offset / page : LIMIT on DELETE is non-standard SQL
1309 # - join : multi-table DELETE syntax varies by database
1310 # - group_by / having : DBIC drops GROUP BY when generating the DELETE
1311 # subquery, producing invalid SQL. Additionally,
1312 # a grouped search does not return individual
1313 # rows -- it returns aggregate results -- so we
1314 # must re-fetch the actual rows using only the
1315 # WHERE condition (stripping group_by/having)
1316 # before deleting.
1317  
1318 my $has_limit = exists $attrs->{rows}
1319 || exists $attrs->{offset}
1320 50 ▶ || exists $attrs->{page};
Condition66%4/6
exists $attrs->{'rows'} || exists $attrs->{'offset'} || exists $attrs->{'page'}
l!l&&r!l&&!r
2048
exists $attrs->{"rows"} or exists $attrs->{"offset"}
l!l&&r!l&&!r
2048
MC/DC33%1/3
exists $attrs->{'rows'} || exists $attrs->{'offset'} || exists $attrs->{'page'}
exists $attrs->{"rows"} exists $attrs->{"offset"} exists $attrs->{'page'}
Truth table50%2/4
A or B || C
A= exists $attrs->{"rows"}B= exists $attrs->{"offset"}C= exists $attrs->{'page'}
ABCresult
1XX1
01X1
0011
0000
1321 50 my $has_join = exists $attrs->{join};
1322 my $has_grouped = exists $attrs->{group_by}
1323 50 ▶ || exists $attrs->{having};
Condition66%2/3
exists $attrs->{'group_by'} || exists $attrs->{'having'}
l!l&&r!l&&!r
2048
MC/DC50%1/2
exists $attrs->{'group_by'} || exists $attrs->{'having'}
exists $attrs->{'group_by'} exists $attrs->{'having'}
Truth table66%2/3
A || B
A= exists $attrs->{'group_by'}B= exists $attrs->{'having'}
ABresult
1X1
011
000
1324  
1325 50 ▶ if ( $has_grouped ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_grouped) 2 48 50
1326 # Strip group_by and having entirely -- we only want the WHERE
1327 # condition to identify which rows to delete. Keeping them would
1328 # cause all() to return aggregate results with no usable PKs.
1329 2 my %safe_attrs = %$attrs;
1330 2 delete @safe_attrs{qw(group_by having)};
1331  
1332 2 return $self->new_result_set({
1333 cond => $cond,
1334 attrs => \%safe_attrs,
1335 })->delete_all;
1336 }
1337  
1338 48 ▶ if ( $has_limit || $has_join ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_limit or $has_join) 3 45 48
Condition100%3/3
$has_limit or $has_join
l!l&&r!l&&!r
2145
MC/DC100%2/2
$has_limit or $has_join
$has_limit $has_join
Truth table100%3/3
A or B
A= $has_limitB= $has_join
ABresult
1X1
011
000
1339 3 return $self->delete_all;
1340 }
1341  
1342 # Simple condition with no dangerous attrs: single-query direct DELETE.
1343 45 ▶ if ( ref($cond) eq 'HASH' && keys %$cond ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $cond eq "HASH" and keys %$cond) 10 35 45
Condition66%2/3
ref $cond eq "HASH" and keys %$cond
!ll&&!rl&&r
03510
MC/DC50%1/2
ref $cond eq "HASH" and keys %$cond
ref $cond eq "HASH" keys %$cond
Truth table66%2/3
A and B
A= ref $cond eq "HASH"B= keys %$cond
ABresult
0X0
100
111
1344 return DBIx::Class::Async::_call_worker(
1345 $self->{_async_db},
1346 'delete',
1347 {
1348 source_name => $self->{_source_name},
1349 10 cond => $cond,
1350 }
1351 );
1352 }
1353  
1354 # No condition, or non-HASH condition (literal SQL): use delete_all for
1355 # safety to avoid accidental full-table wipe on malformed input and to
1356 # handle literal SQL conditions correctly.
1357 35 return $self->delete_all;
1358 }
1359  
1360 =head2 delete_all
1361  
1362 my $future = $rs->search({ status => 'expired' })->delete_all;
1363  
1364 Performs a two-stage asynchronous deletion. First, it retrieves the records
1365 matching the criteria to identify their unique Primary Keys, then it issues a
1366 targeted bulk delete for those specific records.
1367  
1368 =over 4
1369  
1370 =item * Precision
1371  
1372 This method is safer than a direct C<delete> when dealing with ResultSets
1373 that use C<rows>, C<offset>, or complex C<join> attributes, as it ensures
1374 only the specific records visible to the ResultSet are removed.
1375  
1376 =item * Composite Key Support
1377  
1378 Automatically detects and handles tables with multiple primary keys, constructing
1379 a complex C<-or> condition to ensure the correct rows are targeted.
1380  
1381 =item * Short-Circuiting
1382  
1383 If the initial search yields no results, the method returns a resolved Future
1384 with a value of C<0>, saving an unnecessary round-trip to the database worker.
1385  
1386 =item * Return Value
1387  
1388 Resolves to the number of rows that were successfully identified and sent for
1389 deletion.
1390  
1391 =back
1392  
1393 Example: Safely Deleting with Relationships
1394  
1395 # Delete orders for inactive users (complex join)
1396 $schema->resultset('Order')->search({ 'user.is_active' => 0 }, { join => 'user' })
1397 ->delete_all
1398 ->on_done(sub {
1399 my $deleted = shift;
1400 print "Purged $deleted orders from inactive accounts.\n";
1401 });
1402  
1403 =cut
1404  
1405 sub delete_all {
1406 52 ▶ my $self = shift;
Subroutine delete_all: called CC=1 SCAR=0.2
Pod documented
1407  
1408 # Step 1: Use our working 'all' method to get the targets
1409 return $self->all->then(sub {
1410 52 ▶ my $rows = shift;
Subroutine __ANON__: called CC=4 SCAR=14.8
1411  
1412 52 ▶ return Future->done(0) unless $rows && @$rows;
Branch: 1 branch
BranchTrueFalseTotal
unless $rows and @$rows 23 29 52
Condition66%2/3
$rows and @$rows
!ll&&!rl&&r
02329
MC/DC50%1/2
$rows and @$rows
$rows @$rows
Truth table66%2/3
A and B
A= $rowsB= @$rows
ABresult
0X0
100
111
1413  
1414 # Step 2: Identify Primary Keys
1415 29 my @pks = $self->result_source->primary_columns;
1416 29 my $count = scalar @$rows;
1417 29 my $condition;
1418  
1419 29 ▶ if (scalar @pks == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @pks == 1) { } 29 0 29
1420 29 my $pk_col = $pks[0];
1421 29 my @ids = map { $_->get_column($pk_col) } @$rows;
1422 29 $condition = { $pk_col => { -in => \@ids } };
1423 }
1424 else {
1425 # Handle Composite Keys
1426 $condition = { -or => [
1427 map {
1428 0 my $row = $_;
1429 0 { map { $_ => $row->get_column($_) } @pks }
1430 } @$rows
1431 ]};
1432 }
1433  
1434 # Step 3: Send the targeted delete to the worker
1435 return DBIx::Class::Async::_call_worker(
1436 $self->{_async_db},
1437 'delete',
1438 {
1439 source_name => $self->{_source_name},
1440 cond => $condition
1441 }
1442 )->then(sub {
1443 29 ▶ return Future->done($count);
Subroutine __ANON__: called CC=1 SCAR=0.0
1444 29 });
1445 52 });
1446 }
1447  
1448 =head2 delete_query
1449  
1450 my ($sql, @bind) = $rs->delete_query;
1451 my $query = $rs->delete_query;
1452  
1453 Returns the SQL and bind values that would be generated by a delete operation
1454 without actually executing it.
1455  
1456 my $rs = $schema->resultset('User')->search({ inactive => 1 });
1457 my ($sql, @bind) = $rs->delete_query;
1458 # $sql = \'DELETE FROM users WHERE inactive = ?'
1459 # @bind = (1)
1460  
1461 # Verify before deleting
1462 if ($$sql =~ /WHERE/) {
1463 $rs->delete->get; # Safe to execute
1464 } else {
1465 die "Refusing to DELETE without WHERE clause!";
1466 }
1467  
1468 =cut
1469  
1470 sub delete_query {
1471 2 ▶ my $self = shift;
Subroutine delete_query: called CC=6 SCAR=19.6
Pod documented
1472  
1473 2 my $bridge = $self->{_async_db};
1474 2 my $schema_class = $bridge->{_schema_class};
1475  
1476 2 ▶ unless ($schema_class->can('resultset')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($schema_class->can("resultset")) 0 2 2
1477 0 ▶ eval "require $schema_class" or die "delete_query: $@";
Branch: 1 branch
BranchTrueFalseTotal
eval "require $schema_class" or die "delete_query: $@" 0 0 0
1478 }
1479  
1480 # Silence warnings
1481 local $SIG{__WARN__} = sub {
1482 0 ▶ if (ASYNC_TRACE) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1483 warn @_ unless $_[0] =~ /undetermined_driver|sql_limit_dialect|GenericSubQ/
1484 }
1485 2 };
1486  
1487 2 ▶ unless ($bridge->{_metadata_schema}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($bridge->{"_metadata_schema"}) 0 2 2
1488 0 $bridge->{_metadata_schema} = $schema_class->connect('dbi:NullP:');
1489 }
1490  
1491 # Create a sync ResultSet with the same conditions
1492 my $real_rs = $bridge->{_metadata_schema}
1493 ->resultset($self->{_source_name})
1494 2 ->search($self->{_cond}, $self->{_attrs});
1495  
1496 # Generate SQL using DBIC's internal delete SQL generator
1497 2 my $storage = $bridge->{_metadata_schema}->storage;
1498  
1499 2 my ($sql, @bind);
1500  
1501 2 eval {
1502 2 my $source = $real_rs->result_source;
1503 2 my $cond = $real_rs->{cond};
1504  
1505 # Build WHERE clause
1506 2 my ($where_sql, @where_bind) = $storage->sql_maker->where($cond);
1507  
1508 # Construct DELETE statement
1509 2 my $table = $source->from;
1510 2 $sql = \"DELETE FROM $table$where_sql";
1511 2 @bind = @where_bind;
1512 };
1513  
1514 2 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 2 2
1515 0 croak("Failed to generate delete SQL: $@");
1516 }
1517  
1518 2 ▶ return wantarray ? ($sql, @bind) : \[ $sql, @bind ];
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 2 0 2
1519 }
1520  
1521 =head2 first_future
1522  
1523 An alias for L</first>. This naming convention is provided for consistency with
1524 other C<*_future> methods in the library, signaling that the return value is
1525 an asynchronous L<Future>.
1526  
1527 Example: Retrieving the most recent login
1528  
1529 my $future = $schema->resultset('UserLog')->search(
1530 { user_id => 42 },
1531 { order_by => { -desc => 'login_at' } }
1532 )->first;
1533  
1534 $future->on_done(sub {
1535 my $log = shift;
1536 print "Last seen: " . $log->login_at if $log;
1537 });
1538  
1539 =cut
1540  
1541 1 ▶sub first_future { shift->first(@_) }
Subroutine first_future: called CC=1 SCAR=0.0
Pod documented
1542  
1543 =head2 first
1544  
1545 my $future = $rs->first;
1546  
1547 Returns a L<Future> resolving to the first L<DBIx::Class::Async::Row> object in
1548 the ResultSet, or C<undef> if the set is empty.
1549  
1550 =over 4
1551  
1552 =item * Memory First
1553  
1554 If the ResultSet has already been populated (e.g. via a previous call to C<all>),
1555 this method returns the first element from the internal C<_rows> buffer immediately
1556 without a database hit.
1557  
1558 =item * Auto-Inflation
1559  
1560 If the internal buffer contains raw data (hashrefs), it is automatically inflated
1561 into a proper Row object before the Future resolves.
1562  
1563 =item * Optimised Fetch
1564  
1565 If no data is in memory, it executes a targeted query with C<< rows => 1 >> (SQL C<LIMIT 1>).
1566 This is significantly faster and more memory-efficient than fetching the entire result set.
1567  
1568 =back
1569  
1570 =cut
1571  
1572 sub first {
1573 152 ▶ my $self = shift;
Subroutine first: called CC=4 SCAR=14.0
Pod documented
1574  
1575 # 1. If we already have data in memory, use it!
1576 152 ▶ if ($self->{_rows} && @{$self->{_rows}}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_rows"} and @{$self->{"_rows"};}) 2 150 152
Condition66%2/3
$self->{"_rows"} and @{$self->{"_rows"};}
!ll&&!rl&&r
15002
MC/DC50%1/2
$self->{"_rows"} and @{$self->{"_rows"};}
$self->{"_rows"} @{$self->{"_rows"};}
Truth table66%2/3
A and B
A= $self->{"_rows"}B= @{$self->{"_rows"};}
ABresult
0X0
100
111
1577 2 my $data = $self->{_rows}[0];
1578 2 ▶ my $row = (ref($data) eq 'HASH') ? $self->_inflate_row($data, { in_storage => 1 }) : $data;
Branch: 1 branch
BranchTrueFalseTotal
ref $data eq 'HASH' ? : 0 2 2
1579 2 return Future->done($row);
1580 }
1581  
1582 # 2. If no cache, force a LIMIT 1 query to be fast
1583 150 return $self->search(undef, { rows => 1 })->next;
1584 }
1585  
1586 =head2 find
1587  
1588 # Find by Primary Key scalar
1589 my $user_f = $rs->find(123);
1590  
1591 # Find by unique constraint hashref
1592 my $user_f = $rs->find({ email => 'gemini@example.com' });
1593  
1594 Retrieves a single row from the database based on a unique identifier. Returns
1595 a L<Future> resolving to a single L<DBIx::Class::Async::Row> object or C<undef>
1596 if no match is found.
1597  
1598 =over 4
1599  
1600 =item * Scalar Lookup
1601  
1602 If a single value is provided, it is automatically mapped to the table's
1603 Primary Key column. Note: This only works for tables with a single Primary Key.
1604  
1605 =item * HashRef Lookup
1606  
1607 If a hashref is provided, it is used as a specific search condition. This is
1608 useful for finding records by unique columns other than the primary key
1609 (e.g., C<username> or C<slug>).
1610  
1611 =item * Short-Circuiting
1612  
1613 If C<undef> is passed as the identifier, the method immediately returns a
1614 resolved Future containing C<undef>, avoiding a pointless database round-trip.
1615  
1616 =item * Under the Hood
1617  
1618 This method is a wrapper around L</search> and L</single>, ensuring that a
1619 C<LIMIT 1> is always applied to the query for maximum performance.
1620  
1621 =back
1622  
1623 =cut
1624  
1625 sub find {
1626 129 ▶ my ($self, $id_or_cond) = @_;
Subroutine find: called CC=4 SCAR=14.0
Pod documented
1627  
1628 129 ▶ return Future->done(undef) unless defined $id_or_cond;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id_or_cond 0 129 129
1629  
1630 129 my $cond;
1631 129 ▶ if (ref($id_or_cond) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $id_or_cond eq 'HASH') { } 28 101 129
1632 28 $cond = $id_or_cond;
1633 }
1634 else {
1635 # GET THE REAL PK NAME
1636 101 my @pks = $self->result_source->primary_columns;
1637 101 ▶ die "find() with scalar only works on single PK tables" if @pks > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @pks > 1 0 101 101
1638 101 $cond = { $pks[0] => $id_or_cond };
1639 }
1640  
1641 129 return $self->search($cond)->single;
1642 }
1643  
1644 =head2 find_or_new
1645  
1646 my $future = $rs->find_or_new({ email => 'user@example.com' }, \%attrs?);
1647  
1648 Attempts to find a record in the database using unique constraints. If found,
1649 it returns the existing row. If not, it returns a new, **in-memory** row object
1650 populated with the provided data.
1651  
1652 Returns a L<Future> resolving to a L<DBIx::Class::Async::Row> object.
1653  
1654 =over 4
1655  
1656 =item * Unique Lookup
1657  
1658 Uses an internal helper to extract unique identifiers (Primary Keys or Unique
1659 Constraints) from the provided data for the initial C<find> call.
1660  
1661 =item * Data Merging
1662  
1663 If the record is not found, the new object is created by merging the provided
1664 C<$data> with any existing constraints (C<where> clauses) currently on the ResultSet.
1665  
1666 =item * Namespace Cleaning
1667  
1668 Automatically strips DBIC aliases like C<me.>, C<foreign.>, or C<self.> from
1669 column names to ensure the new object has clean, accessible attributes.
1670  
1671 =item * Non-Blocking
1672  
1673 Even though it may return a "new" object that hasn't hit the DB yet, it still
1674 returns a L<Future> to maintain API consistency with the asynchronous C<find> operation.
1675  
1676 =back
1677  
1678 Example: Preparing a record for a form
1679  
1680 $schema->resultset('User')->find_or_new({
1681 username => 'jdoe'
1682 })->then(sub {
1683 my $user = shift;
1684  
1685 # If $user->in_storage is false, we know this is a fresh object
1686 say "Welcome back, " . $user->username if $user->in_storage;
1687 say "Sign up now, " . $user->username unless $user->in_storage;
1688 });
1689  
1690 =cut
1691  
1692 sub find_or_new {
1693 4 ▶ my ($self, $data, $attrs) = @_;
Subroutine find_or_new: called CC=2 SCAR=6.9
Pod documented
1694 4 ▶ $attrs //= {};
Condition50%1/2
$attrs //= {}
l!l
04
MC/DC0%0/1
$attrs //= {}
$attrs
Truth table50%1/2
A
A= $attrs
Aresult
11
00
1695  
1696 # 1. Identify what makes this record unique
1697 4 my $lookup = $self->_extract_unique_lookup($data, $attrs);
1698  
1699 # 2. Call our newly ported find()
1700 return $self->find($lookup, $attrs)->then(sub {
1701 4 ▶ my ($row) = @_;
Subroutine __ANON__: called CC=4 SCAR=13.9
1702  
1703 # If found, return it immediately
1704 4 ▶ return Future->done($row) if $row;
Branch: 1 branch
BranchTrueFalseTotal
if $row 1 3 4
1705  
1706 # 3. Otherwise, prepare data for a new local object
1707 # We merge existing constraints with the provided data
1708 3 ▶ my %new_data = ( %{$self->{_cond} || {}}, %$data );
Branch: 1 branch
BranchTrueFalseTotal
$self->{"_cond"} or {} 0 3 3
1709 3 my %clean_data;
1710 3 ▶ while (my ($k, $v) = each %new_data) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %new_data) 5 3 8
1711 5 (my $clean_key = $k) =~ s/^(?:me|foreign|self)\.//;
1712 5 $clean_data{$clean_key} = $v;
1713 }
1714  
1715 # 4. Return a "new" result object (local memory only)
1716 # Note: new_result should handle passing the _async_db to the row
1717 3 return Future->done($self->new_result(\%clean_data));
1718 4 });
1719 }
1720  
1721 =head2 find_or_create
1722  
1723 my $future = $rs->find_or_create({
1724 email => 'user@example.com',
1725 name => 'John Doe'
1726 });
1727  
1728 Ensures a record exists in the database. Returns a L<Future> resolving to a
1729 L<DBIx::Class::Async::Row> object.
1730  
1731 =over 4
1732  
1733 =item * Optimistic Strategy
1734  
1735 First attempts to locate the record using L</find>. If the record is found,
1736 it is returned immediately.
1737  
1738 =item * Atomic Creation
1739  
1740 If the record is missing, it attempts to L</create> it.
1741  
1742 =item * Race Condition Recovery
1743  
1744 In distributed systems, a "Time-of-Check to Time-of-Use" (TOCTOU) race can
1745 occur. If another process inserts the record after our C<find> but before
1746 our C<create>, the database will throw a Unique Constraint error. This
1747 method catches that error and performs one final C<find> to retrieve the
1748 "winning" record.
1749  
1750 =item * Payload Handling
1751  
1752 Automatically extracts unique constraints from the provided data to build
1753 the lookup criteria.
1754  
1755 =back
1756  
1757 Example: Safe Tagging System
1758  
1759 # Multiple workers might try to create the 'perl' tag at once
1760 $schema->resultset('Tag')->find_or_create({ name => 'perl' })
1761 ->then(sub {
1762 my $tag = shift;
1763 return $post->add_to_tags($tag);
1764 });
1765  
1766 =cut
1767  
1768 sub find_or_create {
1769 4 ▶ my ($self, $data, $attrs) = @_;
Subroutine find_or_create: called CC=2 SCAR=8.0
Pod documented
1770 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
1771  
1772 4 my $lookup = $self->_extract_unique_lookup($data, $attrs);
1773  
1774 # 1. First attempt: Find
1775 return $self->find($lookup, $attrs)->then(sub {
1776 4 ▶ my ($row) = @_;
Subroutine __ANON__: called CC=2 SCAR=10.3
1777 4 ▶ return Future->done($row) if $row;
Branch: 1 branch
BranchTrueFalseTotal
if $row 3 1 4
1778  
1779 # 2. Second attempt: Create
1780 # This calls your async create() which goes through the bridge
1781 return $self->create($data)->catch(sub {
1782 0 ▶ my ($error) = @_;
Subroutine __ANON__: not called CC=2 SCAR=17.9
1783  
1784 # 3. Race Condition Recovery
1785 # If the error is about a unique constraint, someone else inserted it
1786 # between our 'find' and 'create' calls.
1787 0 ▶ if ("$error" =~ /unique constraint|already exists/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ("$error" =~ /unique constraint|already exists/iu) 0 0 0
1788 0 warn "[PID $$] Race condition detected in find_or_create, retrying find"
1789 if ASYNC_TRACE;
1790 0 return $self->find($lookup, $attrs);
1791 }
1792  
1793 # If it's a real error (connection, etc.), fail forward
1794 0 return Future->fail($error);
1795 1 });
1796 4 });
1797 }
1798  
1799 =head2 get_attribute
1800  
1801 my $rows_limit = $rs->get_attribute('rows');
1802  
1803 Returns the value of a specific attribute (e.g., C<rows>, C<offset>, C<join>)
1804 currently set on the ResultSet. This is a synchronous read from the internal
1805 C<_attrs> hashref.
1806  
1807 =cut
1808  
1809 sub get_attribute {
1810 2 ▶ my ($self, $key) = @_;
Subroutine get_attribute: called CC=1 SCAR=0.0
Pod documented
1811 2 return $self->{_attrs}->{$key};
1812 }
1813  
1814 =head2 get
1815  
1816 my $data = $rs->get;
1817  
1818 Returns the current "raw" state of the ResultSet's data buffer.
1819  
1820 =over 4
1821  
1822 =item * Returns the arrayref of inflated B<Row objects> if they exist.
1823  
1824 =item * Falls back to returning B<raw hashrefs> (C<_entries>) if they have been
1825 fetched from a worker but not yet inflated.
1826  
1827 =item * Returns an empty arrayref C<[]> if no data has been fetched.
1828  
1829 =back
1830  
1831 =cut
1832  
1833 sub get {
1834 1 ▶ my $self = shift;
Subroutine get: called CC=5 SCAR=26.5
Pod documented
1835 # 1. Check for inflated objects first
1836 1 ▶ return $self->{_rows} if $self->{_rows} && ref($self->{_rows}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_rows"} and ref $self->{"_rows"} eq "ARRAY" 1 0 1
Condition33%1/3
$self->{"_rows"} and ref $self->{"_rows"} eq "ARRAY"
!ll&&!rl&&r
001
MC/DC0%0/2
$self->{"_rows"} and ref $self->{"_rows"} eq "ARRAY"
$self->{"_rows"} ref $self->{"_rows"} eq "ARRAY"
Truth table33%1/3
A and B
A= $self->{"_rows"}B= ref $self->{"_rows"} eq "ARRAY"
ABresult
0X0
100
111
1837  
1838 # 2. Check for raw data awaiting inflation
1839 0 ▶ return $self->{_entries} if $self->{_entries} && ref($self->{_entries}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_entries"} and ref $self->{"_entries"} eq "ARRAY" 0 0 0
Condition0%0/3
$self->{"_entries"} and ref $self->{"_entries"} eq "ARRAY"
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"_entries"} and ref $self->{"_entries"} eq "ARRAY"
$self->{"_entries"} ref $self->{"_entries"} eq "ARRAY"
Truth table0%0/3
A and B
A= $self->{"_entries"}B= ref $self->{"_entries"} eq "ARRAY"
ABresult
0X0
100
111
1840  
1841 0 return [];
1842 }
1843  
1844 =head2 get_cache
1845  
1846 my $rows = $rs->get_cache;
1847  
1848 Specifically returns the internal buffer of B<inflated Row objects>. Unlike C<get>,
1849 this will return C<undef> if the objects haven't been created yet, adhering
1850 to the standard DBIC behaviour where "cache" implies fully realised results.
1851  
1852 =cut
1853  
1854 sub get_cache {
1855 1 ▶ my $self = shift;
Subroutine get_cache: called CC=3 SCAR=12.5
Pod documented
1856 # Align with your all() logic: Return _rows if populated, otherwise undef
1857 1 ▶ return $self->{_rows} if $self->{_rows} && ref($self->{_rows}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_rows"} and ref $self->{"_rows"} eq "ARRAY" 0 1 1
Condition33%1/3
$self->{"_rows"} and ref $self->{"_rows"} eq "ARRAY"
!ll&&!rl&&r
100
MC/DC0%0/2
$self->{"_rows"} and ref $self->{"_rows"} eq "ARRAY"
$self->{"_rows"} ref $self->{"_rows"} eq "ARRAY"
Truth table33%1/3
A and B
A= $self->{"_rows"}B= ref $self->{"_rows"} eq "ARRAY"
ABresult
0X0
100
111
1858  
1859 # Optional: If you want get_cache to be "smart" like your line 85,
1860 # you could return _entries here, but usually get_cache implies inflated rows.
1861 1 return undef;
1862 }
1863  
1864 =head2 get_column
1865  
1866 my $col_obj = $rs->get_column('price');
1867  
1868 Returns a L<DBIx::Class::Async::ResultSetColumn> object for the specified
1869 column.
1870  
1871 This pivots the API from row-based operations to column-based aggregate
1872 functions. The returned object allows you to perform asynchronous math
1873 directly on the database:
1874  
1875 $rs->get_column('age')->func_future('AVG')->on_done(sub {
1876 my $avg = shift;
1877 print "Average Age: $avg\n";
1878 });
1879  
1880 =over 4
1881  
1882 =item * Context Preservation
1883  
1884 The column object inherits the ResultSet's current filters (C<where> clause)
1885 and the C<async_db> worker bridge.
1886  
1887 =back
1888  
1889 =cut
1890  
1891 sub get_column {
1892 4 ▶ my ($self, $column) = @_;
Subroutine get_column: called CC=1 SCAR=0.0
Pod documented
1893  
1894 return DBIx::Class::Async::ResultSetColumn->new(
1895 resultset => $self,
1896 column => $column,
1897 async_db => $self->{_async_db},
1898 4 );
1899 }
1900  
1901 =head2 is_cache_found
1902  
1903 my $cached_rows = $rs->is_cache_found($cache_key);
1904  
1905 Queries the shared async infrastructure to see if a specific query result is
1906 already available in the C<_query_cache>.
1907  
1908 This is a "surgical" cache lookup. Instead of searching a flat global cache,
1909 it first identifies the "bucket" for the current B<source_name> and then
1910 looks for the specific B<key>.
1911  
1912 =over 4
1913  
1914 =item * Returns
1915  
1916 The cached arrayref of rows if found, or C<undef> if the cache is empty or expired.
1917  
1918 =item * Scope
1919  
1920 This lookup is scoped to the C<_async_db> instance, allowing multiple ResultSets
1921 to benefit from the same background fetch.
1922  
1923 =back
1924  
1925 =cut
1926  
1927 sub is_cache_found {
1928 0 ▶ my ($self, $key) = @_;
Subroutine is_cache_found: not called CC=3 SCAR=24.8
Pod documented
1929  
1930 0 my $db = $self->{_async_db};
1931 0 my $source = $self->{_source_name};
1932  
1933 # Return only if both the source bucket and the specific key exist
1934 return $db->{_query_cache}->{$source}->{$key}
1935 if exists $db->{_query_cache}->{$source}
1936 0 ▶ && exists $db->{_query_cache}->{$source}->{$key};
Branch: 1 branch
BranchTrueFalseTotal
if exists $db->{"_query_cache"}{$source} and exists $db->{"_query_cache"}{$source}{$key} 0 0 0
Condition0%0/3
exists $db->{"_query_cache"}{$source} and exists $db->{"_query_cache"}{$source}{$key}
!ll&&!rl&&r
000
MC/DC0%0/2
exists $db->{"_query_cache"}{$source} and exists $db->{"_query_cache"}{$source}{$key}
exists $db->{"_query_cache"}{$source} exists $db->{"_query_cache"}{$source}{$key}
Truth table0%0/3
A and B
A= exists $db->{"_query_cache"}{$source}B= exists $db->{"_query_cache"}{$source}{$key}
ABresult
0X0
100
111
1937  
1938 0 return undef;
1939 }
1940  
1941 =head2 is_ordered
1942  
1943 if ($rs->is_ordered) { ... }
1944  
1945 Returns a boolean indicating whether the ResultSet has an C<order_by> attribute
1946 defined.
1947  
1948 This is used internally by methods like L</pager> to issue warnings when
1949 pagination is attempted on unordered data, which can lead to non-deterministic
1950 results in distributed systems.
1951  
1952 =cut
1953  
1954 sub is_ordered {
1955 10 ▶ my $self = shift;
Subroutine is_ordered: called CC=3 SCAR=11.1
Pod documented
1956 # Check if 'order_by' exists in the attributes hashref
1957 10 ▶ return (exists $self->{_attrs}->{order_by} && defined $self->{_attrs}->{order_by}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
exists $self->{'_attrs'}{'order_by'} && defined $self->{'_attrs'}{'order_by'} ? : 2 8 10
Condition66%2/3
exists $self->{"_attrs"}{"order_by"} and defined $self->{"_attrs"}{"order_by"}
!ll&&!rl&&r
802
MC/DC50%1/2
exists $self->{"_attrs"}{"order_by"} and defined $self->{"_attrs"}{"order_by"}
exists $self->{"_attrs"}{"order_by"} defined $self->{"_attrs"}{"order_by"}
Truth table66%2/3
A and B
A= exists $self->{"_attrs"}{"order_by"}B= defined $self->{"_attrs"}{"order_by"}
ABresult
0X0
100
111
1958 }
1959  
1960 =head2 is_paged
1961  
1962 say "This is a subset" if $rs->is_paged;
1963  
1964 Returns a boolean indicating whether the ResultSet has a C<page> attribute
1965 defined. This is a reliable way to check if the current ResultSet represents
1966 a "slice" of data rather than the full set.
1967  
1968 =cut
1969  
1970 sub is_paged {
1971 12 ▶ my $self = shift;
Subroutine is_paged: called CC=3 SCAR=11.1
Pod documented
1972 12 ▶ return (exists $self->{_attrs}->{page} && defined $self->{_attrs}->{page}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
exists $self->{'_attrs'}{'page'} && defined $self->{'_attrs'}{'page'} ? : 11 1 12
Condition66%2/3
exists $self->{"_attrs"}{"page"} and defined $self->{"_attrs"}{"page"}
!ll&&!rl&&r
1011
MC/DC50%1/2
exists $self->{"_attrs"}{"page"} and defined $self->{"_attrs"}{"page"}
exists $self->{"_attrs"}{"page"} defined $self->{"_attrs"}{"page"}
Truth table66%2/3
A and B
A= exists $self->{"_attrs"}{"page"}B= defined $self->{"_attrs"}{"page"}
ABresult
0X0
100
111
1973 }
1974  
1975 =head2 next
1976  
1977 $rs->next->then(sub {
1978 my $row = shift;
1979 return unless $row;
1980 # Process row...
1981 });
1982  
1983 Iterates through the resultset. If the buffer is empty, it triggers an C<all>
1984 call internally to populate the local cache and then returns the first element.
1985  
1986 =cut
1987  
1988 sub next {
1989 166 ▶ my $self = shift;
Subroutine next: called CC=5 SCAR=16.2
Pod documented
1990  
1991 # 1. Check if the buffer already exists (Memory Hit)
1992 166 ▶ if ($self->{_rows}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_rows"}) 8 158 166
1993 8 ▶ $self->{_pos} //= 0;
Condition50%1/2
$self->{"_pos"} //= 0
l!l
80
MC/DC0%0/1
$self->{"_pos"} //= 0
$self->{"_pos"}
Truth table50%1/2
A
A= $self->{"_pos"}
Aresult
11
00
1994  
1995 8 ▶ if ($self->{_pos} >= @{$self->{_rows}}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_pos"} >= @{$self->{"_rows"};}) 3 5 8
1996 3 return Future->done(undef);
1997 }
1998  
1999 5 my $data = $self->{_rows}[$self->{_pos}++];
2000  
2001 # Inflate if it's raw data
2002 5 ▶ my $row = (ref($data) eq 'HASH')
Branch: 1 branch
BranchTrueFalseTotal
ref $data eq 'HASH' ? : 0 5 5
2003 ? $self->_inflate_row($data)
2004 : $data;
2005  
2006 5 return Future->done($row);
2007 }
2008  
2009 # 2. Buffer empty: Trigger 'all' (Database Hit)
2010 return $self->all->then(sub {
2011 # $self->all already inflated the rows into $self->{_rows}
2012 # and returns an arrayref of objects.
2013 158 ▶ my $rows = shift;
Subroutine __ANON__: called CC=4 SCAR=14.0
2014  
2015 158 ▶ if (!$rows || !@$rows) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($rows and @$rows) 17 141 158
Condition66%2/3
$rows and @$rows
!ll&&!rl&&r
017141
MC/DC50%1/2
$rows and @$rows
$rows @$rows
Truth table66%2/3
A and B
A= $rowsB= @$rows
ABresult
0X0
100
111
2016 17 return Future->done(undef);
2017 }
2018  
2019 # Reset position and return the first inflated result
2020 141 $self->{_rows} = $rows;
2021 141 $self->{_pos} = 0;
2022 141 my $row = $self->{_rows}[$self->{_pos}++];
2023  
2024 141 ▶ $row = $self->_inflate_row($row) if ref($row) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $row eq "HASH" 0 141 141
2025  
2026 141 return Future->done($row);
2027 158 });
2028 }
2029  
2030 =head2 page / pager
2031  
2032 my $paged_rs = $rs->page(2);
2033 my $pager = $paged_rs->pager; # Returns DBIx::Class::Async::ResultSet::Pager
2034  
2035 C<page> returns a cloned RS with paging attributes. C<pager> provides an object
2036 for UI pagination logic (e.g., C<last_page>, C<entries_per_page>).
2037  
2038 =cut
2039  
2040 sub page {
2041 7 ▶ my ($self, $page_number) = @_;
Subroutine page: called CC=3 SCAR=11.0
Pod documented
2042  
2043 # 1. Ensure we have a valid page number (default to 1)
2044 7 ▶ my $page = $page_number || 1;
Condition50%1/2
$page_number || 1
l!l
70
MC/DC0%0/1
$page_number || 1
$page_number
Truth table50%1/2
A
A= $page_number
Aresult
11
00
2045  
2046 # 2. Capture existing rows attribute from _attrs, or default to 10
2047 # This matches your old design's requirement
2048 7 ▶ my $rows = $self->{_attrs}->{rows} || 10;
Condition100%2/2
$self->{'_attrs'}{'rows'} || 10
l!l
25
MC/DC100%1/1
$self->{'_attrs'}{'rows'} || 10
$self->{'_attrs'}{'rows'}
Truth table100%2/2
A
A= $self->{'_attrs'}{'rows'}
Aresult
11
00
2049  
2050 # 3. Delegate to search() for cloning and state preservation
2051 # This passes through your bridge validation logic
2052 7 return $self->search(undef, {
2053 page => $page,
2054 rows => $rows,
2055 });
2056 }
2057  
2058 sub pager {
2059 8 ▶ my $self = shift;
Subroutine pager: called CC=5 SCAR=18.1
Pod documented
2060  
2061 # 1. Return cached pager if it exists
2062 8 ▶ return $self->{_pager} if $self->{_pager};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_pager"} 0 8 8
2063  
2064 # 2. Strict check for paging attributes
2065 8 ▶ unless ($self->is_paged) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->is_paged) 0 8 8
2066 0 die "Cannot call ->pager on a non-paged resultset. Call ->page(\$n) first.";
2067 }
2068  
2069 # 3. Warning for unordered results (crucial for consistent pagination)
2070 # Checks if we are NOT in a test environment (HARNESS_ACTIVE)
2071 8 ▶ if (!$self->is_ordered && !$ENV{HARNESS_ACTIVE}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->is_ordered or $ENV{"HARNESS_ACTIVE"}) 0 8 8
Condition66%2/3
$self->is_ordered or $ENV{"HARNESS_ACTIVE"}
l!l&&r!l&&!r
170
MC/DC0%0/2
$self->is_ordered or $ENV{"HARNESS_ACTIVE"}
$self->is_ordered $ENV{"HARNESS_ACTIVE"}
Truth table66%2/3
A or B
A= $self->is_orderedB= $ENV{"HARNESS_ACTIVE"}
ABresult
1X1
011
000
2072 0 warn "DBIx::Class::Async Warning: Calling ->pager on an unordered ResultSet. " .
2073 "Results may be inconsistent across pages.\n" if ASYNC_TRACE;
2074 }
2075  
2076 # 4. Lazy-load and instantiate the Async Pager
2077 8 require DBIx::Class::Async::ResultSet::Pager;
2078 8 return $self->{_pager} = DBIx::Class::Async::ResultSet::Pager->new(resultset => $self);
2079 }
2080  
2081 =head2 populate / populate_bulk
2082  
2083 $rs->populate([
2084 { name => 'Alice', age => 30 },
2085 { name => 'Bob', age => 25 },
2086 ]);
2087  
2088 High-speed bulk insertion. Deflates all rows in the parent process before sending
2089 a single batch request to the worker. Returns a L<Future> resolving to an arrayref
2090 of created objects.
2091  
2092 =cut
2093  
2094 sub populate {
2095 21 ▶ my ($self, $data) = @_;
Subroutine populate: called CC=1 SCAR=0.0
Pod documented
2096 21 return $self->_do_populate('populate', $data);
2097 }
2098  
2099 sub populate_bulk {
2100 2 ▶ my ($self, $data) = @_;
Subroutine populate_bulk: called CC=1 SCAR=0.0
Pod documented
2101 2 return $self->_do_populate('populate_bulk', $data);
2102 }
2103  
2104 sub _do_populate {
2105 23 ▶ my ($self, $operation, $data) = @_;
Subroutine _do_populate: called CC=20 SCAR=30.9
2106  
2107 23 ▶ croak("data required") unless defined $data;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $data 0 23 23
2108 23 ▶ croak("data must be an arrayref") unless ref $data eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "ARRAY" 0 23 23
2109 23 ▶ croak("data cannot be empty") unless @$data;
Branch: 1 branch
BranchTrueFalseTotal
unless @$data 0 23 23
2110  
2111 # 1. Build payload and STRICTLY validate
2112 23 my $payload = $self->_build_payload();
2113  
2114 23 ▶ croak("Failed to build payload: _build_payload returned undef")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $payload eq "HASH" 0 23 23
2115 unless ref $payload eq 'HASH';
2116  
2117 croak("Missing source_name in ResultSet")
2118 23 ▶ unless $payload->{source_name} || $self->{_source_name};
Branch: 1 branch
BranchTrueFalseTotal
unless $payload->{"source_name"} or $self->{"_source_name"} 0 23 23
Condition33%1/3
$payload->{"source_name"} or $self->{"_source_name"}
l!l&&r!l&&!r
2300
MC/DC0%0/2
$payload->{"source_name"} or $self->{"_source_name"}
$payload->{"source_name"} $self->{"_source_name"}
Truth table33%1/3
A or B
A= $payload->{"source_name"}B= $self->{"_source_name"}
ABresult
1X1
011
000
2119  
2120 # 2. Deflate the data for the Worker
2121 23 my $db = $self->{_async_db};
2122 23 my $source_name = $self->{_source_name};
2123 23 ▶ my $inflators = $db->{_custom_inflators}{$source_name} || {};
Condition100%2/2
$db->{'_custom_inflators'}{$source_name} || {}
l!l
212
MC/DC100%1/1
$db->{'_custom_inflators'}{$source_name} || {}
$db->{'_custom_inflators'}{$source_name}
Truth table100%2/2
A
A= $db->{'_custom_inflators'}{$source_name}
Aresult
11
00
2124  
2125 # 1. Deflate the data for the Worker
2126 23 my @deflated_data;
2127  
2128 # Check if this is the "Array of Arrays" format (first element is an arrayref)
2129 23 ▶ if (ref $data->[0] eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data->[0] eq 'ARRAY') { } 7 16 23
2130 # This is the header-style populate: [['col1', 'col2'], [val1, val2]]
2131 # We pass it through raw, as the Worker should handle the mapping,
2132 # but we still want to keep our deflation logic if possible.
2133 7 my @rows = @$data; # Copy to avoid mutating original if needed
2134 7 my $header = shift @rows;
2135 7 my $expected_count = scalar @$header;
2136  
2137 7 foreach my $row (@rows) {
2138 15 ▶ if (scalar @$row != $expected_count) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @$row != $expected_count) 1 14 15
2139 1 croak("Row has a different number of columns than the header");
2140 }
2141 }
2142 6 @deflated_data = @$data;
2143 }
2144 else {
2145 # This is the "Array of Hashes" format
2146 # 1. Properly declare $source and %col_info
2147 16 my $source = $self->result_source;
2148 16 my %col_info = %{ $source->columns_info };
2149  
2150 16 foreach my $row_data (@$data) {
2151 89 ▶ croak("populate row must be a HASH ref")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row_data eq "HASH" 0 89 89
2152 unless ref $row_data eq 'HASH';
2153  
2154 # 2. Merge Default Values
2155 89 my %merged_row = %$row_data;
2156 89 ▶ while (my ($col, $info) = each %col_info) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %col_info) 610 89 699
2157 610 ▶ if (!exists $merged_row{$col}
Branch: 1 branch
BranchTrueFalseTotal
if (not exists $merged_row{$col} and exists $info->{"default_value"}) 92 518 610
Condition100%3/3
not exists $merged_row{$col} and exists $info->{"default_value"}
!ll&&!rl&&r
26625292
MC/DC100%2/2
not exists $merged_row{$col} and exists $info->{"default_value"}
not exists $merged_row{$col} exists $info->{"default_value"}
Truth table100%3/3
not(A) and B
A= not exists $merged_row{$col}B= exists $info->{"default_value"}
ABresult
0X0
100
111
2158 && exists $info->{default_value}) {
2159 92 $merged_row{$col} = $info->{default_value};
2160 }
2161 }
2162  
2163 # 3. Deflate for Worker
2164 89 my %deflated_row;
2165 89 ▶ while (my ($k, $v) = each %merged_row) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %merged_row) 358 89 447
2166 358 my $clean_key = $k;
2167 358 $clean_key =~ s/^(?:foreign|self|me)\.//;
2168  
2169 358 ▶ if ($inflators->{$clean_key}
Branch: 1 branch
BranchTrueFalseTotal
if ($inflators->{$clean_key} and $inflators->{$clean_key}{"deflate"}) 0 358 358
Condition33%1/3
$inflators->{$clean_key} and $inflators->{$clean_key}{"deflate"}
!ll&&!rl&&r
35800
MC/DC0%0/2
$inflators->{$clean_key} and $inflators->{$clean_key}{"deflate"}
$inflators->{$clean_key} $inflators->{$clean_key}{"deflate"}
Truth table33%1/3
A and B
A= $inflators->{$clean_key}B= $inflators->{$clean_key}{"deflate"}
ABresult
0X0
100
111
2170 && $inflators->{$clean_key}{deflate}) {
2171 0 $v = $inflators->{$clean_key}{deflate}->($v);
2172 }
2173 358 $deflated_row{$clean_key} = $v;
2174 }
2175 89 push @deflated_data, \%deflated_row;
2176 }
2177 }
2178  
2179 # 3. Patch and Dispatch
2180 22 ▶ $payload->{source_name} //= $source_name;
Condition33%1/3
$payload->{"source_name"} //= $source_name
l!l&&r!l&&!r
2200
MC/DC0%0/2
$payload->{"source_name"} //= $source_name
$payload->{"source_name"} $source_name
Truth table33%1/3
A //= B
A= $payload->{"source_name"}B= $source_name
ABresult
1X1
011
000
2181 22 $payload->{data} = \@deflated_data;
2182  
2183 return DBIx::Class::Async::_call_worker(
2184 $db,
2185 $operation,
2186 $payload
2187 )->then(sub {
2188 22 ▶ my $results = shift;
Subroutine __ANON__: called CC=3 SCAR=11.0
2189 22 ▶ return Future->done([]) unless $results && ref $results eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless $results and ref $results eq "ARRAY" 2 20 22
Condition66%2/3
$results and ref $results eq "ARRAY"
!ll&&!rl&&r
0220
MC/DC50%1/2
$results and ref $results eq "ARRAY"
$results ref $results eq "ARRAY"
Truth table66%2/3
A and B
A= $resultsB= ref $results eq "ARRAY"
ABresult
0X0
100
111
2190  
2191 20 my @objects = map { $self->_inflate_row($_) } @$results;
2192 20 return Future->done(\@objects);
2193 22 });
2194 }
2195  
2196 =head2 prefetch
2197  
2198 my $paged_rs = $rs->prefetch({ 'orders' => 'order_items' });
2199  
2200 Informs the ResultSet to fetch related data alongside the primary records in a
2201 single query.
2202  
2203 This is an alias for calling C<< $rs->search(undef, { prefetch => $prefetch }) >>.
2204  
2205 =over 4
2206  
2207 =item * Efficiency
2208  
2209 Reduces the number of round-trips to the worker pool. Without prefetch,
2210 accessing a relationship on a row might trigger a new asynchronous request;
2211 with it, the data is already present in the row's internal buffer.
2212  
2213 =item * Deep Nesting
2214  
2215 Supports the standard L<DBIx::Class> syntax for nested relationships (hashes
2216 for single dependencies, arrays for multiple).
2217  
2218 =item * Async Inflation
2219  
2220 When the worker returns the data, the parent process's C<new_result> method
2221 automatically identifies the prefetched columns and inflates them into nested
2222 L<DBIx::Class::Async::Row> objects.
2223  
2224 =back
2225  
2226 Example: Eager Loading for an API Response
2227  
2228 # Fetch users and their profiles in one go
2229 $schema->resultset('User')->prefetch('profile')->all->then(sub {
2230 my $users = shift;
2231 foreach my $user (@$users) {
2232 # This is now a synchronous, in-memory call because of prefetch
2233 print $user->username . " lives in " . $user->profile->city . "\n";
2234 }
2235 });
2236  
2237 =cut
2238  
2239 sub prefetch {
2240 4 ▶ my ($self, $prefetch) = @_;
Subroutine prefetch: called CC=1 SCAR=0.0
Pod documented
2241 4 return $self->search(undef, { prefetch => $prefetch });
2242 }
2243  
2244 =head2 result_class
2245  
2246 $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
2247  
2248 Gets or sets the class used to inflate rows. If set to C<HashRefInflator>, C<all>
2249 will return raw hashrefs instead of Row objects, which is significantly faster
2250 for read-only APIs.
2251  
2252 =cut
2253  
2254 sub result_class {
2255 1145 ▶ my $self = shift;
Subroutine result_class: called CC=5 SCAR=16.3
Pod documented
2256  
2257 1145 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 2 1143 1145
2258 2 my $new_class = shift;
2259 # Clone the RS to allow chaining: $rs->result_class('...')->search(...)
2260 2 my $cloned = { %$self };
2261 2 ▶ $cloned->{_attrs} = { %{ $self->{_attrs} || {} } }; # Shallow copy attributes
Branch: 1 branch
BranchTrueFalseTotal
$self->{"_attrs"} or {} 0 2 2
2262 2 $cloned->{_attrs}->{result_class} = $new_class;
2263 2 return bless $cloned, ref $self;
2264 }
2265  
2266 # Hierarchy:
2267 # 1. Attribute override
2268 # 2. Schema metadata (via source name)
2269 # 3. Default fallback
2270 return $self->{_attrs}->{result_class}
2271 || $self->{_result_class} # Value passed during construction
2272 1143 ▶ || 'DBIx::Class::Core';
Condition60%3/5
$self->{'_attrs'}{'result_class'} || $self->{'_result_class'} || 'DBIx::Class::Core'
l!l
11430
$self->{"_attrs"}{"result_class"} or $self->{"_result_class"}
l!l&&r!l&&!r
511380
MC/DC0%0/2
$self->{'_attrs'}{'result_class'} || $self->{'_result_class'} || 'DBIx::Class::Core'
$self->{"_attrs"}{"result_class"} $self->{"_result_class"}
Truth table66%2/3
A or B
A= $self->{"_attrs"}{"result_class"}B= $self->{"_result_class"}
ABresult
1X1
011
000
2273 }
2274  
2275 =head2 related_resultset
2276  
2277 my $orders_rs = $user_rs->related_resultset('orders');
2278  
2279 Returns a new ResultSet representing a relationship. It automatically handles
2280 the JOIN logic and prefixes existing conditions
2281 (e.g., turning C<{ id = 5 }> into C<{ 'user.id' = 5 }>).
2282  
2283 =cut
2284  
2285 sub related_resultset {
2286 11 ▶ my ($self, $rel_name) = @_;
Subroutine related_resultset: called CC=11 SCAR=25.5
Pod documented
2287  
2288 11 ▶ unless (defined $rel_name && length $rel_name) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $rel_name and length $rel_name) 1 10 11
Condition66%2/3
defined $rel_name and length $rel_name
!ll&&!rl&&r
1010
MC/DC50%1/2
defined $rel_name and length $rel_name
defined $rel_name length $rel_name
Truth table66%2/3
A and B
A= defined $rel_nameB= length $rel_name
ABresult
0X0
100
111
2289 1 croak "relationship_name is required for related_resultset";
2290 }
2291  
2292 # 1. Get current source and schema link
2293 10 my $source = $self->result_source;
2294 10 my $schema_inst = $self->{_schema_instance};
2295 10 my $native_schema = $schema_inst->{_native_schema};
2296  
2297 # 2. Resolve relationship info
2298 10 ▶ my $rel_info = $source->relationship_info($rel_name)
Branch: 1 branch
BranchTrueFalseTotal
my $rel_info = $source->relationship_info($rel_name) or die "No such relationship '${rel_name}' on " . $source->source_name 1 9 10
2299 or die "No such relationship '$rel_name' on " . $source->source_name;
2300  
2301 # 3. Determine the Target Moniker
2302 # DBIC often returns full class names (TestSchema::Result::Order)
2303 # but ->source() and ->resultset() want the moniker (Order)
2304 9 my $target_moniker = $rel_info->{source};
2305 9 $target_moniker =~ s/^.*::Result:://;
2306  
2307 # 4. Resolve the target source object (for metadata/pivoting)
2308 9 my $rel_source_obj = eval { $native_schema->source($target_moniker) }
2309 9 ▶ || eval { $native_schema->source($rel_info->{source}) };
Condition33%1/3
eval { do { $native_schema->source($target_moniker) } } || eval { do { $native_schema->source($rel_info->{'source'}) } }
l!l&&r!l&&!r
900
MC/DC0%0/2
eval { do { $native_schema->source($target_moniker) } } || eval { do { $native_schema->source($rel_info->{'source'}) } }
eval { do { $native_schema->source($target_moniker) } } eval { do { $native_schema->source($rel_info->{'source'}) } }
Truth table33%1/3
A || B
A= eval { do { $native_schema->source($target_moniker) } }B= eval { do { $native_schema->source($rel_info->{'source'}) } }
ABresult
1X1
011
000
2310  
2311 9 ▶ unless ($rel_source_obj) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($rel_source_obj) 0 9 9
2312 0 die "Could not resolve source for relationship '$rel_name' (target: $target_moniker)";
2313 }
2314  
2315 # 5. Find the reverse relationship (e.g., 'user') for the JOIN
2316 9 ▶ my $reverse_rel = $self->_find_reverse_relationship($source, $rel_source_obj, $rel_name)
Branch: 1 branch
BranchTrueFalseTotal
my $reverse_rel = $self->_find_reverse_relationship($source, $rel_source_obj, $rel_name) or die "Could not find reverse relationship for '${rel_name}' to " . $source->source_name 0 9 9
2317 or die "Could not find reverse relationship for '$rel_name' to " . $source->source_name;
2318  
2319 # 6. Prefix existing conditions (Pivot logic)
2320 # Turns { age => 30 } into { 'user.age' => 30 }
2321 9 my %new_cond;
2322 9 ▶ if ($self->{_cond} && ref $self->{_cond} eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_cond"} and ref $self->{"_cond"} eq "HASH") 9 0 9
Condition33%1/3
$self->{"_cond"} and ref $self->{"_cond"} eq "HASH"
!ll&&!rl&&r
009
MC/DC0%0/2
$self->{"_cond"} and ref $self->{"_cond"} eq "HASH"
$self->{"_cond"} ref $self->{"_cond"} eq "HASH"
Truth table33%1/3
A and B
A= $self->{"_cond"}B= ref $self->{"_cond"} eq "HASH"
ABresult
0X0
100
111
2323 9 ▶ while (my ($key, $val) = each %{$self->{_cond}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %{$$self{"_cond"};}) 8 9 17
2324 8 ▶ my $new_key = ($key =~ /\./) ? $key : "$reverse_rel.$key";
Branch: 1 branch
BranchTrueFalseTotal
$key =~ /\./u ? : 0 8 8
2325 8 $new_cond{$new_key} = $val;
2326 }
2327 }
2328  
2329 # 7. Build the new Async ResultSet using the MONIKER
2330 # We call resultset('Order'), NOT resultset('orders')
2331 9 return $schema_inst->resultset($target_moniker)->search(
2332 \%new_cond,
2333 { join => $reverse_rel }
2334 );
2335 }
2336  
2337 =head2 result_source
2338  
2339 my $source = $rs->result_source;
2340  
2341 Returns the L<DBIx::Class::ResultSource> object for the current ResultSet.
2342  
2343 This object contains the structural definition of the data source, including
2344 column names, data types, relationships, and the primary key configuration.
2345  
2346 =over 4
2347  
2348 =item * Metadata Access
2349  
2350 Use this to introspect the schema at runtime (e.g., checking if a column
2351 exists or retrieving relationship metadata).
2352  
2353 =item * Internal Proxy
2354  
2355 This is a wrapper around the internal C<_get_source> method, which ensures
2356 the metadata is lazily loaded from the schema definition if it isn't already
2357 present in the parent process.
2358  
2359 =item * Consistency
2360  
2361 While the ResultSet handles the *query logic*, the ResultSource handles the
2362 *data contract*.
2363  
2364 =back
2365  
2366 Example: Introspecting Column Types
2367  
2368 my $source = $rs->result_source;
2369 my $info = $source->column_info('created_at');
2370  
2371 print "Column Type: " . $info->{data_type} . "\n";
2372  
2373 =cut
2374  
2375 10563 ▶sub result_source { shift->_get_source; }
Subroutine result_source: called CC=1 SCAR=0.0
Pod documented
2376  
2377 sub _get_source {
2378 10563 ▶ my $self = shift;
Subroutine _get_source: called CC=2 SCAR=7.0
2379  
2380 10563 ▶ $self->{_source} ||= $self->{_schema_instance}->source($self->{_source_name});
Condition66%2/3
$self->{"_source"} ||= $self->{"_schema_instance"}->source($self->{"_source_name"})
l!l&&r!l&&!r
96139500
MC/DC0%0/2
$self->{"_source"} ||= $self->{"_schema_instance"}->source($self->{"_source_name"})
$self->{"_source"} $self->{"_schema_instance"}->source($self->{"_source_name"})
Truth table66%2/3
A ||= B
A= $self->{"_source"}B= $self->{"_schema_instance"}->source($self->{"_source_name"})
ABresult
1X1
011
000
2381  
2382 10563 return $self->{_source};
2383 }
2384  
2385 =head2 reset_stats
2386  
2387 $rs->reset_stats;
2388  
2389 Clears all performance and telemetry counters within the associated asynchronous
2390 bridge (C<_async_db>).
2391  
2392 This resets counters such as query execution counts, worker round-trip times,
2393 and cache hit/miss ratios to zero. It is typically used at the start of a
2394 profiling block to measure the impact of a specific set of operations.
2395  
2396 =over 4
2397  
2398 =item * Global Scope
2399  
2400 Note that because stats are stored on the C<async_db> object, calling this on
2401 one ResultSet will reset the statistics for all ResultSets sharing that same
2402 worker bridge.
2403  
2404 =item * Chainable
2405  
2406 Returns the ResultSet object to allow for fluent calling styles.
2407  
2408 =back
2409  
2410 =cut
2411  
2412 sub reset_stats {
2413 0 ▶ my $self = shift;
Subroutine reset_stats: not called CC=2 SCAR=17.9
Pod documented
2414 0 foreach my $key (keys %{ $self->{_async_db}->{_stats} }) {
2415 0 $self->{_async_db}->{_stats}->{$key} = 0;
2416 }
2417 0 return $self;
2418 }
2419  
2420 =head2 reset
2421  
2422 $rs->reset;
2423  
2424 Resets the internal cursor position (C<_pos>) of the ResultSet to the beginning.
2425  
2426 After calling C<reset>, the next call to C<next> or C<next_future> will return
2427 the first row in the result set again. This is useful for re-iterating over
2428 results already stored in the local buffer without re-fetching them from the
2429 database.
2430  
2431 =over 4
2432  
2433 =item * Local Operation
2434  
2435 This only affects the iteration state of the current ResultSet instance.
2436  
2437 =back
2438  
2439 Example: Measuring query impact
2440  
2441 $rs->reset_stats;
2442  
2443 $rs->search({ type => 'critical' })->all->then(sub {
2444 my $stats = $rs->{_async_db}->{_stats};
2445 print "Queries executed: " . $stats->{query_count} . "\n";
2446 });
2447  
2448 =cut
2449  
2450 sub reset {
2451 3 ▶ my $self = shift;
Subroutine reset: called CC=1 SCAR=0.0
Pod documented
2452 3 $self->{_pos} = 0;
2453 3 return $self;
2454 }
2455  
2456 =head2 source
2457  
2458 my $source = $rs->source;
2459  
2460 A convenient alias for L</result_source>.
2461  
2462 Returns the L<DBIx::Class::ResultSource> object for the current ResultSet. This
2463 object is the "source of truth" for the table's structure, including column
2464 definitions and relationship mappings.
2465  
2466 =cut
2467  
2468 sub source {
2469 0 ▶ my $self = shift;
Subroutine source: not called CC=1 SCAR=6.9
Pod documented
2470 0 return $self->_get_source;
2471 }
2472  
2473 =head2 source_name
2474  
2475 my $name = $rs->source_name;
2476  
2477 Returns the string identifier of the ResultSource (e.g., C<'User'> or C<'Order'>).
2478  
2479 This is a high-performance, synchronous accessor. In an asynchronous
2480 architecture, the C<source_name> is the primary key used to tell the background
2481 worker which table logic to load before executing a query.
2482  
2483 =over 4
2484  
2485 =item * Immutable
2486  
2487 This value is set when the ResultSet is first instantiated and persists through
2488 searches and clones.
2489  
2490 =item * Lightweight
2491  
2492 Unlike C<source>, this does not trigger any lazy-loading of metadata; it simply
2493 returns the stored string from the internal state.
2494  
2495 =back
2496  
2497 Example: Dynamic Dispatch based on Source
2498  
2499 my $rs = get_some_resultset();
2500  
2501 if ($rs->source_name eq 'User') {
2502 # Perform user-specific async logic
2503 $rs->search({ is_active => 1 })->all->...
2504 }
2505  
2506 =cut
2507  
2508 sub source_name {
2509 5 ▶ my $self = shift;
Subroutine source_name: called CC=1 SCAR=0.0
Pod documented
2510 5 return $self->{_source_name};
2511 }
2512  
2513 =head2 search
2514  
2515 my $new_rs = $rs->search(\%cond);
2516 my $new_rs = $rs->search(\%cond, \%attrs);
2517 my $new_rs = $rs->search(\'literal sql');
2518 my $new_rs = $rs->search(\['sql with ?', @bind]);
2519  
2520 Returns a new L<DBIx::Class::Async::ResultSet> with the given conditions
2521 and attributes merged onto the existing ones.
2522  
2523 Conditions are merged with C<-and> semantics. Empty or undef conditions
2524 on either side are treated as no-ops and not included in the merge.
2525  
2526 Attributes are deep-merged: scalar keys are overwritten by the new value,
2527 while accumulating keys (C<join>, C<prefetch>, C<columns>, C<select>,
2528 C<as>, C<order_by>, C<group_by>, C<having>) are concatenated and
2529 deduplicated.
2530  
2531 This is a synchronous, non-I/O operation that clones the current state.
2532  
2533 B<Empty SELECT Lists>
2534  
2535 As of version 0.62, empty column selection is supported via C<select =E<gt> []>.
2536 This generates database-appropriate SQL for checking row existence without
2537 fetching column data:
2538  
2539 my $rs = $schema->resultset('User')->search(
2540 { active => 1 },
2541 { select => [] },
2542 );
2543  
2544 my ($sql, @bind) = $rs->as_query;
2545 # PostgreSQL: SELECT FROM users WHERE active = ?
2546 # Others: SELECT 1 FROM users WHERE active = ?
2547  
2548 This is useful for existence checks with minimal overhead, though L</count>
2549 is typically more appropriate for simple counting operations:
2550  
2551 # Check if any matching rows exist (minimal data fetch)
2552 my $result = $rs->search({}, { select => [] })->all->get;
2553 my $has_rows = @$result > 0;
2554  
2555 # More efficient for simple counting
2556 my $count = $rs->count->get;
2557  
2558 B<Note:> The PostgreSQL C<SELECT FROM> syntax is a PostgreSQL-specific
2559 optimisation. Other databases use C<SELECT 1 FROM> which is portable
2560 and equally efficient.
2561  
2562 =cut
2563  
2564 sub search {
2565 616 ▶ my ($self, $cond, $attrs) = @_;
Subroutine search: called CC=7 SCAR=21.8
Pod documented
2566  
2567 616 my $existing = $self->{_cond};
2568 616 my $new_cond;
2569  
2570 616 ▶ if (!defined $cond) {
Branch: 5 branches
BranchTrueFalseTotal
if (not defined $cond) { } 199 417 616
elsif (ref $cond eq 'SCALAR') { } 0 417 417
elsif (ref $cond eq 'REF' and ref $$cond eq 'ARRAY') { } 5 412 417
elsif (ref $cond eq 'HASH') { } 412 0 412
elsif (ref $cond) { } 0 0 0
2571 # No new condition - preserve existing as-is
2572 199 $new_cond = $existing;
2573 }
2574 elsif (ref $cond eq 'SCALAR') {
2575 # Literal SQL: \'SELECT ...'
2576 0 $new_cond = _merge_cond($existing, $cond);
2577 }
2578 ▶ elsif (ref $cond eq 'REF' && ref $$cond eq 'ARRAY') {
Condition66%2/3
ref $cond eq "REF" and ref $$cond eq "ARRAY"
!ll&&!rl&&r
41205
MC/DC50%1/2
ref $cond eq "REF" and ref $$cond eq "ARRAY"
ref $cond eq "REF" ref $$cond eq "ARRAY"
Truth table66%2/3
A and B
A= ref $cond eq "REF"B= ref $$cond eq "ARRAY"
ABresult
0X0
100
111
2579 # Literal SQL with bind: \['sql ?', @bind]
2580 5 $new_cond = _merge_cond($existing, $cond);
2581 }
2582 elsif (ref $cond eq 'HASH') {
2583 412 $new_cond = _merge_cond($existing, $cond);
2584 }
2585 elsif (ref $cond) {
2586 # Blessed object or unrecognised ref type - warn and treat as no-op
2587 0 carp(
2588 "search() received unrecognised condition type: "
2589 . ref($cond)
2590 . " - ignoring"
2591 );
2592 0 $new_cond = $existing;
2593 }
2594 else {
2595 # Plain scalar - not valid as a DBIx::Class condition
2596 0 croak(
2597 "search() received a plain scalar as condition: '$cond' "
2598 . "- did you mean \\\"$cond\" for literal SQL?"
2599 );
2600 }
2601  
2602 616 my $merged_attrs = $self->_merge_attrs($self->{_attrs}, $attrs);
2603  
2604 # Rewrite any { -ident => $col, -as => $alias } items in the select list
2605 # to bare column strings before the attrs are stored on the new ResultSet.
2606 # This must happen after _merge_attrs (so the full merged select/as arrays
2607 # are available) and before new_result_set (so the stored _attrs are clean
2608 # and every downstream method -- all_future, count, count_total, etc. --
2609 # sees correct attrs without needing their own normalisation call).
2610 616 $merged_attrs = DBIx::Class::Async::SelectNormaliser->normalise_attrs($merged_attrs);
2611  
2612 616 return $self->new_result_set({
2613 cond => $new_cond,
2614 attrs => $merged_attrs,
2615 pos => 0,
2616 pager => undef,
2617 entries => undef,
2618 is_prefetched => 0,
2619 });
2620 }
2621  
2622 =head2 search_future
2623  
2624 An alias for L</all_future>. Returns a L<Future> that resolves to the
2625 full list of results matching the current ResultSet.
2626  
2627 =cut
2628  
2629 8 ▶sub search_future { shift->all_future(@_) }
Subroutine search_future: called CC=1 SCAR=0.0
Pod documented
2630  
2631 =head2 search_literal
2632  
2633 my $new_rs = $rs->search_literal('price > ?', 100);
2634  
2635 Adds a raw SQL fragment to the query criteria.
2636  
2637 =over 4
2638  
2639 =item * Safety
2640  
2641 Parameters are passed as a bind list, preventing SQL injection.
2642  
2643 =item * Chainability
2644  
2645 Returns a new ResultSet, allowing you to chain further C<search> or
2646 C<search_related> calls.
2647  
2648 =back
2649  
2650 =cut
2651  
2652 sub search_literal {
2653 5 ▶ my ($self, $sql_fragment, @bind) = @_;
Subroutine search_literal: called CC=1 SCAR=0.0
Pod documented
2654  
2655 # By passing it to $self->search, we guarantee:
2656 # 1. The new ResultSet gets the pinned _async_db and _schema_instance.
2657 # 2. Any existing 'where' or 'attrs' (like rows/order_by) are merged.
2658 5 return $self->search(
2659 \[ $sql_fragment, @bind ]
2660 );
2661 }
2662  
2663 =head2 search_rs
2664  
2665 my $new_rs = $rs->search_rs({ status => 'active' });
2666  
2667 A synchronous method that returns a new ResultSet object with the added
2668 search constraints. This is the standard way to chain query builders.
2669  
2670 =cut
2671  
2672 sub search_rs {
2673 1 ▶ my $self = shift;
Subroutine search_rs: called CC=1 SCAR=0.0
Pod documented
2674 1 return $self->search(@_);
2675 }
2676  
2677 =head2 search_related
2678  
2679 my $future = $user_rs->search_related('orders');
2680  
2681 Like C<search_related_rs>, but immediately triggers the database fetch.
2682 Returns a L<Future> resolving to an arrayref of related Row objects.
2683  
2684 =cut
2685  
2686 sub search_related {
2687 1 ▶ my ($self, $rel_name, $cond, $attrs) = @_;
Subroutine search_related: called CC=1 SCAR=0.0
Pod documented
2688  
2689 # Use the helper to get the new configuration
2690 1 my $new_rs = $self->search_related_rs($rel_name, $cond, $attrs);
2691  
2692 # In an async context, search_related usually implies
2693 # wanting the ResultSet object to call ->all_future on later.
2694 1 return $new_rs->all;
2695 }
2696  
2697 =head2 search_related_rs
2698  
2699 my $orders_rs = $user_rs->search_related_rs('orders', { status => 'shipped' });
2700  
2701 Pivots from the current ResultSet to a related data source. This is the core of
2702 L<DBIx::Class> relational power.
2703  
2704 =over 4
2705  
2706 =item * Shadow Translation
2707  
2708 Internally uses a temporary L<DBIx::Class::ResultSet> to calculate the complex
2709 join logic and foreign key mappings.
2710  
2711 =item * State Persistence
2712  
2713 The resulting ResultSet inherits the C<async_db> and C<schema_instance>, allowing
2714 it to execute the related query on the background worker.
2715  
2716 =item * Namespace Resolution
2717  
2718 Automatically resolves the target C<source_name> based on the relationship mapping.
2719  
2720 =back
2721  
2722 =cut
2723  
2724 sub search_related_rs {
2725 3 ▶ my ($self, $rel_name, $cond, $attrs) = @_;
Subroutine search_related_rs: called CC=5 SCAR=18.4
Pod documented
2726  
2727 # 1. Get the source. If _source is undef, pull it from the schema
2728 my $source = $self->{_result_source}
2729 3 ▶ || $self->{_schema_instance}->resultset($self->{_source_name})->result_source;
Condition33%1/3
$self->{'_result_source'} || $self->{'_schema_instance'}->resultset($self->{'_source_name'})->result_source
l!l&&r!l&&!r
030
MC/DC0%0/2
$self->{'_result_source'} || $self->{'_schema_instance'}->resultset($self->{'_source_name'})->result_source
$self->{'_result_source'} $self->{'_schema_instance'}->resultset($self->{'_source_name'})->result_source
Truth table33%1/3
A || B
A= $self->{'_result_source'}B= $self->{'_schema_instance'}->resultset($self->{'_source_name'})->result_source
ABresult
1X1
011
000
2730  
2731 # 2. Create the Shadow RS starting from the PARENT source
2732 3 require DBIx::Class::ResultSet;
2733 my $parent_shadow = DBIx::Class::ResultSet->new($source, {
2734 cond => $self->{_cond} || {},
2735 attrs => $self->{_attrs} || {},
2736 3 ▶ });
Condition50%2/4
$self->{'_cond'} || {}
l!l
30
$self->{'_attrs'} || {}
l!l
30
MC/DC0%0/1
$self->{'_cond'} || {}
$self->{'_cond'}
MC/DC0%0/1
$self->{'_attrs'} || {}
$self->{'_attrs'}
Truth table50%1/2
A
A= $self->{'_cond'}
Aresult
11
00
Truth table50%1/2
A
A= $self->{'_attrs'}
Aresult
11
00
2737  
2738 # 3. Pivot
2739 # my $related_shadow = $shadow_rs->search_related($rel_name, $cond, $attrs);
2740  
2741 # 3. Pivot using the standard DBIC logic
2742 # This forces DBIC to calculate the JOIN or the subquery for 'orders'
2743 3 my $related_shadow = $parent_shadow->search_related($rel_name, $cond, $attrs);
2744  
2745 # 4. Wrap with ALL required keys
2746 return DBIx::Class::Async::ResultSet->new(
2747 schema_instance => $self->{_schema_instance},
2748 async_db => $self->{_async_db},
2749 source_name => $related_shadow->result_source->source_name,
2750  
2751 cond => $related_shadow->{attrs}{where} || $related_shadow->{cond},
2752  
2753 # Only pass serialisable attrs
2754 attrs => {
2755 where => $related_shadow->{attrs}{where},
2756 join => $related_shadow->{attrs}{join},
2757 order_by => $related_shadow->{attrs}{order_by},
2758 rows => $related_shadow->{attrs}{rows},
2759 page => $related_shadow->{attrs}{page},
2760 },
2761 3 ▶ );
Condition33%1/3
$related_shadow->{'attrs'}{'where'} || $related_shadow->{'cond'}
l!l&&r!l&&!r
003
MC/DC0%0/2
$related_shadow->{'attrs'}{'where'} || $related_shadow->{'cond'}
$related_shadow->{'attrs'}{'where'} $related_shadow->{'cond'}
Truth table33%1/3
A || B
A= $related_shadow->{'attrs'}{'where'}B= $related_shadow->{'cond'}
ABresult
1X1
011
000
2762 }
2763  
2764 =head2 search_with_pager
2765  
2766 my ($rows_f, $pager_f) = $rs->search_with_pager({ status => 'active' }, { rows => 20 });
2767  
2768 Executes a paginated search and returns a L<Future> that resolves to both the
2769 retrieved rows and a populated L<Data::Page> (or Async Pager) object.
2770  
2771 This is the most efficient way to handle UI pagination because it dispatches
2772 the data fetch and the total count calculation simultaneously to the background
2773 workers.
2774  
2775 =over 4
2776  
2777 =item * Auto-Paging
2778  
2779 If no C<page> or C<rows> attributes are provided in C<$attrs>, the method defaults
2780 to C<page(1)> to ensure a pager can be instantiated.
2781  
2782 =item * Parallel Execution
2783  
2784 Unlike standard synchronous code which fetches rows and *then* counts them, this
2785 method uses C<Future->needs_all> to maximise throughput by running both queries
2786 at once.
2787  
2788 =item * Pager Syncing
2789  
2790 The returned pager object is fully "hydrated" with the total entry count, meaning
2791 methods like C<last_page>, C<entries_on_this_page>, and C<next_page> are immediately
2792 available for use in your templates or API responses.
2793  
2794 =back
2795  
2796 Example: Implementing a Paginated API Endpoint
2797  
2798 $rs->search_with_pager({ category => 'books' }, { page => 2, rows => 50 })
2799 ->then(sub {
2800 my ($rows, $pager) = @_;
2801  
2802 return Future->done({
2803 data => [ map { $_->TO_JSON } @$rows ],
2804 meta => {
2805 total_records => $pager->total_entries,
2806 current_page => $pager->current_page,
2807 total_pages => $pager->last_page,
2808 }
2809 });
2810 });
2811  
2812 =cut
2813  
2814 sub search_with_pager {
2815 3 ▶ my ($self, $cond, $attrs) = @_;
Subroutine search_with_pager: called CC=2 SCAR=6.9
Pod documented
2816  
2817 # 1. Create the paged resultset
2818 # This applies any search conditions and returns a new RS instance
2819 3 my $paged_rs = $self->search($cond, $attrs);
2820  
2821 # 2. Ensure paging is actually active
2822 # If the user didn't provide 'rows' or 'page' in $attrs, we force page 1
2823 3 ▶ if (!$paged_rs->is_paged) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($paged_rs->is_paged) 1 2 3
2824 1 $paged_rs = $paged_rs->page(1);
2825 }
2826  
2827 # 3. Instantiate the Async Pager (using your existing method)
2828 3 my $pager = $paged_rs->pager;
2829  
2830 # 4. Fire parallel requests to the worker pool
2831 # 'all' initiates the data fetch; 'total_entries' initiates the count(*)
2832 3 my $data_f = $paged_rs->all;
2833 3 my $total_f = $pager->total_entries;
2834  
2835 # 5. Return a combined Future
2836 # This resolves only when BOTH the data and the count are back from workers
2837 return Future->needs_all($data_f, $total_f)->then(sub {
2838 3 ▶ my ($rows, $total) = @_;
Subroutine __ANON__: called CC=1 SCAR=0.0
2839  
2840 # At this point, $pager->total_entries is already resolved internally
2841 # so the user can immediately call $pager->last_page, etc.
2842 3 return Future->done($rows, $pager);
2843 3 });
2844 }
2845  
2846 =head2 single
2847  
2848 my $future = $rs->single($cond?);
2849  
2850 An alias for L</first>. Retrieves the first row matching the ResultSet's
2851 criteria.
2852  
2853 =cut
2854  
2855 134 ▶sub single { shift->first }
Subroutine single: called CC=1 SCAR=0.0
Pod documented
2856  
2857 =head2 single_future
2858  
2859 my $user_f = $rs->single_future({ username => 'm_smith' });
2860  
2861 A convenience method that performs a search for a specific condition and
2862 immediately calls L</first>. It returns a L<Future> resolving to a single
2863 Row object or C<undef>.
2864  
2865 =over 4
2866  
2867 =item * Contextual Search
2868  
2869 If a C<$cond> (hashref) is provided, it creates a temporary narrowed ResultSet
2870 before fetching.
2871  
2872 =item * Efficiency
2873  
2874 Like C<first>, this automatically applies a C<LIMIT 1> if no data is already
2875 cached, ensuring the worker doesn't fetch unnecessary rows.
2876  
2877 =back
2878  
2879 =cut
2880  
2881 sub single_future {
2882 7 ▶ my ($self, $cond) = @_;
Subroutine single_future: called CC=2 SCAR=6.9
Pod documented
2883  
2884 # If a condition is provided, chain it.
2885 # Otherwise, just call first on the current resultset.
2886 7 ▶ return $cond ? $self->search($cond)->first : $self->first;
Branch: 1 branch
BranchTrueFalseTotal
$cond ? : 1 6 7
2887 }
2888  
2889 =head2 stats
2890  
2891 my $all_stats = $rs->stats;
2892 my $q_count = $rs->stats('queries');
2893  
2894 Returns performance metrics from the underlying asynchronous bridge.
2895  
2896 =over 4
2897  
2898 =item * Key Mapping
2899  
2900 Automatically handles both "clean" keys (C<queries>) and internal
2901 keys (C<_queries>).
2902  
2903 =item * Metrics included
2904  
2905 Usually contains C<queries> (execution count), C<cache_hits>, and C<errors>.
2906  
2907 =back
2908  
2909 =cut
2910  
2911 sub stats {
2912 16 ▶ my ($self, $key) = @_;
Subroutine stats: called CC=3 SCAR=11.4
Pod documented
2913  
2914 # Return the whole stats hash if no key is provided
2915 16 ▶ return $self->{_async_db}->{_stats} unless $key;
Branch: 1 branch
BranchTrueFalseTotal
unless $key 0 16 16
2916  
2917 # Otherwise return the specific metric (e.g., 'queries')
2918 # Note: We map the public 'queries' to the internal '_queries'
2919 16 ▶ my $internal_key = $key =~ /^_/ ? $key : "_$key";
Branch: 1 branch
BranchTrueFalseTotal
$key =~ /^_/u ? : 0 16 16
2920 16 return $self->{_async_db}->{_stats}->{$internal_key};
2921 }
2922  
2923 =head2 schema
2924  
2925 my $schema = $rs->schema;
2926  
2927 Returns the L<DBIx::Class::Async::Schema> instance that originally spawned
2928 this ResultSet. This is useful for pivoting to other ResultSets from within
2929 a row-processing callback.
2930  
2931 =cut
2932  
2933 0 ▶sub schema { shift->{_schema}; }
Subroutine schema: not called CC=1 SCAR=6.9
Pod documented
2934  
2935 =head2 slice
2936  
2937 # Scalar context: returns a new ResultSet
2938 my $sub_rs = $rs->slice(10, 19);
2939  
2940 # List context: triggers execution
2941 my $future = $rs->slice(0, 4);
2942  
2943 Returns a subset of the ResultSet based on specific start and end indices.
2944  
2945 =over 4
2946  
2947 =item * Zero-Indexed
2948  
2949 Unlike C<page>, C<slice> uses 0-based indexing. For example, C<slice(0, 9)>
2950 retrieves the first 10 rows.
2951  
2952 =item * Mathematical Translation
2953  
2954 Automatically converts the indices into C<offset> and C<rows> attributes
2955 for the SQL generator.
2956  
2957 =item * Context Sensitivity
2958  
2959 =over 4
2960  
2961 =item * In scalar context, it returns a new ResultSet object. This is
2962 ideal for further chaining or passing to a view.
2963  
2964 =item * In list context, it behaves like L</all> and initiates an
2965 asynchronous fetch, returning a B<Future>.
2966  
2967 =back
2968  
2969 =item * Validation
2970  
2971 Strictly enforces that indices are non-negative and that the first index
2972 does not exceed the last.
2973  
2974 =back
2975  
2976 Example: Retrieving a specific "chunk" for processing
2977  
2978 # Get rows 100 through 150 (inclusive)
2979 $rs->slice(100, 149)->all->then(sub {
2980 my $rows = shift;
2981 process_batch($rows);
2982 });
2983  
2984 =cut
2985  
2986 sub slice {
2987 16 ▶ my ($self, $first, $last) = @_;
Subroutine slice: called CC=7 SCAR=19.5
Pod documented
2988  
2989 # 1. Validation logic (remains the same)
2990 16 ▶ croak("slice requires two arguments (first and last index)")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $first and defined $last 1 15 16
Condition66%2/3
defined $first and defined $last
!ll&&!rl&&r
0115
MC/DC50%1/2
defined $first and defined $last
defined $first defined $last
Truth table66%2/3
A and B
A= defined $firstB= defined $last
ABresult
0X0
100
111
2991 unless defined $first && defined $last;
2992 15 ▶ croak("slice indices must be non-negative integers")
Branch: 1 branch
BranchTrueFalseTotal
if $first < 0 or $last < 0 1 14 15
Condition66%2/3
$first < 0 or $last < 0
l!l&&r!l&&!r
1014
MC/DC50%1/2
$first < 0 or $last < 0
$first < 0 $last < 0
Truth table66%2/3
A or B
A= $first < 0B= $last < 0
ABresult
1X1
011
000
2993 if $first < 0 || $last < 0;
2994 14 ▶ croak("first index must be less than or equal to last index")
Branch: 1 branch
BranchTrueFalseTotal
if $first > $last 1 13 14
2995 if $first > $last;
2996  
2997 # 2. Calculate pagination parameters
2998 13 my $offset = $first;
2999 13 my $rows = $last - $first + 1;
3000  
3001 # 3. Create the limited ResultSet
3002 # Since search() already handles cloning and attr merging, use it!
3003 13 my $sliced_rs = $self->search(undef, {
3004 offset => $offset,
3005 rows => $rows,
3006 });
3007  
3008 # 4. Context-aware return
3009 13 ▶ if (!wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
unless (wantarray) 6 7 13
3010 # Scalar context: Return the RS for further chaining
3011 6 return $sliced_rs;
3012 }
3013  
3014 # List context: This is tricky in Async.
3015 # In standard DBIC, slice() in list context executes immediately.
3016 # To keep your current test style, we'll return the results of 'all'.
3017 # Note: If your 'all' returns a Future, list context users must
3018 # be aware they are getting a single Future object, not the rows yet.
3019 7 return $sliced_rs->all;
3020 }
3021  
3022 =head2 set_cache
3023  
3024 $rs->set_cache(\@data);
3025  
3026 Manually populates the internal data buffer of the ResultSet.
3027  
3028 =over 4
3029  
3030 =item * Input Format
3031  
3032 Requires an arrayref of either raw hashrefs (column data) or already-inflated Row objects.
3033  
3034 =item * Inflation Trigger
3035  
3036 By setting the internal C<_is_prefetched> flag, this method ensures that the
3037 next time L</all> or L</next> is called, the library will process these entries
3038 through the standard inflation logic.
3039  
3040 =item * State Reset
3041  
3042 Automatically clears any previously cached rows (C<_rows>) and resets the
3043 internal cursor position (C<_pos>) to zero. This ensures that iteration
3044 starts fresh with the new dataset.
3045  
3046 =item * Chainable
3047  
3048 Returns the ResultSet object, allowing for fluent initialisation.
3049  
3050 =back
3051  
3052 Example: Hydrating a ResultSet from an external cache
3053  
3054 my $cached_data = $memcached->get("users_batch_1");
3055  
3056 if ($cached_data) {
3057 $rs->set_cache($cached_data);
3058 }
3059  
3060 # Now $rs acts like it just hit the DB
3061 $rs->all->then(sub {
3062 my $rows = shift;
3063 say $_->email for @$rows;
3064 });
3065  
3066 =cut
3067  
3068 sub set_cache {
3069 6 ▶ my ($self, $cache) = @_;
Subroutine set_cache: called CC=3 SCAR=11.3
Pod documented
3070  
3071 6 require Carp;
3072 6 ▶ Carp::croak("set_cache expects an arrayref of entries/objects")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $cache and ref $cache eq "ARRAY" 0 6 6
Condition33%1/3
defined $cache and ref $cache eq "ARRAY"
!ll&&!rl&&r
006
MC/DC0%0/2
defined $cache and ref $cache eq "ARRAY"
defined $cache ref $cache eq "ARRAY"
Truth table33%1/3
A and B
A= defined $cacheB= ref $cache eq "ARRAY"
ABresult
0X0
100
111
3073 unless defined $cache && ref $cache eq 'ARRAY';
3074  
3075 # 1. Store as raw entries
3076 # This feeds line 129 in your 'all' method
3077 6 $self->{_entries} = $cache;
3078  
3079 # 2. Mark as prefetched
3080 # This triggers the inflation logic in line 129
3081 6 $self->{_is_prefetched} = 1;
3082  
3083 # 3. Clear any existing inflated rows and reset position
3084 # This ensures that if the cache is updated, the inflation happens again
3085 6 $self->{_rows} = undef;
3086 6 $self->{_pos} = 0;
3087  
3088 6 return $self;
3089 }
3090  
3091 =head2 update
3092  
3093 # Bulk update all rows in the current ResultSet
3094 $rs->search({ status => 'pending' })->update({ status => 'processing' });
3095  
3096 # Single targeted update ignoring current RS filters
3097 $rs->update({ id => 42 }, { status => 'archived' });
3098  
3099 Performs an asynchronous C<UPDATE> operation on the database.
3100  
3101 =over 4
3102  
3103 =item * Set-Based Operation
3104  
3105 Unlike a row-level update, this method acts on the entire scope of the
3106 ResultSet in a single database round-trip.
3107  
3108 =item * Cache Invalidation
3109  
3110 Automatically calls C<clear_cache> on the ResultSet. This prevents the
3111 parent process from serving stale data after the update has completed.
3112  
3113 =item * Deflation Support
3114  
3115 Automatically detects columns that require custom serialisation (e.g.,
3116 JSON to string, DateTime to ISO string) by consulting the C<_custom_inflators> registry.
3117  
3118 =item * Flexible Signature
3119  
3120 =over 4
3121  
3122 =item * C<update(\%updates)>: Uses the ResultSet's existing C<where> clause.
3123  
3124 =item * C<update(\%cond, \%updates)>: Overrides the current filters with the provided C<%cond>.
3125  
3126 =back
3127  
3128 =back
3129  
3130 Example: Atomic Batch Update with Deflation
3131  
3132 # Assuming 'metadata' is a column that deflates to JSON
3133 my $future = $rs->search({ active => 1 })
3134 ->update({
3135 last_updated => \'NOW()',
3136 metadata => { version => '2.0', source => 'api' }
3137 });
3138  
3139 $future->on_done(sub { say "Batch update complete." });
3140  
3141 =cut
3142  
3143 sub update {
3144 13 ▶ my $self = shift;
Subroutine update: called CC=6 SCAR=18.0
Pod documented
3145 13 my ($cond, $updates);
3146  
3147 # Logic to handle both:
3148 # ->update({ col => val })
3149 # ->update({ id => 1 }, { col => val })
3150 13 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) { } 3 10 13
3151 3 ($cond, $updates) = @_;
3152 } else {
3153 10 $updates = shift;
3154 10 $cond = $self->{_cond};
3155 }
3156  
3157 # Cache Invalidation
3158 #
3159 # The update() function follows a set-based logic. Since the conditional
3160 # operator can match none, one, or several rows, any per-row caching
3161 # using the primary key as a cache key is insufficient for correctness
3162 # as it may not cover other caches that include rows affected by this
3163 # update operation in their result set. To avoid stale reads, perform
3164 # invalidation at the source level, as it is done in other sibling write
3165 # operations such as create() and delete(), which always invoke the
3166 # clear_cache() function.The update() function follows a set-based
3167 # logic. Since the conditional operator can match none, one, or several
3168 # rows, any per-row caching using the primary key as a cache key is
3169 # insufficient for correctness as it may not cover other caches that
3170 # include rows affected by this update operation in their result set.
3171 # To avoid stale reads, perform invalidation at the source level, as it
3172 # is done in other sibling write operations such as create() and
3173 # delete(), which always invoke the clear_cache() function.
3174 13 $self->clear_cache;
3175  
3176 13 my $db = $self->{_async_db};
3177 13 ▶ my $inflators = $db->{_custom_inflators}{ $self->{_source_name} } || {};
Condition50%1/2
$db->{'_custom_inflators'}{$self->{'_source_name'}} || {}
l!l
130
MC/DC0%0/1
$db->{'_custom_inflators'}{$self->{'_source_name'}} || {}
$db->{'_custom_inflators'}{$self->{'_source_name'}}
Truth table50%1/2
A
A= $db->{'_custom_inflators'}{$self->{'_source_name'}}
Aresult
11
00
3178  
3179 # Ensure nested Hashes are turned back into Strings for the database
3180 13 foreach my $col (keys %$updates) {
3181 14 ▶ if ($inflators->{$col} && $inflators->{$col}{deflate}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($inflators->{$col} and $inflators->{$col}{"deflate"}) 1 13 14
Condition66%2/3
$inflators->{$col} and $inflators->{$col}{"deflate"}
!ll&&!rl&&r
1301
MC/DC50%1/2
$inflators->{$col} and $inflators->{$col}{"deflate"}
$inflators->{$col} $inflators->{$col}{"deflate"}
Truth table66%2/3
A and B
A= $inflators->{$col}B= $inflators->{$col}{"deflate"}
ABresult
0X0
100
111
3182 1 $updates->{$col} = $inflators->{$col}{deflate}->($updates->{$col});
3183 }
3184 }
3185  
3186 return DBIx::Class::Async::_call_worker(
3187 $db,
3188 'update',
3189 {
3190 source_name => $self->{_source_name},
3191 13 cond => $cond,
3192 updates => $updates,
3193 }
3194 );
3195 }
3196  
3197 =head2 update_all
3198  
3199 my $future = $rs->search({ type => 'temporary' })->update_all({ type => 'permanent' });
3200  
3201 Performs a two-step asynchronous update. First, it retrieves all rows matching
3202 the current criteria to identify their Primary Keys, then it issues a
3203 bulk update targeting those specific IDs.
3204  
3205 =over 4
3206  
3207 =item * Precision
3208  
3209 By fetching the IDs first, this method ensures that triggers or logic dependent
3210 on the primary key are correctly handled.
3211  
3212 =item * Safety
3213  
3214 If no rows match the initial search, the method short-circuits and returns a
3215 resolved Future with a value of C<0>, avoiding an unnecessary database trip
3216 for the update phase.
3217  
3218 =item * Traceability
3219  
3220 Supports C<ASYNC_TRACE> logging to help debug empty sets or unexpected data
3221 types during the fetch phase.
3222  
3223 =item * Atomicity Note
3224  
3225 Unlike C<update>, this involves two distinct database interactions. If the
3226 data changes between the fetch and the update phase, only the rows identified
3227 in the first phase will be updated.
3228  
3229 =back
3230  
3231 Example: Safe Batch Update
3232  
3233 $rs->update_all({ last_processed => \'NOW()' })->on_done(sub {
3234 my $count = shift;
3235 print "Successfully updated $count specific records.\n";
3236 });
3237  
3238 =cut
3239  
3240 sub update_all {
3241 0 ▶ my ($self, $updates) = @_;
Subroutine update_all: not called CC=1 SCAR=6.9
Pod documented
3242 0 my $bridge = $self->{_async_db};
3243  
3244 return $self->all->then(sub {
3245 0 ▶ my $rows = shift;
Subroutine __ANON__: not called CC=4 SCAR=30.0
3246  
3247 # Hard check: is it really an arrayref?
3248 0 ▶ unless ($rows && ref($rows) eq 'ARRAY' && @$rows) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($rows and ref $rows eq "ARRAY" and @$rows) 0 0 0
Condition0%0/6
$rows and ref $rows eq "ARRAY" and @$rows
!ll&&!rl&&r
000
$rows and ref $rows eq "ARRAY"
!ll&&!rl&&r
000
MC/DC0%0/3
$rows and ref $rows eq "ARRAY" and @$rows
$rows ref $rows eq "ARRAY" @$rows
Truth table0%0/4
A and B and C
A= $rowsB= ref $rows eq "ARRAY"C= @$rows
ABCresult
0XX0
10X0
1100
1111
3249 0 warn "[PID $$] update_all found no rows to update or invalid data type"
3250 if ASYNC_TRACE;
3251 0 return Future->done(0);
3252 }
3253  
3254 0 my ($pk) = $self->result_source->primary_columns;
3255 0 my @ids = map { $_->get_column($pk) } @$rows;
3256  
3257 my $payload = {
3258 source_name => $self->{_source_name},
3259 0 cond => { $pk => { -in => \@ids } },
3260 updates => $updates,
3261 };
3262  
3263 return DBIx::Class::Async::_call_worker(
3264 $bridge,
3265 'update',
3266 $payload)->then(sub {
3267 0 ▶ my $affected = shift;
Subroutine __ANON__: not called CC=1 SCAR=6.9
3268 0 return Future->done($affected);
3269 0 });
3270 0 });
3271 }
3272  
3273 =head2 update_or_new
3274  
3275 my $future = $rs->update_or_new({
3276 email => 'dev@example.com',
3277 name => 'Gemini'
3278 });
3279  
3280 Attempts to locate a record using its unique constraints or primary key.
3281  
3282 =over 4
3283  
3284 =item * Action on Success
3285  
3286 If the record is found, it immediately triggers an asynchronous C<update>
3287 with the provided data and returns a L<Future> resolving to the updated Row object.
3288  
3289 =item * Action on Failure
3290  
3291 If no record is found, it creates a new B<in-memory> row object. This object
3292 is B<not> yet saved to the database (C<in_storage> will be false).
3293  
3294 =item * Data Sanitisation
3295  
3296 Automatically strips table aliases (C<me.>, C<foreign.>) from the data keys
3297 to ensure the Row object constructor receives clean column names.
3298  
3299 =item * Consistency
3300  
3301 This method always returns a B<Future>, regardless of whether it performed a
3302 database update or a local object instantiation.
3303  
3304 =back
3305  
3306 Example: Syncing User Profiles
3307  
3308 $rs->update_or_new({
3309 external_id => $id,
3310 last_login => \'NOW()'
3311 })->then(sub {
3312 my $user = shift;
3313 if ($user->in_storage) {
3314 say "Updated existing user: " . $user->id;
3315 } else {
3316 say "Prepared new user for registration.";
3317 # You must call ->insert on the new object to persist it
3318 return $user->insert;
3319 }
3320 });
3321  
3322 =cut
3323  
3324 sub update_or_new {
3325 2 ▶ my ($self, $data, $attrs) = @_;
Subroutine update_or_new: called CC=2 SCAR=6.9
Pod documented
3326 2 ▶ $attrs //= {};
Condition50%1/2
$attrs //= {}
l!l
02
MC/DC0%0/1
$attrs //= {}
$attrs
Truth table50%1/2
A
A= $attrs
Aresult
11
00
3327  
3328 # Identify the primary key or unique constraint values for the lookup
3329 2 my $lookup = $self->_extract_unique_lookup($data, $attrs);
3330  
3331 return $self->find($lookup, $attrs)->then(sub {
3332 2 ▶ my ($row) = @_;
Subroutine __ANON__: called CC=4 SCAR=13.9
3333  
3334 2 ▶ if ($row) {
Branch: 1 branch
BranchTrueFalseTotal
if ($row) 1 1 2
3335 # Object found in DB: trigger an async UPDATE
3336 1 return $row->update($data);
3337 }
3338  
3339 # Object NOT found: merge condition and data for a local 'new' object
3340 1 ▶ my %new_data = ( %{$self->{_cond} || {}}, %$data );
Branch: 1 branch
BranchTrueFalseTotal
$self->{"_cond"} or {} 0 1 1
3341 1 my %clean_data;
3342 1 ▶ while (my ($k, $v) = each %new_data) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %new_data) 2 1 3
3343 # Strip DBIC aliases so they don't crash the Row constructor
3344 2 (my $clean_key = $k) =~ s/^(?:me|foreign|self)\.//;
3345 2 $clean_data{$clean_key} = $v;
3346 }
3347  
3348 # Returns a Future wrapping the local Row object (in_storage = 0)
3349 1 return Future->done($self->new_result(\%clean_data));
3350 2 });
3351 }
3352  
3353 =head2 update_or_create
3354  
3355 my $future = $rs->update_or_create({
3356 username => 'coder123',
3357 last_seen => \'NOW()'
3358 });
3359  
3360 Attempts to find a record by its unique constraints. If found, it updates it.
3361 If not, it creates a new record in the database.
3362  
3363 =over 4
3364  
3365 =item * Atomic Strategy
3366  
3367 This method manages the "Check-then-Act" pattern safely across asynchronous workers.
3368  
3369 =item * Race Condition Recovery
3370  
3371 In highly concurrent systems, a record might be inserted by another process
3372 between this method's C<find> and C<create> steps. This method detects that
3373 specific database conflict (Unique Constraint Violation) and automatically
3374 recovers by re-finding the newly created record and updating it instead.
3375  
3376 =item * Error Handling
3377  
3378 While it handles "Already Exists" conflicts gracefully, other database errors
3379 (like type mismatches or connection issues) will still trigger a C<fail>
3380 state in the returned Future.
3381  
3382 =back
3383  
3384 Example: Distributed Token Sync
3385  
3386 # Multiple workers might run this for the same 'service_key'
3387 $schema->resultset('AuthToken')->update_or_create({
3388 service_key => 'worker_node_1',
3389 token => $new_secure_token
3390 })->on_done(sub {
3391 my $row = shift;
3392 say "Token synced for ID: " . $row->id;
3393 })->on_fail(sub {
3394 die "Sync failed: " . shift;
3395 });
3396  
3397 =cut
3398  
3399 sub update_or_create {
3400 5 ▶ my ($self, $data, $attrs) = @_;
Subroutine update_or_create: called CC=2 SCAR=9.4
Pod documented
3401 5 ▶ $attrs //= {};
Condition100%2/2
$attrs //= {}
l!l
23
MC/DC100%1/1
$attrs //= {}
$attrs
Truth table100%2/2
A
A= $attrs
Aresult
11
00
3402  
3403 5 my $lookup = $self->_extract_unique_lookup($data, $attrs);
3404  
3405 return $self->find($lookup, $attrs)->then(sub {
3406 5 ▶ my ($row) = @_;
Subroutine __ANON__: called CC=2 SCAR=11.9
3407  
3408 5 ▶ if ($row) {
Branch: 1 branch
BranchTrueFalseTotal
if ($row) 3 2 5
3409 # 1. Standard Update Path
3410 3 return $row->update($data);
3411 }
3412  
3413 # 2. Not Found: Attempt Create
3414 return $self->create($data)->catch(sub {
3415 0 ▶ my ($error, $type) = @_;
Subroutine __ANON__: not called CC=3 SCAR=24.8
3416  
3417 # If it's a DB unique constraint error, someone else beat us to the insert
3418 0 ▶ if ($type eq 'db_error' && "$error" =~ /unique constraint|already exists/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "db_error" and "$error" =~ /unique constraint|already exists/iu) 0 0 0
Condition0%0/3
$type eq "db_error" and "$error" =~ /unique constraint|already exists/iu
!ll&&!rl&&r
000
MC/DC0%0/2
$type eq "db_error" and "$error" =~ /unique constraint|already exists/iu
$type eq "db_error" "$error" =~ /unique constraint|already exists/iu
Truth table0%0/3
A and B
A= $type eq "db_error"B= "$error" =~ /unique constraint|already exists/iu
ABresult
0X0
100
111
3419  
3420 # 3. Race Recovery: Re-find the winner and update them
3421 return $self->find($lookup, $attrs)->then(sub {
3422 0 ▶ my ($recovered) = @_;
Subroutine __ANON__: not called CC=2 SCAR=17.9
3423 0 ▶ return $recovered
Branch: 1 branch
BranchTrueFalseTotal
$recovered ? : 0 0 0
3424 ? $recovered->update($data)
3425 : Future->fail("Race recovery failed: record vanished after conflict", "logic_error");
3426 0 });
3427 }
3428  
3429 # Otherwise, bubble up the original error
3430 0 return Future->fail($error, $type);
3431 2 });
3432 5 });
3433 }
3434  
3435 =head2 update_query
3436  
3437 my ($sql, @bind) = $rs->update_query(\%updates);
3438 my $query = $rs->update_query(\%updates);
3439  
3440 Returns the SQL and bind values that would be generated by an update operation
3441 without actually executing it. This is useful for debugging, logging, auditing,
3442 or testing.
3443  
3444 Returns the same structure as L</as_query>: a reference to an array containing
3445 the SQL (as a scalar reference) and bind values.
3446  
3447 my $rs = $schema->resultset('User')->search({ active => 0 });
3448 my ($sql, @bind) = $rs->update_query({ active => 1 });
3449 # $sql = \'UPDATE users SET active = ? WHERE active = ?'
3450 # @bind = (1, 0)
3451  
3452 # Audit logging
3453 warn "About to execute: $$sql with binds: @bind";
3454 $rs->update({ active => 1 })->get; # Now execute
3455  
3456 =cut
3457  
3458 sub update_query {
3459 2 ▶ my ($self, $values) = @_;
Subroutine update_query: called CC=7 SCAR=20.7
Pod documented
3460  
3461 2 my $bridge = $self->{_async_db};
3462 2 my $schema_class = $bridge->{_schema_class};
3463  
3464 2 ▶ unless ($schema_class->can('resultset')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($schema_class->can("resultset")) 0 2 2
3465 0 ▶ eval "require $schema_class" or die "update_query: $@";
Branch: 1 branch
BranchTrueFalseTotal
eval "require $schema_class" or die "update_query: $@" 0 0 0
3466 }
3467  
3468 # Silence warnings
3469 local $SIG{__WARN__} = sub {
3470 0 ▶ if (ASYNC_TRACE) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
3471 warn @_ unless $_[0] =~ /undetermined_driver|sql_limit_dialect|GenericSubQ/
3472 }
3473 2 };
3474  
3475 2 ▶ unless ($bridge->{_metadata_schema}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($bridge->{"_metadata_schema"}) 0 2 2
3476 0 $bridge->{_metadata_schema} = $schema_class->connect('dbi:NullP:');
3477 }
3478  
3479 # Create a sync ResultSet with the same conditions
3480 my $real_rs = $bridge->{_metadata_schema}
3481 ->resultset($self->{_source_name})
3482 2 ->search($self->{_cond}, $self->{_attrs});
3483  
3484 # Generate SQL using DBIC's internal update SQL generator
3485 2 my $storage = $bridge->{_metadata_schema}->storage;
3486  
3487 # Get the update SQL - use DBIC's internal methods
3488 2 my ($sql, @bind);
3489  
3490 # DBIC stores the SQL generation in storage->update
3491 # We need to use the same path as actual execution but capture the SQL
3492 2 eval {
3493 # Get source and create update statement
3494 2 my $source = $real_rs->result_source;
3495 2 my $cond = $real_rs->{cond};
3496 2 my $attrs = $real_rs->{attrs};
3497  
3498 # Build WHERE clause from search conditions
3499 2 my ($where_sql, @where_bind) = $storage->sql_maker->where($cond);
3500  
3501 # Build SET clause from update values
3502 2 my (@set_parts, @set_bind);
3503 2 for my $col (sort keys %$values) {
3504 2 push @set_parts, "$col = ?";
3505 2 push @set_bind, $values->{$col};
3506 }
3507 2 my $set_sql = join(', ', @set_parts);
3508  
3509 # Construct full UPDATE statement
3510 2 my $table = $source->from;
3511 2 $sql = \"UPDATE $table SET $set_sql$where_sql";
3512 2 @bind = (@set_bind, @where_bind);
3513 };
3514  
3515 2 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 2 2
3516 0 croak("Failed to generate update SQL: $@");
3517 }
3518  
3519 2 ▶ return wantarray ? ($sql, @bind) : \[ $sql, @bind ];
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 2 0 2
3520 }
3521  
3522 #
3523 #
3524 # PRIVATE METHODS
3525  
3526 sub _new_prefetched_dataset {
3527 8 ▶ my ($self, $data, $rel_name) = @_;
Subroutine _new_prefetched_dataset: called CC=3 SCAR=11.0
3528  
3529 # 1. Identify the target source for the relationship
3530 8 ▶ my $rel_info = $self->result_source->relationship_info($rel_name)
Branch: 1 branch
BranchTrueFalseTotal
my $rel_info = $self->result_source->relationship_info($rel_name) or die "No relationship info found for: $rel_name" 0 8 8
3531 or die "No relationship info found for: $rel_name";
3532  
3533 8 my $rel_source_class = $rel_info->{source};
3534  
3535 # Extract moniker: "TestSchema::Result::Order" -> "Order"
3536 8 my $rel_moniker = $rel_source_class;
3537 8 $rel_moniker =~ s/^.*::Result:://;
3538  
3539 # 2. Build args - let the schema handle the source lookup
3540 my %new_args = (
3541 schema_instance => $self->{_schema_instance},
3542 async_db => $self->{_async_db},
3543 8 source_name => $rel_moniker,
3544 cond => {},
3545 attrs => {},
3546 );
3547  
3548 # 3. Create ResultSet via schema to ensure proper source binding
3549 8 my $new_rs = $self->{_schema_instance}->resultset($rel_moniker);
3550  
3551 # 4. Populate internal cache with inflated Row objects
3552 8 ▶ my @rows_data = (ref $data eq 'ARRAY') ? @$data : ($data);
Branch: 1 branch
BranchTrueFalseTotal
ref $data eq 'ARRAY' ? : 8 0 8
3553 8 my @inflated_rows = map { $new_rs->new_result($_) } grep { defined } @rows_data;
3554  
3555 8 $new_rs->{_entries} = \@inflated_rows;
3556 8 $new_rs->{_is_prefetched} = 1;
3557  
3558 8 return $new_rs;
3559 }
3560  
3561 sub _generate_cache_key {
3562 233 ▶ my ($self, $is_count_op) = @_;
Subroutine _generate_cache_key: called CC=12 SCAR=31.0
3563  
3564 # Don't cache if there's dynamic SQL
3565 233 ▶ if ($self->_has_dynamic_sql) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_has_dynamic_sql) 0 233 233
3566 0 return undef;
3567 }
3568  
3569 # Force Data::Dumper to be a "pure" string generator
3570 233 local $Data::Dumper::Terse = 1;
3571 233 local $Data::Dumper::Indent = 0;
3572 233 local $Data::Dumper::Sortkeys = 1;
3573  
3574 233 my %clean_attrs;
3575 233 ▶ my $orig_attrs = $self->{_attrs} // {};
Condition50%1/2
$self->{"_attrs"} // {}
l!l
2330
MC/DC0%0/1
$self->{"_attrs"} // {}
$self->{"_attrs"}
Truth table50%1/2
A
A= $self->{"_attrs"}
Aresult
11
00
3576  
3577 # Whitelist only keys that affect SQL
3578 233 foreach my $key (qw(rows offset alias page order_by group_by select as join prefetch)) {
3579 2330 ▶ $clean_attrs{$key} = $orig_attrs->{$key} if exists $orig_attrs->{$key};
Branch: 1 branch
BranchTrueFalseTotal
if exists $orig_attrs->{$key} 203 2127 2330
3580 }
3581  
3582 233 ▶ if ($is_count_op && ($clean_attrs{rows} || $clean_attrs{offset})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_count_op and $clean_attrs{"rows"} || $clean_attrs{"offset"}) 0 233 233
Condition16%1/6
$is_count_op and $clean_attrs{"rows"} || $clean_attrs{"offset"}
!ll&&!rl&&r
23300
$clean_attrs{"rows"} or $clean_attrs{"offset"}
l!l&&r!l&&!r
000
MC/DC0%0/3
$is_count_op and $clean_attrs{"rows"} || $clean_attrs{"offset"}
$is_count_op $clean_attrs{"rows"} $clean_attrs{"offset"}
Truth table25%1/4
A and B or C
A= $is_count_opB= $clean_attrs{"rows"}C= $clean_attrs{"offset"}
ABCresult
0XX0
1000
11X1
1011
3583 0 ▶ $clean_attrs{alias} //= 'subquery_for_count';
Condition0%0/2
$clean_attrs{"alias"} //= "subquery_for_count"
l!l
00
MC/DC0%0/1
$clean_attrs{"alias"} //= "subquery_for_count"
$clean_attrs{"alias"}
Truth table0%0/2
A
A= $clean_attrs{"alias"}
Aresult
11
00
3584 0 ▶ $clean_attrs{is_subquery} //= 1;
Condition0%0/2
$clean_attrs{"is_subquery"} //= 1
l!l
00
MC/DC0%0/1
$clean_attrs{"is_subquery"} //= 1
$clean_attrs{"is_subquery"}
Truth table0%0/2
A
A= $clean_attrs{"is_subquery"}
Aresult
11
00
3585 }
3586  
3587 # CPAN Security CWE-639: the key has to come from the whole predicate,
3588 # not only the primary key columns. A search like
3589 #
3590 # search({ id => $id, owner => $user })
3591 #
3592 # should return a key different from
3593 #
3594 # search({ id => $id })
3595 #
3596 # or any other call with
3597 #
3598 # search({ id => $id, owner => $other_user });
3599 #
3600 # if collapsed to
3601 #
3602 # { id => $id }
3603 #
3604 # then the cache will respond with the results of one owner's row
3605 # to the requests of other owners.
3606 233 ▶ my $cond = $self->{_cond} // {};
Condition50%1/2
$self->{"_cond"} // {}
l!l
2330
MC/DC0%0/1
$self->{"_cond"} // {}
$self->{"_cond"}
Truth table50%1/2
A
A= $self->{"_cond"}
Aresult
11
00
3607  
3608 # Format Dumper output cleanly
3609 233 my $dumped_cond = Data::Dumper->new([$cond])->Dump;
3610 233 my $dumped_attrs = Data::Dumper->new([\%clean_attrs])->Dump;
3611 233 $dumped_cond =~ s/\n/ /g;
3612 233 $dumped_attrs =~ s/\n/ /g;
3613  
3614 return join('|',
3615 233 ▶ $self->{_source_name} // '',
Condition50%1/2
$self->{"_source_name"} // ""
l!l
2330
MC/DC0%0/1
$self->{"_source_name"} // ""
$self->{"_source_name"}
Truth table50%1/2
A
A= $self->{"_source_name"}
Aresult
11
00
3616 $dumped_cond,
3617 $dumped_attrs,
3618 );
3619 }
3620  
3621 sub _has_dynamic_sql {
3622 810 ▶ my ($self) = @_;
Subroutine _has_dynamic_sql: called CC=31 SCAR=46.0
3623  
3624 810 ▶ my $attrs = $self->{_attrs} || {};
Condition50%1/2
$self->{'_attrs'} || {}
l!l
8100
MC/DC0%0/1
$self->{'_attrs'} || {}
$self->{'_attrs'}
Truth table50%1/2
A
A= $self->{'_attrs'}
Aresult
11
00
3625  
3626 # List of non-deterministic SQL functions that should not be cached
3627 810 my $dynamic_functions = qr/\b(?:
3628 NOW|CURTIME|CURDATE|CURRENT_TIME|CURRENT_DATE|CURRENT_TIMESTAMP|
3629 SYSDATE|LOCALTIME|LOCALTIMESTAMP|UTC_TIME|UTC_DATE|UTC_TIMESTAMP|
3630 UNIX_TIMESTAMP|
3631 DATETIME|
3632 TIMESTAMP|
3633 RAND|RANDOM|
3634 UUID|UUID_SHORT
3635 )\s*\(/ix;
3636  
3637 # Helper to check if a value contains dynamic SQL
3638 my $check_value = sub {
3639 1225 ▶ my ($val) = @_;
Subroutine __ANON__: called CC=9 SCAR=24.8
3640  
3641 # Check for ScalarRef (literal SQL)
3642 1225 ▶ if (ref($val) eq 'SCALAR') {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $val eq 'SCALAR') { } 6 1219 1225
elsif (ref $val eq 'REF' and ref $$val eq 'SCALAR') { } 0 1219 1219
elsif (not ref $val and defined $val) { } 1182 74 1256
3643 6 ▶ return 1 if $$val =~ $dynamic_functions;
Branch: 1 branch
BranchTrueFalseTotal
if $$val =~ /$dynamic_functions/u 0 6 6
3644 }
3645 # Check for RefRef (escaped literal)
3646 ▶ elsif (ref($val) eq 'REF' && ref($$val) eq 'SCALAR') {
Condition66%2/3
ref $val eq "REF" and ref $$val eq "SCALAR"
!ll&&!rl&&r
121630
MC/DC0%0/2
ref $val eq "REF" and ref $$val eq "SCALAR"
ref $val eq "REF" ref $$val eq "SCALAR"
Truth table66%2/3
A and B
A= ref $val eq "REF"B= ref $$val eq "SCALAR"
ABresult
0X0
100
111
3647 0 ▶ return 1 if $$$val =~ $dynamic_functions;
Branch: 1 branch
BranchTrueFalseTotal
if $$$val =~ /$dynamic_functions/u 0 0 0
3648 }
3649 # Check for plain strings that might contain SQL
3650 ▶ elsif (!ref($val) && defined $val) {
Condition66%2/3
not ref $val and defined $val
!ll&&!rl&&r
3701182
MC/DC50%1/2
not ref $val and defined $val
not ref $val defined $val
Truth table66%2/3
not(A) and B
A= not ref $valB= defined $val
ABresult
0X0
100
111
3651 1182 ▶ return 1 if $val =~ $dynamic_functions;
Branch: 1 branch
BranchTrueFalseTotal
if $val =~ /$dynamic_functions/u 0 1182 1182
3652 }
3653  
3654 1225 return 0;
3655 810 };
3656  
3657 # Check +select (additional columns)
3658 810 ▶ if ($attrs->{'+select'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($attrs->{"+select"}) 6 804 810
3659 my @selects = ref($attrs->{'+select'}) eq 'ARRAY'
3660 6 ? @{$attrs->{'+select'}}
3661 6 ▶ : ($attrs->{'+select'});
Branch: 1 branch
BranchTrueFalseTotal
ref $attrs->{'+select'} eq 'ARRAY' ? : 6 0 6
3662  
3663 6 for my $sel (@selects) {
3664 # Hash form: { '' => \'NOW()', -as => 'current_time' }
3665 6 ▶ if (ref($sel) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $sel eq 'HASH') { } 6 0 6
3666 6 for my $key (keys %$sel) {
3667 12 ▶ next if $key eq '-as'; # Skip alias
Branch: 1 branch
BranchTrueFalseTotal
if $key eq "-as" 6 6 12
3668 6 ▶ return 1 if $check_value->($sel->{$key});
Branch: 1 branch
BranchTrueFalseTotal
if &$check_value($sel->{$key}) 0 6 6
3669 }
3670 }
3671 # Direct form: \'NOW()'
3672 else {
3673 0 ▶ return 1 if $check_value->($sel);
Branch: 1 branch
BranchTrueFalseTotal
if &$check_value($sel) 0 0 0
3674 }
3675 }
3676 }
3677  
3678 # Check select (column list)
3679 810 ▶ if ($attrs->{select}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($attrs->{"select"}) 6 804 810
3680 my @selects = ref($attrs->{select}) eq 'ARRAY'
3681 6 ? @{$attrs->{select}}
3682 6 ▶ : ($attrs->{select});
Branch: 1 branch
BranchTrueFalseTotal
ref $attrs->{'select'} eq 'ARRAY' ? : 6 0 6
3683  
3684 6 for my $sel (@selects) {
3685 # Hash form: { count => 'id', -as => 'total' }
3686 3 ▶ if (ref($sel) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $sel eq 'HASH') { } 3 0 3
3687 3 for my $key (keys %$sel) {
3688 3 ▶ next if $key eq '-as'; # Skip alias
Branch: 1 branch
BranchTrueFalseTotal
if $key eq "-as" 0 3 3
3689 3 ▶ return 1 if $check_value->($sel->{$key});
Branch: 1 branch
BranchTrueFalseTotal
if &$check_value($sel->{$key}) 0 3 3
3690 }
3691 }
3692 # Direct form
3693 else {
3694 0 ▶ return 1 if $check_value->($sel);
Branch: 1 branch
BranchTrueFalseTotal
if &$check_value($sel) 0 0 0
3695 }
3696 }
3697 }
3698  
3699 # Check +columns (similar to +select)
3700 810 ▶ if ($attrs->{'+columns'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($attrs->{"+columns"}) 0 810 810
3701 my @cols = ref($attrs->{'+columns'}) eq 'ARRAY'
3702 0 ? @{$attrs->{'+columns'}}
3703 0 ▶ : ($attrs->{'+columns'});
Branch: 1 branch
BranchTrueFalseTotal
ref $attrs->{'+columns'} eq 'ARRAY' ? : 0 0 0
3704  
3705 0 for my $col (@cols) {
3706 0 ▶ if (ref($col) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $col eq 'HASH') { } 0 0 0
3707 0 for my $val (values %$col) {
3708 0 ▶ return 1 if $check_value->($val);
Branch: 1 branch
BranchTrueFalseTotal
if &$check_value($val) 0 0 0
3709 }
3710 }
3711 else {
3712 0 ▶ return 1 if $check_value->($col);
Branch: 1 branch
BranchTrueFalseTotal
if &$check_value($col) 0 0 0
3713 }
3714 }
3715 }
3716  
3717 # Check having clause (may contain aggregate functions with dynamic SQL)
3718 810 ▶ if ($attrs->{having}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($attrs->{"having"}) 0 810 810
3719 0 ▶ if (ref($attrs->{having}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $attrs->{"having"} eq "HASH") 0 0 0
3720 0 for my $val (values %{$attrs->{having}}) {
3721 0 ▶ return 1 if $check_value->($val);
Branch: 1 branch
BranchTrueFalseTotal
if &$check_value($val) 0 0 0
3722 }
3723 }
3724 }
3725  
3726 # Check where conditions for literal SQL
3727 810 ▶ if ($self->{_cond}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_cond"}) 810 0 810
3728 810 my $check_cond;
3729 $check_cond = sub {
3730 859 ▶ my ($cond) = @_;
Subroutine __ANON__: called CC=15 SCAR=31.2
3731  
3732 859 ▶ if (ref($cond) eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $cond eq 'HASH') { } 856 3 859
elsif (ref $cond eq 'ARRAY') { } 0 3 3
3733 856 for my $key (keys %$cond) {
3734 607 my $val = $cond->{$key};
3735  
3736 # Check the key itself (might be literal SQL)
3737 607 ▶ return 1 if $check_value->($key);
Branch: 1 branch
BranchTrueFalseTotal
if &$check_value($key) 0 607 607
3738  
3739 # Recursively check nested conditions
3740 607 ▶ if (ref($val) eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $val eq 'HASH') { } 15 592 607
elsif (ref $val eq 'ARRAY') { } 17 575 592
3741 15 ▶ return 1 if $check_cond->($val);
Branch: 1 branch
BranchTrueFalseTotal
if &$check_cond($val) 0 15 15
3742 }
3743 elsif (ref($val) eq 'ARRAY') {
3744 17 for my $item (@$val) {
3745 34 ▶ return 1 if $check_value->($item);
Branch: 1 branch
BranchTrueFalseTotal
if &$check_value($item) 0 34 34
3746 34 ▶ return 1 if ref($item) eq 'HASH' && $check_cond->($item);
Branch: 1 branch
BranchTrueFalseTotal
if ref $item eq "HASH" and &$check_cond($item) 0 34 34
Condition33%1/3
ref $item eq "HASH" and &$check_cond($item)
!ll&&!rl&&r
0340
MC/DC0%0/2
ref $item eq "HASH" and &$check_cond($item)
ref $item eq "HASH" &$check_cond($item)
Truth table33%1/3
A and B
A= ref $item eq "HASH"B= &$check_cond($item)
ABresult
0X0
100
111
3747 }
3748 }
3749 else {
3750 575 ▶ return 1 if $check_value->($val);
Branch: 1 branch
BranchTrueFalseTotal
if &$check_value($val) 0 575 575
3751 }
3752 }
3753 }
3754 elsif (ref($cond) eq 'ARRAY') {
3755 0 for my $item (@$cond) {
3756 0 ▶ return 1 if $check_cond->($item);
Branch: 1 branch
BranchTrueFalseTotal
if &$check_cond($item) 0 0 0
3757 }
3758 }
3759  
3760 859 return 0;
3761 810 };
3762  
3763 810 ▶ return 1 if $check_cond->($self->{_cond});
Branch: 1 branch
BranchTrueFalseTotal
if &$check_cond($self->{"_cond"}) 0 810 810
3764 }
3765  
3766 810 return 0;
3767 }
3768  
3769 sub _build_payload {
3770 395 ▶ my ($self, $cond, $attrs, $is_count_op) = @_;
Subroutine _build_payload: called CC=18 SCAR=43.2
3771  
3772 # 1. Condition Merging (Improved Literal Awareness)
3773 395 my $base_cond = $self->{_cond};
3774 395 my $new_cond = $cond;
3775 395 my $merged_cond;
3776  
3777 395 ▶ if (ref($base_cond) eq 'HASH' && ref($new_cond) eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $base_cond eq 'HASH' and ref $new_cond eq 'HASH') { } 2 393 395
elsif (ref $new_cond and ref $new_cond ne 'HASH') { } 0 393 393
Condition100%3/3
ref $base_cond eq "HASH" and ref $new_cond eq "HASH"
!ll&&!rl&&r
43892
MC/DC100%2/2
ref $base_cond eq "HASH" and ref $new_cond eq "HASH"
ref $base_cond eq "HASH" ref $new_cond eq "HASH"
Truth table100%3/3
A and B
A= ref $base_cond eq "HASH"B= ref $new_cond eq "HASH"
ABresult
0X0
100
111
3778 2 $merged_cond = { %$base_cond, %$new_cond };
3779 }
3780 ▶ elsif (ref($new_cond) && ref($new_cond) ne 'HASH') {
Condition33%1/3
ref $new_cond and ref $new_cond ne "HASH"
!ll&&!rl&&r
39300
MC/DC0%0/2
ref $new_cond and ref $new_cond ne "HASH"
ref $new_cond ref $new_cond ne "HASH"
Truth table33%1/3
A and B
A= ref $new_condB= ref $new_cond ne "HASH"
ABresult
0X0
100
111
3781 0 $merged_cond = $new_cond; # Literal SQL takes priority
3782 }
3783 else {
3784 393 ▶ $merged_cond = $new_cond // $base_cond // {};
Condition40%2/5
($new_cond // $base_cond) // {}
l!l
3930
$new_cond // $base_cond
l!l&&r!l&&!r
03930
MC/DC0%0/2
($new_cond // $base_cond) // {}
$new_cond $base_cond
Truth table33%1/3
A // B
A= $new_condB= $base_cond
ABresult
1X1
011
000
3785 }
3786  
3787 # 2. Attribute Merging (Harden against non-HASH attrs)
3788 my $merged_attrs = (ref($self->{_attrs}) eq 'HASH' && ref($attrs) eq 'HASH')
3789 0 ▶ ? { %{$self->{_attrs}}, %{$attrs // {}} }
Condition28%2/7
$attrs // {}
l!l
00
($attrs // $self->{"_attrs"}) // {}
l!l
3950
$attrs // $self->{"_attrs"}
l!l&&r!l&&!r
03950
MC/DC0%0/1
$attrs // {}
$attrs
MC/DC0%0/2
($attrs // $self->{"_attrs"}) // {}
$attrs $self->{"_attrs"}
Truth table0%0/2
A
A= $attrs
Aresult
11
00
Truth table33%1/3
A // B
A= $attrsB= $self->{"_attrs"}
ABresult
1X1
011
000
3790 395 ▶ : ($attrs // $self->{_attrs} // {});
Branch: 1 branch
BranchTrueFalseTotal
ref $self->{'_attrs'} eq 'HASH' && ref $attrs eq 'HASH' ? : 0 395 395
Condition33%1/3
ref $self->{"_attrs"} eq "HASH" and ref $attrs eq "HASH"
!ll&&!rl&&r
03950
MC/DC0%0/2
ref $self->{"_attrs"} eq "HASH" and ref $attrs eq "HASH"
ref $self->{"_attrs"} eq "HASH" ref $attrs eq "HASH"
Truth table33%1/3
A and B
A= ref $self->{"_attrs"} eq "HASH"B= ref $attrs eq "HASH"
ABresult
0X0
100
111
3791  
3792 # 3. Only apply the Subquery Alias if we are specifically doing a COUNT
3793 # and there is a limit/offset involved.
3794 395 ▶ if ( $is_count_op
Branch: 1 branch
BranchTrueFalseTotal
if ($is_count_op and $merged_attrs->{"rows"} || $merged_attrs->{"offset"} || $merged_attrs->{"limit"}) 0 395 395
Condition11%1/9
$is_count_op and $merged_attrs->{"rows"} || $merged_attrs->{"offset"} || $merged_attrs->{"limit"}
!ll&&!rl&&r
39500
$merged_attrs->{"rows"} or $merged_attrs->{"offset"} or $merged_attrs->{"limit"}
l!l&&r!l&&!r
000
$merged_attrs->{"rows"} or $merged_attrs->{"offset"}
l!l&&r!l&&!r
000
MC/DC0%0/4
$is_count_op and $merged_attrs->{"rows"} || $merged_attrs->{"offset"} || $merged_attrs->{"limit"}
$is_count_op $merged_attrs->{"rows"} $merged_attrs->{"offset"} $merged_attrs->{"limit"}
Truth table20%1/5
A and B or C or D
A= $is_count_opB= $merged_attrs->{"rows"}C= $merged_attrs->{"offset"}D= $merged_attrs->{"limit"}
ABCDresult
0XXX0
10000
11XX1
101X1
10011
3795 && ( $merged_attrs->{rows}
3796 || $merged_attrs->{offset}
3797 || $merged_attrs->{limit} ) ) {
3798 0 ▶ $merged_attrs->{alias} //= 'subquery_for_count';
Condition0%0/2
$merged_attrs->{"alias"} //= "subquery_for_count"
l!l
00
MC/DC0%0/1
$merged_attrs->{"alias"} //= "subquery_for_count"
$merged_attrs->{"alias"}
Truth table0%0/2
A
A= $merged_attrs->{"alias"}
Aresult
11
00
3799 0 ▶ $merged_attrs->{is_subquery} //= 1;
Condition0%0/2
$merged_attrs->{"is_subquery"} //= 1
l!l
00
MC/DC0%0/1
$merged_attrs->{"is_subquery"} //= 1
$merged_attrs->{"is_subquery"}
Truth table0%0/2
A
A= $merged_attrs->{"is_subquery"}
Aresult
11
00
3800 }
3801  
3802 return {
3803 source_name => $self->{_source_name},
3804 395 cond => $merged_cond,
3805 attrs => $merged_attrs,
3806 };
3807 }
3808  
3809 sub _find_reverse_relationship {
3810 9 ▶ my ($self, $source, $rel_source, $forward_rel) = @_;
Subroutine _find_reverse_relationship: called CC=16 SCAR=36.7
3811  
3812 9 ▶ unless (ref $rel_source && $rel_source->can('relationships')) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $rel_source and $rel_source->can("relationships")) 0 9 9
Condition33%1/3
ref $rel_source and $rel_source->can("relationships")
!ll&&!rl&&r
009
MC/DC0%0/2
ref $rel_source and $rel_source->can("relationships")
ref $rel_source $rel_source->can("relationships")
Truth table33%1/3
A and B
A= ref $rel_sourceB= $rel_source->can("relationships")
ABresult
0X0
100
111
3813 0 ▶ confess("Critical Error: _find_reverse_relationship expected a ResultSource object but got: " . ($rel_source // 'undef'));
Condition0%0/2
$rel_source // "undef"
l!l
00
MC/DC0%0/1
$rel_source // "undef"
$rel_source
Truth table0%0/2
A
A= $rel_source
Aresult
11
00
3814 }
3815  
3816 9 my @rel_names = $rel_source->relationships;
3817 9 my $forward_info = $source->relationship_info($forward_rel);
3818 9 my $forward_cond = $forward_info->{cond};
3819  
3820 # 1. Extract keys from forward condition (e.g., 'foreign.user_id' => 'self.id')
3821 9 my ($forward_foreign, $forward_self);
3822 9 ▶ if (ref $forward_cond eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $forward_cond eq "HASH") 9 0 9
3823 9 my ($f, $s) = %$forward_cond;
3824 # Handle cases where value is a hash (like { -ident => 'id' })
3825 9 ▶ $s = $s->{'-ident'} // $s if ref $s eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $s eq "HASH" 0 9 9
Condition0%0/3
$s->{"-ident"} // $s
l!l&&r!l&&!r
000
MC/DC0%0/2
$s->{"-ident"} // $s
$s->{"-ident"} $s
Truth table0%0/3
A // B
A= $s->{"-ident"}B= $s
ABresult
1X1
011
000
3826  
3827 9 $forward_foreign = $f =~ s/^foreign\.//r;
3828 9 $forward_self = $s =~ s/^self\.//r;
3829 }
3830  
3831 # 2. Look for a relationship that points back to our source with matching keys
3832 9 foreach my $rev_rel (@rel_names) {
3833 9 my $rev_info = $rel_source->relationship_info($rev_rel);
3834 9 my $rev_source_obj = $rel_source->related_source($rev_rel);
3835  
3836 # Check if this relationship points back to our original source
3837 9 ▶ next unless $rev_source_obj->source_name eq $source->source_name;
Branch: 1 branch
BranchTrueFalseTotal
unless $rev_source_obj->source_name eq $source->source_name 0 9 9
3838  
3839 # Validate the foreign keys match (in reverse)
3840 9 my $rev_cond = $rev_info->{cond};
3841 9 ▶ if (ref $rev_cond eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $rev_cond eq "HASH") 9 0 9
3842 9 my ($rev_foreign, $rev_self) = %$rev_cond;
3843 9 ▶ $rev_self = $rev_self->{'-ident'} // $rev_self if ref $rev_self eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $rev_self eq "HASH" 0 9 9
Condition0%0/3
$rev_self->{"-ident"} // $rev_self
l!l&&r!l&&!r
000
MC/DC0%0/2
$rev_self->{"-ident"} // $rev_self
$rev_self->{"-ident"} $rev_self
Truth table0%0/3
A // B
A= $rev_self->{"-ident"}B= $rev_self
ABresult
1X1
011
000
3844  
3845 9 my $rf_clean = $rev_foreign =~ s/^foreign\.//r;
3846 9 my $rs_clean = $rev_self =~ s/^self\.//r;
3847  
3848 # The logic check:
3849 # If Forward is: Order(user_id) -> User(id)
3850 # Reverse must be: User(id) -> Order(user_id)
3851 9 ▶ if ($rf_clean eq $forward_self && $rs_clean eq $forward_foreign) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rf_clean eq $forward_self and $rs_clean eq $forward_foreign) 9 0 9
Condition33%1/3
$rf_clean eq $forward_self and $rs_clean eq $forward_foreign
!ll&&!rl&&r
009
MC/DC0%0/2
$rf_clean eq $forward_self and $rs_clean eq $forward_foreign
$rf_clean eq $forward_self $rs_clean eq $forward_foreign
Truth table33%1/3
A and B
A= $rf_clean eq $forward_selfB= $rs_clean eq $forward_foreign
ABresult
0X0
100
111
3852 9 return $rev_rel;
3853 }
3854 }
3855 }
3856  
3857 # 3. Fallback: If we couldn't find it by key matching, try by source name only
3858 0 foreach my $rev_rel (@rel_names) {
3859 0 ▶ if ($rel_source->related_source($rev_rel)->source_name eq $source->source_name) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rel_source->related_source($rev_rel)->source_name eq $source->source_name) 0 0 0
3860 0 return $rev_rel;
3861 }
3862 }
3863  
3864 0 return undef;
3865 }
3866  
3867 sub _extract_unique_lookup {
3868 16 ▶ my ($self, $data, $attrs) = @_;
Subroutine _extract_unique_lookup: called CC=11 SCAR=24.0
3869  
3870 16 my $source = $self->result_source;
3871 16 ▶ my $key_name = $attrs->{key} || 'primary';
Condition100%2/2
$attrs->{'key'} || 'primary'
l!l
412
MC/DC100%1/1
$attrs->{'key'} || 'primary'
$attrs->{'key'}
Truth table100%2/2
A
A= $attrs->{'key'}
Aresult
11
00
3872 16 my @unique_cols = $source->unique_constraint_columns($key_name);
3873  
3874 # Alias-aware grep for primary check
3875 16 ▶ if (!grep { exists $data->{$_} || exists $data->{"me.$_"} } @unique_cols) {
Branch: 2 branches
BranchTrueFalseTotal
unless (grep {exists $data->{$_} or exists $$data{"me.$_"};} @unique_cols) 12 4 16
exists $data->{$_} or exists $$data{"me.$_"} 12 4 16
3876 12 foreach my $constraint ($source->unique_constraint_names) {
3877 21 my @cols = $source->unique_constraint_columns($constraint);
3878 # Alias-aware grep for discovery loop
3879 21 ▶ if (grep { exists $data->{$_} || exists $data->{"me.$_"} } @cols) {
Branch: 2 branches
BranchTrueFalseTotal
if (grep {exists $data->{$_} or exists $$data{"me.$_"};} @cols) 7 14 21
exists $data->{$_} or exists $$data{"me.$_"} 16 5 21
3880 7 @unique_cols = @cols;
3881 7 last;
3882 }
3883 }
3884 }
3885  
3886 # Build the lookup, checking for aliases
3887 16 my %lookup;
3888 16 foreach my $col (@unique_cols) {
3889 16 ▶ if (exists $data->{$col}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $data->{$col}) { } 9 7 16
elsif (exists $$data{"me.$col"}) { } 2 5 7
3890 9 $lookup{$col} = $data->{$col};
3891 }
3892 elsif (exists $data->{"me.$col"}) {
3893 2 $lookup{$col} = $data->{"me.$col"};
3894 }
3895 }
3896  
3897 # Absolute fallback
3898 16 ▶ return keys %lookup ? \%lookup : $data;
Branch: 1 branch
BranchTrueFalseTotal
keys %lookup ? : 11 5 16
3899 }
3900  
3901 sub _inflate_row {
3902 584 ▶ my ($self, $hash) = @_;
Subroutine _inflate_row: called CC=25 SCAR=54.1
3903 584 ▶ return undef unless $hash;
Branch: 1 branch
BranchTrueFalseTotal
unless $hash 0 584 584
3904  
3905 # Apply Column Inflation
3906 584 my $db = $self->{_async_db};
3907 584 my $source_name = $self->{_source_name};
3908 584 ▶ my $inflators = $db->{_custom_inflators}{$source_name} || {};
Condition100%2/2
$db->{'_custom_inflators'}{$source_name} || {}
l!l
51272
MC/DC100%1/1
$db->{'_custom_inflators'}{$source_name} || {}
$db->{'_custom_inflators'}{$source_name}
Truth table100%2/2
A
A= $db->{'_custom_inflators'}{$source_name}
Aresult
11
00
3909  
3910 584 foreach my $col (keys %$inflators) {
3911 512 ▶ if (exists $hash->{$col} && $inflators->{$col}{inflate}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $hash->{$col} and $inflators->{$col}{"inflate"}) 408 104 512
Condition66%2/3
exists $hash->{$col} and $inflators->{$col}{"inflate"}
!ll&&!rl&&r
1040408
MC/DC50%1/2
exists $hash->{$col} and $inflators->{$col}{"inflate"}
exists $hash->{$col} $inflators->{$col}{"inflate"}
Truth table66%2/3
A and B
A= exists $hash->{$col}B= $inflators->{$col}{"inflate"}
ABresult
0X0
100
111
3912 # This turns your JSON string back into a HASH ref!
3913 408 $hash->{$col} = $inflators->{$col}{inflate}->($hash->{$col});
3914 }
3915 }
3916  
3917 # ------------------------------------------------------------------
3918 # Inflate datetime columns for result classes that load
3919 # InflateColumn::DateTime. The worker inflates correctly but sends
3920 # raw strings back to the parent. We re-inflate here using the
3921 # storage formatter detected from the DSN, since the parent process
3922 # holds no active DB connection and ->storage returns nothing.
3923 # This also applies the PR#138 fix by setting the formatter on the
3924 # resulting DateTime object.
3925 # ------------------------------------------------------------------
3926 584 my $result_source = $self->result_source;
3927 584 my $result_class = $result_source->result_class;
3928  
3929 584 ▶ if ( $result_class->isa('DBIx::Class::InflateColumn::DateTime') ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($result_class->isa("DBIx::Class::InflateColumn::DateTime")) 0 584 584
3930 0 my $formatter = $db->{_datetime_formatter};
3931 0 my $parse_dt;
3932  
3933 0 ▶ if ($formatter) {
Branch: 1 branch
BranchTrueFalseTotal
if ($formatter) 0 0 0
3934 $parse_dt = $formatter->isa('DateTime::Format::Pg')
3935 0 ▶ ? sub { $formatter->parse_timestamptz($_[0]) }
Subroutine __ANON__: not called CC=1 SCAR=6.9
3936 0 ▶ : sub { $formatter->parse_datetime($_[0]) };
Subroutine __ANON__: not called CC=1 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$formatter->isa('DateTime::Format::Pg') ? : 0 0 0
3937 }
3938  
3939 0 ▶ if ($parse_dt) {
Branch: 1 branch
BranchTrueFalseTotal
if ($parse_dt) 0 0 0
3940 0 for my $col (keys %$hash) {
3941 0 ▶ next unless defined $hash->{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $hash->{$col} 0 0 0
3942 0 ▶ next if ref $hash->{$col};
Branch: 1 branch
BranchTrueFalseTotal
if ref $hash->{$col} 0 0 0
3943 0 ▶ next if $inflators->{$col};
Branch: 1 branch
BranchTrueFalseTotal
if $inflators->{$col} 0 0 0
3944  
3945 0 ▶ my $col_info = eval { $result_source->column_info($col) } // {};
Condition0%0/2
eval { do { $result_source->column_info($col) } } // {}
l!l
00
MC/DC0%0/1
eval { do { $result_source->column_info($col) } } // {}
eval { do { $result_source->column_info($col) } }
Truth table0%0/2
A
A= eval { do { $result_source->column_info($col) } }
Aresult
11
00
3946 0 ▶ my $data_type = lc( $col_info->{data_type} // '' );
Condition0%0/2
$col_info->{"data_type"} // ""
l!l
00
MC/DC0%0/1
$col_info->{"data_type"} // ""
$col_info->{"data_type"}
Truth table0%0/2
A
A= $col_info->{"data_type"}
Aresult
11
00
3947 0 ▶ next unless $DATETIME_COLUMN_TYPES{$data_type};
Branch: 1 branch
BranchTrueFalseTotal
unless $DATETIME_COLUMN_TYPES{$data_type} 0 0 0
3948 next if exists $col_info->{inflate_datetime}
3949 0 ▶ && !$col_info->{inflate_datetime};
Branch: 1 branch
BranchTrueFalseTotal
if exists $col_info->{"inflate_datetime"} and not $col_info->{"inflate_datetime"} 0 0 0
Condition0%0/3
exists $col_info->{"inflate_datetime"} and not $col_info->{"inflate_datetime"}
!ll&&!rl&&r
000
MC/DC0%0/2
exists $col_info->{"inflate_datetime"} and not $col_info->{"inflate_datetime"}
exists $col_info->{"inflate_datetime"} not $col_info->{"inflate_datetime"}
Truth table0%0/3
A and not(B)
A= exists $col_info->{"inflate_datetime"}B= not $col_info->{"inflate_datetime"}
ABresult
0X0
100
111
3950  
3951 0 my $dt = eval { $parse_dt->( $hash->{$col} ) };
3952 0 ▶ next if $@ || !defined $dt;
Branch: 1 branch
BranchTrueFalseTotal
if $@ or not defined $dt 0 0 0
Condition0%0/3
$@ or not defined $dt
l!l&&r!l&&!r
000
MC/DC0%0/2
$@ or not defined $dt
$@ not defined $dt
Truth table0%0/3
A or not(B)
A= $@B= not defined $dt
ABresult
1X1
011
000
3953  
3954 $dt->set_formatter($formatter)
3955 0 ▶ if eval { $dt->isa('DateTime') } && !$dt->formatter;
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { $dt->isa("DateTime") } } and not $dt->formatter 0 0 0
Condition0%0/3
eval { do { $dt->isa("DateTime") } } and not $dt->formatter
!ll&&!rl&&r
000
MC/DC0%0/2
eval { do { $dt->isa("DateTime") } } and not $dt->formatter
eval { do { $dt->isa("DateTime") } } not $dt->formatter
Truth table0%0/3
A and not(B)
A= eval { do { $dt->isa("DateTime") } }B= not $dt->formatter
ABresult
0X0
100
111
3956  
3957 0 $hash->{$col} = $dt;
3958 }
3959 }
3960 }
3961  
3962 # Create the base row object
3963 584 my $row = $self->new_result($hash);
3964 584 $row->in_storage(1);
3965  
3966 # Inject Relationship Data (already perfect)
3967 584 for my $rel ($self->result_source->relationships) {
3968 583 ▶ if (exists $hash->{$rel}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $hash->{$rel}) 13 570 583
3969 13 $row->{_relationship_data}{$rel} = $hash->{$rel};
3970 }
3971 }
3972  
3973 584 return $row;
3974 }
3975  
3976 # _merge_attrs
3977 #
3978 # my $merged = $self->_merge_attrs(\%base, \%extra);
3979 #
3980 # Internal method. Deep-merges two attribute hashes.
3981 #
3982 # Accumulating keys (C<join>, C<prefetch>, C<columns>, C<+columns>,
3983 # C<select>, C<as>, C<order_by>, C<group_by>, C<having>) are concatenated
3984 # and deduplicated by string value. All other keys are overwritten by the
3985 # extra value.
3986  
3987 sub _merge_attrs {
3988 616 ▶ my ($self, $base, $extra) = @_;
Subroutine _merge_attrs: called CC=8 SCAR=20.8
3989  
3990 616 ▶ $base //= {};
Condition50%1/2
$base //= {}
l!l
6160
MC/DC0%0/1
$base //= {}
$base
Truth table50%1/2
A
A= $base
Aresult
11
00
3991 616 ▶ $extra //= {};
Condition100%2/2
$extra //= {}
l!l
299317
MC/DC100%1/1
$extra //= {}
$extra
Truth table100%2/2
A
A= $extra
Aresult
11
00
3992  
3993 616 my %merged = %$base;
3994  
3995 616 for my $key (keys %$extra) {
3996 359 ▶ if ($ACCUMULATING_ATTRS{$key} && exists $merged{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ACCUMULATING_ATTRS{$key} and exists $merged{$key}) { } 9 350 359
Condition100%3/3
$ACCUMULATING_ATTRS{$key} and exists $merged{$key}
!ll&&!rl&&r
268829
MC/DC100%2/2
$ACCUMULATING_ATTRS{$key} and exists $merged{$key}
$ACCUMULATING_ATTRS{$key} exists $merged{$key}
Truth table100%3/3
A and B
A= $ACCUMULATING_ATTRS{$key}B= exists $merged{$key}
ABresult
0X0
100
111
3997 # Normalise both sides to flat arrayrefs
3998 my $base_val = ref $merged{$key} eq 'ARRAY'
3999 ? $merged{$key}
4000 9 ▶ : [ $merged{$key} ];
Branch: 1 branch
BranchTrueFalseTotal
ref $merged{$key} eq 'ARRAY' ? : 1 8 9
4001 my $extra_val = ref $extra->{$key} eq 'ARRAY'
4002 ? $extra->{$key}
4003 9 ▶ : [ $extra->{$key} ];
Branch: 1 branch
BranchTrueFalseTotal
ref $extra->{$key} eq 'ARRAY' ? : 1 8 9
4004  
4005 # Concatenate and deduplicate by string value.
4006 # We preserve order (first occurrence wins) to keep
4007 # join/prefetch ordering stable and avoid surprising
4008 # SQL changes on re-runs.
4009 9 my %seen;
4010 $merged{$key} = [
4011 9 grep { !$seen{ _dedup_key($_) }++ }
4012 @$base_val, @$extra_val
4013 ];
4014 }
4015 else {
4016 # Scalar or non-accumulating key: extra wins
4017 350 $merged{$key} = $extra->{$key};
4018 }
4019 }
4020  
4021 616 return \%merged;
4022 }
4023  
4024 # Produce a stable string key for deduplication.
4025 # Handles plain strings, hashrefs (e.g. { rel => 'sub_rel' }),
4026 # and arrayrefs (nested join specs).
4027  
4028 sub _dedup_key {
4029 18 ▶ my $val = shift;
Subroutine _dedup_key: called CC=3 SCAR=15.7
4030 18 ▶ return 'undef' unless defined $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 0 18 18
4031 18 ▶ return $val unless ref $val;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $val 18 0 18
4032 # Lean on Data::Dumper for a cheap stable serialisation of
4033 # nested join/prefetch specs like { orders => 'items' }.
4034 # Sorted keys ensures { a=>1, b=>1 } eq { b=>1, a=>1 }.
4035 0 require Data::Dumper;
4036 0 local $Data::Dumper::Sortkeys = 1;
4037 0 local $Data::Dumper::Indent = 0;
4038 0 local $Data::Dumper::Terse = 1;
4039 0 return Data::Dumper::Dumper($val);
4040 }
4041  
4042 sub _is_empty_cond {
4043 834 ▶ my $c = shift;
Subroutine _is_empty_cond: called CC=6 SCAR=18.7
4044 834 ▶ return 1 unless defined $c;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $c 0 834 834
4045 834 ▶ return 1 if ref $c eq 'HASH' && !keys %$c;
Branch: 1 branch
BranchTrueFalseTotal
if ref $c eq "HASH" and not keys %$c 480 354 834
Condition100%3/3
ref $c eq "HASH" and not keys %$c
!ll&&!rl&&r
6348480
MC/DC100%2/2
ref $c eq "HASH" and not keys %$c
ref $c eq "HASH" not keys %$c
Truth table100%3/3
A and not(B)
A= ref $c eq "HASH"B= not keys %$c
ABresult
0X0
100
111
4046 354 ▶ return 1 if ref $c eq 'ARRAY' && !@$c;
Branch: 1 branch
BranchTrueFalseTotal
if ref $c eq "ARRAY" and not @$c 0 354 354
Condition33%1/3
ref $c eq "ARRAY" and not @$c
!ll&&!rl&&r
35400
MC/DC0%0/2
ref $c eq "ARRAY" and not @$c
ref $c eq "ARRAY" not @$c
Truth table33%1/3
A and not(B)
A= ref $c eq "ARRAY"B= not @$c
ABresult
0X0
100
111
4047 354 return 0;
4048 }
4049  
4050 sub _merge_cond {
4051 417 ▶ my ($existing, $new) = @_;
Subroutine _merge_cond: called CC=7 SCAR=19.5
4052  
4053 417 my $existing_empty = _is_empty_cond($existing);
4054 417 my $new_empty = _is_empty_cond($new);
4055  
4056 417 ▶ return {} if $existing_empty && $new_empty;
Branch: 1 branch
BranchTrueFalseTotal
if $existing_empty and $new_empty 79 338 417
Condition100%3/3
$existing_empty and $new_empty
!ll&&!rl&&r
1832079
MC/DC100%2/2
$existing_empty and $new_empty
$existing_empty $new_empty
Truth table100%3/3
A and B
A= $existing_emptyB= $new_empty
ABresult
0X0
100
111
4057 338 ▶ return $new if $existing_empty && !$new_empty;
Branch: 1 branch
BranchTrueFalseTotal
if $existing_empty and not $new_empty 320 18 338
Condition66%2/3
$existing_empty and not $new_empty
!ll&&!rl&&r
180320
MC/DC50%1/2
$existing_empty and not $new_empty
$existing_empty not $new_empty
Truth table66%2/3
A and not(B)
A= $existing_emptyB= not $new_empty
ABresult
0X0
100
111
4058 18 ▶ return $existing if !$existing_empty && $new_empty;
Branch: 1 branch
BranchTrueFalseTotal
if not $existing_empty and $new_empty 2 16 18
Condition66%2/3
not $existing_empty and $new_empty
!ll&&!rl&&r
0162
MC/DC50%1/2
not $existing_empty and $new_empty
not $existing_empty $new_empty
Truth table66%2/3
not(A) and B
A= not $existing_emptyB= $new_empty
ABresult
0X0
100
111
4059 16 return { -and => [ $existing, $new ] };
4060 }
4061  
4062 sub _generate_empty_select_query {
4063 2 ▶ my $self = shift;
Subroutine _generate_empty_select_query: called CC=5 SCAR=16.7
4064  
4065 2 my $bridge = $self->{_async_db};
4066 2 my $storage = $bridge->{_metadata_schema}->storage;
4067 2 my $source = $bridge->{_metadata_schema}->source($self->{_source_name});
4068  
4069 # Build WHERE clause if conditions exist
4070 2 ▶ my $cond = $self->{_cond} || {};
Condition50%1/2
$self->{'_cond'} || {}
l!l
20
MC/DC0%0/1
$self->{'_cond'} || {}
$self->{'_cond'}
Truth table50%1/2
A
A= $self->{'_cond'}
Aresult
11
00
4071 2 my ($where_sql, @bind) = $storage->sql_maker->where($cond);
4072  
4073 # Get table name (handles joins, subqueries, etc.)
4074 2 my $table = $source->from;
4075  
4076 # Detect database type for optimal SQL generation
4077 2 ▶ my $driver = eval { $storage->sqlt_type } || '';
Condition50%1/2
eval { do { $storage->sqlt_type } } || ''
l!l
20
MC/DC0%0/1
eval { do { $storage->sqlt_type } } || ''
eval { do { $storage->sqlt_type } }
Truth table50%1/2
A
A= eval { do { $storage->sqlt_type } }
Aresult
11
00
4078  
4079 2 my $sql;
4080 2 ▶ if ($driver =~ /^(PostgreSQL|Pg)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($driver =~ /^(PostgreSQL|Pg)$/iu) { } 0 2 2
4081 # PostgreSQL natively supports column-less SELECT
4082 0 $sql = \"SELECT FROM $table$where_sql";
4083 }
4084 else {
4085 # For other databases, use SELECT 1 as minimal portable query
4086 # SQLite, MySQL, Oracle, etc. all support this
4087 2 $sql = \"SELECT 1 FROM $table$where_sql";
4088 }
4089  
4090 # Return in same format as real as_query
4091 2 ▶ return wantarray ? ($sql, @bind) : \[$sql, @bind];
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 2 0 2
4092 }
4093  
4094 =head1 AUTOMATIC CACHE SAFETY
4095  
4096 L<DBIx::Class::Async> automatically analyses your queries for non-deterministic
4097 SQL functions (e.g., B<NOW()>, B<CURTIME()>, B<RAND()>, B<UUID()>).
4098  
4099 If detected in the B<WHERE> clause, B<SELECT> list, or B<HAVING> clause, the
4100 caching mechanism will be B<automatically bypassed> for that specific query,
4101 even if B<cache_ttl> is enabled, to ensure data integrity.
4102  
4103 =head1 AUTHOR
4104  
4105 Mohammad Sajid Anwar, C<< <mohammad.anwar at yahoo.com> >>
4106  
4107 =head1 REPOSITORY
4108  
4109 L<https://github.com/manwar/DBIx-Class-Async>
4110  
4111 =head1 BUGS
4112  
4113 Please report any bugs or feature requests through the web interface at L<https://github.com/manwar/DBIx-Class-Async/issues>.
4114 I will be notified and then you'll automatically be notified of progress on your
4115 bug as I make changes.
4116  
4117 =head1 SUPPORT
4118  
4119 You can find documentation for this module with the perldoc command.
4120  
4121 perldoc DBIx::Class::Async::ResultSet
4122  
4123 You can also look for information at:
4124  
4125 =over 4
4126  
4127 =item * BUG Report
4128  
4129 L<https://github.com/manwar/DBIx-Class-Async/issues>
4130  
4131 =item * CPAN Ratings
4132  
4133 L<http://cpanratings.perl.org/d/DBIx-Class-Async>
4134  
4135 =item * Search MetaCPAN
4136  
4137 L<https://metacpan.org/dist/DBIx-Class-Async/>
4138  
4139 =back
4140  
4141 =head1 LICENSE AND COPYRIGHT
4142  
4143 Copyright (C) 2026 Mohammad Sajid Anwar.
4144  
4145 This program is free software; you can redistribute it and / or modify it under
4146 the terms of the the Artistic License (2.0). You may obtain a copy of the full
4147 license at:
4148 L<http://www.perlfoundation.org/artistic_license_2_0>
4149 Any use, modification, and distribution of the Standard or Modified Versions is
4150 governed by this Artistic License.By using, modifying or distributing the Package,
4151 you accept this license. Do not use, modify, or distribute the Package, if you do
4152 not accept this license.
4153 If your Modified Version has been derived from a Modified Version made by someone
4154 other than you,you are nevertheless required to ensure that your Modified Version
4155 complies with the requirements of this license.
4156 This license does not grant you the right to use any trademark, service mark,
4157 tradename, or logo of the Copyright Holder.
4158 This license includes the non-exclusive, worldwide, free-of-charge patent license
4159 to make, have made, use, offer to sell, sell, import and otherwise transfer the
4160 Package with respect to any patent claims licensable by the Copyright Holder that
4161 are necessarily infringed by the Package. If you institute patent litigation
4162 (including a cross-claim or counterclaim) against any party alleging that the
4163 Package constitutes direct or contributory patent infringement,then this Artistic
4164 License to you shall terminate on the date that such litigation is filed.
4165 Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND
4166 CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED
4167 WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
4168 NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS
4169 REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT,
4170 INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE
4171 OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
4172  
4173 =cut
4174  
4175 99 1; # End of DBIx::Class::Async::ResultSet
« Async/Row.pm ↑ Summary Async/Exception/Factory.pm »