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