1 package Catalyst::Helper::Model::DBIC::Schema;
3 use namespace::autoclean;
5 no warnings 'uninitialized';
8 $VERSION = eval $VERSION;
13 use List::Util 'first';
14 use MooseX::Types::Moose qw/Str HashRef Bool ArrayRef/;
15 use Catalyst::Model::DBIC::Schema::Types 'CreateOption';
16 use List::MoreUtils 'firstidx';
17 use Scalar::Util 'looks_like_number';
18 use File::Find 'finddepth';
24 Catalyst::Helper::Model::DBIC::Schema - Helper for DBIC Schema Models
28 script/create.pl model CatalystModelName DBIC::Schema MyApp::SchemaClass \
29 [ create=dynamic | create=static ] [ traits=trait1,trait2... ] \
30 [ Schema::Loader opts ] [ dsn user pass ] \
31 [ other connect_info args ]
35 Helper for the DBIC Schema Models.
39 C<CatalystModelName> is the short name for the Catalyst Model class
40 being generated (i.e. callable with C<$c-E<gt>model('CatalystModelName')>).
42 C<MyApp::SchemaClass> is the fully qualified classname of your Schema,
43 which might or might not yet exist. Note that you should have a good
44 reason to create this under a new global namespace, otherwise use an
45 existing top level namespace for your schema class.
47 C<create=dynamic> instructs this Helper to generate the named Schema
48 class for you, basing it on L<DBIx::Class::Schema::Loader> (which
49 means the table information will always be dynamically loaded at
50 runtime from the database).
52 C<create=static> instructs this Helper to generate the named Schema
53 class for you, using L<DBIx::Class::Schema::Loader> in "one shot"
54 mode to create a standard, manually-defined L<DBIx::Class::Schema>
55 setup, based on what the Loader sees in your database at this moment.
56 A Schema/Model pair generated this way will not require
57 L<DBIx::Class::Schema::Loader> at runtime, and will not automatically
58 adapt itself to changes in your database structure. You can edit
59 the generated classes by hand to refine them.
61 C<traits> is the list of traits to apply to the model, see
62 L<Catalyst::Model::DBIC::Schema> for details.
64 C<Schema::Loader opts> are described in L</TYPICAL EXAMPLES> below.
66 C<connect_info> arguments are the same as what
67 DBIx::Class::Schema::connect expects, and are storage_type-specific.
68 For DBI-based storage, these arguments are the dsn, username,
69 password, and connect options, respectively. These are optional for
70 existing Schemas, but required if you use either of the C<create=>
73 username and password can be omitted for C<SQLite> dsns.
75 Use of either of the C<create=> options requires L<DBIx::Class::Schema::Loader>.
77 =head1 TYPICAL EXAMPLES
79 Use DBIx::Class::Schema::Loader to create a static DBIx::Class::Schema,
80 and a Model which references it:
82 script/myapp_create.pl model CatalystModelName DBIC::Schema \
83 MyApp::SchemaClass create=static dbi:mysql:foodb myuname mypass
85 Same, with extra connect_info args
86 user and pass can be omitted for sqlite, since they are always empty
88 script/myapp_create.pl model CatalystModelName DBIC::Schema \
89 MyApp::SchemaClass create=static dbi:SQLite:foo.db \
90 AutoCommit=1 cursor_class=DBIx::Class::Cursor::Cached \
91 on_connect_do='["select 1", "select 2"]' quote_char='"'
93 If using a 2 character quote_char:
95 script/myapp_create.pl ... quote_char='[]'
97 B<ON WINDOWS COMMAND LINES QUOTING RULES ARE DIFFERENT>
99 In C<cmd.exe> the above example would be:
101 script/myapp_create.pl model CatalystModelName DBIC::Schema \
102 MyApp::SchemaClass create=static dbi:SQLite:foo.db \
103 AutoCommit=1 cursor_class=DBIx::Class::Cursor::Cached \
104 on_connect_do="[\"select 1\", \"select 2\"]" quote_char="\""
106 Same, but with extra Schema::Loader args (separate multiple values by commas):
108 script/myapp_create.pl model CatalystModelName DBIC::Schema \
109 MyApp::SchemaClass create=static db_schema=foodb components=Foo,Bar \
110 exclude='^(wibble|wobble)$' moniker_map='{ foo => "FOO" }' \
111 dbi:Pg:dbname=foodb myuname mypass
113 Coderefs are also supported:
115 script/myapp_create.pl model CatalystModelName DBIC::Schema \
116 MyApp::SchemaClass create=static \
117 inflect_singular='sub { $_[0] =~ /\A(.+?)(_id)?\z/; $1 }' \
118 moniker_map='sub { join(q{}, map ucfirst, split(/[\W_]+/, lc $_[0])); }' \
119 dbi:mysql:foodb myuname mypass
121 See L<DBIx::Class::Schema::Loader::Base> for a list of options
123 Create a dynamic DBIx::Class::Schema::Loader-based Schema,
124 and a Model which references it (B<DEPRECATED>):
126 script/myapp_create.pl model CatalystModelName DBIC::Schema \
127 MyApp::SchemaClass create=dynamic dbi:mysql:foodb myuname mypass
129 Reference an existing Schema of any kind, and provide some connection information for ->config:
131 script/myapp_create.pl model CatalystModelName DBIC::Schema \
132 MyApp::SchemaClass dbi:mysql:foodb myuname mypass
134 Same, but don't supply connect information yet (you'll need to do this
135 in your app config, or [not recommended] in the schema itself).
137 script/myapp_create.pl model ModelName DBIC::Schema My::SchemaClass
141 has helper => (is => 'ro', isa => 'Catalyst::Helper', required => 1);
142 has create => (is => 'rw', isa => CreateOption);
143 has args => (is => 'ro', isa => ArrayRef);
144 has traits => (is => 'rw', isa => ArrayRef);
145 has schema_class => (is => 'ro', isa => Str, required => 1);
146 has loader_args => (is => 'rw', isa => HashRef);
147 has connect_info => (is => 'rw', isa => HashRef);
148 has old_schema => (is => 'rw', isa => Bool, lazy_build => 1);
149 has is_moose_schema => (is => 'rw', isa => Bool, lazy_build => 1);
150 has result_namespace => (is => 'rw', isa => Str, lazy_build => 1);
151 has components => (is => 'rw', isa => ArrayRef);
157 This is called by L<Catalyst::Helper> with the commandline args to generate the
163 my ($package, $helper, $schema_class, @args) = @_;
165 my $self = $package->new(
167 schema_class => $schema_class,
176 my $helper = $self->helper;
177 my @args = @{ $self->args || [] };
179 $helper->{schema_class} = $self->schema_class;
181 @args = $self->_cleanup_args(\@args);
183 my ($traits_idx, $traits);
184 if (($traits_idx = firstidx { ($traits) = /^traits=(\S*)\z/ } @args) != -1) {
185 my @traits = split /,/ => $traits;
187 $self->traits(\@traits);
189 $helper->{traits} = '['
190 .(join ',' => map { qq{'$_'} } @traits)
193 splice @args, $traits_idx, 1, ();
196 if ($args[0] && $args[0] =~ /^create=(\S*)\z/) {
201 $self->_parse_loader_args(\@args);
203 $helper->{loader_args} = $self->_build_helper_loader_args;
208 if (first { ($dbi_dsn_part) = /^(dbi):/i } @args) {
210 qq{DSN must start with 'dbi:' not '$dbi_dsn_part' (case matters!)}
211 if $dbi_dsn_part ne 'dbi';
213 $helper->{setup_connect_info} = 1;
215 $helper->{connect_info} =
216 $self->_build_helper_connect_info(\@args);
218 $self->_parse_connect_info(\@args);
221 $helper->{generator} = ref $self;
222 $helper->{generator_version} = $VERSION;
227 Can be called on an instance to generate the files.
234 if ($self->create eq 'dynamic') {
235 $self->_print_dynamic_deprecation_warning;
236 $self->_gen_dynamic_schema;
237 } elsif ($self->create eq 'static') {
238 $self->_gen_static_schema;
244 sub _parse_loader_args {
245 my ($self, $args) = @_;
247 my %loader_args = $self->_read_loader_args($args);
249 while (my ($key, $val) = each %loader_args) {
250 next if $key =~ /^(?:components|constraint|exclude)\z/;
252 $loader_args{$key} = $self->_eval($val);
253 die "syntax error for loader args key '$key' with value '$val': $@"
257 my @components = $self->_build_loader_components(
258 delete $loader_args{components},
259 $loader_args{use_namespaces},
262 $self->components(\@components);
264 for my $re_opt (qw/constraint exclude/) {
265 $loader_args{$re_opt} = qr/$loader_args{$re_opt}/
266 if exists $loader_args{$re_opt};
269 tie my %result, 'Tie::IxHash';
273 use_moose => $self->is_moose_schema ? 1 : 0,
274 col_collision_map => 'column_%s',
275 (!$self->old_schema ? (
279 components => \@components
281 (%loader_args ? %loader_args : ()),
284 $self->loader_args(\%result);
286 wantarray ? %result : \%result;
289 sub _read_loader_args {
290 my ($self, $args) = @_;
294 while (@$args && $args->[0] !~ /^dbi:/i) {
295 my ($key, $val) = split /=/, shift(@$args), 2;
297 if ($self->_is_struct($val)) {
298 $loader_args{$key} = $val;
299 } elsif ((my @vals = split /,/ => $val) > 1) {
300 $loader_args{$key} = \@vals;
302 $loader_args{$key} = $val;
306 wantarray ? %loader_args : \%loader_args;
309 sub _build_helper_loader_args {
312 my $args = $self->loader_args;
314 tie my %loader_args, 'Tie::IxHash';
316 while (my ($arg, $val) = each %$args) {
318 $loader_args{$arg} = $self->_data_struct_to_string($val);
320 $loader_args{$arg} = qq{'$val'};
327 sub _build_loader_components {
328 my ($self, $components, $use_namespaces) = @_;
330 my @components = $self->old_schema && (not $use_namespaces) ? ()
331 : ('InflateColumn::DateTime');
334 $components = [ $components ] if !ref $components;
335 push @components, @$components;
338 wantarray ? @components : \@components;
341 sub _build_helper_connect_info {
342 my ($self, $connect_info) = @_;
344 my @connect_info = @$connect_info;
346 my ($dsn, $user, $password) = $self->_get_dsn_user_pass(\@connect_info);
348 tie my %helper_connect_info, 'Tie::IxHash';
350 %helper_connect_info = (
353 password => qq{'$password'}
356 for (@connect_info) {
357 if (/^\s*{.*}\s*\z/) {
358 my $hash = $self->_eval($_);
359 die "Syntax errorr in connect_info hash: $_: $@" if $@;
362 for my $key (keys %hash) {
363 my $val = $hash{$key};
366 $val = $self->_data_struct_to_string($val);
368 $val = $self->_quote($val);
371 $helper_connect_info{$key} = $val;
377 my ($key, $val) = split /=/, $_, 2;
379 if ($key eq 'quote_char') {
380 $helper_connect_info{$key} = length($val) == 1 ?
381 $self->_quote($val) :
382 $self->_data_struct_to_string([split //, $val]);
384 $helper_connect_info{$key} = $self->_quote_unless_struct($val);
388 \%helper_connect_info
391 sub _build_old_schema {
394 return $self->result_namespace eq '' ? 1 : 0;
397 sub _build_is_moose_schema {
400 my @schema_parts = split '::', $self->schema_class;
402 my $result_dir = File::Spec->catfile(
403 $self->helper->{base}, 'lib', @schema_parts, $self->result_namespace
406 # assume yes for new schemas
407 return 1 if not -d $result_dir;
415 return if $File::Find::name !~ /\.pm\z/;
417 open my $fh, '<', $File::Find::name
418 or die "Could not open $File::Find::name: $!";
420 my $code = do { local $/; <$fh> };
423 $uses_moose = 0 if $code !~ /\nuse Moose;\n/;
434 sub _build_result_namespace {
437 my @schema_parts = split '::', $self->schema_class;
439 File::Spec->catfile($self->helper->{base}, 'lib', @schema_parts) . '.pm';
441 if (not -f $schema_pm) {
442 try { Class::MOP::load_class('DBIx::Class::Schema::Loader') };
444 return 'Result' if $@;
446 return DBIx::Class::Schema::Loader->VERSION('0.05') ? 'Result' : '';
449 open my $fh, '<', $schema_pm or die "Could not open $schema_pm: $!";
450 my $code = do { local $/; <$fh> };
453 my ($result_namespace) = $code =~ /result_namespace => '([^']+)'/;
455 if (not $result_namespace) {
456 if ($code =~ /->load_classes/) {
457 $result_namespace = '';
460 $result_namespace = 'Result';
464 return $result_namespace;
467 sub _data_struct_to_string {
468 my ($self, $data) = @_;
470 local $Data::Dumper::Terse = 1;
471 local $Data::Dumper::Quotekeys = 0;
472 local $Data::Dumper::Indent = 0;
473 local $Data::Dumper::Useqq = 1;
475 return Data::Dumper->Dump([$data]);
478 sub _get_dsn_user_pass {
479 my ($self, $connect_info) = @_;
481 my $dsn = shift @$connect_info;
482 my ($user, $password);
484 if ($dsn =~ /sqlite/i) {
485 ($user, $password) = ('', '');
486 shift @$connect_info while @$connect_info and $connect_info->[0] eq '';
488 ($user, $password) = splice @$connect_info, 0, 2;
491 ($dsn, $user, $password)
494 sub _parse_connect_info {
495 my ($self, $connect_info) = @_;
497 my @connect_info = @$connect_info;
499 my ($dsn, $user, $password) = $self->_get_dsn_user_pass(\@connect_info);
501 tie my %connect_info, 'Tie::IxHash';
502 @connect_info{qw/dsn user password/} = ($dsn, $user, $password);
504 for (@connect_info) {
505 if (/^\s*{.*}\s*\z/) {
506 my $hash = $self->_eval($_);
507 die "Syntax errorr in connect_info hash: $_: $@" if $@;
509 %connect_info = (%connect_info, %$hash);
514 my ($key, $val) = split /=/, $_, 2;
516 if ($key eq 'quote_char') {
517 $connect_info{$key} = length($val) == 1 ? $val : [split //, $val];
518 } elsif ($key =~ /^(?:name_sep|limit_dialect)\z/) {
519 $connect_info{$key} = $val;
521 $connect_info{$key} = $self->_eval($val);
524 die "syntax error for connect_info key '$key' with value '$val': $@"
528 $self->connect_info(\%connect_info);
534 my ($self, $val) = @_;
536 return $val =~ /^\s*(?:sub|[[{])/;
540 my ($self, $val) = @_;
542 return 'q{'.$val.'}';
545 sub _quote_unless_struct {
546 my ($self, $val) = @_;
548 $val = $self->_quote($val) if not $self->_is_struct($val);
554 my ($self, $code) = @_;
556 return $code if looks_like_number $code;
558 return $code if not $self->_is_struct($code);
560 return eval "{no strict; $code}";
563 sub _gen_dynamic_schema {
566 my $helper = $self->helper;
568 my @schema_parts = split(/\:\:/, $self->schema_class);
569 my $schema_file_part = pop @schema_parts;
571 my $schema_dir = File::Spec->catfile(
572 $helper->{base}, 'lib', @schema_parts
574 my $schema_file = File::Spec->catfile(
575 $schema_dir, $schema_file_part . '.pm'
578 $helper->mk_dir($schema_dir);
579 $helper->render_file('schemaclass', $schema_file);
582 sub _gen_static_schema {
585 die "cannot load schema without connect info" unless $self->connect_info;
587 my $helper = $self->helper;
589 my $schema_dir = File::Spec->catfile($helper->{base}, 'lib');
591 try { Class::MOP::load_class('DBIx::Class::Schema::Loader') };
592 die "Cannot load DBIx::Class::Schema::Loader: $@" if $@;
594 DBIx::Class::Schema::Loader->import(
595 "dump_to_dir:$schema_dir", 'make_schema_at'
601 [$self->connect_info]
607 my $helper = $self->helper;
609 $helper->render_file('compclass', $helper->{file} );
612 sub _print_dynamic_deprecation_warning {
614 ************************************ WARNING **********************************
615 * create=dynamic is DEPRECATED, please use create=static instead. *
616 *******************************************************************************
618 print "Continue? [y/n]: ";
619 chomp(my $response = <STDIN>);
620 exit 0 if $response =~ /^n(o)?\z/;
624 my ($self, $args) = @_;
626 # remove blanks, ie. someoned doing foo \ bar
627 my @res = grep !/^\s+\z/, @$args;
629 # remove leading whitespace, ie. foo \ bar
637 General Catalyst Stuff:
639 L<Catalyst::Manual>, L<Catalyst::Test>, L<Catalyst::Request>,
640 L<Catalyst::Response>, L<Catalyst::Helper>, L<Catalyst>,
642 Stuff related to DBIC and this Model style:
644 L<DBIx::Class>, L<DBIx::Class::Schema>,
645 L<DBIx::Class::Schema::Loader>, L<Catalyst::Model::DBIC::Schema>
649 See L<Catalyst::Model::DBIC::Schema/AUTHOR> and
650 L<Catalyst::Model::DBIC::Schema/CONTRIBUTORS>.
654 See L<Catalyst::Model::DBIC::Schema/COPYRIGHT>.
658 This library is free software, you can redistribute it and/or modify
659 it under the same terms as Perl itself.
670 package [% schema_class %];
673 use base qw/DBIx::Class::Schema::Loader/;
675 __PACKAGE__->loader_options(
676 [%- FOREACH key = loader_args.keys %]
677 [% key %] => [% loader_args.${key} %],
684 [% schema_class %] - L<DBIx::Class::Schema::Loader> class
692 Dynamic L<DBIx::Class::Schema::Loader> schema for use in L<[% class %]>
696 [% generator %] - [% generator_version %]
700 [% author.replace(',+$', '') %]
704 This library is free software, you can redistribute it and/or modify
705 it under the same terms as Perl itself.
715 use base 'Catalyst::Model::DBIC::Schema';
718 schema_class => '[% schema_class %]',
719 [% IF traits %]traits => [% traits %],[% END %]
720 [% IF setup_connect_info %]connect_info => {
721 [%- FOREACH key = connect_info.keys %]
722 [% key %] => [% connect_info.${key} %],
730 [% class %] - Catalyst DBIC Schema Model
738 L<Catalyst::Model::DBIC::Schema> Model using schema L<[% schema_class %]>
742 [% generator %] - [% generator_version %]
746 [% author.replace(',+$', '') %]
750 This library is free software, you can redistribute it and/or modify
751 it under the same terms as Perl itself.