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