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