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