DBIC::Schema - add tests for helper
[catagits/Catalyst-Model-DBIC-Schema.git] / lib / Catalyst / Helper / Model / DBIC / Schema.pm
CommitLineData
ad91060a 1package Catalyst::Helper::Model::DBIC::Schema;
2
f090a149 3use Moose;
ffbf1967 4no warnings 'uninitialized';
018eb0e2 5
2201c2e4 6our $VERSION = '0.24';
7
0f2fd2c0 8use Carp;
2201c2e4 9use Tie::IxHash ();
10use Data::Dumper ();
c4fee9b8 11use List::Util 'first';
4cbe63e7 12use MooseX::Types::Moose qw/Str HashRef Bool ArrayRef/;
13use Catalyst::Model::DBIC::Schema::Types 'CreateOption';
14use Moose::Autobox;
15use List::MoreUtils 'firstidx';
2201c2e4 16
f090a149 17use namespace::clean -except => 'meta';
ad91060a 18
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 \
2ff00e2b 26 [ create=dynamic | create=static ] [ roles=role1,role2... ] \
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
2ff00e2b 58C<roles> is the list of roles to apply to the model, see
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
90B<ON WINDOWS COMMAND LINES QUOTING RULES ARE DIFFERENT>
91
92In 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
99Same, but with extra Schema::Loader args (separate multiple values by commas):
0b2a7108 100
2201c2e4 101 script/myapp_create.pl model CatalystModelName DBIC::Schema \
102 MyApp::SchemaClass create=static db_schema=foodb components=Foo,Bar \
4cbe63e7 103 exclude='^(wibble|wobble)$' moniker_map='{ foo => "FOO" }' \
2201c2e4 104 dbi:Pg:dbname=foodb myuname mypass
34f036a0 105
a75b6e58 106See L<DBIx::Class::Schema::Loader::Base> for a list of options
107
108Create a dynamic DBIx::Class::Schema::Loader-based Schema,
109and a Model which references it (B<DEPRECATED>):
34f036a0 110
2201c2e4 111 script/myapp_create.pl model CatalystModelName DBIC::Schema \
112 MyApp::SchemaClass create=dynamic dbi:mysql:foodb myuname mypass
ad91060a 113
a75b6e58 114Reference an existing Schema of any kind, and provide some connection information for ->config:
115
2201c2e4 116 script/myapp_create.pl model CatalystModelName DBIC::Schema \
117 MyApp::SchemaClass dbi:mysql:foodb myuname mypass
ad91060a 118
a75b6e58 119Same, but don't supply connect information yet (you'll need to do this
120in your app config, or [not recommended] in the schema itself).
121
d89e6c8a 122 script/myapp_create.pl model ModelName DBIC::Schema My::SchemaClass
ad91060a 123
f090a149 124=cut
125
126has helper => (is => 'ro', isa => 'Catalyst::Helper', required => 1);
4cbe63e7 127has create => (is => 'rw', isa => CreateOption);
128has args => (is => 'ro', isa => ArrayRef);
129has roles => (is => 'rw', isa => ArrayRef);
61ed82a5 130has schema_class => (is => 'ro', isa => Str, required => 1);
61ed82a5 131has loader_args => (is => 'rw', isa => HashRef);
132has connect_info => (is => 'rw', isa => HashRef);
61ed82a5 133has old_schema => (is => 'rw', isa => Bool, lazy_build => 1);
4cbe63e7 134has components => (is => 'rw', isa => ArrayRef);
f090a149 135
018eb0e2 136=head1 METHODS
ad91060a 137
018eb0e2 138=head2 mk_compclass
ad91060a 139
0fbbc8d5 140This is called by L<Catalyst::Helper> with the commandline args to generate the
141files.
142
ad91060a 143=cut
144
145sub mk_compclass {
2201c2e4 146 my ($package, $helper, $schema_class, @args) = @_;
147
4cbe63e7 148 my $self = $package->new(
149 helper => $helper,
150 schema_class => $schema_class,
151 args => \@args
152 );
0f2fd2c0 153
4cbe63e7 154 $self->run;
155}
156
157sub 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;
c4fee9b8 163
164 @args = $self->_cleanup_args(\@args);
d89e6c8a 165
4cbe63e7 166 my ($roles_idx, $roles);
167 if (($roles_idx = firstidx { ($roles) = /^roles=(\S*)\z/ } @args) != -1) {
168 my @roles = split /,/ => $roles;
2201c2e4 169
4cbe63e7 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;
2ff00e2b 182
2201c2e4 183 if (@args) {
184 $self->_parse_loader_args(\@args);
185
4cbe63e7 186 $helper->{loader_args} = $self->_build_helper_loader_args;
187
c4fee9b8 188 if (first { /^dbi:/i } @args) {
2201c2e4 189 $helper->{setup_connect_info} = 1;
190
191 $helper->{connect_info} =
f090a149 192 $self->_build_helper_connect_info(\@args);
2201c2e4 193
4cbe63e7 194 $self->_parse_connect_info(\@args);
2201c2e4 195 }
196 }
d89e6c8a 197 }
0f2fd2c0 198
2201c2e4 199 $helper->{generator} = ref $self;
200 $helper->{generator_version} = $VERSION;
4cbe63e7 201}
202
203sub run {
204 my $self = shift;
2201c2e4 205
4cbe63e7 206 if ($self->create eq 'dynamic') {
c4fee9b8 207 $self->_print_dynamic_deprecation_warning;
2201c2e4 208 $self->_gen_dynamic_schema;
4cbe63e7 209 } elsif ($self->create eq 'static') {
2201c2e4 210 $self->_gen_static_schema;
211 }
212
213 $self->_gen_model;
214}
215
216sub _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;
c4fee9b8 225 die "syntax error for loader args key '$key' with value '$val': $@"
2201c2e4 226 if $@;
227 }
228
229 my @components =
230 $self->_build_loader_components(delete $loader_args{components});
231
4cbe63e7 232 $self->components(\@components);
233
2201c2e4 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 : ()),
f090a149 244 (!$self->old_schema ? (
2201c2e4 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
257sub _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;
ca14239e 264
4cbe63e7 265 if ($self->_is_struct($val)) {
266 $loader_args{$key} = $val;
267 } elsif ((my @vals = split /,/ => $val) > 1) {
2201c2e4 268 $loader_args{$key} = \@vals;
ca14239e 269 } else {
2201c2e4 270 $loader_args{$key} = $val;
ca14239e 271 }
272 }
273
2201c2e4 274 wantarray ? %loader_args : \%loader_args;
275}
276
277sub _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'};
0b2a7108 289 }
0f2fd2c0 290 }
291
2201c2e4 292 \%loader_args
293}
294
295sub _build_loader_components {
296 my ($self, $components) = @_;
d89e6c8a 297
f090a149 298 my @components = $self->old_schema ? () : ('InflateColumn::DateTime');
d89e6c8a 299
2201c2e4 300 if ($components) {
301 $components = [ $components ] if !ref $components;
302 push @components, @$components;
d89e6c8a 303 }
2201c2e4 304
305 wantarray ? @components : \@components;
306}
307
308sub _build_helper_connect_info {
309 my ($self, $connect_info) = @_;
310
311 my @connect_info = @$connect_info;
312
a75b6e58 313 my ($dsn, $user, $password) = $self->_get_dsn_user_pass(\@connect_info);
2201c2e4 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 $_;
c4fee9b8 326 die "Syntax errorr in connect_info hash: $_: $@" if $@;
2201c2e4 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 {
4cbe63e7 335 $val = 'q{'.$val.'}';
2201c2e4 336 }
337
338 $helper_connect_info{$key} = $val;
592cd3ae 339 }
2201c2e4 340
341 next;
592cd3ae 342 }
343
2201c2e4 344 my ($key, $val) = split /=/, $_, 2;
1d155058 345
2201c2e4 346 $helper_connect_info{$key} = $self->_quote_unless_struct($val);
347 }
1d155058 348
2201c2e4 349 \%helper_connect_info
350}
1d155058 351
61ed82a5 352sub _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
2201c2e4 368sub _data_struct_to_string {
369 my ($self, $data) = @_;
34f036a0 370
2201c2e4 371 local $Data::Dumper::Terse = 1;
372 local $Data::Dumper::Quotekeys = 0;
373 local $Data::Dumper::Indent = 0;
374 local $Data::Dumper::Useqq = 1;
34f036a0 375
2201c2e4 376 return Data::Dumper->Dump([$data]);
377}
34f036a0 378
a75b6e58 379sub _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
2201c2e4 395sub _parse_connect_info {
396 my ($self, $connect_info) = @_;
397
398 my @connect_info = @$connect_info;
399
a75b6e58 400 my ($dsn, $user, $password) = $self->_get_dsn_user_pass(\@connect_info);
2201c2e4 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 $_;
c4fee9b8 408 die "Syntax errorr in connect_info hash: $_: $@" if $@;
2201c2e4 409
410 %connect_info = (%connect_info, %$hash);
ca14239e 411
2201c2e4 412 next;
ca14239e 413 }
414
2201c2e4 415 my ($key, $val) = split /=/, $_, 2;
416
3f139b02 417 if ($key =~ /^(?:quote_char|name_sep)\z/) {
418 $connect_info{$key} = $val;
419 } else {
420 $connect_info{$key} = eval $val;
421 }
422
c4fee9b8 423 die "syntax error for connect_info key '$key' with value '$val': $@"
2201c2e4 424 if $@;
d89e6c8a 425 }
202d09c8 426
2201c2e4 427 $self->connect_info(\%connect_info);
428
429 \%connect_info
430}
431
4cbe63e7 432sub _is_struct {
433 my ($self, $val) = @_;
434
435 return $val =~ /^\s*[[{]/;
436}
437
2201c2e4 438sub _quote_unless_struct {
439 my ($self, $val) = @_;
440
4cbe63e7 441 $val = 'q{'.$val.'}' if not $self->_is_struct($val);
2201c2e4 442
443 $val;
444}
445
446sub _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
465sub _gen_static_schema {
466 my $self = shift;
467
c4fee9b8 468 die "cannot load schema without connect info" unless $self->connect_info;
2201c2e4 469
470 my $helper = $self->helper;
471
472 my $schema_dir = File::Spec->catfile($helper->{base}, 'lib');
473
f090a149 474 eval { Class::MOP::load_class('DBIx::Class::Schema::Loader') };
c4fee9b8 475 die "Cannot load DBIx::Class::Schema::Loader: $@" if $@;
f090a149 476
477 DBIx::Class::Schema::Loader->import(
2201c2e4 478 "dump_to_dir:$schema_dir", 'make_schema_at'
f090a149 479 );
2201c2e4 480
481 make_schema_at(
482 $self->schema_class,
483 $self->loader_args,
484 [$self->connect_info]
485 );
486}
487
2201c2e4 488sub _gen_model {
489 my $self = shift;
490 my $helper = $self->helper;
491
492 $helper->render_file('compclass', $helper->{file} );
ad91060a 493}
494
c4fee9b8 495sub _print_dynamic_deprecation_warning {
496 warn <<EOF;
497************************************ WARNING **********************************
498* create=dynamic is DEPRECATED, please use create=static instead. *
499*******************************************************************************
500EOF
501 print "Continue? [y/n]: ";
502 chomp(my $response = <STDIN>);
503 exit 0 if $response =~ /^n(o)?\z/;
504}
505
506sub _cleanup_args {
507 my ($self, $args) = @_;
508
509# remove blanks, ie. someoned doing foo \ bar
61ed82a5 510 my @res = grep !/^\s+\z/, @$args;
c4fee9b8 511
512# remove leading whitespace, ie. foo \ bar
513 s/^\s*// for @res;
514
515 @res
516}
517
ad91060a 518=head1 SEE ALSO
519
7b39f3f0 520General Catalyst Stuff:
521
ad91060a 522L<Catalyst::Manual>, L<Catalyst::Test>, L<Catalyst::Request>,
7b39f3f0 523L<Catalyst::Response>, L<Catalyst::Helper>, L<Catalyst>,
524
525Stuff related to DBIC and this Model style:
526
527L<DBIx::Class>, L<DBIx::Class::Schema>,
ef91bcf9 528L<DBIx::Class::Schema::Loader>, L<Catalyst::Model::DBIC::Schema>
ad91060a 529
530=head1 AUTHOR
531
532Brandon L Black, C<blblack@gmail.com>
533
2ff00e2b 534Contributors:
535
536Rafael Kitover, C<<rkitover at cpan.org>>
537
ad91060a 538=head1 LICENSE
539
540This library is free software, you can redistribute it and/or modify
541it under the same terms as Perl itself.
542
543=cut
544
dce0dfe8 5451;
546
ad91060a 547__DATA__
548
5d11d759 549=begin pod_to_ignore
550
d89e6c8a 551__schemaclass__
552package [% schema_class %];
553
554use strict;
555use base qw/DBIx::Class::Schema::Loader/;
556
557__PACKAGE__->loader_options(
2201c2e4 558 [%- FOREACH key = loader_args.keys %]
559 [% key %] => [% loader_args.${key} %],
560 [%- END -%]
561
d89e6c8a 562);
563
564=head1 NAME
565
2201c2e4 566[% schema_class %] - L<DBIx::Class::Schema::Loader> class
d89e6c8a 567
568=head1 SYNOPSIS
569
570See L<[% app %]>
571
572=head1 DESCRIPTION
573
2201c2e4 574Dynamic L<DBIx::Class::Schema::Loader> schema for use in L<[% class %]>
575
576=head1 GENERATED BY
577
578[% generator %] - [% generator_version %]
d89e6c8a 579
580=head1 AUTHOR
581
2201c2e4 582[% author.replace(',+$', '') %]
d89e6c8a 583
584=head1 LICENSE
585
586This library is free software, you can redistribute it and/or modify
587it under the same terms as Perl itself.
588
589=cut
590
5911;
592
ad91060a 593__compclass__
594package [% class %];
595
596use strict;
597use base 'Catalyst::Model::DBIC::Schema';
598
599__PACKAGE__->config(
0f2fd2c0 600 schema_class => '[% schema_class %]',
2ff00e2b 601 [% IF roles %]roles => [% roles %],[% END %]
2201c2e4 602 [% IF setup_connect_info %]connect_info => {
603 [%- FOREACH key = connect_info.keys %]
604 [% key %] => [% connect_info.${key} %],
605 [%- END -%]
606
607 }[% END %]
ad91060a 608);
609
610=head1 NAME
611
1aeb6e1e 612[% class %] - Catalyst DBIC Schema Model
2201c2e4 613
ad91060a 614=head1 SYNOPSIS
615
616See L<[% app %]>
617
618=head1 DESCRIPTION
619
d89e6c8a 620L<Catalyst::Model::DBIC::Schema> Model using schema L<[% schema_class %]>
ad91060a 621
2201c2e4 622=head1 GENERATED BY
623
624[% generator %] - [% generator_version %]
625
ad91060a 626=head1 AUTHOR
627
2201c2e4 628[% author.replace(',+$', '') %]
ad91060a 629
630=head1 LICENSE
631
632This library is free software, you can redistribute it and/or modify
633it under the same terms as Perl itself.
634
635=cut
636
6371;
a75b6e58 638__END__
639# vim:sts=4 sw=4: