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