blib/lib/Dancer2/Plugin/QuickORM.pm

filter: Statementstmt 100% 93 / 93 Branchbran 100% 26 / 26 Conditioncond 100% 5 / 5 MC/DCmcdc 100% 3 / 3 Subroutinesub 100% 15 / 15 Podpod 100% 2 / 2 totaltotal 100% 144 / 144 CC 22 SCAR 17.4
CC
22
Cov
100%
BUILD
12.0
__ANON__
5.0
__ANON__
3.0
CRAP 5.7
↑ Summary
1 package Dancer2::Plugin::QuickORM 1.0000;
2 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 3 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 3 ▶use Dancer2::Core::DSL;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 3 ▶use Dancer2::Plugin;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 3 ▶use Carp qw/croak/;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 3 ▶use Lingua::EN::Inflect::Phrase;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 3 our $AUTHORITY = 'cpan:GEEKRUTH'; # AUTHORITY
10  
11 3 my $_orms = {};
12  
13 3 plugin_keywords qw/orm/;
14  
15 4 ▶sub BUILD {
Subroutine BUILD: called CC=12 SCAR=24.8
Pod documented
16 4 my ($self) = @_;
17 4 my $config = $self->config;
18 4 my $new_keywords = {};
19 4 foreach my $name ( keys %$config ) {
20 5 my $orm_config = $config->{$name};
21 my $class = $orm_config->{class}
22 5 ▶ or croak "ORM '$name' is missing 'class' in the configuration";
Branch: 1 branch
BranchTrueFalseTotal
my $class = $orm_config->{"class"} or croak("ORM '${name}' is missing 'class' in the configuration") 4 1 5
23 4 $ENV{"QuickORM_${name}_name"} = $name;
24 4 foreach my $key ( keys %$orm_config ) {
25 4 $ENV{"QuickORM_${name}_$key"} = $orm_config->{$key};
26 }
27 4 ( my $class_file = "$class.pm" ) =~ s{::}{/}g;
28 4 ▶ eval { require $class_file }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require $class_file } } or croak("Failed to load ORM class '${class}': $@") 3 1 4
29 or croak "Failed to load ORM class '$class': $@";
30 3 my $orm = $class->orm($name);
31 3 $_orms->{$name} = $orm;
32 3 foreach my $table ( $orm->schema($name)->tables ) {
33 15 my $table_name = $table->name;
34 15 my $singular = $self->_source_name_to_method_name($table_name);
35 15 my $plural = $self->_source_name_to_plural_name($table_name);
36  
37 # scalar/arrayref: fetch the single row by primary key.
38 # Dancer2::Plugin always calls keyword subs as ($plugin, @args), so
39 # the plugin instance itself is shifted off and discarded here.
40 8 ▶ my $row_sub = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
41 8 my ( undef, $id ) = @_;
42 8 ▶ croak "'$table_name' requires a primary key value"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id 1 7 8
43 unless defined $id;
44 7 ▶ croak
Branch: 1 branch
BranchTrueFalseTotal
if ref $id eq "HASH" 1 6 7
45 "'$table_name' expects a single primary key value, not a hashref of search conditions"
46 if ref($id) eq 'HASH';
47 6 return $orm->handle($table_name)->by_id($id);
48 15 };
49  
50 # hashref: run it through SQL::Abstract as search conditions.
51 # no argument: return every row.
52 5 ▶ my $set_sub = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
53 5 my ( undef, $where ) = @_;
54 5 my $handle = $orm->handle($table_name);
55 5 ▶ return $handle->all unless defined $where;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $where 1 4 5
56 4 ▶ croak "'$table_name' expects a hashref of search conditions"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $where eq "HASH" 1 3 4
57 unless ref($where) eq 'HASH';
58 3 return $handle->where($where)->all;
59 15 };
60  
61 15 my @words;
62 15 ▶ if ( $singular eq $plural ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($singular eq $plural) { } 3 12 15
63  
64 # words like "moose" only get one keyword, so it has to
65 # tell a row lookup from a search by the shape of its argument.
66 8 ▶ my $smart_sub = sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
67 8 my ( undef, $arg ) = @_;
68 8 ▶ croak
Branch: 1 branch
BranchTrueFalseTotal
unless defined $arg 1 7 8
69 "'$table_name' requires a primary key value or a hashref of search conditions"
70 unless defined $arg;
71 7 ▶ return $orm->handle($table_name)->where($arg)->all
Branch: 1 branch
BranchTrueFalseTotal
if ref $arg eq "HASH" 2 5 7
72 if ref($arg) eq 'HASH';
73 5 ▶ croak "'$table_name' does not accept a reference of type '"
Branch: 1 branch
BranchTrueFalseTotal
if ref $arg and ref $arg ne "ARRAY" 1 4 5
Condition100%3/3
ref $arg and ref $arg ne "ARRAY"
!ll&&!rl&&r
311
MC/DC100%2/2
ref $arg and ref $arg ne "ARRAY"
ref $arg ref $arg ne "ARRAY"
Truth table100%3/3
A and B
A= ref $argB= ref $arg ne "ARRAY"
ABresult
0X0
100
111
74 . ref($arg) . q/'/
75 if ref($arg) && ref($arg) ne 'ARRAY';
76 4 return $orm->handle($table_name)->by_id($arg);
77 3 };
78 3 @words = ( [ $singular => $smart_sub ] );
79 }
80 else {
81 12 @words = ( [ $singular => $row_sub ], [ $plural => $set_sub ] );
82 }
83  
84 15 foreach my $pair (@words) {
85 27 my ( $word, $sub ) = @$pair;
86 27 ▶ if ( defined $new_keywords->{$word} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $new_keywords->{$word}) { } 9 18 27
87  
88 # it already exists, so let's make that one an error
89 3 ▶ $new_keywords->{$word} = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
90 3 croak "$word is ambiguous; use <schema>_$word instead!";
91 9 };
92 }
93 else {
94 18 $new_keywords->{$word} = $sub;
95 }
96 27 $new_keywords->{"${name}_${word}"} = $sub;
97 }
98 }
99 }
100 2 foreach my $dsl_keyword ( keys %{ Dancer2::Core::DSL->dsl_keywords } ) {
101 162 delete $new_keywords->{$dsl_keyword};
102 }
103 2 foreach my $new_keyword ( keys %$new_keywords ) {
104 39 ▶ next if defined $self->keywords->{$new_keyword};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->keywords->{$new_keyword} 2 37 39
105 37 $self->keywords->{$new_keyword} = $new_keywords->{$new_keyword};
106 }
107 2 return;
108 }
109  
110 4 ▶sub orm {
Subroutine orm: called CC=3 SCAR=11.0
Pod documented
111 4 my ( $self, $name ) = @_;
112 4 ▶ $name //= 'default';
Condition100%2/2
$name //= "default"
l!l
22
MC/DC100%1/1
$name //= "default"
$name
Truth table100%2/2
A
A= $name
Aresult
11
00
113 4 ▶ if ( !$_orms->{$name} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($_orms->{$name}) 1 3 4
114 1 croak "ORM '$name' is not defined in the configuration";
115 }
116 3 return $_orms->{$name};
117 }
118  
119 15 ▶sub _source_name_to_method_name {
Subroutine _source_name_to_method_name: called CC=1 SCAR=0.0
120 15 my ( $class, $source_name ) = @_;
121 15 my $phrase = $class->_source_name_to_phrase($source_name);
122 15 my $singularised = Lingua::EN::Inflect::Phrase::to_S($phrase);
123 15 return join '_', split q{ }, $singularised;
124 }
125  
126 30 ▶sub _source_name_to_phrase {
Subroutine _source_name_to_phrase: called CC=1 SCAR=0.0
127 30 my ( $class, $source_name ) = @_;
128 return join q{ }, map {
129 30 join( q{ }, map {lc} grep {length} split /([A-Z]{1}[^A-Z]*)/ )
130 } split /::/, $source_name;
131 }
132  
133 15 ▶sub _source_name_to_plural_name {
Subroutine _source_name_to_plural_name: called CC=1 SCAR=0.0
134 15 my ( $class, $source_name ) = @_;
135 15 my $phrase = $class->_source_name_to_phrase($source_name);
136 15 my $pluralised = Lingua::EN::Inflect::Phrase::to_PL($phrase);
137 15 return join '_', split q{ }, $pluralised;
138 }
139 3 1;
140  
141 =pod
142  
143 =encoding UTF-8
144  
145 =head1 NAME
146  
147 Dancer2::Plugin::QuickORM - Adds QuickORM syntactic sugar to Dancer2
148  
149 =head1 VERSION
150  
151 version 1.0000
152  
153 =head1 SYNOPSIS
154  
155 package MyApp;
156 use Dancer2;
157 use Dancer2::Plugin::QuickORM;
158  
159 set plugins => {
160 QuickORM => {
161 default => {
162 class => 'MyApp::ORM',
163 },
164 },
165 };
166  
167 # 'widget' table -> singular/plural keywords widget()/widgets()
168 get '/widget/:id' => sub {
169 return widget( route_parameters->get('id') );
170 };
171  
172 get '/widgets' => sub {
173 return [ widgets( { color => 'blue' } ) ];
174 };
175  
176 # get at the raw ORM connection directly
177 get '/stats' => sub {
178 return { row_count => orm()->handle('widget')->all };
179 };
180  
181 =head1 DESCRIPTION
182  
183 C<Dancer2::Plugin::QuickORM> looks at the ORM(s) you've configured with L<DBIx::QuickORM>,
184 walks every table in their schema(s), and generates a Dancer2 keyword (i.e. an
185 importable function) for each one, so routes can query it without any
186 boilerplate.
187  
188 For each configured ORM name (see L</CONFIGURATION AND ENVIRONMENT>), the
189 plugin's C<BUILD> step:
190  
191 =over 4
192  
193 =item 1.
194  
195 Loads the configured C<class> and calls C<< $class->orm($name) >> to obtain
196 a connection.
197  
198 =item 2.
199  
200 Iterates C<< $orm->schema($name)->tables >> and, for each table, derives a
201 singular and a plural keyword name from the table name (splitting
202 C<StudlyCaps>/C<CamelCase> into words and singularising/pluralising with
203 L<Lingua::EN::Inflect::Phrase>).
204  
205 =item 3.
206  
207 Registers those keywords, plus schema-prefixed variants
208 (C<< <name>_<singular> >> and C<< <name>_<plural> >>), so a table is always
209 reachable unambiguously even if more than one configured ORM exposes a
210 table of the same name.
211  
212 =back
213  
214 =head2 Generated keywords
215  
216 If a table's singular and plural forms differ (the common case, e.g.
217 C<widget>/C<widgets>), two keywords are generated:
218  
219 =over 4
220  
221 =item C<< singular($id) >>
222  
223 Fetches the single row with that primary key. Croaks if called with no
224 argument, or with a hashref (which is a search, not a primary key).
225  
226 =item C<< plural($where) >>
227  
228 Runs a search. Called with no arguments, returns every row. Called with a
229 hashref, runs it as search conditions against the table. Croaks if given
230 anything other than a hashref.
231  
232 =back
233  
234 If a table's singular and plural forms are identical (e.g. C<moose>), a
235 single "smart" keyword is generated instead, which inspects the shape of
236 its argument to decide what you meant:
237  
238 =over 4
239  
240 =item * a hashref is treated as search conditions (like the plural form above);
241  
242 =item * C<undef> (i.e. no argument) croaks, since there's no sensible default;
243  
244 =item * anything else (a plain scalar, or an arrayref) is treated as a
245 primary key value and looked up like the singular form above;
246  
247 =item * any other kind of reference (coderef, scalarref, etc.) croaks,
248 since it's neither a valid search nor a valid primary key.
249  
250 =back
251  
252 =head2 Keyword collisions
253  
254 Two different kinds of collision are handled, and handled differently:
255  
256 =over 4
257  
258 =item Two configured ORMs derive the same bare keyword
259  
260 The bare keyword (e.g. C<widget>) becomes ambiguous: calling it croaks,
261 telling you to use the schema-prefixed form (e.g. C<default_widget> or
262 C<second_widget>) instead. The schema-prefixed forms always work.
263  
264 =item A derived keyword collides with an existing keyword
265  
266 If the bare keyword name is already in use (either because it's a core
267 Dancer2 DSL keyword, e.g. C<session> or C<response_header>, or because
268 this plugin has already registered it itself - its own C<orm> keyword,
269 see below), the bare form is silently skipped so the existing keyword
270 keeps working. The schema-prefixed form is still registered and
271 reachable.
272  
273 =back
274  
275 =head1 SUBROUTINES/METHODS
276  
277 =head2 orm
278  
279 orm(); # the connection configured as 'default'
280 orm($name); # the connection configured under $name
281  
282 Returns the raw ORM connection object for the given configured name
283 (defaults to C<'default'> when no name is given). Croaks if C<$name> was
284 not configured.
285  
286 This is the one keyword the plugin always registers itself (via
287 C<plugin_keywords>), regardless of what tables are configured; use it when
288 you need something the generated per-table keywords don't cover.
289  
290 =head2 BUILD
291  
292 Runs once when the plugin is instantiated. Reads the plugin configuration,
293 loads each configured ORM class, and generates the per-table keywords
294 described in L</DESCRIPTION>. Not intended to be called directly.
295  
296 =head1 ATTRIBUTES
297  
298 This plugin exposes no public attributes of its own. All of its behaviour
299 is driven by the C<plugins-E<gt>QuickORM> section of your Dancer2
300 configuration; see L</CONFIGURATION AND ENVIRONMENT>.
301  
302 =head1 DIAGNOSTICS
303  
304 =over 4
305  
306 =item C<< ORM '%s' is missing 'class' in the configuration >>
307  
308 A configured ORM name has no C<class> key. Every entry under
309 C<plugins-E<gt>QuickORM> must specify one.
310  
311 =item C<< Failed to load ORM class '%s': %s >>
312  
313 The configured C<class> could not be C<require>d; the underlying error is
314 appended.
315  
316 =item C<< ORM '%s' is not defined in the configuration >>
317  
318 C<orm($name)> was called with a name that wasn't configured.
319  
320 =item C<< '%s' requires a primary key value >>
321  
322 A singular (or smart) keyword was called with no argument.
323  
324 =item C<< '%s' expects a single primary key value, not a hashref of search conditions >>
325  
326 A singular keyword was called with a hashref; use the plural (search)
327 keyword instead.
328  
329 =item C<< '%s' expects a hashref of search conditions >>
330  
331 A plural keyword was called with a non-hashref, non-undef argument.
332  
333 =item C<< '%s' requires a primary key value or a hashref of search conditions >>
334  
335 A smart keyword (identical singular/plural table) was called with no
336 argument.
337  
338 =item C<< '%s' does not accept a reference of type '%s' >>
339  
340 A smart keyword was called with a reference that's neither a hashref
341 (search) nor usable as a primary key.
342  
343 =item C<< %s is ambiguous; use <schema>_%s instead! >>
344  
345 The bare keyword is generated by more than one configured ORM; call the
346 schema-prefixed form instead.
347  
348 =back
349  
350 =head1 CONFIGURATION AND ENVIRONMENT
351  
352 Configure one or more named ORMs under C<plugins-E<gt>QuickORM> in your
353 Dancer2 config:
354  
355 plugins:
356 QuickORM:
357 default:
358 class: MyApp::ORM
359 dsn: "dbi:Pg:dbname=myapp"
360 reporting:
361 class: MyApp::ORM
362 dsn: "dbi:Pg:dbname=myapp_reporting"
363  
364 Each key under C<QuickORM> is an ORM name (C<default> is used when
365 C<orm()> is called without an argument); each value is a hashref that must
366 contain a C<class>, plus whatever other keys your ORM class needs.
367  
368 Every key/value pair in a given ORM's configuration (including C<class>
369 itself) is also copied into C<%ENV> as C<< QuickORM_<name>_<key> >>, and
370 the name itself is set as C<< QuickORM_<name>_name >>, so the ORM class's
371 C<orm()> constructor can pick up its configuration from the environment if
372 it prefers that to being passed arguments directly.
373  
374 The configured C<class> must implement the following L<DBIx::QuickORM> features:
375  
376 $class->orm($name) # -> connection object
377 $orm->schema($name)->tables # -> list of table objects
378 $table->name # -> table name string
379 $orm->handle($table_name) # -> handle object
380 $handle->by_id($id) # -> single row (hashref) or undef
381 $handle->where($hashref)->all # -> list of matching rows
382 $handle->all # -> list of every row
383  
384 =head1 DEPENDENCIES
385  
386 =over 4
387  
388 =item *
389  
390 L<Dancer2>, naturally.
391  
392 =item *
393  
394 L<DBIx::QuickORM>
395  
396 =item *
397  
398 L<Carp>,
399  
400 =item *
401  
402 L<Lingua::EN::Inflect::Phrase>
403  
404 =head1 BUGS AND LIMITATIONS
405  
406 Table names that singularise/pluralise to the same word as a Dancer2 core
407 DSL keyword or another already-registered keyword are only reachable via
408 their schema-prefixed keyword; see L</Keyword collisions>.
409  
410 For tables whose singular and plural forms are identical, an arrayref
411 argument is treated as a primary key value (passed straight through to the
412 backend) rather than being rejected outright, since it isn't a hashref and
413 isn't some other clearly-invalid reference type; whether that's a
414 meaningful primary key value is left to the configured ORM class.
415  
416 Please report any bugs or feature requests through the issue tracker for
417 this distribution.
418  
419 =head1 SEE ALSO
420  
421 L<Dancer2>, L<Dancer2::Plugin>, L<DBIx::QuickORM>
422  
423 =head1 AUTHOR
424  
425 D Ruth Holloway <ruth@hiruthie.me>
426  
427 =head1 COPYRIGHT AND LICENSE
428  
429 This software is copyright (c) 2026 by D Ruth Holloway.
430  
431 This is free software; you can redistribute it and/or modify it under
432 the same terms as the Perl 5 programming language system itself.
433  
434 =cut
435  
436 __END__
↑ Summary