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