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_names=1
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_names=1
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 Coderefs are also supported:
111 script/myapp_create.pl model CatalystModelName DBIC::Schema \
112 MyApp::SchemaClass create=static \
113 inflect_singular='sub { $_[0] =~ /\A(.+?)(_id)?\z/; $1 }' \
114 moniker_map='sub { join(q{}, map ucfirst, split(/[\W_]+/, lc $_[0])); }' \
115 dbi:mysql:foodb myuname mypass
117 See L<DBIx::Class::Schema::Loader::Base> for a list of options
119 Create a dynamic DBIx::Class::Schema::Loader-based Schema,
120 and a Model which references it (B<DEPRECATED>):
122 script/myapp_create.pl model CatalystModelName DBIC::Schema \
123 MyApp::SchemaClass create=dynamic dbi:mysql:foodb myuname mypass
125 Reference an existing Schema of any kind, and provide some connection information for ->config:
127 script/myapp_create.pl model CatalystModelName DBIC::Schema \
128 MyApp::SchemaClass dbi:mysql:foodb myuname mypass
130 Same, but don't supply connect information yet (you'll need to do this
131 in your app config, or [not recommended] in the schema itself).
133 script/myapp_create.pl model ModelName DBIC::Schema My::SchemaClass
137 has helper => (is => 'ro', isa => 'Catalyst::Helper', required => 1);
138 has create => (is => 'rw', isa => CreateOption);
139 has args => (is => 'ro', isa => ArrayRef);
140 has traits => (is => 'rw', isa => ArrayRef);
141 has schema_class => (is => 'ro', isa => Str, required => 1);
142 has loader_args => (is => 'rw', isa => HashRef);
143 has connect_info => (is => 'rw', isa => HashRef);
144 has old_schema => (is => 'rw', isa => Bool, lazy_build => 1);
145 has is_moose_schema => (is => 'rw', isa => Bool, lazy_build => 1);
146 has result_namespace => (is => 'rw', isa => Str, lazy_build => 1);
147 has components => (is => 'rw', isa => ArrayRef);
153 This is called by L<Catalyst::Helper> with the commandline args to generate the
159 my ($package, $helper, $schema_class, @args) = @_;
161 my $self = $package->new(
163 schema_class => $schema_class,
172 my $helper = $self->helper;
173 my @args = @{ $self->args || [] };
175 $helper->{schema_class} = $self->schema_class;
177 @args = $self->_cleanup_args(\@args);
179 my ($traits_idx, $traits);
180 if (($traits_idx = firstidx { ($traits) = /^traits=(\S*)\z/ } @args) != -1) {
181 my @traits = split /,/ => $traits;
183 $self->traits(\@traits);
185 $helper->{traits} = '['
186 .(join ',' => map { qq{'$_'} } @traits)
189 splice @args, $traits_idx, 1, ();
192 if ($args[0] && $args[0] =~ /^create=(\S*)\z/) {
197 $self->_parse_loader_args(\@args);
199 $helper->{loader_args} = $self->_build_helper_loader_args;
204 if (first { ($dbi_dsn_part) = /^(dbi):/i } @args) {
206 qq{DSN must start with 'dbi:' not '$dbi_dsn_part' (case matters!)}
207 if $dbi_dsn_part ne 'dbi';
209 $helper->{setup_connect_info} = 1;
211 $helper->{connect_info} =
212 $self->_build_helper_connect_info(\@args);
214 $self->_parse_connect_info(\@args);
217 $helper->{generator} = ref $self;
218 $helper->{generator_version} = $VERSION;
223 Can be called on an instance to generate the files.
230 if ($self->create eq 'dynamic') {
231 $self->_print_dynamic_deprecation_warning;
232 $self->_gen_dynamic_schema;
233 } elsif ($self->create eq 'static') {
234 $self->_gen_static_schema;
240 sub _parse_loader_args {
241 my ($self, $args) = @_;
243 my %loader_args = $self->_read_loader_args($args);
245 while (my ($key, $val) = each %loader_args) {
246 next if $key =~ /^(?:components|constraint|exclude)\z/;
248 $loader_args{$key} = $self->_eval($val);
249 die "syntax error for loader args key '$key' with value '$val': $@"
253 my @components = $self->_build_loader_components(
254 delete $loader_args{components},
255 $loader_args{use_namespaces},
258 $self->components(\@components);
260 for my $re_opt (qw/constraint exclude/) {
261 $loader_args{$re_opt} = qr/$loader_args{$re_opt}/
262 if exists $loader_args{$re_opt};
265 tie my %result, 'Tie::IxHash';
269 use_moose => $self->is_moose_schema ? 1 : 0,
270 col_collision_map => 'column_%s',
271 (!$self->old_schema ? (
275 components => \@components
277 (%loader_args ? %loader_args : ()),
280 $self->loader_args(\%result);
282 wantarray ? %result : \%result;
285 sub _read_loader_args {
286 my ($self, $args) = @_;
290 while (@$args && $args->[0] !~ /^dbi:/i) {
291 my ($key, $val) = split /=/, shift(@$args), 2;
293 if ($self->_is_struct($val)) {
294 $loader_args{$key} = $val;
295 } elsif ((my @vals = split /,/ => $val) > 1) {
296 $loader_args{$key} = \@vals;
298 $loader_args{$key} = $val;
302 wantarray ? %loader_args : \%loader_args;
305 sub _build_helper_loader_args {
308 my $args = $self->loader_args;
310 tie my %loader_args, 'Tie::IxHash';
312 while (my ($arg, $val) = each %$args) {
314 $loader_args{$arg} = $self->_data_struct_to_string($val);
316 $loader_args{$arg} = qq{'$val'};
323 sub _build_loader_components {
324 my ($self, $components, $use_namespaces) = @_;
326 my @components = $self->old_schema && (not $use_namespaces) ? ()
327 : ('InflateColumn::DateTime');
330 $components = [ $components ] if !ref $components;
331 push @components, @$components;
334 wantarray ? @components : \@components;
337 sub _build_helper_connect_info {
338 my ($self, $connect_info) = @_;
340 my @connect_info = @$connect_info;
342 my ($dsn, $user, $password) = $self->_get_dsn_user_pass(\@connect_info);
344 tie my %helper_connect_info, 'Tie::IxHash';
346 %helper_connect_info = (
349 password => qq{'$password'}
352 for (@connect_info) {
353 if (/^\s*{.*}\s*\z/) {
354 my $hash = $self->_eval($_);
355 die "Syntax errorr in connect_info hash: $_: $@" if $@;
358 for my $key (keys %hash) {
359 my $val = $hash{$key};
362 $val = $self->_data_struct_to_string($val);
364 $val = $self->_quote($val);
367 $helper_connect_info{$key} = $val;
373 my ($key, $val) = split /=/, $_, 2;
375 if ($key eq 'quote_char') {
376 $helper_connect_info{$key} = length($val) == 1 ?
377 $self->_quote($val) :
378 $self->_data_struct_to_string([split //, $val]);
380 $helper_connect_info{$key} = $self->_quote_unless_struct($val);
384 \%helper_connect_info
387 sub _build_old_schema {
390 return $self->result_namespace eq '' ? 1 : 0;
393 sub _build_is_moose_schema {
396 my @schema_parts = split '::', $self->schema_class;
398 my $result_dir = File::Spec->catfile(
399 $self->helper->{base}, 'lib', @schema_parts, $self->result_namespace
402 # assume yes for new schemas
403 return 1 if not -d $result_dir;
411 return if $File::Find::name !~ /\.pm\z/;
413 open my $fh, '<', $File::Find::name
414 or die "Could not open $File::Find::name: $!";
416 my $code = do { local $/; <$fh> };
419 $uses_moose = 0 if $code !~ /\nuse Moose;\n/;
430 sub _build_result_namespace {
433 my @schema_parts = split '::', $self->schema_class;
435 File::Spec->catfile($self->helper->{base}, 'lib', @schema_parts) . '.pm';
437 if (not -f $schema_pm) {
438 eval { Class::MOP::load_class('DBIx::Class::Schema::Loader') };
440 return 'Result' if $@;
442 return (try { DBIx::Class::Schema::Loader->VERSION('0.05') }) ? 'Result' : '';
445 open my $fh, '<', $schema_pm or die "Could not open $schema_pm: $!";
446 my $code = do { local $/; <$fh> };
449 my ($result_namespace) = $code =~ /result_namespace => '([^']+)'/;
451 return $result_namespace if $result_namespace;
453 return '' if $code =~ /->load_classes/;
458 sub _data_struct_to_string {
459 my ($self, $data) = @_;
461 local $Data::Dumper::Terse = 1;
462 local $Data::Dumper::Quotekeys = 0;
463 local $Data::Dumper::Indent = 0;
464 local $Data::Dumper::Useqq = 1;
466 return Data::Dumper->Dump([$data]);
469 sub _get_dsn_user_pass {
470 my ($self, $connect_info) = @_;
472 my $dsn = shift @$connect_info;
473 my ($user, $password);
475 if ($dsn =~ /sqlite/i) {
476 ($user, $password) = ('', '');
477 shift @$connect_info while @$connect_info and $connect_info->[0] eq '';
479 ($user, $password) = splice @$connect_info, 0, 2;
482 ($dsn, $user, $password)
485 sub _parse_connect_info {
486 my ($self, $connect_info) = @_;
488 my @connect_info = @$connect_info;
490 my ($dsn, $user, $password) = $self->_get_dsn_user_pass(\@connect_info);
492 tie my %connect_info, 'Tie::IxHash';
493 @connect_info{qw/dsn user password/} = ($dsn, $user, $password);
495 for (@connect_info) {
496 if (/^\s*{.*}\s*\z/) {
497 my $hash = $self->_eval($_);
498 die "Syntax errorr in connect_info hash: $_: $@" if $@;
500 %connect_info = (%connect_info, %$hash);
505 my ($key, $val) = split /=/, $_, 2;
507 if ($key eq 'quote_char') {
508 $connect_info{$key} = length($val) == 1 ? $val : [split //, $val];
509 } elsif ($key =~ /^(?:name_sep|limit_dialect)\z/) {
510 $connect_info{$key} = $val;
512 $connect_info{$key} = $self->_eval($val);
515 die "syntax error for connect_info key '$key' with value '$val': $@"
519 $self->connect_info(\%connect_info);
525 my ($self, $val) = @_;
527 return $val =~ /^\s*(?:sub|[[{])/;
531 my ($self, $val) = @_;
533 return 'q{'.$val.'}';
536 sub _quote_unless_struct {
537 my ($self, $val) = @_;
539 $val = $self->_quote($val) if not $self->_is_struct($val);
545 my ($self, $code) = @_;
547 return $code if looks_like_number $code;
549 return $code if not $self->_is_struct($code);
551 return eval "{no strict; $code}";
554 sub _gen_dynamic_schema {
557 my $helper = $self->helper;
559 my @schema_parts = split(/\:\:/, $self->schema_class);
560 my $schema_file_part = pop @schema_parts;
562 my $schema_dir = File::Spec->catfile(
563 $helper->{base}, 'lib', @schema_parts
565 my $schema_file = File::Spec->catfile(
566 $schema_dir, $schema_file_part . '.pm'
569 $helper->mk_dir($schema_dir);
570 $helper->render_file('schemaclass', $schema_file);
573 sub _gen_static_schema {
576 die "cannot load schema without connect info" unless $self->connect_info;
578 my $helper = $self->helper;
580 my $schema_dir = File::Spec->catfile($helper->{base}, 'lib');
583 Class::MOP::load_class('DBIx::Class::Schema::Loader')
586 die "Cannot load DBIx::Class::Schema::Loader: $_";
589 DBIx::Class::Schema::Loader->import(
590 "dump_to_dir:$schema_dir", 'make_schema_at'
596 [$self->connect_info]
602 my $helper = $self->helper;
604 $helper->render_file('compclass', $helper->{file} );
607 sub _print_dynamic_deprecation_warning {
609 ************************************ WARNING **********************************
610 * create=dynamic is DEPRECATED, please use create=static instead. *
611 *******************************************************************************
613 print "Continue? [y/n]: ";
614 chomp(my $response = <STDIN>);
615 exit 0 if $response =~ /^n(o)?\z/;
619 my ($self, $args) = @_;
621 # remove blanks, ie. someoned doing foo \ bar
622 my @res = grep !/^\s+\z/, @$args;
624 # remove leading whitespace, ie. foo \ bar
632 General Catalyst Stuff:
634 L<Catalyst::Manual>, L<Catalyst::Test>, L<Catalyst::Request>,
635 L<Catalyst::Response>, L<Catalyst::Helper>, L<Catalyst>,
637 Stuff related to DBIC and this Model style:
639 L<DBIx::Class>, L<DBIx::Class::Schema>,
640 L<DBIx::Class::Schema::Loader>, L<Catalyst::Model::DBIC::Schema>
644 See L<Catalyst::Model::DBIC::Schema/AUTHOR> and
645 L<Catalyst::Model::DBIC::Schema/CONTRIBUTORS>.
649 See L<Catalyst::Model::DBIC::Schema/COPYRIGHT>.
653 This library is free software, you can redistribute it and/or modify
654 it under the same terms as Perl itself.
665 package [% schema_class %];
668 use base qw/DBIx::Class::Schema::Loader/;
670 __PACKAGE__->loader_options(
671 [%- FOREACH key = loader_args.keys %]
672 [% key %] => [% loader_args.${key} %],
679 [% schema_class %] - L<DBIx::Class::Schema::Loader> class
687 Dynamic L<DBIx::Class::Schema::Loader> schema for use in L<[% class %]>
691 [% generator %] - [% generator_version %]
695 [% author.replace(',+$', '') %]
699 This library is free software, you can redistribute it and/or modify
700 it under the same terms as Perl itself.
710 use base 'Catalyst::Model::DBIC::Schema';
713 schema_class => '[% schema_class %]',
714 [% IF traits %]traits => [% traits %],[% END %]
715 [% IF setup_connect_info %]connect_info => {
716 [%- FOREACH key = connect_info.keys %]
717 [% key %] => [% connect_info.${key} %],
725 [% class %] - Catalyst DBIC Schema Model
733 L<Catalyst::Model::DBIC::Schema> Model using schema L<[% schema_class %]>
737 [% generator %] - [% generator_version %]
741 [% author.replace(',+$', '') %]
745 This library is free software, you can redistribute it and/or modify
746 it under the same terms as Perl itself.