C::M::DBIC::Schema - cleanups
[catagits/Catalyst-Model-DBIC-Schema.git] / lib / Catalyst / Helper / Model / DBIC / Schema.pm
1 package Catalyst::Helper::Model::DBIC::Schema;
2
3 use strict;
4 use warnings;
5 no warnings 'uninitialized';
6
7 our $VERSION = '0.24';
8
9 use parent 'Class::Accessor::Fast';
10
11 use Carp;
12 use UNIVERSAL::require;
13 use Tie::IxHash ();
14 use Data::Dumper ();
15 use List::Util ();
16
17 __PACKAGE__->mk_accessors(qw/
18   helper schema_class loader_args connect_info _old_schema
19 /);
20
21 =head1 NAME
22
23 Catalyst::Helper::Model::DBIC::Schema - Helper for DBIC Schema Models
24
25 =head1 SYNOPSIS
26
27   script/create.pl model CatalystModelName DBIC::Schema MyApp::SchemaClass \
28     [ create=dynamic | create=static ] [ roles=role1,role2... ] \
29     [ Schema::Loader opts ] [ dsn user pass ] \
30     [ other connect_info args ]
31
32 =head1 DESCRIPTION
33
34 Helper for the DBIC Schema Models.
35
36 =head2 Arguments:
37
38 C<CatalystModelName> is the short name for the Catalyst Model class
39 being generated (i.e. callable with C<$c-E<gt>model('CatalystModelName')>).
40
41 C<MyApp::SchemaClass> is the fully qualified classname of your Schema,
42 which might or might not yet exist.  Note that you should have a good
43 reason to create this under a new global namespace, otherwise use an
44 existing top level namespace for your schema class.
45
46 C<create=dynamic> instructs this Helper to generate the named Schema
47 class for you, basing it on L<DBIx::Class::Schema::Loader> (which
48 means the table information will always be dynamically loaded at
49 runtime from the database).
50
51 C<create=static> instructs this Helper to generate the named Schema
52 class for you, using L<DBIx::Class::Schema::Loader> in "one shot"
53 mode to create a standard, manually-defined L<DBIx::Class::Schema>
54 setup, based on what the Loader sees in your database at this moment.
55 A Schema/Model pair generated this way will not require
56 L<DBIx::Class::Schema::Loader> at runtime, and will not automatically
57 adapt itself to changes in your database structure.  You can edit
58 the generated classes by hand to refine them.
59
60 C<roles> is the list of roles to apply to the model, see
61 L<Catalyst::Model::DBIC::Schema> for details.
62
63 C<Schema::Loader opts> are described in L</TYPICAL EXAMPLES> below.
64
65 C<connect_info> arguments are the same as what
66 DBIx::Class::Schema::connect expects, and are storage_type-specific.
67 For DBI-based storage, these arguments are the dsn, username,
68 password, and connect options, respectively.  These are optional for
69 existing Schemas, but required if you use either of the C<create=>
70 options.
71
72 Use of either of the C<create=> options requires L<DBIx::Class::Schema::Loader>.
73
74 =head1 TYPICAL EXAMPLES
75
76   # Use DBIx::Class::Schema::Loader to create a static DBIx::Class::Schema,
77   #  and a Model which references it:
78   script/myapp_create.pl model CatalystModelName DBIC::Schema \
79     MyApp::SchemaClass create=static dbi:mysql:foodb myuname mypass
80
81   # Same, with extra connect_info args
82   script/myapp_create.pl model CatalystModelName DBIC::Schema \
83     MyApp::SchemaClass create=static dbi:SQLite:foo.db '' '' \
84     AutoCommit=1 cursor_class=DBIx::Class::Cursor::Cached \
85     on_connect_do='["select 1", "select 2"]'
86
87   # Same, but with extra Schema::Loader args (separate multiple values by commas):
88   script/myapp_create.pl model CatalystModelName DBIC::Schema \
89     MyApp::SchemaClass create=static db_schema=foodb components=Foo,Bar \
90     exclude='^wibble|wobble$' moniker_map='{ foo => "FFFFUUUU" }' \
91     dbi:Pg:dbname=foodb myuname mypass
92
93   # See DBIx::Class::Schema::Loader::Base for list of options
94
95   # Create a dynamic DBIx::Class::Schema::Loader-based Schema,
96   #  and a Model which references it:
97   script/myapp_create.pl model CatalystModelName DBIC::Schema \
98     MyApp::SchemaClass create=dynamic dbi:mysql:foodb myuname mypass
99
100   # Reference an existing Schema of any kind, and provide some connection information for ->config:
101   script/myapp_create.pl model CatalystModelName DBIC::Schema \
102     MyApp::SchemaClass dbi:mysql:foodb myuname mypass
103
104   # Same, but don't supply connect information yet (you'll need to do this
105   #  in your app config, or [not recommended] in the schema itself).
106   script/myapp_create.pl model ModelName DBIC::Schema My::SchemaClass
107
108 =head1 METHODS
109
110 =head2 mk_compclass
111
112 This is called by L<Catalyst::Helper> with the commandline args to generate the
113 files.
114
115 =cut
116
117 sub mk_compclass {
118     my ($package, $helper, $schema_class, @args) = @_;
119
120     my $self = $package->new;
121
122     $helper->{schema_class} = $schema_class
123         or croak "Must supply schema class name";
124
125     $self->schema_class($schema_class);
126     $self->helper($helper);
127
128     my $create = '';
129     if ($args[0] && $args[0] =~ /^create=(dynamic|static)\z/) {
130         $create = $1;
131         shift @args;
132
133         if ($args[0] && $args[0] =~ /^roles=(.*)\z/) {
134             $helper->{roles} = '['
135                 .(join ',' => map { qq{'$_'} } (split /,/ => $1))
136                 .']';
137             shift @args;
138         }
139
140         if (@args) {
141             $self->_parse_loader_args(\@args);
142
143             if (List::Util::first { /dbi:/ } @args) {
144                 $helper->{setup_connect_info} = 1;
145
146                 $helper->{connect_info} =
147                 $self->_build_helper_connect_info(\@args);
148
149                 $self->_parse_connect_info(\@args) if $create eq 'static';
150             }
151         }
152     }
153
154     $helper->{generator} = ref $self;
155     $helper->{generator_version} = $VERSION;
156
157     if ($create eq 'dynamic') {
158         $self->helper->{loader_args} = $self->_build_helper_loader_args;
159         $self->_gen_dynamic_schema;
160     } elsif ($create eq 'static') {
161         $self->_gen_static_schema;
162     }
163
164     $self->_gen_model;
165 }
166
167 sub _parse_loader_args {
168     my ($self, $args) = @_;
169
170     my %loader_args = $self->_read_loader_args($args);
171
172     while (my ($key, $val) = each %loader_args) {
173         next if $key =~ /^(?:components|constraint|exclude)\z/;
174
175         $loader_args{$key} = eval $val;
176         croak "syntax error for loader args key '$key' with value '$val': $@"
177             if $@;
178     }
179
180     my @components =
181     $self->_build_loader_components(delete $loader_args{components});
182
183     for my $re_opt (qw/constraint exclude/) {
184         $loader_args{$re_opt} = qr/$loader_args{$re_opt}/
185         if exists $loader_args{$re_opt};
186     }
187
188     tie my %result, 'Tie::IxHash';
189
190     %result = (
191         relationships => 1,
192         (%loader_args ? %loader_args : ()),
193         (!$self->_is_old_schema ? (
194                 use_namespaces => 1
195             ) : ()),
196         (@components ? (
197                 components => \@components
198             ) : ())
199     );
200
201     $self->loader_args(\%result);
202
203     wantarray ? %result : \%result;
204 }
205
206 sub _read_loader_args {
207     my ($self, $args) = @_;
208
209     my %loader_args;
210
211     while (@$args && $args->[0] !~ /^dbi:/) {
212         my ($key, $val) = split /=/, shift(@$args), 2;
213
214         if ((my @vals = split /,/ => $val) > 1) {
215             $loader_args{$key} = \@vals;
216         } else {
217             $loader_args{$key} = $val;
218         }
219     }
220
221     wantarray ? %loader_args : \%loader_args;
222 }
223
224 sub _build_helper_loader_args {
225     my $self = shift;
226
227     my $args = $self->loader_args;
228
229     tie my %loader_args, 'Tie::IxHash';
230
231     while (my ($arg, $val) = each %$args) {
232         if (ref $val) {
233             $loader_args{$arg} = $self->_data_struct_to_string($val);
234         } else {
235             $loader_args{$arg} = qq{'$val'};
236         }
237     }
238
239     \%loader_args
240 }
241
242 sub _build_loader_components {
243     my ($self, $components) = @_;
244
245     my @components = $self->_is_old_schema ? () : ('InflateColumn::DateTime');
246
247     if ($components) {
248         $components = [ $components ] if !ref $components;
249         push @components, @$components;
250     }
251
252     wantarray ? @components : \@components;
253 }
254
255 sub _build_helper_connect_info {
256     my ($self, $connect_info) = @_;
257
258     my @connect_info = @$connect_info;
259
260     my ($dsn, $user, $password) = splice @connect_info, 0, 3;
261
262     tie my %helper_connect_info, 'Tie::IxHash';
263
264     %helper_connect_info = (
265         dsn => qq{'$dsn'},
266         user => qq{'$user'},
267         password => qq{'$password'}
268     );
269
270     for (@connect_info) {
271         if (/^\s*{.*}\s*\z/) {
272             my $hash = eval $_;
273             croak "Syntax errorr in connect_info hash: $_: $@" if $@;
274             my %hash = %$hash;
275
276             for my $key (keys %hash) {
277                 my $val = $hash{$key};
278
279                 if (ref $val) {
280                     $val = $self->_data_struct_to_string($val);
281                 } else {
282                     $val = qq{'$val'};
283                 }
284
285                 $helper_connect_info{$key} = $val;
286             }
287
288             next;
289         }
290
291         my ($key, $val) = split /=/, $_, 2;
292
293         $helper_connect_info{$key} = $self->_quote_unless_struct($val);
294     }
295
296     \%helper_connect_info
297 }
298
299 sub _data_struct_to_string {
300     my ($self, $data) = @_;
301
302     local $Data::Dumper::Terse = 1;
303     local $Data::Dumper::Quotekeys = 0;
304     local $Data::Dumper::Indent = 0;
305     local $Data::Dumper::Useqq = 1;
306
307     return Data::Dumper->Dump([$data]);
308 }
309
310 sub _parse_connect_info {
311     my ($self, $connect_info) = @_;
312
313     my @connect_info = @$connect_info;
314
315     my ($dsn, $user, $password) = splice @connect_info, 0, 3;
316
317     tie my %connect_info, 'Tie::IxHash';
318     @connect_info{qw/dsn user password/} = ($dsn, $user, $password);
319
320     for (@connect_info) {
321         if (/^\s*{.*}\s*\z/) {
322             my $hash = eval $_;
323             croak "Syntax errorr in connect_info hash: $_: $@" if $@;
324
325             %connect_info = (%connect_info, %$hash);
326
327             next;
328         }
329
330         my ($key, $val) = split /=/, $_, 2;
331
332         $connect_info{$key} = eval $val;
333         croak "syntax error for connect_info key '$key' with value '$val': $@"
334             if $@;
335     }
336
337     $self->connect_info(\%connect_info);
338
339     \%connect_info
340 }
341
342 sub _quote_unless_struct {
343     my ($self, $val) = @_;
344
345     $val = qq{'$val'} if $val !~ /^\s*[[{]/;
346
347     $val;
348 }
349
350 sub _gen_dynamic_schema {
351     my $self = shift;
352
353     my $helper = $self->helper;
354
355     my @schema_parts = split(/\:\:/, $self->schema_class);
356     my $schema_file_part = pop @schema_parts;
357
358     my $schema_dir  = File::Spec->catfile(
359         $helper->{base}, 'lib', @schema_parts
360     );
361     my $schema_file = File::Spec->catfile(
362         $schema_dir, $schema_file_part . '.pm'
363     );
364
365     $helper->mk_dir($schema_dir);
366     $helper->render_file('schemaclass', $schema_file);
367 }
368
369 sub _gen_static_schema {
370     my $self = shift;
371
372     croak "cannot load schema without connect info" unless $self->connect_info;
373
374     my $helper = $self->helper;
375
376     my $schema_dir = File::Spec->catfile($helper->{base}, 'lib');
377
378     DBIx::Class::Schema::Loader->use(
379         "dump_to_dir:$schema_dir", 'make_schema_at'
380     ) or croak "Cannot load DBIx::Class::Schema::Loader: $@";
381
382     make_schema_at(
383         $self->schema_class,
384         $self->loader_args,
385         [$self->connect_info]
386     );
387 }
388
389 sub _is_old_schema {
390     my $self = shift;
391
392     return $self->_old_schema if defined $self->_old_schema;
393
394     my @schema_pm   = split '::', $self->schema_class;
395     $schema_pm[-1] .= '.pm';
396     my $schema_file =
397     File::Spec->catfile($self->helper->{base}, 'lib', @schema_pm);
398
399     if (-f $schema_file) {
400         my $schema_code = do { local (@ARGV, $/) = $schema_file; <> };
401         $self->_old_schema(1) if $schema_code =~ /->load_classes/;
402     } else {
403         $self->_old_schema(0);
404     }
405
406     return $self->_old_schema;
407 }
408
409 sub _gen_model {
410     my $self = shift;
411     my $helper = $self->helper;
412
413     $helper->render_file('compclass', $helper->{file} );
414 }
415
416 =head1 SEE ALSO
417
418 General Catalyst Stuff:
419
420 L<Catalyst::Manual>, L<Catalyst::Test>, L<Catalyst::Request>,
421 L<Catalyst::Response>, L<Catalyst::Helper>, L<Catalyst>,
422
423 Stuff related to DBIC and this Model style:
424
425 L<DBIx::Class>, L<DBIx::Class::Schema>,
426 L<DBIx::Class::Schema::Loader>, L<Catalyst::Model::DBIC::Schema>
427
428 =head1 AUTHOR
429
430 Brandon L Black, C<blblack@gmail.com>
431
432 Contributors:
433
434 Rafael Kitover, C<<rkitover at cpan.org>>
435
436 =head1 LICENSE
437
438 This library is free software, you can redistribute it and/or modify
439 it under the same terms as Perl itself.
440
441 =cut
442
443 1;
444
445 __DATA__
446
447 =begin pod_to_ignore
448
449 __schemaclass__
450 package [% schema_class %];
451
452 use strict;
453 use base qw/DBIx::Class::Schema::Loader/;
454
455 __PACKAGE__->loader_options(
456     [%- FOREACH key = loader_args.keys %]
457     [% key %] => [% loader_args.${key} %],
458     [%- END -%]
459
460 );
461
462 =head1 NAME
463
464 [% schema_class %] - L<DBIx::Class::Schema::Loader> class
465
466 =head1 SYNOPSIS
467
468 See L<[% app %]>
469
470 =head1 DESCRIPTION
471
472 Dynamic L<DBIx::Class::Schema::Loader> schema for use in L<[% class %]>
473
474 =head1 GENERATED BY
475
476 [% generator %] - [% generator_version %]
477
478 =head1 AUTHOR
479
480 [% author.replace(',+$', '') %]
481
482 =head1 LICENSE
483
484 This library is free software, you can redistribute it and/or modify
485 it under the same terms as Perl itself.
486
487 =cut
488
489 1;
490
491 __compclass__
492 package [% class %];
493
494 use strict;
495 use base 'Catalyst::Model::DBIC::Schema';
496
497 __PACKAGE__->config(
498     schema_class => '[% schema_class %]',
499     [% IF roles %]roles => [% roles %],[% END %]
500     [% IF setup_connect_info %]connect_info => {
501         [%- FOREACH key = connect_info.keys %]
502         [% key %] => [% connect_info.${key} %],
503         [%- END -%]
504
505     }[% END %]
506 );
507
508 =head1 NAME
509
510 [% class %] - Catalyst DBIC Schema Model
511
512 =head1 SYNOPSIS
513
514 See L<[% app %]>
515
516 =head1 DESCRIPTION
517
518 L<Catalyst::Model::DBIC::Schema> Model using schema L<[% schema_class %]>
519
520 =head1 GENERATED BY
521
522 [% generator %] - [% generator_version %]
523
524 =head1 AUTHOR
525
526 [% author.replace(',+$', '') %]
527
528 =head1 LICENSE
529
530 This library is free software, you can redistribute it and/or modify
531 it under the same terms as Perl itself.
532
533 =cut
534
535 1;