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