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';
21 Catalyst::Helper::Model::DBIC::Schema - Helper for DBIC Schema Models
25 script/create.pl model CatalystModelName DBIC::Schema MyApp::SchemaClass \
26 [ create=dynamic | create=static ] [ traits=trait1,trait2... ] \
27 [ Schema::Loader opts ] [ dsn user pass ] \
28 [ other connect_info args ]
32 Helper for the DBIC Schema Models.
36 C<CatalystModelName> is the short name for the Catalyst Model class
37 being generated (i.e. callable with C<$c-E<gt>model('CatalystModelName')>).
39 C<MyApp::SchemaClass> is the fully qualified classname of your Schema,
40 which might or might not yet exist. Note that you should have a good
41 reason to create this under a new global namespace, otherwise use an
42 existing top level namespace for your schema class.
44 C<create=dynamic> instructs this Helper to generate the named Schema
45 class for you, basing it on L<DBIx::Class::Schema::Loader> (which
46 means the table information will always be dynamically loaded at
47 runtime from the database).
49 C<create=static> instructs this Helper to generate the named Schema
50 class for you, using L<DBIx::Class::Schema::Loader> in "one shot"
51 mode to create a standard, manually-defined L<DBIx::Class::Schema>
52 setup, based on what the Loader sees in your database at this moment.
53 A Schema/Model pair generated this way will not require
54 L<DBIx::Class::Schema::Loader> at runtime, and will not automatically
55 adapt itself to changes in your database structure. You can edit
56 the generated classes by hand to refine them.
58 C<traits> is the list of traits to apply to the model, see
59 L<Catalyst::Model::DBIC::Schema> for details.
61 C<Schema::Loader opts> are described in L</TYPICAL EXAMPLES> below.
63 C<connect_info> arguments are the same as what
64 DBIx::Class::Schema::connect expects, and are storage_type-specific.
65 For DBI-based storage, these arguments are the dsn, username,
66 password, and connect options, respectively. These are optional for
67 existing Schemas, but required if you use either of the C<create=>
70 username and password can be omitted for C<SQLite> dsns.
72 Use of either of the C<create=> options requires L<DBIx::Class::Schema::Loader>.
74 =head1 TYPICAL EXAMPLES
76 Use DBIx::Class::Schema::Loader to create a static DBIx::Class::Schema,
77 and a Model which references it:
79 script/myapp_create.pl model CatalystModelName DBIC::Schema \
80 MyApp::SchemaClass create=static dbi:mysql:foodb myuname mypass
82 Same, with extra connect_info args
83 user and pass can be omitted for sqlite, since they are always empty
85 script/myapp_create.pl model CatalystModelName DBIC::Schema \
86 MyApp::SchemaClass create=static dbi:SQLite:foo.db \
87 AutoCommit=1 cursor_class=DBIx::Class::Cursor::Cached \
88 on_connect_do='["select 1", "select 2"]' quote_char='"'
90 If using a 2 character quote_char:
92 script/myapp_create.pl ... quote_char='[]'
94 B<ON WINDOWS COMMAND LINES QUOTING RULES ARE DIFFERENT>
96 In C<cmd.exe> the above example would be:
98 script/myapp_create.pl model CatalystModelName DBIC::Schema \
99 MyApp::SchemaClass create=static dbi:SQLite:foo.db \
100 AutoCommit=1 cursor_class=DBIx::Class::Cursor::Cached \
101 on_connect_do="[\"select 1\", \"select 2\"]" quote_char="\""
103 Same, but with extra Schema::Loader args (separate multiple values by commas):
105 script/myapp_create.pl model CatalystModelName DBIC::Schema \
106 MyApp::SchemaClass create=static db_schema=foodb components=Foo,Bar \
107 exclude='^(wibble|wobble)$' moniker_map='{ foo => "FOO" }' \
108 dbi:Pg:dbname=foodb myuname mypass
110 Coderefs are also supported:
112 script/myapp_create.pl model CatalystModelName DBIC::Schema \
113 MyApp::SchemaClass create=static \
114 inflect_singular='sub { $_[0] =~ /\A(.+?)(_id)?\z/; $1 }' \
115 moniker_map='sub { join(q{}, map ucfirst, split(/[\W_]+/, lc $_[0])); }' \
116 dbi:mysql:foodb myuname mypass
118 See L<DBIx::Class::Schema::Loader::Base> for a list of options
120 Create a dynamic DBIx::Class::Schema::Loader-based Schema,
121 and a Model which references it (B<DEPRECATED>):
123 script/myapp_create.pl model CatalystModelName DBIC::Schema \
124 MyApp::SchemaClass create=dynamic dbi:mysql:foodb myuname mypass
126 Reference an existing Schema of any kind, and provide some connection information for ->config:
128 script/myapp_create.pl model CatalystModelName DBIC::Schema \
129 MyApp::SchemaClass dbi:mysql:foodb myuname mypass
131 Same, but don't supply connect information yet (you'll need to do this
132 in your app config, or [not recommended] in the schema itself).
134 script/myapp_create.pl model ModelName DBIC::Schema My::SchemaClass
138 has helper => (is => 'ro', isa => 'Catalyst::Helper', required => 1);
139 has create => (is => 'rw', isa => CreateOption);
140 has args => (is => 'ro', isa => ArrayRef);
141 has traits => (is => 'rw', isa => ArrayRef);
142 has schema_class => (is => 'ro', isa => Str, required => 1);
143 has loader_args => (is => 'rw', isa => HashRef);
144 has connect_info => (is => 'rw', isa => HashRef);
145 has old_schema => (is => 'rw', isa => Bool, lazy_build => 1);
146 has components => (is => 'rw', isa => ArrayRef);
152 This is called by L<Catalyst::Helper> with the commandline args to generate the
158 my ($package, $helper, $schema_class, @args) = @_;
160 my $self = $package->new(
162 schema_class => $schema_class,
171 my $helper = $self->helper;
172 my @args = @{ $self->args || [] };
174 $helper->{schema_class} = $self->schema_class;
176 @args = $self->_cleanup_args(\@args);
178 my ($traits_idx, $traits);
179 if (($traits_idx = firstidx { ($traits) = /^traits=(\S*)\z/ } @args) != -1) {
180 my @traits = split /,/ => $traits;
182 $self->traits(\@traits);
184 $helper->{traits} = '['
185 .(join ',' => map { qq{'$_'} } @traits)
188 splice @args, $traits_idx, 1, ();
191 if ($args[0] && $args[0] =~ /^create=(\S*)\z/) {
196 $self->_parse_loader_args(\@args);
198 $helper->{loader_args} = $self->_build_helper_loader_args;
203 if (first { ($dbi_dsn_part) = /^(dbi):/i } @args) {
205 qq{DSN must start with 'dbi:' not '$dbi_dsn_part' (case matters!)}
206 if $dbi_dsn_part ne 'dbi';
208 $helper->{setup_connect_info} = 1;
210 $helper->{connect_info} =
211 $self->_build_helper_connect_info(\@args);
213 $self->_parse_connect_info(\@args);
216 $helper->{generator} = ref $self;
217 $helper->{generator_version} = $VERSION;
222 Can be called on an instance to generate the files.
229 if ($self->create eq 'dynamic') {
230 $self->_print_dynamic_deprecation_warning;
231 $self->_gen_dynamic_schema;
232 } elsif ($self->create eq 'static') {
233 $self->_gen_static_schema;
239 sub _parse_loader_args {
240 my ($self, $args) = @_;
242 my %loader_args = $self->_read_loader_args($args);
244 while (my ($key, $val) = each %loader_args) {
245 next if $key =~ /^(?:components|constraint|exclude)\z/;
247 $loader_args{$key} = $self->_eval($val);
248 die "syntax error for loader args key '$key' with value '$val': $@"
253 $self->_build_loader_components(delete $loader_args{components});
255 $self->components(\@components);
257 for my $re_opt (qw/constraint exclude/) {
258 $loader_args{$re_opt} = qr/$loader_args{$re_opt}/
259 if exists $loader_args{$re_opt};
262 tie my %result, 'Tie::IxHash';
266 (%loader_args ? %loader_args : ()),
267 (!$self->old_schema ? (
271 components => \@components
275 $self->loader_args(\%result);
277 wantarray ? %result : \%result;
280 sub _read_loader_args {
281 my ($self, $args) = @_;
285 while (@$args && $args->[0] !~ /^dbi:/i) {
286 my ($key, $val) = split /=/, shift(@$args), 2;
288 if ($self->_is_struct($val)) {
289 $loader_args{$key} = $val;
290 } elsif ((my @vals = split /,/ => $val) > 1) {
291 $loader_args{$key} = \@vals;
293 $loader_args{$key} = $val;
297 wantarray ? %loader_args : \%loader_args;
300 sub _build_helper_loader_args {
303 my $args = $self->loader_args;
305 tie my %loader_args, 'Tie::IxHash';
307 while (my ($arg, $val) = each %$args) {
309 $loader_args{$arg} = $self->_data_struct_to_string($val);
311 $loader_args{$arg} = qq{'$val'};
318 sub _build_loader_components {
319 my ($self, $components) = @_;
321 my @components = $self->old_schema ? () : ('InflateColumn::DateTime');
324 $components = [ $components ] if !ref $components;
325 push @components, @$components;
328 wantarray ? @components : \@components;
331 sub _build_helper_connect_info {
332 my ($self, $connect_info) = @_;
334 my @connect_info = @$connect_info;
336 my ($dsn, $user, $password) = $self->_get_dsn_user_pass(\@connect_info);
338 tie my %helper_connect_info, 'Tie::IxHash';
340 %helper_connect_info = (
343 password => qq{'$password'}
346 for (@connect_info) {
347 if (/^\s*{.*}\s*\z/) {
348 my $hash = $self->_eval($_);
349 die "Syntax errorr in connect_info hash: $_: $@" if $@;
352 for my $key (keys %hash) {
353 my $val = $hash{$key};
356 $val = $self->_data_struct_to_string($val);
358 $val = $self->_quote($val);
361 $helper_connect_info{$key} = $val;
367 my ($key, $val) = split /=/, $_, 2;
369 if ($key eq 'quote_char') {
370 $helper_connect_info{$key} = length($val) == 1 ?
371 $self->_quote($val) :
372 $self->_data_struct_to_string([split //, $val]);
374 $helper_connect_info{$key} = $self->_quote_unless_struct($val);
378 \%helper_connect_info
381 sub _build_old_schema {
384 my @schema_pm = split '::', $self->schema_class;
385 $schema_pm[-1] .= '.pm';
387 File::Spec->catfile($self->helper->{base}, 'lib', @schema_pm);
389 if (-f $schema_file) {
390 my $schema_code = do { local (@ARGV, $/) = $schema_file; <> };
391 return 1 if $schema_code =~ /->load_classes/;
397 sub _data_struct_to_string {
398 my ($self, $data) = @_;
400 local $Data::Dumper::Terse = 1;
401 local $Data::Dumper::Quotekeys = 0;
402 local $Data::Dumper::Indent = 0;
403 local $Data::Dumper::Useqq = 1;
405 return Data::Dumper->Dump([$data]);
408 sub _get_dsn_user_pass {
409 my ($self, $connect_info) = @_;
411 my $dsn = shift @$connect_info;
412 my ($user, $password);
414 if ($dsn =~ /sqlite/i) {
415 ($user, $password) = ('', '');
416 shift @$connect_info while @$connect_info and $connect_info->[0] eq '';
418 ($user, $password) = splice @$connect_info, 0, 2;
421 ($dsn, $user, $password)
424 sub _parse_connect_info {
425 my ($self, $connect_info) = @_;
427 my @connect_info = @$connect_info;
429 my ($dsn, $user, $password) = $self->_get_dsn_user_pass(\@connect_info);
431 tie my %connect_info, 'Tie::IxHash';
432 @connect_info{qw/dsn user password/} = ($dsn, $user, $password);
434 for (@connect_info) {
435 if (/^\s*{.*}\s*\z/) {
436 my $hash = $self->_eval($_);
437 die "Syntax errorr in connect_info hash: $_: $@" if $@;
439 %connect_info = (%connect_info, %$hash);
444 my ($key, $val) = split /=/, $_, 2;
446 if ($key eq 'quote_char') {
447 $connect_info{$key} = length($val) == 1 ? $val : [split //, $val];
448 } elsif ($key =~ /^(?:name_sep|limit_dialect)\z/) {
449 $connect_info{$key} = $val;
451 $connect_info{$key} = $self->_eval($val);
454 die "syntax error for connect_info key '$key' with value '$val': $@"
458 $self->connect_info(\%connect_info);
464 my ($self, $val) = @_;
466 return $val =~ /^\s*(?:sub|[[{])/;
470 my ($self, $val) = @_;
472 return 'q{'.$val.'}';
475 sub _quote_unless_struct {
476 my ($self, $val) = @_;
478 $val = $self->_quote($val) if not $self->_is_struct($val);
484 my ($self, $code) = @_;
486 return $code if looks_like_number $code;
488 return $code if $code =~ m{^[\w;:/]*\z};
490 return eval "{no strict; $code}";
493 sub _gen_dynamic_schema {
496 my $helper = $self->helper;
498 my @schema_parts = split(/\:\:/, $self->schema_class);
499 my $schema_file_part = pop @schema_parts;
501 my $schema_dir = File::Spec->catfile(
502 $helper->{base}, 'lib', @schema_parts
504 my $schema_file = File::Spec->catfile(
505 $schema_dir, $schema_file_part . '.pm'
508 $helper->mk_dir($schema_dir);
509 $helper->render_file('schemaclass', $schema_file);
512 sub _gen_static_schema {
515 die "cannot load schema without connect info" unless $self->connect_info;
517 my $helper = $self->helper;
519 my $schema_dir = File::Spec->catfile($helper->{base}, 'lib');
521 eval { Class::MOP::load_class('DBIx::Class::Schema::Loader') };
522 die "Cannot load DBIx::Class::Schema::Loader: $@" if $@;
524 DBIx::Class::Schema::Loader->import(
525 "dump_to_dir:$schema_dir", 'make_schema_at'
531 [$self->connect_info]
537 my $helper = $self->helper;
539 $helper->render_file('compclass', $helper->{file} );
542 sub _print_dynamic_deprecation_warning {
544 ************************************ WARNING **********************************
545 * create=dynamic is DEPRECATED, please use create=static instead. *
546 *******************************************************************************
548 print "Continue? [y/n]: ";
549 chomp(my $response = <STDIN>);
550 exit 0 if $response =~ /^n(o)?\z/;
554 my ($self, $args) = @_;
556 # remove blanks, ie. someoned doing foo \ bar
557 my @res = grep !/^\s+\z/, @$args;
559 # remove leading whitespace, ie. foo \ bar
567 General Catalyst Stuff:
569 L<Catalyst::Manual>, L<Catalyst::Test>, L<Catalyst::Request>,
570 L<Catalyst::Response>, L<Catalyst::Helper>, L<Catalyst>,
572 Stuff related to DBIC and this Model style:
574 L<DBIx::Class>, L<DBIx::Class::Schema>,
575 L<DBIx::Class::Schema::Loader>, L<Catalyst::Model::DBIC::Schema>
579 See L<Catalyst::Model::DBIC::Schema/AUTHOR> and
580 L<Catalyst::Model::DBIC::Schema/CONTRIBUTORS>.
584 See L<Catalyst::Model::DBIC::Schema/COPYRIGHT>.
588 This library is free software, you can redistribute it and/or modify
589 it under the same terms as Perl itself.
600 package [% schema_class %];
603 use base qw/DBIx::Class::Schema::Loader/;
605 __PACKAGE__->loader_options(
606 [%- FOREACH key = loader_args.keys %]
607 [% key %] => [% loader_args.${key} %],
614 [% schema_class %] - L<DBIx::Class::Schema::Loader> class
622 Dynamic L<DBIx::Class::Schema::Loader> schema for use in L<[% class %]>
626 [% generator %] - [% generator_version %]
630 [% author.replace(',+$', '') %]
634 This library is free software, you can redistribute it and/or modify
635 it under the same terms as Perl itself.
645 use base 'Catalyst::Model::DBIC::Schema';
648 schema_class => '[% schema_class %]',
649 [% IF traits %]traits => [% traits %],[% END %]
650 [% IF setup_connect_info %]connect_info => {
651 [%- FOREACH key = connect_info.keys %]
652 [% key %] => [% connect_info.${key} %],
660 [% class %] - Catalyst DBIC Schema Model
668 L<Catalyst::Model::DBIC::Schema> Model using schema L<[% schema_class %]>
672 [% generator %] - [% generator_version %]
676 [% author.replace(',+$', '') %]
680 This library is free software, you can redistribute it and/or modify
681 it under the same terms as Perl itself.