C::M::DBIC::Schema - warn on create=dynamic, other cleanups, ::Role::Replicated ...
[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';
2201c2e4 12
f090a149 13use namespace::clean -except => 'meta';
ad91060a 14
15=head1 NAME
16
17Catalyst::Helper::Model::DBIC::Schema - Helper for DBIC Schema Models
18
19=head1 SYNOPSIS
20
2201c2e4 21 script/create.pl model CatalystModelName DBIC::Schema MyApp::SchemaClass \
2ff00e2b 22 [ create=dynamic | create=static ] [ roles=role1,role2... ] \
23 [ Schema::Loader opts ] [ dsn user pass ] \
24 [ other connect_info args ]
0f2fd2c0 25
d89e6c8a 26=head1 DESCRIPTION
27
28Helper for the DBIC Schema Models.
29
30=head2 Arguments:
31
018eb0e2 32C<CatalystModelName> is the short name for the Catalyst Model class
33being generated (i.e. callable with C<$c-E<gt>model('CatalystModelName')>).
6116daed 34
018eb0e2 35C<MyApp::SchemaClass> is the fully qualified classname of your Schema,
6116daed 36which might or might not yet exist. Note that you should have a good
37reason to create this under a new global namespace, otherwise use an
38existing top level namespace for your schema class.
39
018eb0e2 40C<create=dynamic> instructs this Helper to generate the named Schema
6116daed 41class for you, basing it on L<DBIx::Class::Schema::Loader> (which
42means the table information will always be dynamically loaded at
43runtime from the database).
44
018eb0e2 45C<create=static> instructs this Helper to generate the named Schema
6116daed 46class for you, using L<DBIx::Class::Schema::Loader> in "one shot"
47mode to create a standard, manually-defined L<DBIx::Class::Schema>
48setup, based on what the Loader sees in your database at this moment.
49A Schema/Model pair generated this way will not require
50L<DBIx::Class::Schema::Loader> at runtime, and will not automatically
51adapt itself to changes in your database structure. You can edit
52the generated classes by hand to refine them.
53
2ff00e2b 54C<roles> is the list of roles to apply to the model, see
55L<Catalyst::Model::DBIC::Schema> for details.
56
57C<Schema::Loader opts> are described in L</TYPICAL EXAMPLES> below.
58
018eb0e2 59C<connect_info> arguments are the same as what
6116daed 60DBIx::Class::Schema::connect expects, and are storage_type-specific.
61For DBI-based storage, these arguments are the dsn, username,
62password, and connect options, respectively. These are optional for
63existing Schemas, but required if you use either of the C<create=>
64options.
d89e6c8a 65
66Use of either of the C<create=> options requires L<DBIx::Class::Schema::Loader>.
0b2a7108 67
68=head1 TYPICAL EXAMPLES
69
d89e6c8a 70 # Use DBIx::Class::Schema::Loader to create a static DBIx::Class::Schema,
71 # and a Model which references it:
2201c2e4 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"]'
0b2a7108 80
ca14239e 81 # Same, but with extra Schema::Loader args (separate multiple values by commas):
2201c2e4 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
34f036a0 86
ca14239e 87 # See DBIx::Class::Schema::Loader::Base for list of options
34f036a0 88
d89e6c8a 89 # Create a dynamic DBIx::Class::Schema::Loader-based Schema,
90 # and a Model which references it:
2201c2e4 91 script/myapp_create.pl model CatalystModelName DBIC::Schema \
92 MyApp::SchemaClass create=dynamic dbi:mysql:foodb myuname mypass
ad91060a 93
d89e6c8a 94 # Reference an existing Schema of any kind, and provide some connection information for ->config:
2201c2e4 95 script/myapp_create.pl model CatalystModelName DBIC::Schema \
96 MyApp::SchemaClass dbi:mysql:foodb myuname mypass
ad91060a 97
d89e6c8a 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
ad91060a 101
f090a149 102=cut
103
104has helper => (is => 'ro', isa => 'Catalyst::Helper', required => 1);
105
106has schema_class => (is => 'ro', isa => 'Str', required => 1);
107
108has loader_args => (is => 'rw', isa => 'HashRef');
109has connect_info => (is => 'rw', isa => 'HashRef');
110
111has 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
018eb0e2 127=head1 METHODS
ad91060a 128
018eb0e2 129=head2 mk_compclass
ad91060a 130
0fbbc8d5 131This is called by L<Catalyst::Helper> with the commandline args to generate the
132files.
133
ad91060a 134=cut
135
136sub mk_compclass {
2201c2e4 137 my ($package, $helper, $schema_class, @args) = @_;
138
f090a149 139 my $self = $package->new(helper => $helper, schema_class => $schema_class);
0f2fd2c0 140
d89e6c8a 141 $helper->{schema_class} = $schema_class
c4fee9b8 142 or die "Must supply schema class name";
143
144 @args = $self->_cleanup_args(\@args);
d89e6c8a 145
146 my $create = '';
2ff00e2b 147 if ($args[0] && $args[0] =~ /^create=(dynamic|static)\z/) {
d89e6c8a 148 $create = $1;
2201c2e4 149 shift @args;
150
2ff00e2b 151 if ($args[0] && $args[0] =~ /^roles=(.*)\z/) {
152 $helper->{roles} = '['
153 .(join ',' => map { qq{'$_'} } (split /,/ => $1))
154 .']';
155 shift @args;
156 }
157
2201c2e4 158 if (@args) {
159 $self->_parse_loader_args(\@args);
160
c4fee9b8 161 if (first { /^dbi:/i } @args) {
2201c2e4 162 $helper->{setup_connect_info} = 1;
163
164 $helper->{connect_info} =
f090a149 165 $self->_build_helper_connect_info(\@args);
2201c2e4 166
167 $self->_parse_connect_info(\@args) if $create eq 'static';
168 }
169 }
d89e6c8a 170 }
0f2fd2c0 171
2201c2e4 172 $helper->{generator} = ref $self;
173 $helper->{generator_version} = $VERSION;
174
175 if ($create eq 'dynamic') {
c4fee9b8 176 $self->_print_dynamic_deprecation_warning;
2201c2e4 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
186sub _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;
c4fee9b8 195 die "syntax error for loader args key '$key' with value '$val': $@"
2201c2e4 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 : ()),
f090a149 212 (!$self->old_schema ? (
2201c2e4 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
225sub _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;
ca14239e 232
233 if ((my @vals = split /,/ => $val) > 1) {
2201c2e4 234 $loader_args{$key} = \@vals;
ca14239e 235 } else {
2201c2e4 236 $loader_args{$key} = $val;
ca14239e 237 }
238 }
239
2201c2e4 240 wantarray ? %loader_args : \%loader_args;
241}
242
243sub _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'};
0b2a7108 255 }
0f2fd2c0 256 }
257
2201c2e4 258 \%loader_args
259}
260
261sub _build_loader_components {
262 my ($self, $components) = @_;
d89e6c8a 263
f090a149 264 my @components = $self->old_schema ? () : ('InflateColumn::DateTime');
d89e6c8a 265
2201c2e4 266 if ($components) {
267 $components = [ $components ] if !ref $components;
268 push @components, @$components;
d89e6c8a 269 }
2201c2e4 270
271 wantarray ? @components : \@components;
272}
273
274sub _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 $_;
c4fee9b8 292 die "Syntax errorr in connect_info hash: $_: $@" if $@;
2201c2e4 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;
592cd3ae 305 }
2201c2e4 306
307 next;
592cd3ae 308 }
309
2201c2e4 310 my ($key, $val) = split /=/, $_, 2;
1d155058 311
2201c2e4 312 $helper_connect_info{$key} = $self->_quote_unless_struct($val);
313 }
1d155058 314
2201c2e4 315 \%helper_connect_info
316}
1d155058 317
2201c2e4 318sub _data_struct_to_string {
319 my ($self, $data) = @_;
34f036a0 320
2201c2e4 321 local $Data::Dumper::Terse = 1;
322 local $Data::Dumper::Quotekeys = 0;
323 local $Data::Dumper::Indent = 0;
324 local $Data::Dumper::Useqq = 1;
34f036a0 325
2201c2e4 326 return Data::Dumper->Dump([$data]);
327}
34f036a0 328
2201c2e4 329sub _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 $_;
c4fee9b8 342 die "Syntax errorr in connect_info hash: $_: $@" if $@;
2201c2e4 343
344 %connect_info = (%connect_info, %$hash);
ca14239e 345
2201c2e4 346 next;
ca14239e 347 }
348
2201c2e4 349 my ($key, $val) = split /=/, $_, 2;
350
351 $connect_info{$key} = eval $val;
c4fee9b8 352 die "syntax error for connect_info key '$key' with value '$val': $@"
2201c2e4 353 if $@;
d89e6c8a 354 }
202d09c8 355
2201c2e4 356 $self->connect_info(\%connect_info);
357
358 \%connect_info
359}
360
361sub _quote_unless_struct {
362 my ($self, $val) = @_;
363
364 $val = qq{'$val'} if $val !~ /^\s*[[{]/;
365
366 $val;
367}
368
369sub _gen_dynamic_schema {
370 my $self = shift;
371
372 my $helper = $self->helper;
373
374 my @schema_parts = split(/\:\:/, $self->schema_class);
375 my $schema_file_part = pop @schema_parts;
376
377 my $schema_dir = File::Spec->catfile(
378 $helper->{base}, 'lib', @schema_parts
379 );
380 my $schema_file = File::Spec->catfile(
381 $schema_dir, $schema_file_part . '.pm'
382 );
383
384 $helper->mk_dir($schema_dir);
385 $helper->render_file('schemaclass', $schema_file);
386}
387
388sub _gen_static_schema {
389 my $self = shift;
390
c4fee9b8 391 die "cannot load schema without connect info" unless $self->connect_info;
2201c2e4 392
393 my $helper = $self->helper;
394
395 my $schema_dir = File::Spec->catfile($helper->{base}, 'lib');
396
f090a149 397 eval { Class::MOP::load_class('DBIx::Class::Schema::Loader') };
c4fee9b8 398 die "Cannot load DBIx::Class::Schema::Loader: $@" if $@;
f090a149 399
400 DBIx::Class::Schema::Loader->import(
2201c2e4 401 "dump_to_dir:$schema_dir", 'make_schema_at'
f090a149 402 );
2201c2e4 403
404 make_schema_at(
405 $self->schema_class,
406 $self->loader_args,
407 [$self->connect_info]
408 );
409}
410
2201c2e4 411sub _gen_model {
412 my $self = shift;
413 my $helper = $self->helper;
414
415 $helper->render_file('compclass', $helper->{file} );
ad91060a 416}
417
c4fee9b8 418sub _print_dynamic_deprecation_warning {
419 warn <<EOF;
420************************************ WARNING **********************************
421* create=dynamic is DEPRECATED, please use create=static instead. *
422*******************************************************************************
423EOF
424 print "Continue? [y/n]: ";
425 chomp(my $response = <STDIN>);
426 exit 0 if $response =~ /^n(o)?\z/;
427}
428
429sub _cleanup_args {
430 my ($self, $args) = @_;
431
432# remove blanks, ie. someoned doing foo \ bar
433 my @res = grep !/^\s*\z/, @$args;
434
435# remove leading whitespace, ie. foo \ bar
436 s/^\s*// for @res;
437
438 @res
439}
440
ad91060a 441=head1 SEE ALSO
442
7b39f3f0 443General Catalyst Stuff:
444
ad91060a 445L<Catalyst::Manual>, L<Catalyst::Test>, L<Catalyst::Request>,
7b39f3f0 446L<Catalyst::Response>, L<Catalyst::Helper>, L<Catalyst>,
447
448Stuff related to DBIC and this Model style:
449
450L<DBIx::Class>, L<DBIx::Class::Schema>,
ef91bcf9 451L<DBIx::Class::Schema::Loader>, L<Catalyst::Model::DBIC::Schema>
ad91060a 452
453=head1 AUTHOR
454
455Brandon L Black, C<blblack@gmail.com>
456
2ff00e2b 457Contributors:
458
459Rafael Kitover, C<<rkitover at cpan.org>>
460
ad91060a 461=head1 LICENSE
462
463This library is free software, you can redistribute it and/or modify
464it under the same terms as Perl itself.
465
466=cut
467
dce0dfe8 4681;
469
ad91060a 470__DATA__
471
5d11d759 472=begin pod_to_ignore
473
d89e6c8a 474__schemaclass__
475package [% schema_class %];
476
477use strict;
478use base qw/DBIx::Class::Schema::Loader/;
479
480__PACKAGE__->loader_options(
2201c2e4 481 [%- FOREACH key = loader_args.keys %]
482 [% key %] => [% loader_args.${key} %],
483 [%- END -%]
484
d89e6c8a 485);
486
487=head1 NAME
488
2201c2e4 489[% schema_class %] - L<DBIx::Class::Schema::Loader> class
d89e6c8a 490
491=head1 SYNOPSIS
492
493See L<[% app %]>
494
495=head1 DESCRIPTION
496
2201c2e4 497Dynamic L<DBIx::Class::Schema::Loader> schema for use in L<[% class %]>
498
499=head1 GENERATED BY
500
501[% generator %] - [% generator_version %]
d89e6c8a 502
503=head1 AUTHOR
504
2201c2e4 505[% author.replace(',+$', '') %]
d89e6c8a 506
507=head1 LICENSE
508
509This library is free software, you can redistribute it and/or modify
510it under the same terms as Perl itself.
511
512=cut
513
5141;
515
ad91060a 516__compclass__
517package [% class %];
518
519use strict;
520use base 'Catalyst::Model::DBIC::Schema';
521
522__PACKAGE__->config(
0f2fd2c0 523 schema_class => '[% schema_class %]',
2ff00e2b 524 [% IF roles %]roles => [% roles %],[% END %]
2201c2e4 525 [% IF setup_connect_info %]connect_info => {
526 [%- FOREACH key = connect_info.keys %]
527 [% key %] => [% connect_info.${key} %],
528 [%- END -%]
529
530 }[% END %]
ad91060a 531);
532
533=head1 NAME
534
1aeb6e1e 535[% class %] - Catalyst DBIC Schema Model
2201c2e4 536
ad91060a 537=head1 SYNOPSIS
538
539See L<[% app %]>
540
541=head1 DESCRIPTION
542
d89e6c8a 543L<Catalyst::Model::DBIC::Schema> Model using schema L<[% schema_class %]>
ad91060a 544
2201c2e4 545=head1 GENERATED BY
546
547[% generator %] - [% generator_version %]
548
ad91060a 549=head1 AUTHOR
550
2201c2e4 551[% author.replace(',+$', '') %]
ad91060a 552
553=head1 LICENSE
554
555This library is free software, you can redistribute it and/or modify
556it under the same terms as Perl itself.
557
558=cut
559
5601;