DBIC::Schema - add tests for helper
[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 sub run {
204     my $self = shift;
205
206     if ($self->create eq 'dynamic') {
207         $self->_print_dynamic_deprecation_warning;
208         $self->_gen_dynamic_schema;
209     } elsif ($self->create eq 'static') {
210         $self->_gen_static_schema;
211     }
212
213     $self->_gen_model;
214 }
215
216 sub _parse_loader_args {
217     my ($self, $args) = @_;
218
219     my %loader_args = $self->_read_loader_args($args);
220
221     while (my ($key, $val) = each %loader_args) {
222         next if $key =~ /^(?:components|constraint|exclude)\z/;
223
224         $loader_args{$key} = eval $val;
225         die "syntax error for loader args key '$key' with value '$val': $@"
226             if $@;
227     }
228
229     my @components =
230     $self->_build_loader_components(delete $loader_args{components});
231
232     $self->components(\@components);
233
234     for my $re_opt (qw/constraint exclude/) {
235         $loader_args{$re_opt} = qr/$loader_args{$re_opt}/
236         if exists $loader_args{$re_opt};
237     }
238
239     tie my %result, 'Tie::IxHash';
240
241     %result = (
242         relationships => 1,
243         (%loader_args ? %loader_args : ()),
244         (!$self->old_schema ? (
245                 use_namespaces => 1
246             ) : ()),
247         (@components ? (
248                 components => \@components
249             ) : ())
250     );
251
252     $self->loader_args(\%result);
253
254     wantarray ? %result : \%result;
255 }
256
257 sub _read_loader_args {
258     my ($self, $args) = @_;
259
260     my %loader_args;
261
262     while (@$args && $args->[0] !~ /^dbi:/) {
263         my ($key, $val) = split /=/, shift(@$args), 2;
264
265         if ($self->_is_struct($val)) {
266             $loader_args{$key} = $val;
267         } elsif ((my @vals = split /,/ => $val) > 1) {
268             $loader_args{$key} = \@vals;
269         } else {
270             $loader_args{$key} = $val;
271         }
272     }
273
274     wantarray ? %loader_args : \%loader_args;
275 }
276
277 sub _build_helper_loader_args {
278     my $self = shift;
279
280     my $args = $self->loader_args;
281
282     tie my %loader_args, 'Tie::IxHash';
283
284     while (my ($arg, $val) = each %$args) {
285         if (ref $val) {
286             $loader_args{$arg} = $self->_data_struct_to_string($val);
287         } else {
288             $loader_args{$arg} = qq{'$val'};
289         }
290     }
291
292     \%loader_args
293 }
294
295 sub _build_loader_components {
296     my ($self, $components) = @_;
297
298     my @components = $self->old_schema ? () : ('InflateColumn::DateTime');
299
300     if ($components) {
301         $components = [ $components ] if !ref $components;
302         push @components, @$components;
303     }
304
305     wantarray ? @components : \@components;
306 }
307
308 sub _build_helper_connect_info {
309     my ($self, $connect_info) = @_;
310
311     my @connect_info = @$connect_info;
312
313     my ($dsn, $user, $password) = $self->_get_dsn_user_pass(\@connect_info);
314
315     tie my %helper_connect_info, 'Tie::IxHash';
316
317     %helper_connect_info = (
318         dsn => qq{'$dsn'},
319         user => qq{'$user'},
320         password => qq{'$password'}
321     );
322
323     for (@connect_info) {
324         if (/^\s*{.*}\s*\z/) {
325             my $hash = eval $_;
326             die "Syntax errorr in connect_info hash: $_: $@" if $@;
327             my %hash = %$hash;
328
329             for my $key (keys %hash) {
330                 my $val = $hash{$key};
331
332                 if (ref $val) {
333                     $val = $self->_data_struct_to_string($val);
334                 } else {
335                     $val = 'q{'.$val.'}';
336                 }
337
338                 $helper_connect_info{$key} = $val;
339             }
340
341             next;
342         }
343
344         my ($key, $val) = split /=/, $_, 2;
345
346         $helper_connect_info{$key} = $self->_quote_unless_struct($val);
347     }
348
349     \%helper_connect_info
350 }
351
352 sub _build_old_schema {
353     my $self = shift;
354
355     my @schema_pm   = split '::', $self->schema_class;
356     $schema_pm[-1] .= '.pm';
357     my $schema_file =
358     File::Spec->catfile($self->helper->{base}, 'lib', @schema_pm);
359
360     if (-f $schema_file) {
361         my $schema_code = do { local (@ARGV, $/) = $schema_file; <> };
362         return 1 if $schema_code =~ /->load_classes/;
363     }
364
365     0;
366 }
367
368 sub _data_struct_to_string {
369     my ($self, $data) = @_;
370
371     local $Data::Dumper::Terse = 1;
372     local $Data::Dumper::Quotekeys = 0;
373     local $Data::Dumper::Indent = 0;
374     local $Data::Dumper::Useqq = 1;
375
376     return Data::Dumper->Dump([$data]);
377 }
378
379 sub _get_dsn_user_pass {
380     my ($self, $connect_info) = @_;
381
382     my $dsn = shift @$connect_info;
383     my ($user, $password);
384
385     if ($dsn =~ /sqlite/i) {
386         ($user, $password) = ('', '');
387         shift @$connect_info while $connect_info->[0] eq '';
388     } else {
389         ($user, $password) = splice @$connect_info, 0, 2;
390     }
391     
392     ($dsn, $user, $password)
393 }
394
395 sub _parse_connect_info {
396     my ($self, $connect_info) = @_;
397
398     my @connect_info = @$connect_info;
399
400     my ($dsn, $user, $password) = $self->_get_dsn_user_pass(\@connect_info);
401
402     tie my %connect_info, 'Tie::IxHash';
403     @connect_info{qw/dsn user password/} = ($dsn, $user, $password);
404
405     for (@connect_info) {
406         if (/^\s*{.*}\s*\z/) {
407             my $hash = eval $_;
408             die "Syntax errorr in connect_info hash: $_: $@" if $@;
409
410             %connect_info = (%connect_info, %$hash);
411
412             next;
413         }
414
415         my ($key, $val) = split /=/, $_, 2;
416
417         if ($key =~ /^(?:quote_char|name_sep)\z/) {
418             $connect_info{$key} = $val;
419         } else {
420             $connect_info{$key} = eval $val;
421         }
422
423         die "syntax error for connect_info key '$key' with value '$val': $@"
424             if $@;
425     }
426
427     $self->connect_info(\%connect_info);
428
429     \%connect_info
430 }
431
432 sub _is_struct {
433     my ($self, $val) = @_;
434
435     return $val =~ /^\s*[[{]/;
436 }
437
438 sub _quote_unless_struct {
439     my ($self, $val) = @_;
440
441     $val = 'q{'.$val.'}' if not $self->_is_struct($val);
442
443     $val;
444 }
445
446 sub _gen_dynamic_schema {
447     my $self = shift;
448
449     my $helper = $self->helper;
450
451     my @schema_parts = split(/\:\:/, $self->schema_class);
452     my $schema_file_part = pop @schema_parts;
453
454     my $schema_dir  = File::Spec->catfile(
455         $helper->{base}, 'lib', @schema_parts
456     );
457     my $schema_file = File::Spec->catfile(
458         $schema_dir, $schema_file_part . '.pm'
459     );
460
461     $helper->mk_dir($schema_dir);
462     $helper->render_file('schemaclass', $schema_file);
463 }
464
465 sub _gen_static_schema {
466     my $self = shift;
467
468     die "cannot load schema without connect info" unless $self->connect_info;
469
470     my $helper = $self->helper;
471
472     my $schema_dir = File::Spec->catfile($helper->{base}, 'lib');
473
474     eval { Class::MOP::load_class('DBIx::Class::Schema::Loader') };
475     die "Cannot load DBIx::Class::Schema::Loader: $@" if $@;
476
477     DBIx::Class::Schema::Loader->import(
478         "dump_to_dir:$schema_dir", 'make_schema_at'
479     );
480
481     make_schema_at(
482         $self->schema_class,
483         $self->loader_args,
484         [$self->connect_info]
485     );
486 }
487
488 sub _gen_model {
489     my $self = shift;
490     my $helper = $self->helper;
491
492     $helper->render_file('compclass', $helper->{file} );
493 }
494
495 sub _print_dynamic_deprecation_warning {
496     warn <<EOF;
497 ************************************ WARNING **********************************
498 * create=dynamic is DEPRECATED, please use create=static instead.             *
499 *******************************************************************************
500 EOF
501     print "Continue? [y/n]: ";
502     chomp(my $response = <STDIN>);
503     exit 0 if $response =~ /^n(o)?\z/;
504 }
505
506 sub _cleanup_args {
507     my ($self, $args) = @_;
508
509 # remove blanks, ie. someoned doing foo \  bar
510     my @res = grep !/^\s+\z/, @$args;
511
512 # remove leading whitespace, ie. foo \ bar
513     s/^\s*// for @res;
514
515     @res
516 }
517
518 =head1 SEE ALSO
519
520 General Catalyst Stuff:
521
522 L<Catalyst::Manual>, L<Catalyst::Test>, L<Catalyst::Request>,
523 L<Catalyst::Response>, L<Catalyst::Helper>, L<Catalyst>,
524
525 Stuff related to DBIC and this Model style:
526
527 L<DBIx::Class>, L<DBIx::Class::Schema>,
528 L<DBIx::Class::Schema::Loader>, L<Catalyst::Model::DBIC::Schema>
529
530 =head1 AUTHOR
531
532 Brandon L Black, C<blblack@gmail.com>
533
534 Contributors:
535
536 Rafael Kitover, C<<rkitover at cpan.org>>
537
538 =head1 LICENSE
539
540 This library is free software, you can redistribute it and/or modify
541 it under the same terms as Perl itself.
542
543 =cut
544
545 1;
546
547 __DATA__
548
549 =begin pod_to_ignore
550
551 __schemaclass__
552 package [% schema_class %];
553
554 use strict;
555 use base qw/DBIx::Class::Schema::Loader/;
556
557 __PACKAGE__->loader_options(
558     [%- FOREACH key = loader_args.keys %]
559     [% key %] => [% loader_args.${key} %],
560     [%- END -%]
561
562 );
563
564 =head1 NAME
565
566 [% schema_class %] - L<DBIx::Class::Schema::Loader> class
567
568 =head1 SYNOPSIS
569
570 See L<[% app %]>
571
572 =head1 DESCRIPTION
573
574 Dynamic L<DBIx::Class::Schema::Loader> schema for use in L<[% class %]>
575
576 =head1 GENERATED BY
577
578 [% generator %] - [% generator_version %]
579
580 =head1 AUTHOR
581
582 [% author.replace(',+$', '') %]
583
584 =head1 LICENSE
585
586 This library is free software, you can redistribute it and/or modify
587 it under the same terms as Perl itself.
588
589 =cut
590
591 1;
592
593 __compclass__
594 package [% class %];
595
596 use strict;
597 use base 'Catalyst::Model::DBIC::Schema';
598
599 __PACKAGE__->config(
600     schema_class => '[% schema_class %]',
601     [% IF roles %]roles => [% roles %],[% END %]
602     [% IF setup_connect_info %]connect_info => {
603         [%- FOREACH key = connect_info.keys %]
604         [% key %] => [% connect_info.${key} %],
605         [%- END -%]
606
607     }[% END %]
608 );
609
610 =head1 NAME
611
612 [% class %] - Catalyst DBIC Schema Model
613
614 =head1 SYNOPSIS
615
616 See L<[% app %]>
617
618 =head1 DESCRIPTION
619
620 L<Catalyst::Model::DBIC::Schema> Model using schema L<[% schema_class %]>
621
622 =head1 GENERATED BY
623
624 [% generator %] - [% generator_version %]
625
626 =head1 AUTHOR
627
628 [% author.replace(',+$', '') %]
629
630 =head1 LICENSE
631
632 This library is free software, you can redistribute it and/or modify
633 it under the same terms as Perl itself.
634
635 =cut
636
637 1;
638 __END__
639 # vim:sts=4 sw=4: