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