1 package Catalyst::Helper::Model::DBIC::Schema;
4 no warnings 'uninitialized';
11 use List::Util 'first';
12 use MooseX::Types::Moose qw/Str HashRef Bool ArrayRef/;
13 use Catalyst::Model::DBIC::Schema::Types 'CreateOption';
15 use List::MoreUtils 'firstidx';
16 use Scalar::Util 'looks_like_number';
18 use namespace::clean -except => 'meta';
22 Catalyst::Helper::Model::DBIC::Schema - Helper for DBIC Schema Models
26 script/create.pl model CatalystModelName DBIC::Schema MyApp::SchemaClass \
27 [ create=dynamic | create=static ] [ roles=role1,role2... ] \
28 [ Schema::Loader opts ] [ dsn user pass ] \
29 [ other connect_info args ]
33 Helper for the DBIC Schema Models.
37 C<CatalystModelName> is the short name for the Catalyst Model class
38 being generated (i.e. callable with C<$c-E<gt>model('CatalystModelName')>).
40 C<MyApp::SchemaClass> is the fully qualified classname of your Schema,
41 which might or might not yet exist. Note that you should have a good
42 reason to create this under a new global namespace, otherwise use an
43 existing top level namespace for your schema class.
45 C<create=dynamic> instructs this Helper to generate the named Schema
46 class for you, basing it on L<DBIx::Class::Schema::Loader> (which
47 means the table information will always be dynamically loaded at
48 runtime from the database).
50 C<create=static> instructs this Helper to generate the named Schema
51 class for you, using L<DBIx::Class::Schema::Loader> in "one shot"
52 mode to create a standard, manually-defined L<DBIx::Class::Schema>
53 setup, based on what the Loader sees in your database at this moment.
54 A Schema/Model pair generated this way will not require
55 L<DBIx::Class::Schema::Loader> at runtime, and will not automatically
56 adapt itself to changes in your database structure. You can edit
57 the generated classes by hand to refine them.
59 C<roles> is the list of roles to apply to the model, see
60 L<Catalyst::Model::DBIC::Schema> for details.
62 C<Schema::Loader opts> are described in L</TYPICAL EXAMPLES> below.
64 C<connect_info> arguments are the same as what
65 DBIx::Class::Schema::connect expects, and are storage_type-specific.
66 For DBI-based storage, these arguments are the dsn, username,
67 password, and connect options, respectively. These are optional for
68 existing Schemas, but required if you use either of the C<create=>
71 username and password can be omitted for C<SQLite> dsns.
73 Use of either of the C<create=> options requires L<DBIx::Class::Schema::Loader>.
75 =head1 TYPICAL EXAMPLES
77 Use DBIx::Class::Schema::Loader to create a static DBIx::Class::Schema,
78 and a Model which references it:
80 script/myapp_create.pl model CatalystModelName DBIC::Schema \
81 MyApp::SchemaClass create=static dbi:mysql:foodb myuname mypass
83 Same, with extra connect_info args
84 user and pass can be omitted for sqlite, since they are always empty
86 script/myapp_create.pl model CatalystModelName DBIC::Schema \
87 MyApp::SchemaClass create=static dbi:SQLite:foo.db \
88 AutoCommit=1 cursor_class=DBIx::Class::Cursor::Cached \
89 on_connect_do='["select 1", "select 2"]' quote_char='"'
91 B<ON WINDOWS COMMAND LINES QUOTING RULES ARE DIFFERENT>
93 In C<cmd.exe> the above example would be:
95 script/myapp_create.pl model CatalystModelName DBIC::Schema \
96 MyApp::SchemaClass create=static dbi:SQLite:foo.db \
97 AutoCommit=1 cursor_class=DBIx::Class::Cursor::Cached \
98 on_connect_do="[\"select 1\", \"select 2\"]" quote_char="\""
100 Same, but with extra Schema::Loader args (separate multiple values by commas):
102 script/myapp_create.pl model CatalystModelName DBIC::Schema \
103 MyApp::SchemaClass create=static db_schema=foodb components=Foo,Bar \
104 exclude='^(wibble|wobble)$' moniker_map='{ foo => "FOO" }' \
105 dbi:Pg:dbname=foodb myuname mypass
107 See L<DBIx::Class::Schema::Loader::Base> for a list of options
109 Create a dynamic DBIx::Class::Schema::Loader-based Schema,
110 and a Model which references it (B<DEPRECATED>):
112 script/myapp_create.pl model CatalystModelName DBIC::Schema \
113 MyApp::SchemaClass create=dynamic dbi:mysql:foodb myuname mypass
115 Reference an existing Schema of any kind, and provide some connection information for ->config:
117 script/myapp_create.pl model CatalystModelName DBIC::Schema \
118 MyApp::SchemaClass dbi:mysql:foodb myuname mypass
120 Same, but don't supply connect information yet (you'll need to do this
121 in your app config, or [not recommended] in the schema itself).
123 script/myapp_create.pl model ModelName DBIC::Schema My::SchemaClass
127 has helper => (is => 'ro', isa => 'Catalyst::Helper', required => 1);
128 has create => (is => 'rw', isa => CreateOption);
129 has args => (is => 'ro', isa => ArrayRef);
130 has roles => (is => 'rw', isa => ArrayRef);
131 has schema_class => (is => 'ro', isa => Str, required => 1);
132 has loader_args => (is => 'rw', isa => HashRef);
133 has connect_info => (is => 'rw', isa => HashRef);
134 has old_schema => (is => 'rw', isa => Bool, lazy_build => 1);
135 has components => (is => 'rw', isa => ArrayRef);
141 This is called by L<Catalyst::Helper> with the commandline args to generate the
147 my ($package, $helper, $schema_class, @args) = @_;
149 my $self = $package->new(
151 schema_class => $schema_class,
160 my $helper = $self->helper;
161 my @args = $self->args->flatten if $self->args;
163 $helper->{schema_class} = $self->schema_class;
165 @args = $self->_cleanup_args(\@args);
167 my ($roles_idx, $roles);
168 if (($roles_idx = firstidx { ($roles) = /^roles=(\S*)\z/ } @args) != -1) {
169 my @roles = split /,/ => $roles;
171 $self->roles(\@roles);
173 $helper->{roles} = '['
174 .(join ',' => map { qq{'$_'} } ($self->roles->flatten))
177 splice @args, $roles_idx, 1, ();
180 if ($args[0] && $args[0] =~ /^create=(\S*)\z/) {
185 $self->_parse_loader_args(\@args);
187 $helper->{loader_args} = $self->_build_helper_loader_args;
189 if (first { /^dbi:/i } @args) {
190 $helper->{setup_connect_info} = 1;
192 $helper->{connect_info} =
193 $self->_build_helper_connect_info(\@args);
195 $self->_parse_connect_info(\@args);
200 $helper->{generator} = ref $self;
201 $helper->{generator_version} = $VERSION;
206 Can be called on an instance to generate the files.
213 if ($self->create eq 'dynamic') {
214 $self->_print_dynamic_deprecation_warning;
215 $self->_gen_dynamic_schema;
216 } elsif ($self->create eq 'static') {
217 $self->_gen_static_schema;
223 sub _parse_loader_args {
224 my ($self, $args) = @_;
226 my %loader_args = $self->_read_loader_args($args);
228 while (my ($key, $val) = each %loader_args) {
229 next if $key =~ /^(?:components|constraint|exclude)\z/;
231 $loader_args{$key} = $self->_eval($val);
232 die "syntax error for loader args key '$key' with value '$val': $@"
237 $self->_build_loader_components(delete $loader_args{components});
239 $self->components(\@components);
241 for my $re_opt (qw/constraint exclude/) {
242 $loader_args{$re_opt} = qr/$loader_args{$re_opt}/
243 if exists $loader_args{$re_opt};
246 tie my %result, 'Tie::IxHash';
250 (%loader_args ? %loader_args : ()),
251 (!$self->old_schema ? (
255 components => \@components
259 $self->loader_args(\%result);
261 wantarray ? %result : \%result;
264 sub _read_loader_args {
265 my ($self, $args) = @_;
269 while (@$args && $args->[0] !~ /^dbi:/) {
270 my ($key, $val) = split /=/, shift(@$args), 2;
272 if ($self->_is_struct($val)) {
273 $loader_args{$key} = $val;
274 } elsif ((my @vals = split /,/ => $val) > 1) {
275 $loader_args{$key} = \@vals;
277 $loader_args{$key} = $val;
281 wantarray ? %loader_args : \%loader_args;
284 sub _build_helper_loader_args {
287 my $args = $self->loader_args;
289 tie my %loader_args, 'Tie::IxHash';
291 while (my ($arg, $val) = each %$args) {
293 $loader_args{$arg} = $self->_data_struct_to_string($val);
295 $loader_args{$arg} = qq{'$val'};
302 sub _build_loader_components {
303 my ($self, $components) = @_;
305 my @components = $self->old_schema ? () : ('InflateColumn::DateTime');
308 $components = [ $components ] if !ref $components;
309 push @components, @$components;
312 wantarray ? @components : \@components;
315 sub _build_helper_connect_info {
316 my ($self, $connect_info) = @_;
318 my @connect_info = @$connect_info;
320 my ($dsn, $user, $password) = $self->_get_dsn_user_pass(\@connect_info);
322 tie my %helper_connect_info, 'Tie::IxHash';
324 %helper_connect_info = (
327 password => qq{'$password'}
330 for (@connect_info) {
331 if (/^\s*{.*}\s*\z/) {
332 my $hash = $self->_eval($_);
333 die "Syntax errorr in connect_info hash: $_: $@" if $@;
336 for my $key (keys %hash) {
337 my $val = $hash{$key};
340 $val = $self->_data_struct_to_string($val);
342 $val = 'q{'.$val.'}';
345 $helper_connect_info{$key} = $val;
351 my ($key, $val) = split /=/, $_, 2;
353 $helper_connect_info{$key} = $self->_quote_unless_struct($val);
356 \%helper_connect_info
359 sub _build_old_schema {
362 my @schema_pm = split '::', $self->schema_class;
363 $schema_pm[-1] .= '.pm';
365 File::Spec->catfile($self->helper->{base}, 'lib', @schema_pm);
367 if (-f $schema_file) {
368 my $schema_code = do { local (@ARGV, $/) = $schema_file; <> };
369 return 1 if $schema_code =~ /->load_classes/;
375 sub _data_struct_to_string {
376 my ($self, $data) = @_;
378 local $Data::Dumper::Terse = 1;
379 local $Data::Dumper::Quotekeys = 0;
380 local $Data::Dumper::Indent = 0;
381 local $Data::Dumper::Useqq = 1;
383 return Data::Dumper->Dump([$data]);
386 sub _get_dsn_user_pass {
387 my ($self, $connect_info) = @_;
389 my $dsn = shift @$connect_info;
390 my ($user, $password);
392 if ($dsn =~ /sqlite/i) {
393 ($user, $password) = ('', '');
394 shift @$connect_info while $connect_info->[0] eq '';
396 ($user, $password) = splice @$connect_info, 0, 2;
399 ($dsn, $user, $password)
402 sub _parse_connect_info {
403 my ($self, $connect_info) = @_;
405 my @connect_info = @$connect_info;
407 my ($dsn, $user, $password) = $self->_get_dsn_user_pass(\@connect_info);
409 tie my %connect_info, 'Tie::IxHash';
410 @connect_info{qw/dsn user password/} = ($dsn, $user, $password);
412 for (@connect_info) {
413 if (/^\s*{.*}\s*\z/) {
414 my $hash = $self->_eval($_);
415 die "Syntax errorr in connect_info hash: $_: $@" if $@;
417 %connect_info = (%connect_info, %$hash);
422 my ($key, $val) = split /=/, $_, 2;
424 if ($key =~ /^(?:quote_char|name_sep|limit_dialect)\z/) {
425 $connect_info{$key} = $val;
427 $connect_info{$key} = $self->_eval($val);
430 die "syntax error for connect_info key '$key' with value '$val': $@"
434 $self->connect_info(\%connect_info);
440 my ($self, $val) = @_;
442 return $val =~ /^\s*[[{]/;
445 sub _quote_unless_struct {
446 my ($self, $val) = @_;
448 $val = 'q{'.$val.'}' if not $self->_is_struct($val);
454 my ($self, $code) = @_;
456 return $code if looks_like_number $code;
458 return $code if $code =~ m{^[\w;:/]*\z};
460 return eval "{no strict; $code}";
463 sub _gen_dynamic_schema {
466 my $helper = $self->helper;
468 my @schema_parts = split(/\:\:/, $self->schema_class);
469 my $schema_file_part = pop @schema_parts;
471 my $schema_dir = File::Spec->catfile(
472 $helper->{base}, 'lib', @schema_parts
474 my $schema_file = File::Spec->catfile(
475 $schema_dir, $schema_file_part . '.pm'
478 $helper->mk_dir($schema_dir);
479 $helper->render_file('schemaclass', $schema_file);
482 sub _gen_static_schema {
485 die "cannot load schema without connect info" unless $self->connect_info;
487 my $helper = $self->helper;
489 my $schema_dir = File::Spec->catfile($helper->{base}, 'lib');
491 eval { Class::MOP::load_class('DBIx::Class::Schema::Loader') };
492 die "Cannot load DBIx::Class::Schema::Loader: $@" if $@;
494 DBIx::Class::Schema::Loader->import(
495 "dump_to_dir:$schema_dir", 'make_schema_at'
501 [$self->connect_info]
507 my $helper = $self->helper;
509 $helper->render_file('compclass', $helper->{file} );
512 sub _print_dynamic_deprecation_warning {
514 ************************************ WARNING **********************************
515 * create=dynamic is DEPRECATED, please use create=static instead. *
516 *******************************************************************************
518 print "Continue? [y/n]: ";
519 chomp(my $response = <STDIN>);
520 exit 0 if $response =~ /^n(o)?\z/;
524 my ($self, $args) = @_;
526 # remove blanks, ie. someoned doing foo \ bar
527 my @res = grep !/^\s+\z/, @$args;
529 # remove leading whitespace, ie. foo \ bar
537 General Catalyst Stuff:
539 L<Catalyst::Manual>, L<Catalyst::Test>, L<Catalyst::Request>,
540 L<Catalyst::Response>, L<Catalyst::Helper>, L<Catalyst>,
542 Stuff related to DBIC and this Model style:
544 L<DBIx::Class>, L<DBIx::Class::Schema>,
545 L<DBIx::Class::Schema::Loader>, L<Catalyst::Model::DBIC::Schema>
549 Brandon L Black, C<blblack@gmail.com>
553 Rafael Kitover, C<<rkitover at cpan.org>>
557 This library is free software, you can redistribute it and/or modify
558 it under the same terms as Perl itself.
569 package [% schema_class %];
572 use base qw/DBIx::Class::Schema::Loader/;
574 __PACKAGE__->loader_options(
575 [%- FOREACH key = loader_args.keys %]
576 [% key %] => [% loader_args.${key} %],
583 [% schema_class %] - L<DBIx::Class::Schema::Loader> class
591 Dynamic L<DBIx::Class::Schema::Loader> schema for use in L<[% class %]>
595 [% generator %] - [% generator_version %]
599 [% author.replace(',+$', '') %]
603 This library is free software, you can redistribute it and/or modify
604 it under the same terms as Perl itself.
614 use base 'Catalyst::Model::DBIC::Schema';
617 schema_class => '[% schema_class %]',
618 [% IF roles %]roles => [% roles %],[% END %]
619 [% IF setup_connect_info %]connect_info => {
620 [%- FOREACH key = connect_info.keys %]
621 [% key %] => [% connect_info.${key} %],
629 [% class %] - Catalyst DBIC Schema Model
637 L<Catalyst::Model::DBIC::Schema> Model using schema L<[% schema_class %]>
641 [% generator %] - [% generator_version %]
645 [% author.replace(',+$', '') %]
649 This library is free software, you can redistribute it and/or modify
650 it under the same terms as Perl itself.