fix bug where non-result files were picked up for Moose check
[catagits/Catalyst-Model-DBIC-Schema.git] / lib / Catalyst / Helper / Model / DBIC / Schema.pm
1 package Catalyst::Helper::Model::DBIC::Schema;
2
3 use namespace::autoclean;
4 use Moose;
5 no warnings 'uninitialized';
6
7 our $VERSION = '0.44';
8 $VERSION = eval $VERSION;
9
10 use Carp;
11 use Tie::IxHash ();
12 use Data::Dumper ();
13 use List::Util 'first';
14 use MooseX::Types::Moose qw/Str HashRef Bool ArrayRef/;
15 use Catalyst::Model::DBIC::Schema::Types 'CreateOption';
16 use List::MoreUtils 'firstidx';
17 use Scalar::Util 'looks_like_number';
18 use File::Find 'finddepth';
19 use Try::Tiny;
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 ] [ traits=trait1,trait2... ] \
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<traits> is the list of traits 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 username and password can be omitted for C<SQLite> dsns.
73
74 Use of either of the C<create=> options requires L<DBIx::Class::Schema::Loader>.
75
76 =head1 TYPICAL EXAMPLES
77
78 Use DBIx::Class::Schema::Loader to create a static DBIx::Class::Schema,
79 and a Model which references it:
80
81   script/myapp_create.pl model CatalystModelName DBIC::Schema \
82     MyApp::SchemaClass create=static dbi:mysql:foodb myuname mypass
83
84 Same, with extra connect_info args
85 user and pass can be omitted for sqlite, since they are always empty
86
87   script/myapp_create.pl model CatalystModelName DBIC::Schema \
88     MyApp::SchemaClass create=static dbi:SQLite:foo.db \
89     AutoCommit=1 cursor_class=DBIx::Class::Cursor::Cached \
90     on_connect_do='["select 1", "select 2"]' quote_char='"'
91
92 If using a 2 character quote_char:
93
94   script/myapp_create.pl ... quote_char='[]'
95
96 B<ON WINDOWS COMMAND LINES QUOTING RULES ARE DIFFERENT>
97
98 In C<cmd.exe> the above example would be:
99
100   script/myapp_create.pl model CatalystModelName DBIC::Schema \
101     MyApp::SchemaClass create=static dbi:SQLite:foo.db \
102     AutoCommit=1 cursor_class=DBIx::Class::Cursor::Cached \
103     on_connect_do="[\"select 1\", \"select 2\"]" quote_char="\""
104
105 Same, but with extra Schema::Loader args (separate multiple values by commas):
106
107   script/myapp_create.pl model CatalystModelName DBIC::Schema \
108     MyApp::SchemaClass create=static db_schema=foodb components=Foo,Bar \
109     exclude='^(wibble|wobble)$' moniker_map='{ foo => "FOO" }' \
110     dbi:Pg:dbname=foodb myuname mypass
111
112 Coderefs are also supported:
113
114   script/myapp_create.pl model CatalystModelName DBIC::Schema \
115     MyApp::SchemaClass create=static \
116     inflect_singular='sub { $_[0] =~ /\A(.+?)(_id)?\z/; $1 }' \
117     moniker_map='sub { join(q{}, map ucfirst, split(/[\W_]+/, lc $_[0])); }' \
118     dbi:mysql:foodb myuname mypass
119
120 See L<DBIx::Class::Schema::Loader::Base> for a list of options
121
122 Create a dynamic DBIx::Class::Schema::Loader-based Schema,
123 and a Model which references it (B<DEPRECATED>):
124
125   script/myapp_create.pl model CatalystModelName DBIC::Schema \
126     MyApp::SchemaClass create=dynamic dbi:mysql:foodb myuname mypass
127
128 Reference an existing Schema of any kind, and provide some connection information for ->config:
129
130   script/myapp_create.pl model CatalystModelName DBIC::Schema \
131     MyApp::SchemaClass dbi:mysql:foodb myuname mypass
132
133 Same, but don't supply connect information yet (you'll need to do this
134 in your app config, or [not recommended] in the schema itself).
135
136   script/myapp_create.pl model ModelName DBIC::Schema My::SchemaClass
137
138 =cut
139
140 has helper => (is => 'ro', isa => 'Catalyst::Helper', required => 1);
141 has create => (is => 'rw', isa => CreateOption);
142 has args => (is => 'ro', isa => ArrayRef);
143 has traits => (is => 'rw', isa => ArrayRef);
144 has schema_class => (is => 'ro', isa => Str, required => 1);
145 has loader_args => (is => 'rw', isa => HashRef);
146 has connect_info => (is => 'rw', isa => HashRef);
147 has old_schema => (is => 'rw', isa => Bool, lazy_build => 1);
148 has is_moose_schema => (is => 'rw', isa => Bool, lazy_build => 1);
149 has components => (is => 'rw', isa => ArrayRef);
150
151 =head1 METHODS
152
153 =head2 mk_compclass
154
155 This is called by L<Catalyst::Helper> with the commandline args to generate the
156 files.
157
158 =cut
159
160 sub mk_compclass {
161     my ($package, $helper, $schema_class, @args) = @_;
162
163     my $self = $package->new(
164         helper => $helper,
165         schema_class => $schema_class,
166         args => \@args
167     );
168
169     $self->run;
170 }
171
172 sub BUILD {
173     my $self   = shift;
174     my $helper = $self->helper;
175     my @args   = @{ $self->args || [] };
176
177     $helper->{schema_class} = $self->schema_class;
178
179     @args = $self->_cleanup_args(\@args);
180
181     my ($traits_idx, $traits);
182     if (($traits_idx = firstidx { ($traits) = /^traits=(\S*)\z/ } @args) != -1) {
183         my @traits = split /,/ => $traits;
184
185         $self->traits(\@traits);
186
187         $helper->{traits} = '['
188             .(join ',' => map { qq{'$_'} } @traits)
189             .']';
190
191         splice @args, $traits_idx, 1, ();
192     }
193
194     if ($args[0] && $args[0] =~ /^create=(\S*)\z/) {
195         $self->create($1);
196         shift @args;
197
198         if (@args) {
199             $self->_parse_loader_args(\@args);
200
201             $helper->{loader_args} = $self->_build_helper_loader_args;
202         }
203     }
204
205     my $dbi_dsn_part;
206     if (first { ($dbi_dsn_part) = /^(dbi):/i } @args) {
207         die
208 qq{DSN must start with 'dbi:' not '$dbi_dsn_part' (case matters!)}
209             if $dbi_dsn_part ne 'dbi';
210
211         $helper->{setup_connect_info} = 1;
212
213         $helper->{connect_info} =
214             $self->_build_helper_connect_info(\@args);
215
216         $self->_parse_connect_info(\@args);
217     }
218
219     $helper->{generator} = ref $self;
220     $helper->{generator_version} = $VERSION;
221 }
222
223 =head2 run
224
225 Can be called on an instance to generate the files.
226
227 =cut
228
229 sub run {
230     my $self = shift;
231
232     if ($self->create eq 'dynamic') {
233         $self->_print_dynamic_deprecation_warning;
234         $self->_gen_dynamic_schema;
235     } elsif ($self->create eq 'static') {
236         $self->_gen_static_schema;
237     }
238
239     $self->_gen_model;
240 }
241
242 sub _parse_loader_args {
243     my ($self, $args) = @_;
244
245     my %loader_args = $self->_read_loader_args($args);
246
247     while (my ($key, $val) = each %loader_args) {
248         next if $key =~ /^(?:components|constraint|exclude)\z/;
249
250         $loader_args{$key} = $self->_eval($val);
251         die "syntax error for loader args key '$key' with value '$val': $@"
252             if $@;
253     }
254
255     my @components = $self->_build_loader_components(
256         delete $loader_args{components},
257         $loader_args{use_namespaces},
258     );
259
260     $self->components(\@components);
261
262     for my $re_opt (qw/constraint exclude/) {
263         $loader_args{$re_opt} = qr/$loader_args{$re_opt}/
264         if exists $loader_args{$re_opt};
265     }
266
267     tie my %result, 'Tie::IxHash';
268
269     %result = (
270         relationships => 1,
271         use_moose => $self->is_moose_schema ? 1 : 0,
272         col_collision_map => 'column_%s',
273         (!$self->old_schema ? (
274                 use_namespaces => 1
275             ) : ()),
276         (@components ? (
277                 components => \@components
278             ) : ()),
279         (%loader_args ? %loader_args : ()),
280     );
281
282     $self->loader_args(\%result);
283
284     wantarray ? %result : \%result;
285 }
286
287 sub _read_loader_args {
288     my ($self, $args) = @_;
289
290     my %loader_args;
291
292     while (@$args && $args->[0] !~ /^dbi:/i) {
293         my ($key, $val) = split /=/, shift(@$args), 2;
294
295         if ($self->_is_struct($val)) {
296             $loader_args{$key} = $val;
297         } elsif ((my @vals = split /,/ => $val) > 1) {
298             $loader_args{$key} = \@vals;
299         } else {
300             $loader_args{$key} = $val;
301         }
302     }
303
304     wantarray ? %loader_args : \%loader_args;
305 }
306
307 sub _build_helper_loader_args {
308     my $self = shift;
309
310     my $args = $self->loader_args;
311
312     tie my %loader_args, 'Tie::IxHash';
313
314     while (my ($arg, $val) = each %$args) {
315         if (ref $val) {
316             $loader_args{$arg} = $self->_data_struct_to_string($val);
317         } else {
318             $loader_args{$arg} = qq{'$val'};
319         }
320     }
321
322     \%loader_args
323 }
324
325 sub _build_loader_components {
326     my ($self, $components, $use_namespaces) = @_;
327
328     my @components = $self->old_schema && (not $use_namespaces) ? ()
329         : ('InflateColumn::DateTime');
330
331     if ($components) {
332         $components = [ $components ] if !ref $components;
333         push @components, @$components;
334     }
335
336     wantarray ? @components : \@components;
337 }
338
339 sub _build_helper_connect_info {
340     my ($self, $connect_info) = @_;
341
342     my @connect_info = @$connect_info;
343
344     my ($dsn, $user, $password) = $self->_get_dsn_user_pass(\@connect_info);
345
346     tie my %helper_connect_info, 'Tie::IxHash';
347
348     %helper_connect_info = (
349         dsn => qq{'$dsn'},
350         user => qq{'$user'},
351         password => qq{'$password'}
352     );
353
354     for (@connect_info) {
355         if (/^\s*{.*}\s*\z/) {
356             my $hash = $self->_eval($_);
357             die "Syntax errorr in connect_info hash: $_: $@" if $@;
358             my %hash = %$hash;
359
360             for my $key (keys %hash) {
361                 my $val = $hash{$key};
362
363                 if (ref $val) {
364                     $val = $self->_data_struct_to_string($val);
365                 } else {
366                     $val = $self->_quote($val);
367                 }
368
369                 $helper_connect_info{$key} = $val;
370             }
371
372             next;
373         }
374
375         my ($key, $val) = split /=/, $_, 2;
376
377         if ($key eq 'quote_char') {
378             $helper_connect_info{$key} = length($val) == 1 ?
379                 $self->_quote($val) :
380                 $self->_data_struct_to_string([split //, $val]);
381         } else {
382             $helper_connect_info{$key} = $self->_quote_unless_struct($val);
383         }
384     }
385
386     \%helper_connect_info
387 }
388
389 sub _build_old_schema {
390     my $self = shift;
391
392     my @schema_pm   = split '::', $self->schema_class;
393     $schema_pm[-1] .= '.pm';
394     my $schema_file =
395     File::Spec->catfile($self->helper->{base}, 'lib', @schema_pm);
396
397     if (-f $schema_file) {
398         my $schema_code = do { local (@ARGV, $/) = $schema_file; <> };
399         return 1 if $schema_code =~ /->load_classes/;
400     }
401
402     0;
403 }
404
405 sub _build_is_moose_schema {
406     my $self = shift;
407
408     my @schema_parts = split '::', $self->schema_class;
409     my $schema_dir =
410         File::Spec->catfile($self->helper->{base}, 'lib', @schema_parts);
411
412     # assume yes for new schemas
413     return 1 if not -d $schema_dir;
414
415     my $uses_moose = 1;
416
417     try {
418         finddepth(sub {
419             return if $File::Find::name !~ /\.pm\z/;
420
421             open my $fh, '<', $File::Find::name
422                 or die "Could not open $File::Find::name: $!";
423
424             my $code = do { local $/; <$fh> };
425             close $fh;
426
427             $uses_moose = 0 if $code !~ /\nuse Moose;\n/;
428
429             die;
430         }, $schema_dir);
431     };
432
433     return $uses_moose;
434 }
435
436 sub _data_struct_to_string {
437     my ($self, $data) = @_;
438
439     local $Data::Dumper::Terse = 1;
440     local $Data::Dumper::Quotekeys = 0;
441     local $Data::Dumper::Indent = 0;
442     local $Data::Dumper::Useqq = 1;
443
444     return Data::Dumper->Dump([$data]);
445 }
446
447 sub _get_dsn_user_pass {
448     my ($self, $connect_info) = @_;
449
450     my $dsn = shift @$connect_info;
451     my ($user, $password);
452
453     if ($dsn =~ /sqlite/i) {
454         ($user, $password) = ('', '');
455         shift @$connect_info while @$connect_info and $connect_info->[0] eq '';
456     } else {
457         ($user, $password) = splice @$connect_info, 0, 2;
458     }
459     
460     ($dsn, $user, $password)
461 }
462
463 sub _parse_connect_info {
464     my ($self, $connect_info) = @_;
465
466     my @connect_info = @$connect_info;
467
468     my ($dsn, $user, $password) = $self->_get_dsn_user_pass(\@connect_info);
469
470     tie my %connect_info, 'Tie::IxHash';
471     @connect_info{qw/dsn user password/} = ($dsn, $user, $password);
472
473     for (@connect_info) {
474         if (/^\s*{.*}\s*\z/) {
475             my $hash = $self->_eval($_);
476             die "Syntax errorr in connect_info hash: $_: $@" if $@;
477
478             %connect_info = (%connect_info, %$hash);
479
480             next;
481         }
482
483         my ($key, $val) = split /=/, $_, 2;
484
485         if ($key eq 'quote_char') {
486             $connect_info{$key} = length($val) == 1 ? $val : [split //, $val];
487         } elsif ($key =~ /^(?:name_sep|limit_dialect)\z/) {
488             $connect_info{$key} = $val;
489         } else {
490             $connect_info{$key} = $self->_eval($val);
491         }
492
493         die "syntax error for connect_info key '$key' with value '$val': $@"
494             if $@;
495     }
496
497     $self->connect_info(\%connect_info);
498
499     \%connect_info
500 }
501
502 sub _is_struct {
503     my ($self, $val) = @_;
504
505     return $val =~ /^\s*(?:sub|[[{])/;
506 }
507
508 sub _quote {
509     my ($self, $val) = @_;
510
511     return 'q{'.$val.'}';
512 }
513
514 sub _quote_unless_struct {
515     my ($self, $val) = @_;
516
517     $val = $self->_quote($val) if not $self->_is_struct($val);
518
519     return $val;
520 }
521
522 sub _eval {
523     my ($self, $code) = @_;
524
525     return $code if looks_like_number $code;
526
527     return $code if not $self->_is_struct($code);
528
529     return eval "{no strict; $code}";
530 }
531
532 sub _gen_dynamic_schema {
533     my $self = shift;
534
535     my $helper = $self->helper;
536
537     my @schema_parts = split(/\:\:/, $self->schema_class);
538     my $schema_file_part = pop @schema_parts;
539
540     my $schema_dir  = File::Spec->catfile(
541         $helper->{base}, 'lib', @schema_parts
542     );
543     my $schema_file = File::Spec->catfile(
544         $schema_dir, $schema_file_part . '.pm'
545     );
546
547     $helper->mk_dir($schema_dir);
548     $helper->render_file('schemaclass', $schema_file);
549 }
550
551 sub _gen_static_schema {
552     my $self = shift;
553
554     die "cannot load schema without connect info" unless $self->connect_info;
555
556     my $helper = $self->helper;
557
558     my $schema_dir = File::Spec->catfile($helper->{base}, 'lib');
559
560     eval { Class::MOP::load_class('DBIx::Class::Schema::Loader') };
561     die "Cannot load DBIx::Class::Schema::Loader: $@" if $@;
562
563     DBIx::Class::Schema::Loader->import(
564         "dump_to_dir:$schema_dir", 'make_schema_at'
565     );
566
567     make_schema_at(
568         $self->schema_class,
569         $self->loader_args,
570         [$self->connect_info]
571     );
572 }
573
574 sub _gen_model {
575     my $self = shift;
576     my $helper = $self->helper;
577
578     $helper->render_file('compclass', $helper->{file} );
579 }
580
581 sub _print_dynamic_deprecation_warning {
582     warn <<EOF;
583 ************************************ WARNING **********************************
584 * create=dynamic is DEPRECATED, please use create=static instead.             *
585 *******************************************************************************
586 EOF
587     print "Continue? [y/n]: ";
588     chomp(my $response = <STDIN>);
589     exit 0 if $response =~ /^n(o)?\z/;
590 }
591
592 sub _cleanup_args {
593     my ($self, $args) = @_;
594
595 # remove blanks, ie. someoned doing foo \  bar
596     my @res = grep !/^\s+\z/, @$args;
597
598 # remove leading whitespace, ie. foo \ bar
599     s/^\s*// for @res;
600
601     @res
602 }
603
604 =head1 SEE ALSO
605
606 General Catalyst Stuff:
607
608 L<Catalyst::Manual>, L<Catalyst::Test>, L<Catalyst::Request>,
609 L<Catalyst::Response>, L<Catalyst::Helper>, L<Catalyst>,
610
611 Stuff related to DBIC and this Model style:
612
613 L<DBIx::Class>, L<DBIx::Class::Schema>,
614 L<DBIx::Class::Schema::Loader>, L<Catalyst::Model::DBIC::Schema>
615
616 =head1 AUTHOR
617
618 See L<Catalyst::Model::DBIC::Schema/AUTHOR> and
619 L<Catalyst::Model::DBIC::Schema/CONTRIBUTORS>.
620
621 =head1 COPYRIGHT
622
623 See L<Catalyst::Model::DBIC::Schema/COPYRIGHT>.
624
625 =head1 LICENSE
626
627 This library is free software, you can redistribute it and/or modify
628 it under the same terms as Perl itself.
629
630 =cut
631
632 1;
633
634 __DATA__
635
636 =begin pod_to_ignore
637
638 __schemaclass__
639 package [% schema_class %];
640
641 use strict;
642 use base qw/DBIx::Class::Schema::Loader/;
643
644 __PACKAGE__->loader_options(
645     [%- FOREACH key = loader_args.keys %]
646     [% key %] => [% loader_args.${key} %],
647     [%- END -%]
648
649 );
650
651 =head1 NAME
652
653 [% schema_class %] - L<DBIx::Class::Schema::Loader> class
654
655 =head1 SYNOPSIS
656
657 See L<[% app %]>
658
659 =head1 DESCRIPTION
660
661 Dynamic L<DBIx::Class::Schema::Loader> schema for use in L<[% class %]>
662
663 =head1 GENERATED BY
664
665 [% generator %] - [% generator_version %]
666
667 =head1 AUTHOR
668
669 [% author.replace(',+$', '') %]
670
671 =head1 LICENSE
672
673 This library is free software, you can redistribute it and/or modify
674 it under the same terms as Perl itself.
675
676 =cut
677
678 1;
679
680 __compclass__
681 package [% class %];
682
683 use strict;
684 use base 'Catalyst::Model::DBIC::Schema';
685
686 __PACKAGE__->config(
687     schema_class => '[% schema_class %]',
688     [% IF traits %]traits => [% traits %],[% END %]
689     [% IF setup_connect_info %]connect_info => {
690         [%- FOREACH key = connect_info.keys %]
691         [% key %] => [% connect_info.${key} %],
692         [%- END -%]
693
694     }[% END %]
695 );
696
697 =head1 NAME
698
699 [% class %] - Catalyst DBIC Schema Model
700
701 =head1 SYNOPSIS
702
703 See L<[% app %]>
704
705 =head1 DESCRIPTION
706
707 L<Catalyst::Model::DBIC::Schema> Model using schema L<[% schema_class %]>
708
709 =head1 GENERATED BY
710
711 [% generator %] - [% generator_version %]
712
713 =head1 AUTHOR
714
715 [% author.replace(',+$', '') %]
716
717 =head1 LICENSE
718
719 This library is free software, you can redistribute it and/or modify
720 it under the same terms as Perl itself.
721
722 =cut
723
724 1;
725 __END__
726 # vim:sts=4 sw=4: