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/;
14 use namespace::clean -except => 'meta';
18 Catalyst::Helper::Model::DBIC::Schema - Helper for DBIC Schema Models
22 script/create.pl model CatalystModelName DBIC::Schema MyApp::SchemaClass \
23 [ create=dynamic | create=static ] [ roles=role1,role2... ] \
24 [ Schema::Loader opts ] [ dsn user pass ] \
25 [ other connect_info args ]
29 Helper for the DBIC Schema Models.
33 C<CatalystModelName> is the short name for the Catalyst Model class
34 being generated (i.e. callable with C<$c-E<gt>model('CatalystModelName')>).
36 C<MyApp::SchemaClass> is the fully qualified classname of your Schema,
37 which might or might not yet exist. Note that you should have a good
38 reason to create this under a new global namespace, otherwise use an
39 existing top level namespace for your schema class.
41 C<create=dynamic> instructs this Helper to generate the named Schema
42 class for you, basing it on L<DBIx::Class::Schema::Loader> (which
43 means the table information will always be dynamically loaded at
44 runtime from the database).
46 C<create=static> instructs this Helper to generate the named Schema
47 class for you, using L<DBIx::Class::Schema::Loader> in "one shot"
48 mode to create a standard, manually-defined L<DBIx::Class::Schema>
49 setup, based on what the Loader sees in your database at this moment.
50 A Schema/Model pair generated this way will not require
51 L<DBIx::Class::Schema::Loader> at runtime, and will not automatically
52 adapt itself to changes in your database structure. You can edit
53 the generated classes by hand to refine them.
55 C<roles> is the list of roles to apply to the model, see
56 L<Catalyst::Model::DBIC::Schema> for details.
58 C<Schema::Loader opts> are described in L</TYPICAL EXAMPLES> below.
60 C<connect_info> arguments are the same as what
61 DBIx::Class::Schema::connect expects, and are storage_type-specific.
62 For DBI-based storage, these arguments are the dsn, username,
63 password, and connect options, respectively. These are optional for
64 existing Schemas, but required if you use either of the C<create=>
67 Use of either of the C<create=> options requires L<DBIx::Class::Schema::Loader>.
69 =head1 TYPICAL EXAMPLES
71 # Use DBIx::Class::Schema::Loader to create a static DBIx::Class::Schema,
72 # and a Model which references it:
73 script/myapp_create.pl model CatalystModelName DBIC::Schema \
74 MyApp::SchemaClass create=static dbi:mysql:foodb myuname mypass
76 # Same, with extra connect_info args
77 script/myapp_create.pl model CatalystModelName DBIC::Schema \
78 MyApp::SchemaClass create=static dbi:SQLite:foo.db '' '' \
79 AutoCommit=1 cursor_class=DBIx::Class::Cursor::Cached \
80 on_connect_do='["select 1", "select 2"]'
82 # Same, but with extra Schema::Loader args (separate multiple values by commas):
83 script/myapp_create.pl model CatalystModelName DBIC::Schema \
84 MyApp::SchemaClass create=static db_schema=foodb components=Foo,Bar \
85 exclude='^wibble|wobble$' moniker_map='{ foo => "FFFFUUUU" }' \
86 dbi:Pg:dbname=foodb myuname mypass
88 # See DBIx::Class::Schema::Loader::Base for list of options
90 # Create a dynamic DBIx::Class::Schema::Loader-based Schema,
91 # and a Model which references it:
92 script/myapp_create.pl model CatalystModelName DBIC::Schema \
93 MyApp::SchemaClass create=dynamic dbi:mysql:foodb myuname mypass
95 # Reference an existing Schema of any kind, and provide some connection information for ->config:
96 script/myapp_create.pl model CatalystModelName DBIC::Schema \
97 MyApp::SchemaClass dbi:mysql:foodb myuname mypass
99 # Same, but don't supply connect information yet (you'll need to do this
100 # in your app config, or [not recommended] in the schema itself).
101 script/myapp_create.pl model ModelName DBIC::Schema My::SchemaClass
105 has helper => (is => 'ro', isa => 'Catalyst::Helper', required => 1);
107 has schema_class => (is => 'ro', isa => Str, required => 1);
109 has loader_args => (is => 'rw', isa => HashRef);
110 has connect_info => (is => 'rw', isa => HashRef);
112 has old_schema => (is => 'rw', isa => Bool, lazy_build => 1);
118 This is called by L<Catalyst::Helper> with the commandline args to generate the
124 my ($package, $helper, $schema_class, @args) = @_;
126 my $self = $package->new(helper => $helper, schema_class => $schema_class);
128 $helper->{schema_class} = $schema_class;
130 @args = $self->_cleanup_args(\@args);
133 if ($args[0] && $args[0] =~ /^create=(dynamic|static)\z/) {
137 if ($args[0] && $args[0] =~ /^roles=(.*)\z/) {
138 $helper->{roles} = '['
139 .(join ',' => map { qq{'$_'} } (split /,/ => $1))
145 $self->_parse_loader_args(\@args);
147 if (first { /^dbi:/i } @args) {
148 $helper->{setup_connect_info} = 1;
150 $helper->{connect_info} =
151 $self->_build_helper_connect_info(\@args);
153 $self->_parse_connect_info(\@args) if $create eq 'static';
158 $helper->{generator} = ref $self;
159 $helper->{generator_version} = $VERSION;
161 if ($create eq 'dynamic') {
162 $self->_print_dynamic_deprecation_warning;
163 $self->helper->{loader_args} = $self->_build_helper_loader_args;
164 $self->_gen_dynamic_schema;
165 } elsif ($create eq 'static') {
166 $self->_gen_static_schema;
172 sub _parse_loader_args {
173 my ($self, $args) = @_;
175 my %loader_args = $self->_read_loader_args($args);
177 while (my ($key, $val) = each %loader_args) {
178 next if $key =~ /^(?:components|constraint|exclude)\z/;
180 $loader_args{$key} = eval $val;
181 die "syntax error for loader args key '$key' with value '$val': $@"
186 $self->_build_loader_components(delete $loader_args{components});
188 for my $re_opt (qw/constraint exclude/) {
189 $loader_args{$re_opt} = qr/$loader_args{$re_opt}/
190 if exists $loader_args{$re_opt};
193 tie my %result, 'Tie::IxHash';
197 (%loader_args ? %loader_args : ()),
198 (!$self->old_schema ? (
202 components => \@components
206 $self->loader_args(\%result);
208 wantarray ? %result : \%result;
211 sub _read_loader_args {
212 my ($self, $args) = @_;
216 while (@$args && $args->[0] !~ /^dbi:/) {
217 my ($key, $val) = split /=/, shift(@$args), 2;
219 if ((my @vals = split /,/ => $val) > 1) {
220 $loader_args{$key} = \@vals;
222 $loader_args{$key} = $val;
226 wantarray ? %loader_args : \%loader_args;
229 sub _build_helper_loader_args {
232 my $args = $self->loader_args;
234 tie my %loader_args, 'Tie::IxHash';
236 while (my ($arg, $val) = each %$args) {
238 $loader_args{$arg} = $self->_data_struct_to_string($val);
240 $loader_args{$arg} = qq{'$val'};
247 sub _build_loader_components {
248 my ($self, $components) = @_;
250 my @components = $self->old_schema ? () : ('InflateColumn::DateTime');
253 $components = [ $components ] if !ref $components;
254 push @components, @$components;
257 wantarray ? @components : \@components;
260 sub _build_helper_connect_info {
261 my ($self, $connect_info) = @_;
263 my @connect_info = @$connect_info;
265 my ($dsn, $user, $password) = splice @connect_info, 0, 3;
267 tie my %helper_connect_info, 'Tie::IxHash';
269 %helper_connect_info = (
272 password => qq{'$password'}
275 for (@connect_info) {
276 if (/^\s*{.*}\s*\z/) {
278 die "Syntax errorr in connect_info hash: $_: $@" if $@;
281 for my $key (keys %hash) {
282 my $val = $hash{$key};
285 $val = $self->_data_struct_to_string($val);
290 $helper_connect_info{$key} = $val;
296 my ($key, $val) = split /=/, $_, 2;
298 $helper_connect_info{$key} = $self->_quote_unless_struct($val);
301 \%helper_connect_info
304 sub _build_old_schema {
307 my @schema_pm = split '::', $self->schema_class;
308 $schema_pm[-1] .= '.pm';
310 File::Spec->catfile($self->helper->{base}, 'lib', @schema_pm);
312 if (-f $schema_file) {
313 my $schema_code = do { local (@ARGV, $/) = $schema_file; <> };
314 return 1 if $schema_code =~ /->load_classes/;
320 sub _data_struct_to_string {
321 my ($self, $data) = @_;
323 local $Data::Dumper::Terse = 1;
324 local $Data::Dumper::Quotekeys = 0;
325 local $Data::Dumper::Indent = 0;
326 local $Data::Dumper::Useqq = 1;
328 return Data::Dumper->Dump([$data]);
331 sub _parse_connect_info {
332 my ($self, $connect_info) = @_;
334 my @connect_info = @$connect_info;
336 my ($dsn, $user, $password) = splice @connect_info, 0, 3;
338 tie my %connect_info, 'Tie::IxHash';
339 @connect_info{qw/dsn user password/} = ($dsn, $user, $password);
341 for (@connect_info) {
342 if (/^\s*{.*}\s*\z/) {
344 die "Syntax errorr in connect_info hash: $_: $@" if $@;
346 %connect_info = (%connect_info, %$hash);
351 my ($key, $val) = split /=/, $_, 2;
353 if ($key =~ /^(?:quote_char|name_sep)\z/) {
354 $connect_info{$key} = $val;
356 $connect_info{$key} = eval $val;
359 die "syntax error for connect_info key '$key' with value '$val': $@"
363 $self->connect_info(\%connect_info);
368 sub _quote_unless_struct {
369 my ($self, $val) = @_;
371 $val = qq{'$val'} if $val !~ /^\s*[[{]/;
376 sub _gen_dynamic_schema {
379 my $helper = $self->helper;
381 my @schema_parts = split(/\:\:/, $self->schema_class);
382 my $schema_file_part = pop @schema_parts;
384 my $schema_dir = File::Spec->catfile(
385 $helper->{base}, 'lib', @schema_parts
387 my $schema_file = File::Spec->catfile(
388 $schema_dir, $schema_file_part . '.pm'
391 $helper->mk_dir($schema_dir);
392 $helper->render_file('schemaclass', $schema_file);
395 sub _gen_static_schema {
398 die "cannot load schema without connect info" unless $self->connect_info;
400 my $helper = $self->helper;
402 my $schema_dir = File::Spec->catfile($helper->{base}, 'lib');
404 eval { Class::MOP::load_class('DBIx::Class::Schema::Loader') };
405 die "Cannot load DBIx::Class::Schema::Loader: $@" if $@;
407 DBIx::Class::Schema::Loader->import(
408 "dump_to_dir:$schema_dir", 'make_schema_at'
414 [$self->connect_info]
420 my $helper = $self->helper;
422 $helper->render_file('compclass', $helper->{file} );
425 sub _print_dynamic_deprecation_warning {
427 ************************************ WARNING **********************************
428 * create=dynamic is DEPRECATED, please use create=static instead. *
429 *******************************************************************************
431 print "Continue? [y/n]: ";
432 chomp(my $response = <STDIN>);
433 exit 0 if $response =~ /^n(o)?\z/;
437 my ($self, $args) = @_;
439 # remove blanks, ie. someoned doing foo \ bar
440 my @res = grep !/^\s+\z/, @$args;
442 # remove leading whitespace, ie. foo \ bar
450 General Catalyst Stuff:
452 L<Catalyst::Manual>, L<Catalyst::Test>, L<Catalyst::Request>,
453 L<Catalyst::Response>, L<Catalyst::Helper>, L<Catalyst>,
455 Stuff related to DBIC and this Model style:
457 L<DBIx::Class>, L<DBIx::Class::Schema>,
458 L<DBIx::Class::Schema::Loader>, L<Catalyst::Model::DBIC::Schema>
462 Brandon L Black, C<blblack@gmail.com>
466 Rafael Kitover, C<<rkitover at cpan.org>>
470 This library is free software, you can redistribute it and/or modify
471 it under the same terms as Perl itself.
482 package [% schema_class %];
485 use base qw/DBIx::Class::Schema::Loader/;
487 __PACKAGE__->loader_options(
488 [%- FOREACH key = loader_args.keys %]
489 [% key %] => [% loader_args.${key} %],
496 [% schema_class %] - L<DBIx::Class::Schema::Loader> class
504 Dynamic L<DBIx::Class::Schema::Loader> schema for use in L<[% class %]>
508 [% generator %] - [% generator_version %]
512 [% author.replace(',+$', '') %]
516 This library is free software, you can redistribute it and/or modify
517 it under the same terms as Perl itself.
527 use base 'Catalyst::Model::DBIC::Schema';
530 schema_class => '[% schema_class %]',
531 [% IF roles %]roles => [% roles %],[% END %]
532 [% IF setup_connect_info %]connect_info => {
533 [%- FOREACH key = connect_info.keys %]
534 [% key %] => [% connect_info.${key} %],
542 [% class %] - Catalyst DBIC Schema Model
550 L<Catalyst::Model::DBIC::Schema> Model using schema L<[% schema_class %]>
554 [% generator %] - [% generator_version %]
558 [% author.replace(',+$', '') %]
562 This library is free software, you can redistribute it and/or modify
563 it under the same terms as Perl itself.