Async/ResultSet.pm

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