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