1 package Catalyst::Helper::Model::DBIC::Schema;
3 use namespace::autoclean;
5 no warnings 'uninitialized';
12 use List::Util 'first';
13 use MooseX::Types::Moose qw/Str HashRef Bool ArrayRef/;
14 use Catalyst::Model::DBIC::Schema::Types 'CreateOption';
15 use List::MoreUtils 'firstidx';
16 use Scalar::Util 'looks_like_number';
20 Catalyst::Helper::Model::DBIC::Schema - Helper for DBIC Schema Models
24 script/create.pl model CatalystModelName DBIC::Schema MyApp::SchemaClass \
25 [ create=dynamic | create=static ] [ traits=trait1,trait2... ] \
26 [ Schema::Loader opts ] [ dsn user pass ] \
27 [ other connect_info args ]
31 Helper for the DBIC Schema Models.
35 C<CatalystModelName> is the short name for the Catalyst Model class
36 being generated (i.e. callable with C<$c-E<gt>model('CatalystModelName')>).
38 C<MyApp::SchemaClass> is the fully qualified classname of your Schema,
39 which might or might not yet exist. Note that you should have a good
40 reason to create this under a new global namespace, otherwise use an
41 existing top level namespace for your schema class.
43 C<create=dynamic> instructs this Helper to generate the named Schema
44 class for you, basing it on L<DBIx::Class::Schema::Loader> (which
45 means the table information will always be dynamically loaded at
46 runtime from the database).
48 C<create=static> instructs this Helper to generate the named Schema
49 class for you, using L<DBIx::Class::Schema::Loader> in "one shot"
50 mode to create a standard, manually-defined L<DBIx::Class::Schema>
51 setup, based on what the Loader sees in your database at this moment.
52 A Schema/Model pair generated this way will not require
53 L<DBIx::Class::Schema::Loader> at runtime, and will not automatically
54 adapt itself to changes in your database structure. You can edit
55 the generated classes by hand to refine them.
57 C<traits> is the list of traits to apply to the model, see
58 L<Catalyst::Model::DBIC::Schema> for details.
60 C<Schema::Loader opts> are described in L</TYPICAL EXAMPLES> below.
62 C<connect_info> arguments are the same as what
63 DBIx::Class::Schema::connect expects, and are storage_type-specific.
64 For DBI-based storage, these arguments are the dsn, username,
65 password, and connect options, respectively. These are optional for
66 existing Schemas, but required if you use either of the C<create=>
69 username and password can be omitted for C<SQLite> dsns.
71 Use of either of the C<create=> options requires L<DBIx::Class::Schema::Loader>.
73 =head1 TYPICAL EXAMPLES
75 Use DBIx::Class::Schema::Loader to create a static DBIx::Class::Schema,
76 and a Model which references it:
78 script/myapp_create.pl model CatalystModelName DBIC::Schema \
79 MyApp::SchemaClass create=static dbi:mysql:foodb myuname mypass
81 Same, with extra connect_info args
82 user and pass can be omitted for sqlite, since they are always empty
84 script/myapp_create.pl model CatalystModelName DBIC::Schema \
85 MyApp::SchemaClass create=static dbi:SQLite:foo.db \
86 AutoCommit=1 cursor_class=DBIx::Class::Cursor::Cached \
87 on_connect_do='["select 1", "select 2"]' quote_char='"'
89 If using a 2 character quote_char:
91 script/myapp_create.pl ... quote_char='[]'
93 B<ON WINDOWS COMMAND LINES QUOTING RULES ARE DIFFERENT>
95 In C<cmd.exe> the above example would be:
97 script/myapp_create.pl model CatalystModelName DBIC::Schema \
98 MyApp::SchemaClass create=static dbi:SQLite:foo.db \
99 AutoCommit=1 cursor_class=DBIx::Class::Cursor::Cached \
100 on_connect_do="[\"select 1\", \"select 2\"]" quote_char="\""
102 Same, but with extra Schema::Loader args (separate multiple values by commas):
104 script/myapp_create.pl model CatalystModelName DBIC::Schema \
105 MyApp::SchemaClass create=static db_schema=foodb components=Foo,Bar \
106 exclude='^(wibble|wobble)$' moniker_map='{ foo => "FOO" }' \
107 dbi:Pg:dbname=foodb myuname mypass
109 See L<DBIx::Class::Schema::Loader::Base> for a list of options
111 Create a dynamic DBIx::Class::Schema::Loader-based Schema,
112 and a Model which references it (B<DEPRECATED>):
114 script/myapp_create.pl model CatalystModelName DBIC::Schema \
115 MyApp::SchemaClass create=dynamic dbi:mysql:foodb myuname mypass
117 Reference an existing Schema of any kind, and provide some connection information for ->config:
119 script/myapp_create.pl model CatalystModelName DBIC::Schema \
120 MyApp::SchemaClass dbi:mysql:foodb myuname mypass
122 Same, but don't supply connect information yet (you'll need to do this
123 in your app config, or [not recommended] in the schema itself).
125 script/myapp_create.pl model ModelName DBIC::Schema My::SchemaClass
129 has helper => (is => 'ro', isa => 'Catalyst::Helper', required => 1);
130 has create => (is => 'rw', isa => CreateOption);
131 has args => (is => 'ro', isa => ArrayRef);
132 has traits => (is => 'rw', isa => ArrayRef);
133 has schema_class => (is => 'ro', isa => Str, required => 1);
134 has loader_args => (is => 'rw', isa => HashRef);
135 has connect_info => (is => 'rw', isa => HashRef);
136 has old_schema => (is => 'rw', isa => Bool, lazy_build => 1);
137 has components => (is => 'rw', isa => ArrayRef);
143 This is called by L<Catalyst::Helper> with the commandline args to generate the
149 my ($package, $helper, $schema_class, @args) = @_;
151 my $self = $package->new(
153 schema_class => $schema_class,
162 my $helper = $self->helper;
163 my @args = @{ $self->args || [] };
165 $helper->{schema_class} = $self->schema_class;
167 @args = $self->_cleanup_args(\@args);
169 my ($traits_idx, $traits);
170 if (($traits_idx = firstidx { ($traits) = /^traits=(\S*)\z/ } @args) != -1) {
171 my @traits = split /,/ => $traits;
173 $self->traits(\@traits);
175 $helper->{traits} = '['
176 .(join ',' => map { qq{'$_'} } @traits)
179 splice @args, $traits_idx, 1, ();
182 if ($args[0] && $args[0] =~ /^create=(\S*)\z/) {
187 $self->_parse_loader_args(\@args);
189 $helper->{loader_args} = $self->_build_helper_loader_args;
194 if (first { ($dbi_dsn_part) = /^(dbi):/i } @args) {
196 qq{DSN must start with 'dbi:' not '$dbi_dsn_part' (case matters!)}
197 if $dbi_dsn_part ne 'dbi';
199 $helper->{setup_connect_info} = 1;
201 $helper->{connect_info} =
202 $self->_build_helper_connect_info(\@args);
204 $self->_parse_connect_info(\@args);
207 $helper->{generator} = ref $self;
208 $helper->{generator_version} = $VERSION;
213 Can be called on an instance to generate the files.
220 if ($self->create eq 'dynamic') {
221 $self->_print_dynamic_deprecation_warning;
222 $self->_gen_dynamic_schema;
223 } elsif ($self->create eq 'static') {
224 $self->_gen_static_schema;
230 sub _parse_loader_args {
231 my ($self, $args) = @_;
233 my %loader_args = $self->_read_loader_args($args);
235 while (my ($key, $val) = each %loader_args) {
236 next if $key =~ /^(?:components|constraint|exclude)\z/;
238 $loader_args{$key} = $self->_eval($val);
239 die "syntax error for loader args key '$key' with value '$val': $@"
244 $self->_build_loader_components(delete $loader_args{components});
246 $self->components(\@components);
248 for my $re_opt (qw/constraint exclude/) {
249 $loader_args{$re_opt} = qr/$loader_args{$re_opt}/
250 if exists $loader_args{$re_opt};
253 tie my %result, 'Tie::IxHash';
257 (%loader_args ? %loader_args : ()),
258 (!$self->old_schema ? (
262 components => \@components
266 $self->loader_args(\%result);
268 wantarray ? %result : \%result;
271 sub _read_loader_args {
272 my ($self, $args) = @_;
276 while (@$args && $args->[0] !~ /^dbi:/i) {
277 my ($key, $val) = split /=/, shift(@$args), 2;
279 if ($self->_is_struct($val)) {
280 $loader_args{$key} = $val;
281 } elsif ((my @vals = split /,/ => $val) > 1) {
282 $loader_args{$key} = \@vals;
284 $loader_args{$key} = $val;
288 wantarray ? %loader_args : \%loader_args;
291 sub _build_helper_loader_args {
294 my $args = $self->loader_args;
296 tie my %loader_args, 'Tie::IxHash';
298 while (my ($arg, $val) = each %$args) {
300 $loader_args{$arg} = $self->_data_struct_to_string($val);
302 $loader_args{$arg} = qq{'$val'};
309 sub _build_loader_components {
310 my ($self, $components) = @_;
312 my @components = $self->old_schema ? () : ('InflateColumn::DateTime');
315 $components = [ $components ] if !ref $components;
316 push @components, @$components;
319 wantarray ? @components : \@components;
322 sub _build_helper_connect_info {
323 my ($self, $connect_info) = @_;
325 my @connect_info = @$connect_info;
327 my ($dsn, $user, $password) = $self->_get_dsn_user_pass(\@connect_info);
329 tie my %helper_connect_info, 'Tie::IxHash';
331 %helper_connect_info = (
334 password => qq{'$password'}
337 for (@connect_info) {
338 if (/^\s*{.*}\s*\z/) {
339 my $hash = $self->_eval($_);
340 die "Syntax errorr in connect_info hash: $_: $@" if $@;
343 for my $key (keys %hash) {
344 my $val = $hash{$key};
347 $val = $self->_data_struct_to_string($val);
349 $val = $self->_quote($val);
352 $helper_connect_info{$key} = $val;
358 my ($key, $val) = split /=/, $_, 2;
360 if ($key eq 'quote_char') {
361 $helper_connect_info{$key} = length($val) == 1 ?
362 $self->_quote($val) :
363 $self->_data_struct_to_string([split //, $val]);
365 $helper_connect_info{$key} = $self->_quote_unless_struct($val);
369 \%helper_connect_info
372 sub _build_old_schema {
375 my @schema_pm = split '::', $self->schema_class;
376 $schema_pm[-1] .= '.pm';
378 File::Spec->catfile($self->helper->{base}, 'lib', @schema_pm);
380 if (-f $schema_file) {
381 my $schema_code = do { local (@ARGV, $/) = $schema_file; <> };
382 return 1 if $schema_code =~ /->load_classes/;
388 sub _data_struct_to_string {
389 my ($self, $data) = @_;
391 local $Data::Dumper::Terse = 1;
392 local $Data::Dumper::Quotekeys = 0;
393 local $Data::Dumper::Indent = 0;
394 local $Data::Dumper::Useqq = 1;
396 return Data::Dumper->Dump([$data]);
399 sub _get_dsn_user_pass {
400 my ($self, $connect_info) = @_;
402 my $dsn = shift @$connect_info;
403 my ($user, $password);
405 if ($dsn =~ /sqlite/i) {
406 ($user, $password) = ('', '');
407 shift @$connect_info while @$connect_info and $connect_info->[0] eq '';
409 ($user, $password) = splice @$connect_info, 0, 2;
412 ($dsn, $user, $password)
415 sub _parse_connect_info {
416 my ($self, $connect_info) = @_;
418 my @connect_info = @$connect_info;
420 my ($dsn, $user, $password) = $self->_get_dsn_user_pass(\@connect_info);
422 tie my %connect_info, 'Tie::IxHash';
423 @connect_info{qw/dsn user password/} = ($dsn, $user, $password);
425 for (@connect_info) {
426 if (/^\s*{.*}\s*\z/) {
427 my $hash = $self->_eval($_);
428 die "Syntax errorr in connect_info hash: $_: $@" if $@;
430 %connect_info = (%connect_info, %$hash);
435 my ($key, $val) = split /=/, $_, 2;
437 if ($key eq 'quote_char') {
438 $connect_info{$key} = length($val) == 1 ? $val : [split //, $val];
439 } elsif ($key =~ /^(?:name_sep|limit_dialect)\z/) {
440 $connect_info{$key} = $val;
442 $connect_info{$key} = $self->_eval($val);
445 die "syntax error for connect_info key '$key' with value '$val': $@"
449 $self->connect_info(\%connect_info);
455 my ($self, $val) = @_;
457 return $val =~ /^\s*[[{]/;
461 my ($self, $val) = @_;
463 return 'q{'.$val.'}';
466 sub _quote_unless_struct {
467 my ($self, $val) = @_;
469 $val = $self->_quote($val) if not $self->_is_struct($val);
475 my ($self, $code) = @_;
477 return $code if looks_like_number $code;
479 return $code if $code =~ m{^[\w;:/]*\z};
481 return eval "{no strict; $code}";
484 sub _gen_dynamic_schema {
487 my $helper = $self->helper;
489 my @schema_parts = split(/\:\:/, $self->schema_class);
490 my $schema_file_part = pop @schema_parts;
492 my $schema_dir = File::Spec->catfile(
493 $helper->{base}, 'lib', @schema_parts
495 my $schema_file = File::Spec->catfile(
496 $schema_dir, $schema_file_part . '.pm'
499 $helper->mk_dir($schema_dir);
500 $helper->render_file('schemaclass', $schema_file);
503 sub _gen_static_schema {
506 die "cannot load schema without connect info" unless $self->connect_info;
508 my $helper = $self->helper;
510 my $schema_dir = File::Spec->catfile($helper->{base}, 'lib');
512 eval { Class::MOP::load_class('DBIx::Class::Schema::Loader') };
513 die "Cannot load DBIx::Class::Schema::Loader: $@" if $@;
515 DBIx::Class::Schema::Loader->import(
516 "dump_to_dir:$schema_dir", 'make_schema_at'
522 [$self->connect_info]
528 my $helper = $self->helper;
530 $helper->render_file('compclass', $helper->{file} );
533 sub _print_dynamic_deprecation_warning {
535 ************************************ WARNING **********************************
536 * create=dynamic is DEPRECATED, please use create=static instead. *
537 *******************************************************************************
539 print "Continue? [y/n]: ";
540 chomp(my $response = <STDIN>);
541 exit 0 if $response =~ /^n(o)?\z/;
545 my ($self, $args) = @_;
547 # remove blanks, ie. someoned doing foo \ bar
548 my @res = grep !/^\s+\z/, @$args;
550 # remove leading whitespace, ie. foo \ bar
558 General Catalyst Stuff:
560 L<Catalyst::Manual>, L<Catalyst::Test>, L<Catalyst::Request>,
561 L<Catalyst::Response>, L<Catalyst::Helper>, L<Catalyst>,
563 Stuff related to DBIC and this Model style:
565 L<DBIx::Class>, L<DBIx::Class::Schema>,
566 L<DBIx::Class::Schema::Loader>, L<Catalyst::Model::DBIC::Schema>
570 Brandon L Black, C<blblack@gmail.com>
574 Rafael Kitover, C<rkitover at cpan.org>
578 This library is free software, you can redistribute it and/or modify
579 it under the same terms as Perl itself.
590 package [% schema_class %];
593 use base qw/DBIx::Class::Schema::Loader/;
595 __PACKAGE__->loader_options(
596 [%- FOREACH key = loader_args.keys %]
597 [% key %] => [% loader_args.${key} %],
604 [% schema_class %] - L<DBIx::Class::Schema::Loader> class
612 Dynamic L<DBIx::Class::Schema::Loader> schema for use in L<[% class %]>
616 [% generator %] - [% generator_version %]
620 [% author.replace(',+$', '') %]
624 This library is free software, you can redistribute it and/or modify
625 it under the same terms as Perl itself.
635 use base 'Catalyst::Model::DBIC::Schema';
638 schema_class => '[% schema_class %]',
639 [% IF traits %]traits => [% traits %],[% END %]
640 [% IF setup_connect_info %]connect_info => {
641 [%- FOREACH key = connect_info.keys %]
642 [% key %] => [% connect_info.${key} %],
650 [% class %] - Catalyst DBIC Schema Model
658 L<Catalyst::Model::DBIC::Schema> Model using schema L<[% schema_class %]>
662 [% generator %] - [% generator_version %]
666 [% author.replace(',+$', '') %]
670 This library is free software, you can redistribute it and/or modify
671 it under the same terms as Perl itself.