blib/lib/DBIx/Class/Schema/GraphQL.pm

filter: Statementstmt 14.4% 43 / 298 Branchbran 6.3% 6 / 94 Conditioncond 6.2% 2 / 32 MC/DCmcdc 5.2% 1 / 19 Subroutinesub 33.3% 12 / 36 Podpod 100% 1 / 1 totaltotal 13.5% 65 / 480 CC 74 SCAR 41.8
CC
74
Cov
12%
_apply_pagination
240.0
_filter_to_dbic
156.0
__ANON__
56.0
CRAP 65.5
↑ Summary
1 package DBIx::Class::Schema::GraphQL;
2  
3 7 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 7 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 7 ▶use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 7 our $VERSION = qv('v0.0.1');
8 7 our $AUTHORITY = 'cpan:MANWAR';
9  
10 =head1 NAME
11  
12 DBIx::Class::Schema::GraphQL - Auto-generate a GraphQL schema from a DBIx::Class schema
13  
14 =head1 VERSION
15  
16 Version v0.0.1
17  
18 =cut
19  
20 7 ▶use MIME::Base64 qw(encode_base64 decode_base64);
Subroutine BEGIN: called CC=1 SCAR=0.0
21  
22 7 ▶use GraphQL::Schema;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 7 ▶use GraphQL::Type::Object;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 7 ▶use GraphQL::Type::InputObject;
Subroutine BEGIN: called CC=1 SCAR=0.0
25 7 ▶use GraphQL::Type::List;
Subroutine BEGIN: called CC=1 SCAR=0.0
26 7 ▶use GraphQL::Type::NonNull;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 7 ▶use GraphQL::Type::Enum;
Subroutine BEGIN: called CC=1 SCAR=0.0
28 7 ▶use GraphQL::Type::Scalar qw($Int $String $Float $Boolean);
Subroutine BEGIN: called CC=1 SCAR=0.0
29  
30 =head1 SYNOPSIS
31  
32 use DBIx::Class::Schema::GraphQL;
33 use GraphQL::Execution qw(execute);
34  
35 my $db = My::Schema->connect(...);
36 my $result = DBIx::Class::Schema::GraphQL->to_graphql($db);
37  
38 # Simple plural query - always include at least one scalar field
39 # alongside nodes (e.g. total) - see KNOWN BEHAVIOUR below.
40 execute($result->{schema},
41 '{ allBooks { total nodes { title } } }',
42 undef, $result->{context});
43  
44 # Filtered + paginated + ordered
45 execute($result->{schema}, '
46 query {
47 allBooks(
48 filter: { title_like: "%Perl%" }
49 orderBy: { field: "title", direction: ASC }
50 page: { skip: 0, take: 5 }
51 ) {
52 total
53 hasNextPage
54 nodes { id title }
55 }
56 }', undef, $result->{context});
57  
58 # Cursor pagination
59 execute($result->{schema}, '
60 query($after: String) {
61 allBooks(cursor: { after: $after, first: 5 }) {
62 total
63 nextCursor
64 hasNextPage
65 nodes { id title }
66 }
67 }', undef, $result->{context}, { after => $cursor });
68  
69 # Mutation
70 execute($result->{schema},
71 'mutation { createBook(title: "Dune", author_id: 4) { id title } }',
72 undef, $result->{context});
73  
74 =head1 DESCRIPTION
75  
76 Introspects every source registered with the supplied L<DBIx::Class::Schema>
77 and builds a complete, executable L<GraphQL::Schema> with:
78  
79 =over 4
80  
81 =item * One scalar field per column, typed as C<Int>, C<Float>, C<Boolean>,
82 or C<String> based on the column's declared C<data_type>.
83  
84 =item * One relationship field per DBIC relationship (C<has_many> resolves to
85 a List type; C<belongs_to> / C<might_have> resolve to a single object type).
86  
87 =item * A root C<Query> type with singular lookup and plural
88 C<allE<lt>SourceE<gt>s> queries supporting filtering, ordering, and both
89 offset and cursor pagination.
90  
91 =item * A root C<Mutation> type with C<createX>, C<updateX>, and C<deleteX>
92 entry points for every source.
93  
94 =back
95  
96 Composite primary keys are fully supported throughout.
97  
98 =head1 METHODS
99  
100 =head2 to_graphql
101  
102 my $result = DBIx::Class::Schema::GraphQL->to_graphql($db);
103  
104 Class method. Accepts a connected L<DBIx::Class::Schema> instance.
105 Returns a hashref:
106  
107 {
108 schema => $graphql_schema, # GraphQL::Schema, pass to execute()
109 context => $db, # the original schema, for convenience
110 }
111  
112 =cut
113  
114 sub to_graphql {
115 0 ▶ my ($class, $db) = @_;
Subroutine to_graphql: not called CC=4 SCAR=30.0
Pod documented
116  
117 0 my $shared = _build_shared_types();
118  
119 # Phase 1: Shell types
120 0 my %gql_types;
121 0 for my $moniker ($db->sources) {
122 $gql_types{$moniker} = GraphQL::Type::Object->new(
123 name => $moniker,
124 description => "Auto-generated GraphQL type for DBIx::Class source '$moniker'",
125 0 ▶ fields => sub { {} },
Subroutine __ANON__: not called CC=1 SCAR=6.9
126 0 );
127 }
128  
129 # Phase 2: Real fields (safe because %gql_types is fully populated)
130 0 for my $moniker ($db->sources) {
131 0 my $source_obj = $db->source($moniker);
132 0 my $this_moniker = $moniker;
133 0 my %types_snapshot = %gql_types;
134  
135 $gql_types{$moniker}->{fields} = sub {
136 0 ▶ my %fields;
Subroutine __ANON__: not called CC=7 SCAR=40.3
137  
138 0 for my $col ($source_obj->columns) {
139 0 $fields{$col} = { type => _scalar_for_column($source_obj, $col) };
140 }
141  
142 0 for my $rel ($source_obj->relationships) {
143 0 my $rel_info = $source_obj->relationship_info($rel);
144 0 my $target_moniker = $rel_info->{source};
145 0 $target_moniker =~ s/^.*:://;
146  
147 0 ▶ my $target_type = $types_snapshot{$target_moniker} or next;
Branch: 1 branch
BranchTrueFalseTotal
my $target_type = $types_snapshot{$target_moniker} or next 0 0 0
148  
149 my $is_plural = (
150 $rel_info->{attrs}{accessor}
151 0 ▶ && $rel_info->{attrs}{accessor} eq 'multi'
Branch: 1 branch
BranchTrueFalseTotal
$rel_info->{'attrs'}{'accessor'} && $rel_info->{'attrs'}{'accessor'} eq 'multi' ? : 0 0 0
Condition0%0/3
$rel_info->{"attrs"}{"accessor"} and $rel_info->{"attrs"}{"accessor"} eq "multi"
!ll&&!rl&&r
000
MC/DC0%0/2
$rel_info->{"attrs"}{"accessor"} and $rel_info->{"attrs"}{"accessor"} eq "multi"
$rel_info->{"attrs"}{"accessor"} $rel_info->{"attrs"}{"accessor"} eq "multi"
Truth table0%0/3
A and B
A= $rel_info->{"attrs"}{"accessor"}B= $rel_info->{"attrs"}{"accessor"} eq "multi"
ABresult
0X0
100
111
152 ) ? 1 : 0;
153  
154 0 my ($captured_rel, $captured_moniker, $captured_plural)
155 = ($rel, $this_moniker, $is_plural);
156  
157 $fields{$rel} = {
158 type => $is_plural
159 ? GraphQL::Type::List->new(of => $target_type)
160 : $target_type,
161 resolve => sub {
162 0 ▶ my ($row, $args, $ctx) = @_;
Subroutine __ANON__: not called CC=5 SCAR=34.0
163 0 ▶ if (ref($row) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $row eq "HASH") 0 0 0
164 0 ▶ $row = _pk_find($ctx, $captured_moniker, $row) or return;
Branch: 1 branch
BranchTrueFalseTotal
$row = _pk_find($ctx, $captured_moniker, $row) or return 0 0 0
165 }
166 0 ▶ if ($captured_plural) {
Branch: 1 branch
BranchTrueFalseTotal
if ($captured_plural) { } 0 0 0
167 return [
168 0 map { { $_->get_columns } }
169 $row->$captured_rel->all
170 ];
171 }
172 else {
173 0 my $related = $row->$captured_rel;
174 0 ▶ return $related ? { $related->get_columns } : undef;
Branch: 1 branch
BranchTrueFalseTotal
$related ? : 0 0 0
175 }
176 },
177 0 ▶ };
Branch: 1 branch
BranchTrueFalseTotal
$is_plural ? : 0 0 0
178 }
179  
180 0 return \%fields;
181 0 };
182 }
183  
184 # Phase 3: Root Query + Mutation types
185 0 my (%query_fields, %mutation_fields);
186  
187 0 for my $moniker ($db->sources) {
188 0 my $graphql_type = $gql_types{$moniker};
189 0 my $source_obj = $db->source($moniker);
190 0 my $singular_args = _build_singular_args($source_obj);
191 0 my $filter_type = _build_filter_type($source_obj, $moniker);
192 0 my $connection_type = _build_connection_type($moniker, $graphql_type);
193  
194 # Singular query
195 $query_fields{ lcfirst($moniker) } = {
196 type => $graphql_type,
197 args => $singular_args,
198 resolve => sub {
199 0 ▶ my ($root, $args, $ctx) = @_;
Subroutine __ANON__: not called CC=3 SCAR=24.8
200 0 ▶ return unless grep { defined $args->{$_} } keys %$singular_args;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {defined $args->{$_};} keys %$singular_args 0 0 0
201 0 my $row = $ctx->resultset($moniker)->find($args);
202 0 ▶ return $row ? { $row->get_columns } : undef;
Branch: 1 branch
BranchTrueFalseTotal
$row ? : 0 0 0
203 },
204 0 };
205  
206 # Plural query with filter + pagination + ordering
207 $query_fields{ 'all' . ucfirst($moniker) . 's' } = {
208 type => $connection_type,
209 description => "Fetch a filtered, paginated, ordered list of $moniker rows.",
210 args => {
211 filter => { type => $filter_type,
212 description => "Column filters with exact, comparison, and logical operators." },
213 page => { type => $shared->{page_input},
214 description => "Offset pagination: skip N rows, take M rows." },
215 cursor => { type => $shared->{cursor_input},
216 description => "Cursor pagination: fetch first N rows after a cursor." },
217 orderBy => { type => $shared->{order_by_input},
218 description => "Order results by a column, ASC or DESC." },
219 },
220 resolve => sub {
221 0 ▶ my ($root, $args, $ctx) = @_;
Subroutine __ANON__: not called CC=5 SCAR=34.0
222 0 ▶ $args //= {};
Condition0%0/2
$args //= {}
l!l
00
MC/DC0%0/1
$args //= {}
$args
Truth table0%0/2
A
A= $args
Aresult
11
00
223  
224 # Build the base filtered resultset
225 0 my $rs = $ctx->resultset($moniker);
226 0 ▶ if (my $filter = $args->{filter}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $filter = $args->{"filter"}) 0 0 0
227 0 my $cond = _filter_to_dbic($filter, $ctx->source($moniker));
228 0 ▶ $rs = $rs->search($cond) if $cond && %$cond;
Branch: 1 branch
BranchTrueFalseTotal
if $cond and %$cond 0 0 0
Condition0%0/3
$cond and %$cond
!ll&&!rl&&r
000
MC/DC0%0/2
$cond and %$cond
$cond %$cond
Truth table0%0/3
A and B
A= $condB= %$cond
ABresult
0X0
100
111
229 }
230  
231 # Clone the rs for counting so pagination does not
232 # affect the count query and vice-versa.
233 0 my $count_rs = $rs->search_rs({});
234 0 my $total = $count_rs->count;
235  
236 0 my ($nodes, $next_cursor, $has_next) =
237 _apply_pagination($rs, $args, $ctx->source($moniker));
238  
239 return {
240 0 nodes => $nodes,
241 total => $total,
242 nextCursor => $next_cursor,
243 hasNextPage => $has_next,
244 };
245 },
246 0 };
247  
248 # Mutations
249 0 %mutation_fields = (
250 %mutation_fields,
251 _build_mutation_fields($source_obj, $moniker, $graphql_type),
252 );
253 }
254  
255 0 my $query_type = GraphQL::Type::Object->new(
256 name => 'Query',
257 fields => \%query_fields,
258 );
259  
260 0 my $mutation_type = GraphQL::Type::Object->new(
261 name => 'Mutation',
262 description => 'Auto-generated create/update/delete mutations',
263 fields => \%mutation_fields,
264 );
265  
266 0 my $schema = GraphQL::Schema->new(
267 query => $query_type,
268 mutation => $mutation_type,
269 );
270  
271 return {
272 0 schema => $schema,
273 context => $db,
274 };
275 }
276  
277 #
278 #
279 # INTERNAL METHODS
280  
281 # _scalar_for_column($source, $col_name)
282 #
283 # Maps a DBIC column to a GraphQL scalar. Resolution order matters:
284 # 1. Boolean: must come before Int because tinyint(1) is the MySQL idiom
285 # 2. Float : decimal/numeric before the int catch-all
286 # 3. Int : all integer family types
287 # 4. String : safe fallback for anything unrecognised
288 sub _scalar_for_column {
289 40 ▶ my ($source, $col) = @_;
Subroutine _scalar_for_column: called CC=5 SCAR=16.1
290 40 my $info = $source->column_info($col);
291 40 ▶ my $data_type = $info->{data_type} // '';
Condition100%2/2
$info->{"data_type"} // ""
l!l
391
MC/DC100%1/1
$info->{"data_type"} // ""
$info->{"data_type"}
Truth table100%2/2
A
A= $info->{"data_type"}
Aresult
11
00
292  
293 40 ▶ return $Boolean if $data_type =~ /(?:\b(?:bool(?:ean)?)|tinyint\(1\))(?=\s|\z)/i;
Branch: 1 branch
BranchTrueFalseTotal
if $data_type =~ /(?:\b(?:bool(?:ean)?)|tinyint\(1\))(?=\s|\z)/i 7 33 40
294 33 ▶ return $Float if $data_type =~ /\b(?:float|double(?:\s+precision)?|real|money|decimal|numeric)\b/i;
Branch: 1 branch
BranchTrueFalseTotal
if $data_type =~ /\b(?:float|double(?:\s+precision)?|real|money|decimal|numeric)\b/i 12 21 33
295 21 ▶ return $Int if $data_type =~ /\b(?:int(?:eger)?|bigint|smallint|tinyint|mediumint|serial)\b/i;
Branch: 1 branch
BranchTrueFalseTotal
if $data_type =~ /\b(?:int(?:eger)?|bigint|smallint|tinyint|mediumint|serial)\b/i 11 10 21
296 10 return $String;
297 }
298  
299 sub _col_is_required {
300 0 ▶ my ($source, $col) = @_;
Subroutine _col_is_required: not called CC=4 SCAR=30.0
301 0 my $info = $source->column_info($col);
302 0 ▶ return 0 if $info->{is_auto_increment};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_auto_increment"} 0 0 0
303 0 ▶ return 0 if defined $info->{default_value};
Branch: 1 branch
BranchTrueFalseTotal
if defined $info->{"default_value"} 0 0 0
304 0 ▶ return 0 if $info->{is_nullable};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_nullable"} 0 0 0
305 0 return 1;
306 }
307  
308 sub _pk_find {
309 0 ▶ my ($ctx, $moniker, $row_hash) = @_;
Subroutine _pk_find: not called CC=2 SCAR=17.9
310 0 my $source = $ctx->source($moniker);
311 0 my @pk_cols = $source->primary_columns;
312 0 my %pk_vals = map { $_ => $row_hash->{$_} } @pk_cols;
313 0 ▶ return unless grep { defined } values %pk_vals == @pk_cols;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {defined $_;} values %pk_vals == @pk_cols 0 0 0
314 0 return $ctx->resultset($moniker)->find(\%pk_vals);
315 }
316  
317 sub _build_singular_args {
318 0 ▶ my ($source) = @_;
Subroutine _build_singular_args: not called CC=2 SCAR=17.9
319 0 my %args;
320 0 for my $pk_col ($source->primary_columns) {
321 0 $args{$pk_col} = { type => _scalar_for_column($source, $pk_col) };
322 }
323 0 return \%args;
324 }
325  
326 sub _build_lookup_args {
327 0 ▶ my ($source) = @_;
Subroutine _build_lookup_args: not called CC=6 SCAR=37.4
328 0 my %args;
329  
330 0 for my $col ($source->primary_columns) {
331 0 $args{$col} = { type => _scalar_for_column($source, $col) };
332 }
333  
334 0 my %unique = $source->unique_constraints;
335 0 for my $constraint_name (keys %unique) {
336 0 ▶ next if $constraint_name eq 'primary';
Branch: 1 branch
BranchTrueFalseTotal
if $constraint_name eq "primary" 0 0 0
337 0 for my $col (@{ $unique{$constraint_name} }) {
338 0 ▶ $args{$col} //= { type => _scalar_for_column($source, $col) };
Condition0%0/2
$args{$col} //= {"type", _scalar_for_column($source, $col)}
l!l
00
MC/DC0%0/1
$args{$col} //= {"type", _scalar_for_column($source, $col)}
$args{$col}
Truth table0%0/2
A
A= $args{$col}
Aresult
11
00
339 }
340 }
341  
342 0 return \%args;
343 }
344  
345 sub _resolve_row {
346 0 ▶ my ($ctx, $moniker, $args) = @_;
Subroutine _resolve_row: not called CC=6 SCAR=37.4
347 0 my $source = $ctx->source($moniker);
348 0 my $rs = $ctx->resultset($moniker);
349  
350 0 my @pk_cols = $source->primary_columns;
351 0 my @pk_vals = map { $args->{$_} } @pk_cols;
352 0 ▶ unless (grep { !defined } @pk_vals) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {not defined $_;} @pk_vals) 0 0 0
353 0 my $row = $rs->find({ map { $pk_cols[$_] => $pk_vals[$_] }
354 0 .. $#pk_cols });
355 0 ▶ return $row if $row;
Branch: 1 branch
BranchTrueFalseTotal
if $row 0 0 0
356 }
357  
358 0 my %unique = $source->unique_constraints;
359 0 for my $constraint_name (sort grep { $_ ne 'primary' } keys %unique) {
360 0 my @cols = @{ $unique{$constraint_name} };
361 0 my @vals = map { $args->{$_} } @cols;
362 0 ▶ next if grep { !defined } @vals;
Branch: 1 branch
BranchTrueFalseTotal
if grep {not defined $_;} @vals 0 0 0
363 0 my $row = $rs->find({ map { $cols[$_] => $vals[$_] } 0 .. $#cols });
364 0 ▶ return $row if $row;
Branch: 1 branch
BranchTrueFalseTotal
if $row 0 0 0
365 }
366  
367 0 return undef;
368 }
369  
370 #
371 # Cursors are base64(val1:val2:...), stateless, no extra dependencies.
372 # Colons inside values are percent-encoded so the separator is unambiguous.
373  
374 sub _encode_cursor {
375 0 ▶ my (@vals) = @_;
Subroutine _encode_cursor: not called CC=1 SCAR=6.9
376 0 my $raw = join ':', map { (my $v = $_) =~ s/%/%25/g; $v =~ s/:/%3A/g; $v } @vals;
377 0 return encode_base64($raw, ''); # no newline
378 }
379  
380 sub _decode_cursor {
381 0 ▶ my ($cursor) = @_;
Subroutine _decode_cursor: not called CC=1 SCAR=6.9
382 0 my $raw = decode_base64($cursor);
383 0 my @vals = map { (my $v = $_) =~ s/%3A/:/gi; $v =~ s/%25/%/g; $v }
384 split /:/, $raw;
385 0 return @vals;
386 }
387  
388 # _build_shared_types()
389 #
390 # Builds the input/enum types that are shared across all plural queries:
391 #
392 # OrderDirection: enum ASC | DESC
393 # OrderByInput : input { field: String!, direction: OrderDirection }
394 # PageInput : input { skip: Int, take: Int }
395 # CursorInput : input { after: String, first: Int }
396 #
397 # Returns a hashref of type objects.
398 sub _build_shared_types {
399 0 ▶ my $order_direction = GraphQL::Type::Enum->new(
Subroutine _build_shared_types: not called CC=1 SCAR=6.9
400 name => 'OrderDirection',
401 values => {
402 ASC => { value => 'ASC' },
403 DESC => { value => 'DESC' },
404 },
405 );
406  
407 0 my $order_by_input = GraphQL::Type::InputObject->new(
408 name => 'OrderByInput',
409 fields => {
410 field => { type => GraphQL::Type::NonNull->new(of => $String) },
411 direction => { type => $order_direction },
412 },
413 );
414  
415 0 my $page_input = GraphQL::Type::InputObject->new(
416 name => 'PageInput',
417 fields => {
418 skip => { type => $Int },
419 take => { type => $Int },
420 },
421 );
422  
423 0 my $cursor_input = GraphQL::Type::InputObject->new(
424 name => 'CursorInput',
425 fields => {
426 after => { type => $String },
427 first => { type => $Int },
428 },
429 );
430  
431 return {
432 0 order_direction => $order_direction,
433 order_by_input => $order_by_input,
434 page_input => $page_input,
435 cursor_input => $cursor_input,
436 };
437 }
438  
439 # _build_filter_type($source, $moniker)
440 #
441 # Builds a per-source InputObject for filtering. For each column we emit:
442 # col : exact match
443 # col_not : inequality
444 # col_like: SQL LIKE (String columns only)
445 # col_gt / col_gte / col_lt / col_lte: comparisons (Int/Float columns)
446 #
447 # Plus recursive AND / OR combinators.
448 sub _build_filter_type {
449 0 ▶ my ($source, $moniker) = @_;
Subroutine _build_filter_type: not called CC=3 SCAR=24.8
450  
451 # We need a forward-declaration trick for the recursive AND/OR fields.
452 # Create the type object first with an empty fields sub, then fill it in.
453 my $filter_type = GraphQL::Type::InputObject->new(
454 name => "${moniker}Filter",
455 0 ▶ fields => sub { {} }, # placeholder
Subroutine __ANON__: not called CC=1 SCAR=6.9
456 0 );
457  
458 0 my %fields;
459  
460 0 for my $col ($source->columns) {
461 0 my $scalar = _scalar_for_column($source, $col);
462 0 my $name = $scalar->name;
463  
464 # exact match
465 0 $fields{$col} = { type => $scalar };
466  
467 # inequality
468 0 $fields{"${col}_not"} = { type => $scalar };
469  
470 0 ▶ if ($name eq 'String') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq 'String') { } 0 0 0
471 # LIKE pattern match (String columns only)
472 0 $fields{"${col}_like"} = { type => $String };
473 }
474 else {
475 # Numeric / boolean comparisons
476 0 $fields{"${col}_gt"} = { type => $scalar };
477 0 $fields{"${col}_gte"} = { type => $scalar };
478 0 $fields{"${col}_lt"} = { type => $scalar };
479 0 $fields{"${col}_lte"} = { type => $scalar };
480 }
481 }
482  
483 # Recursive AND / OR — each takes a list of the same filter type
484 0 $fields{AND} = { type => GraphQL::Type::List->new(of => $filter_type) };
485 0 $fields{OR} = { type => GraphQL::Type::List->new(of => $filter_type) };
486  
487 # Now replace the placeholder
488 0 ▶ $filter_type->{fields} = sub { \%fields };
Subroutine __ANON__: not called CC=1 SCAR=6.9
489  
490 0 return $filter_type;
491 }
492  
493 # _build_connection_type($moniker, $gql_type)
494 #
495 # Builds the per-source connection wrapper returned by plural queries:
496 #
497 # type BookConnection {
498 # nodes: [Book]
499 # total: Int
500 # nextCursor: String
501 # hasNextPage: Boolean
502 # }
503 sub _build_connection_type {
504 0 ▶ my ($moniker, $gql_type) = @_;
Subroutine _build_connection_type: not called CC=1 SCAR=6.9
505  
506 0 return GraphQL::Type::Object->new(
507 name => "${moniker}Connection",
508 fields => {
509 nodes => { type => GraphQL::Type::List->new(of => $gql_type) },
510 total => { type => $Int },
511 nextCursor => { type => $String },
512 hasNextPage => { type => $Boolean },
513 },
514 );
515 }
516  
517 # _filter_to_dbic($filter, $source)
518 #
519 # Recursively converts a GraphQL filter hashref into a DBIC search condition.
520 #
521 # { title_like: "%Perl%" , OR: [{ id: 1 }, { id: 2 }] }
522 # => { title => { like => '%Perl%' }, -or => [ { id => 1 }, { id => 2 } ] }
523 sub _filter_to_dbic {
524 0 ▶ my ($filter, $source) = @_;
Subroutine _filter_to_dbic: not called CC=12 SCAR=50.5
525 0 ▶ return {} unless $filter && %$filter;
Branch: 1 branch
BranchTrueFalseTotal
unless $filter and %$filter 0 0 0
Condition0%0/3
$filter and %$filter
!ll&&!rl&&r
000
MC/DC0%0/2
$filter and %$filter
$filter %$filter
Truth table0%0/3
A and B
A= $filterB= %$filter
ABresult
0X0
100
111
526  
527 0 my %cond;
528 my @and_parts;
529  
530 # AND / OR combinators
531 0 ▶ if (my $and = $filter->{AND}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $and = $filter->{"AND"}) 0 0 0
532 0 push @and_parts, { -and => [ map { _filter_to_dbic($_, $source) } @$and ] };
533 }
534 0 ▶ if (my $or = $filter->{OR}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $or = $filter->{"OR"}) 0 0 0
535 0 push @and_parts, { -or => [ map { _filter_to_dbic($_, $source) } @$or ] };
536 }
537  
538 # Column conditions
539 0 for my $key (keys %$filter) {
540 0 ▶ next if $key eq 'AND' || $key eq 'OR';
Branch: 1 branch
BranchTrueFalseTotal
if $key eq "AND" or $key eq "OR" 0 0 0
Condition0%0/3
$key eq "AND" or $key eq "OR"
l!l&&r!l&&!r
000
MC/DC0%0/2
$key eq "AND" or $key eq "OR"
$key eq "AND" $key eq "OR"
Truth table0%0/3
A or B
A= $key eq "AND"B= $key eq "OR"
ABresult
1X1
011
000
541 0 ▶ next unless defined $filter->{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $filter->{$key} 0 0 0
542  
543 0 ▶ if ($key =~ /^(.+)_(not|like|gt|gte|lt|lte)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($key =~ /^(.+)_(not|like|gt|gte|lt|lte)$/) { } 0 0 0
544 0 my ($col, $op) = ($1, $2);
545 my $dbic_op = { not => '!=' , like => 'like',
546 gt => '>' , gte => '>=',
547 0 lt => '<' , lte => '<=' }->{$op};
548 0 push @and_parts, { $col => { $dbic_op => $filter->{$key} } };
549 }
550 else {
551 # exact match
552 0 push @and_parts, { $key => $filter->{$key} };
553 }
554 }
555  
556 0 ▶ return @and_parts == 1 ? $and_parts[0]
Branch: 2 branches
BranchTrueFalseTotal
@and_parts == 1 ? : 0 0 0
@and_parts > 1 ? : 0 0 0
557 : @and_parts > 1 ? { -and => \@and_parts }
558 : {};
559 }
560  
561 # _apply_pagination($rs, $args, $source)
562 #
563 # Applies ordering, then either offset (page) or cursor (cursor) pagination.
564 # Returns ($paged_rs, $next_cursor, $has_next_page).
565 #
566 # Precedence: cursor pagination wins if both are supplied.
567 sub _apply_pagination {
568 0 ▶ my ($rs, $args, $source) = @_;
Subroutine _apply_pagination: not called CC=15 SCAR=54.8
569  
570 0 my @pk_cols = $source->primary_columns;
571  
572 # Ordering
573 0 my $order_by = $args->{orderBy};
574 0 ▶ if ($order_by && $order_by->{field}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($order_by and $order_by->{'field'}) { } 0 0 0
Condition0%0/3
$order_by and $order_by->{"field"}
!ll&&!rl&&r
000
MC/DC0%0/2
$order_by and $order_by->{"field"}
$order_by $order_by->{"field"}
Truth table0%0/3
A and B
A= $order_byB= $order_by->{"field"}
ABresult
0X0
100
111
575 0 ▶ my $dir = lc($order_by->{direction} // 'ASC');
Condition0%0/2
$order_by->{"direction"} // "ASC"
l!l
00
MC/DC0%0/1
$order_by->{"direction"} // "ASC"
$order_by->{"direction"}
Truth table0%0/2
A
A= $order_by->{"direction"}
Aresult
11
00
576 $rs = $rs->search(undef, {
577 order_by => { "-$dir" => $order_by->{field} }
578 0 });
579 }
580 else {
581 # Default: stable order by PK
582 0 $rs = $rs->search(undef, { order_by => [ map { { -asc => $_ } } @pk_cols ] });
583 }
584  
585 # Cursor pagination
586 0 ▶ if (my $cursor_args = $args->{cursor}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cursor_args = $args->{"cursor"}) 0 0 0
587 0 ▶ my $first = $cursor_args->{first} // 10;
Condition0%0/2
$cursor_args->{"first"} // 10
l!l
00
MC/DC0%0/1
$cursor_args->{"first"} // 10
$cursor_args->{"first"}
Truth table0%0/2
A
A= $cursor_args->{"first"}
Aresult
11
00
588 0 my $after = $cursor_args->{after};
589  
590 0 ▶ if ($after) {
Branch: 1 branch
BranchTrueFalseTotal
if ($after) 0 0 0
591 0 my @decoded = _decode_cursor($after);
592 0 ▶ if (@pk_cols == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@pk_cols == 1) { } 0 0 0
593 # Simple: WHERE pk > cursor_val (works for ordered-by-PK default)
594 0 $rs = $rs->search({ $pk_cols[0] => { '>' => $decoded[0] } });
595 }
596 else {
597 # Composite PK: fetch everything after decoded position
598 # by re-applying a compound condition
599 0 my %after_cond = map { $pk_cols[$_] => { '>' => $decoded[$_] } }
600 0 .. $#pk_cols;
601 0 $rs = $rs->search(\%after_cond);
602 }
603 }
604  
605 # Fetch one extra to detect hasNextPage
606 0 my @rows = $rs->search(undef, { rows => $first + 1 })->all;
607 0 my $has_next = @rows > $first;
608 0 ▶ @rows = @rows[0 .. $first - 1] if $has_next;
Branch: 1 branch
BranchTrueFalseTotal
if $has_next 0 0 0
609  
610 0 my $next_cursor;
611 0 ▶ if ($has_next && @rows) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_next and @rows) 0 0 0
Condition0%0/3
$has_next and @rows
!ll&&!rl&&r
000
MC/DC0%0/2
$has_next and @rows
$has_next @rows
Truth table0%0/3
A and B
A= $has_nextB= @rows
ABresult
0X0
100
111
612 0 my $last_row = $rows[-1];
613 0 $next_cursor = _encode_cursor(map { $last_row->get_column($_) } @pk_cols);
614 }
615  
616 return (
617 0 ▶ [ map { { $_->get_columns } } @rows ],
Branch: 1 branch
BranchTrueFalseTotal
$has_next ? : 0 0 0
618 $next_cursor,
619 $has_next ? 1 : 0,
620 );
621 }
622  
623 # Offset pagination
624 0 ▶ if (my $page_args = $args->{page}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $page_args = $args->{"page"}) 0 0 0
625 0 ▶ my $skip = $page_args->{skip} // 0;
Condition0%0/2
$page_args->{"skip"} // 0
l!l
00
MC/DC0%0/1
$page_args->{"skip"} // 0
$page_args->{"skip"}
Truth table0%0/2
A
A= $page_args->{"skip"}
Aresult
11
00
626 0 ▶ my $take = $page_args->{take} // 10;
Condition0%0/2
$page_args->{"take"} // 10
l!l
00
MC/DC0%0/1
$page_args->{"take"} // 10
$page_args->{"take"}
Truth table0%0/2
A
A= $page_args->{"take"}
Aresult
11
00
627 0 my @rows = $rs->search(undef, { rows => $take, offset => $skip })->all;
628 return (
629 0 [ map { { $_->get_columns } } @rows ],
630 undef, # no cursor for offset pagination
631 0,
632 );
633 }
634  
635 # No pagination: return everything
636 0 my @rows = $rs->all;
637 return (
638 0 [ map { { $_->get_columns } } @rows ],
639 undef,
640 0,
641 );
642 }
643  
644 sub _build_mutation_fields {
645 0 ▶ my ($source, $moniker, $gql_type) = @_;
Subroutine _build_mutation_fields: not called CC=3 SCAR=24.8
646 0 my %fields;
647  
648 0 my @pk_cols = $source->primary_columns;
649 0 my %is_pk = map { $_ => 1 } @pk_cols;
650 0 my @all_cols = $source->columns;
651 0 my @data_cols = grep { !$is_pk{$_} } @all_cols;
652  
653 # createX
654 0 my %create_args;
655 0 for my $col (@all_cols) {
656 0 my $scalar = _scalar_for_column($source, $col);
657 0 ▶ $create_args{$col} = {
Branch: 1 branch
BranchTrueFalseTotal
_col_is_required($source, $col) ? : 0 0 0
658 type => _col_is_required($source, $col)
659 ? GraphQL::Type::NonNull->new(of => $scalar)
660 : $scalar,
661 };
662 }
663  
664 $fields{ 'create' . ucfirst($moniker) } = {
665 type => $gql_type,
666 args => \%create_args,
667 description => "Insert a new $moniker row. Required columns are marked non-null.",
668 resolve => sub {
669 0 ▶ my ($root, $args, $ctx) = @_;
Subroutine __ANON__: not called CC=2 SCAR=17.9
670 0 my %data = map { $_ => $args->{$_} }
671 0 grep { defined $args->{$_} } keys %$args;
672 0 my $row = eval { $ctx->resultset($moniker)->create(\%data) };
673 0 ▶ die $@ if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
674 0 return { $row->get_columns };
675 },
676 0 };
677  
678 # updateX
679 0 my %update_lookup_args = %{ _build_lookup_args($source) };
680 my %update_data_args = map {
681 0 $_ => { type => _scalar_for_column($source, $_) }
682 } @data_cols;
683  
684 $fields{ 'update' . ucfirst($moniker) } = {
685 type => $gql_type,
686 args => { %update_lookup_args, %update_data_args },
687 description => "Update an existing $moniker row identified by its primary key "
688 . "or any unique constraint. Pass all non-key columns.",
689 resolve => sub {
690 0 ▶ my ($root, $args, $ctx) = @_;
Subroutine __ANON__: not called CC=4 SCAR=30.0
691 0 my $row = _resolve_row($ctx, $moniker, $args);
692 0 ▶ die "No $moniker row found for the supplied key(s)\n" unless $row;
Branch: 1 branch
BranchTrueFalseTotal
unless $row 0 0 0
693 0 my %data = map { $_ => $args->{$_} }
694 0 ▶ grep { !$is_pk{$_} && defined $args->{$_} } keys %$args;
Branch: 1 branch
BranchTrueFalseTotal
not $is_pk{$_} and defined $args->{$_} 0 0 0
695 0 $row = eval { $row->update(\%data); $row->discard_changes; $row };
696 0 ▶ die $@ if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
697 0 return { $row->get_columns };
698 },
699 0 };
700  
701 # deleteX
702 $fields{ 'delete' . ucfirst($moniker) } = {
703 type => $Boolean,
704 args => _build_lookup_args($source),
705 description => "Delete a $moniker row identified by its primary key "
706 . "or any unique constraint. Returns true on success.",
707 resolve => sub {
708 0 ▶ my ($root, $args, $ctx) = @_;
Subroutine __ANON__: not called CC=3 SCAR=24.8
709 0 my $row = _resolve_row($ctx, $moniker, $args);
710 0 ▶ return 0 unless $row;
Branch: 1 branch
BranchTrueFalseTotal
unless $row 0 0 0
711 0 eval { $row->delete };
712 0 ▶ return $@ ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$@ ? : 0 0 0
713 },
714 0 };
715  
716 0 return %fields;
717 }
718  
719 =head1 SCALAR TYPE MAPPING
720  
721 SQL column types are mapped to GraphQL scalars in the following priority order:
722  
723 Boolean: bool, boolean, tinyint(1)
724 Float : float, double, double precision, real, money, decimal, numeric
725 Int : int, integer, bigint, smallint, tinyint, mediumint, serial
726 String : everything else (safe fallback)
727  
728 =head1 PLURAL QUERIES
729  
730 Every source C<X> gets an C<allXs> query returning an C<XConnection>:
731  
732 type XConnection {
733 nodes: [X]
734 total: Int # total rows matching filter, before pagination
735 nextCursor: String # opaque cursor; set only during cursor pagination
736 hasNextPage: Boolean # true when more pages follow
737 }
738  
739 Always request C<total> or another scalar field alongside C<nodes> in your
740 selection set - see L</KNOWN BEHAVIOUR>.
741  
742 =head2 Filtering
743  
744 allBooks(filter: { title_like: "%Perl%", author_id: 3 }) {
745 total nodes { title }
746 }
747  
748 Per-column operators:
749  
750 col exact match
751 col_not inequality (!=)
752 col_like LIKE pattern (String columns only)
753 col_gt greater than
754 col_gte greater than or equal
755 col_lt less than
756 col_lte less than or equal
757  
758 Logical combinators (nest recursively and combine freely):
759  
760 allBooks(filter: {
761 AND: [
762 { author_id: 1 }
763 { OR: [{ title_like: "%Hobbit%" }, { title_like: "%Ring%" }] }
764 ]
765 }) { total nodes { title } }
766  
767 =head2 Ordering
768  
769 allBooks(orderBy: { field: "title", direction: ASC }) {
770 total nodes { title }
771 }
772  
773 C<direction> is the C<OrderDirection> enum: C<ASC> or C<DESC>. When omitted,
774 results are ordered by primary key ascending.
775  
776 =head2 Offset pagination
777  
778 allBooks(page: { skip: 10, take: 5 }) { total nodes { title } }
779  
780 C<skip> defaults to 0, C<take> defaults to 10.
781  
782 =head2 Cursor pagination
783  
784 # First page
785 allBooks(cursor: { first: 5 }) {
786 total nextCursor hasNextPage nodes { title }
787 }
788  
789 # Subsequent pages - pass nextCursor from the previous response
790 allBooks(cursor: { after: "...", first: 5 }) {
791 total nextCursor hasNextPage nodes { title }
792 }
793  
794 C<first> defaults to 10. Cursor pagination takes precedence over offset
795 pagination if both are supplied in the same query. Cursors are opaque
796 base64-encoded strings derived from the row's primary key and should be
797 treated as implementation details subject to change.
798  
799 =head1 MUTATIONS
800  
801 For every source C<X>, three mutations are generated:
802  
803 =head2 createX
804  
805 mutation { createBook(title: "Dune", author_id: 4) { id title } }
806  
807 Accepts all column values as arguments. Columns that are non-nullable,
808 have no declared default, and are not auto-increment are wrapped in
809 C<NonNull> and must be supplied. On failure, C<die>s - the error appears
810 in the top-level C<errors> array of the response.
811  
812 =head2 updateX
813  
814 mutation { updateBook(id: 1, title: "Dune Messiah") { id title } }
815  
816 Identifies the target row by its primary key B<or> by a complete set of
817 columns from any unique constraint declared on the source. All non-key
818 columns must be supplied (full update). C<die>s if the row cannot be found
819 or the update fails.
820  
821 =head2 deleteX
822  
823 mutation { deleteBook(id: 1) }
824  
825 Identifies the target row by primary key or unique constraint. Returns
826 C<true> (C<Boolean>) on success, C<false> if the row is not found.
827  
828 =head1 ERROR HANDLING
829  
830 C<createX> and C<updateX> resolver failures C<die>. GraphQL catches the
831 exception and surfaces it in the top-level C<errors> array; the C<data>
832 field for the failed mutation will be C<null>. C<deleteX> returns C<false>
833 rather than dying when a row is not found.
834  
835 =head1 LIMITATIONS
836  
837 =over 4
838  
839 =item * B<Relationship fields are unfiltered.> Relationship fields within a
840 query (e.g. C<author { books { title } }>) return all related rows. They do
841 not accept C<filter>, C<orderBy>, or pagination arguments.
842  
843 =item * B<No nested input for mutations.> C<createX> and C<updateX> accept
844 only scalar column values. Related rows must be created or linked separately
845 using their own mutations and raw foreign-key values.
846  
847 =item * B<updateX is a full update.> All non-primary-key columns must be
848 supplied; partial (sparse) updates are not supported.
849  
850 =item * B<Cursor pagination assumes primary-key order.> The C<after> cursor
851 encodes the primary key of the last returned row and applies a
852 C<pk E<gt> value> condition. If you supply a custom C<orderBy> using a
853 non-primary-key column, the cursor will not advance correctly. Use offset
854 pagination (C<page>) when ordering by non-PK columns.
855  
856 =item * B<No custom scalars.> Column types such as C<date>, C<datetime>,
857 C<json>, and C<uuid> all map to C<String>. Custom GraphQL scalars are not
858 generated.
859  
860 =item * B<No subscriptions.> Only C<Query> and C<Mutation> operation types
861 are generated.
862  
863 =item * B<C<col_like> case sensitivity is database-dependent.> SQLite
864 C<LIKE> is case-insensitive for ASCII characters but case-sensitive for
865 Unicode. PostgreSQL C<LIKE> is always case-sensitive. Use C<col_like>
866 accordingly.
867  
868 =back
869  
870 =head1 KNOWN BEHAVIOUR
871  
872 When querying a plural C<allXs> field, always include at least one scalar
873 field (C<total>, C<hasNextPage>, or C<nextCursor>) alongside C<nodes> in
874 your selection set:
875  
876 # Correct
877 { allBooks { total nodes { title } } }
878  
879 # May silently return empty nodes in some GraphQL executor versions
880 { allBooks { nodes { title } } }
881  
882 This is a quirk of how C<GraphQL::Execution> resolves connection object
883 types when the selection set contains only a list field.
884  
885 =head1 DEPENDENCIES
886  
887 L<DBIx::Class>, L<GraphQL::Schema>, L<GraphQL::Type::Object>,
888 L<GraphQL::Type::InputObject>, L<GraphQL::Type::List>,
889 L<GraphQL::Type::NonNull>, L<GraphQL::Type::Enum>,
890 L<GraphQL::Type::Scalar>, L<MIME::Base64> (core).
891  
892 =head1 SEE ALSO
893  
894 L<GraphQL::Plugin::Convert::DBIC>, L<DBIx::Class::Schema>, L<GraphQL::Schema>
895  
896 =head1 AUTHOR
897  
898 Mohammad Sajid Anwar, C<< <mohammad.anwar at yahoo.com> >>
899  
900 =head1 REPOSITORY
901  
902 L<https://github.com/manwar/DBIx-Class-Schema-GraphQL>
903  
904 =head1 BUGS
905  
906 Please report any bugs or feature requests through the web interface at L<https://github.com/manwar/DBIx-Class-Schema-GraphQL/issues>.
907 I will be notified and then you'll automatically be notified of progress on your
908 bug as I make changes.
909  
910 =head1 SUPPORT
911  
912 You can find documentation for this module with the perldoc command.
913  
914 perldoc DBix::Class::Schema::GraphQL
915  
916 You can also look for information at:
917  
918 =over 4
919  
920 =item * BUG Report
921  
922 L<https://github.com/manwar/DBIx-Class-Schema-GraphQL/issues>
923  
924 =item * CPAN Ratings
925  
926 L<http://cpanratings.perl.org/d/DBIx-Class-Schema-GraphQL>
927  
928 =item * Search MetaCPAN
929  
930 L<https://metacpan.org/dist/DBIx-Class-Schema-GraphQL>
931  
932 =back
933  
934 =head1 LICENSE AND COPYRIGHT
935  
936 Copyright (C) 2026 Mohammad Sajid Anwar.
937  
938 This program is free software; you can redistribute it and / or modify it under
939 the terms of the the Artistic License (2.0). You may obtain a copy of the full
940 license at:
941  
942 L<http://www.perlfoundation.org/artistic_license_2_0>
943  
944 Any use, modification, and distribution of the Standard or Modified Versions is
945 governed by this Artistic License.By using, modifying or distributing the Package,
946 you accept this license. Do not use, modify, or distribute the Package, if you do
947 not accept this license.
948  
949 If your Modified Version has been derived from a Modified Version made by someone
950 other than you,you are nevertheless required to ensure that your Modified Version
951 complies with the requirements of this license.
952  
953 This license does not grant you the right to use any trademark, service mark,
954 tradename, or logo of the Copyright Holder.
955  
956 This license includes the non-exclusive, worldwide, free-of-charge patent license
957 to make, have made, use, offer to sell, sell, import and otherwise transfer the
958 Package with respect to any patent claims licensable by the Copyright Holder that
959 are necessarily infringed by the Package. If you institute patent litigation
960 (including a cross-claim or counterclaim) against any party alleging that the
961 Package constitutes direct or contributory patent infringement,then this Artistic
962 License to you shall terminate on the date that such litigation is filed.
963  
964 Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND
965 CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED
966 WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
967 NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS
968 REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT,
969 INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE
970 OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
971  
972 =cut
973  
974 7 1; # End of DBIx::Class::Schema::GraphQL
↑ Summary