DBIx.pm

filter: Statementstmt 75.0% 6 / 8 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 81.8% 9 / 11 CC 1 SCAR 0.9
CC
1
Cov
75%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« DBIx/Command/schema_load.pm ↑ Summary
1 package Mojolicious::Plugin::ORM::DBIx 0.02;
2 1 ▶use v5.26;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 # ABSTRACT: Easily load and access DBIx::Class functionality in Mojolicious apps
6  
7 =encoding UTF-8
8
9 =head1 NAME
10
11 Mojolicious::Plugin::ORM::DBix - Easily load and access DBIx::Class functionality in Mojolicious apps
12
13 =head1 SYNOPSIS
14  
15 # Register plugin
16 $self->plugin('ORM::DBIx' => {
17 dsn => $conf->{dsn},
18 username => $conf->{user},
19 password => $conf->{pass},
20 });
21  
22 ...
23  
24 # access in controller
25 sub get_user($self) {
26 my $user = $self->model("User")->find($self->req->param('id'));
27 $self->render(json => {user => $user->username});
28 }
29  
30 ..
31  
32 # use from command-line during development, following schema migration
33
34 tyrrminal@devserver:/app$ script/myapp schema-load --noquiet
35 Dumping manual schema for Myapp::Model to directory /app/lib ...
36 Schema dump completed.
37  
38 =head1 DESCRIPTION
39  
40 Mojolicious::Plugin::ORM::DBIx streamlines the process of getting DBIC classes
41 generated and accessible from within a Mojolicious application.
42  
43 =head1 METHODS
44  
45 L<Mojolicious::Plugin::ORM::DBIx> inherits all methods from L<Mojolicious::Plugin>
46 and implements the following new ones
47  
48 =cut
49  
50 0 ▶use Mojo::Base 'Mojolicious::Plugin';
Subroutine BEGIN: called CC=1 SCAR=2.6
51  
52 use DBIx::Class::Schema::Loader qw(make_schema_at);
53 use Mojo::Util qw(class_to_path);
54 use Module::Load::Conditional qw(check_install);
55 use Readonly;
56 use Syntax::Keyword::Try;
57 use version;
58  
59 use experimental qw(signatures);
60  
61 Readonly::Scalar my $DEFAULT_DSN => 'dbi:SQLite:dbname=:memory:';
62 Readonly::Array my @DEFAULT_DBIX_COMPONENTS => qw(Relationship::Predicate InflateColumn::DateTime);
63  
64 =pod
65  
66 =head2 register( $args )
67  
68 Register plugin in L<Mojolicious> application. The following keys are supported
69 in C<$args>
70  
71 =head4 dsn
72  
73 The L<data source name|https://en.wikipedia.org/wiki/Data_source_name> for connecting
74 to the database. Defaults to C<dbi:SQLite:dbname=:memory:> if omitted.
75  
76 =head4 namespace
77  
78 The perl class name of the root schema object for the application. Defaults to
79 C<$Moniker::Model> if omitted, where C<$Moniker> is the mojolicious moniker with the
80 first letter capitalized. This class does not need to be manually created, as
81 L</run_schema_load> can create it along with the rest of the schema.
82  
83 =head4 username
84  
85 The database connection username
86  
87 =head4 password
88  
89 The database connection password
90  
91 =head4 connect_params
92  
93 An optional HashRef of additional connection parameters to be passed to DBI at
94 connection time.
95  
96 I<The following parameters pertain to DBIx schema loader code generation>
97  
98 =head4 lib
99  
100 The directory where the schema loader files will be written to.
101 Default C<$MOJO_HOME/lib>
102  
103 =head4 codegen_filters
104  
105 An optional ordered ArrayRef of functions for filtering/modifying the code
106 generated by the schema loader. See
107 L<DBIx::Class::Schema::Loader::Base/filter_generated_code> for details.
108  
109 =head4 overwrite
110  
111 A proxy value for L<DBIx::Class::Schema::Loader::Base/overwrite_modifications>.
112 B<N.B.> defaults to true
113  
114 =head4 feature_bundle
115  
116 When generating code, add a C<use vX.XX;> line near the end of the file, such
117 that it applies to manual additions to the Result class files (but not to the
118 generated code itself). Defaults to the perl version being used to generate the
119 code. Any value that is not a valid perl
120 L<version|https://perldoc.perl.org/version> will cause this option to be disabled
121 with a warning written to the mojolicious log. Pass undef to disable this option
122 without a warning.
123  
124 See L<FEATURE-BUNDLES|https://perldoc.perl.org/feature#FEATURE-BUNDLES> for
125 more information on valid values.
126  
127 If enabled, this line is added to the code before running any custom
128 L</codegen_filters>
129  
130 =head4 tidy_format_skipping
131  
132 When using L<Perl::Tidy> you may wind up with formatting disagreements between
133 the generated code and perltidy's ruleset. This option allows you to add lines
134 around the generated code to disable perltidy formatting, while leaving it
135 enabled for any custom code added to the end of the Result class files.
136  
137 Takes an ArrayRef containing two strings: C<[$disable_formatting, $enable_formatting]>.
138 Default is C<['#E<lt>E<lt>E<lt>','#E<gt>E<gt>E<gt>']>
139  
140 See L<https://perltidy.sourceforge.net/perltidy.html#Skipping-Selected-Sections-of-Code>.
141  
142 Pass undef to disable this behavior.
143  
144 If enabled, these lines are added after running any custom L</codegen_filters>
145  
146 =head4 dbix_components
147  
148 An optional ArrayRef of DBIx components to load into generated classes. Defaults
149 to C<[>L<InflateColumn::DateTime|DBIx::Class::InflateColumn::DateTime>C<,>L<Relationship::Predicate|DBIx::Class::Relationship::Predicate>C<]>
150  
151 The defaults will be prepended to the contents of the passed ArrayRef; to
152 circumvent this behavior, pass C<undef> as the first element of the array.
153  
154 =head4 loader_options
155  
156 An optional HashRef of additional parameters to pass to
157 L<DBIx::Class::Schema::Loader/make_schema_at>. See
158 L<DBIx::Class::Schema::Loader::Base> for possible values and their meanings.
159  
160 =cut
161  
162 sub register($self, $app, $conf) {
163 push($app->commands->namespaces->@*, 'Mojolicious::Plugin::ORM::DBIx::Command');
164 my $conf_dbix_components = $conf->{dbix_components} // [];
165  
166 my @credentials = grep {defined} ($conf->{username}, $conf->{password});
167 my $model_directory = $conf->{lib} // $app->home->child('lib')->to_string;
168 my $dsn = $conf->{dsn} // $DEFAULT_DSN;
169 my $namespace = $conf->{namespace} // join(q{::}, ucfirst($app->moniker), 'Model');
170 my $connect_params = $conf->{connect_params} // {};
171 my $codegen_filters = $conf->{codegen_filters} // [];
172 my $overwrite = $conf->{overwrite} // 1;
173 my $loader_options = $conf->{loader_options} // {};
174 my $feature_bundle = $conf->{feature_bundle} // (exists($conf->{feature_bundle}) ? undef : "$^V");
175 my $tidy_fs = $conf->{tidy_format_skipping} // (exists($conf->{tidy_format_skipping}) ? undef : ['#<<<', '#>>>']);
176 my $dbix_components = [@DEFAULT_DBIX_COMPONENTS, $conf_dbix_components->@*];
177 splice($dbix_components->@*, 0, scalar(@DEFAULT_DBIX_COMPONENTS))
178 if (scalar($conf_dbix_components->@*) && !defined($conf_dbix_components->[0]));
179  
180 try {
181 version->declare($feature_bundle); #ensure feature_bundle is a properly-formed version number/string
182 } catch ($e) {
183 $app->log->warn("ORM::DBIx ignoring feature_bundle due to invalid version format: $feature_bundle");
184 $feature_bundle = undef;
185 }
186  
187 my $schema;
188 if (check_install(module => $namespace)) {
189 require(class_to_path($namespace));
190 $schema = $namespace->connect($dsn, @credentials, $connect_params);
191 } else {
192 $app->log->fatal(
193 "ORM::DBIx error: '$namespace' could not be loaded. ORM functions unavailable; do you need to run schema-load?");
194 }
195  
196 =pod
197  
198 =head2 db
199  
200 Returns the root schema object for the application, a subclass of L<DBIx::Class::Schema>
201  
202 =cut
203  
204 $app->helper(
205 db => sub($c) {
206 return $schema;
207 }
208 );
209  
210 =pod
211  
212 =head2 model( $model_name )
213  
214 Returns the resultset object for the specified model name. Identical to C<app-E<gt>db-E<gt>resultset($model_name)>
215  
216 =cut
217  
218 $app->helper(
219 model => sub($c, $model) {
220 return undef unless (defined($schema));
221 return $schema->resultset($model);
222 }
223 );
224  
225 =pod
226  
227 =head2 run_schema_load( $debug, $quiet )
228  
229 Generate (or regenerate) model classes from database schema. More or less, this
230 just runs L<DBIx::Class::Schema::Loader/make_schema_at> with options set at the
231 time of plugin registration.
232  
233 Parameters:
234  
235 =head4 $debug
236  
237 Write generated classes to C<STDERR>. Default: false
238  
239 See L<DBIx::Class::Schema::Loader::Base/debug>
240  
241 =head4 $quiet
242  
243 Don't print the C<Dumping manual schema...>, C<Schema dump completed> messages.
244 Default: true
245  
246 See L<DBIx::Class::Schema::Loader::Base/quiet>
247  
248 =cut
249  
250 $app->helper(
251 run_schema_load => sub($c, $debug = 0, $quiet = 1) {
252 $c->log->debug("Creating model from database schema");
253 my @filters = $codegen_filters->@*;
254 if (defined($feature_bundle)) {
255 unshift(@filters, sub($type, $class, $text) {$text .= sprintf("\nuse %s;", $feature_bundle)});
256 }
257 if (defined($tidy_fs)) {
258 my ($end, $start) = (reverse($tidy_fs->@*))[0, 1];
259 push(@filters, sub($type, $class, $text) {join("\n", $start, $text, $end)});
260 }
261 make_schema_at(
262 $namespace, {
263 $loader_options->%*,
264 debug => $debug,
265 quiet => $quiet,
266 overwrite_modifications => $overwrite,
267 dump_directory => $model_directory,
268 components => $dbix_components,
269 filter_generated_code => sub ($type, $class, $text) {
270 $text = $_->($type, $class, $text) foreach (@filters);
271 return $text;
272 },
273 },
274 [$dsn, @credentials]
275 );
276 }
277 );
278  
279 }
280  
281 =pod
282  
283 =head1 COMMANDS
284  
285 =head2 schema-load [--debug] [--[no]quiet]
286  
287 Mojolicious command to execute L</run_schema_load>
288  
289 =head1 AUTHOR
290  
291 Mark Tyrrell C<< <mark@tyrrminal.dev> >>
292  
293 =head1 LICENSE
294  
295 Copyright (c) 2024 Mark Tyrrell
296  
297 Permission is hereby granted, free of charge, to any person obtaining a copy
298 of this software and associated documentation files (the "Software"), to deal
299 in the Software without restriction, including without limitation the rights
300 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
301 copies of the Software, and to permit persons to whom the Software is
302 furnished to do so, subject to the following conditions:
303  
304 The above copyright notice and this permission notice shall be included in all
305 copies or substantial portions of the Software.
306  
307 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
308 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
309 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
310 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
311 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
312 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
313 SOFTWARE.
314  
315 =cut
316  
317 1;
318  
319 __END__
« DBIx/Command/schema_load.pm ↑ Summary