1 package Catalyst::Helper::Model::DBIC::Schema;
3 use namespace::autoclean;
5 no warnings 'uninitialized';
12 use List::Util 'first';
13 use MooseX::Types::Moose qw/Str HashRef Bool ArrayRef/;
14 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 See L<DBIx::Class::Schema::Loader::Base> for a list of options
112 Create a dynamic DBIx::Class::Schema::Loader-based Schema,
113 and a Model which references it (B<DEPRECATED>):
115 script/myapp_create.pl model CatalystModelName DBIC::Schema \
116 MyApp::SchemaClass create=dynamic dbi:mysql:foodb myuname mypass
118 Reference an existing Schema of any kind, and provide some connection information for ->config:
120 script/myapp_create.pl model CatalystModelName DBIC::Schema \
121 MyApp::SchemaClass dbi:mysql:foodb myuname mypass
123 Same, but don't supply connect information yet (you'll need to do this
124 in your app config, or [not recommended] in the schema itself).
126 script/myapp_create.pl model ModelName DBIC::Schema My::SchemaClass
130 has helper => (is => 'ro', isa => 'Catalyst::Helper', required => 1);
131 has create => (is => 'rw', isa => CreateOption);
132 has args => (is => 'ro', isa => ArrayRef);
133 has traits => (is => 'rw', isa => ArrayRef);
134 has schema_class => (is => 'ro', isa => Str, required => 1);
135 has loader_args => (is => 'rw', isa => HashRef);
136 has connect_info => (is => 'rw', isa => HashRef);
137 has old_schema => (is => 'rw', isa => Bool, lazy_build => 1);
138 has components => (is => 'rw', isa => ArrayRef);
144 This is called by L<Catalyst::Helper> with the commandline args to generate the
150 my ($package, $helper, $schema_class, @args) = @_;
152 my $self = $package->new(
154 schema_class => $schema_class,
163 my $helper = $self->helper;
164 my @args = $self->args->flatten if $self->args;
166 $helper->{schema_class} = $self->schema_class;
168 @args = $self->_cleanup_args(\@args);
170 my ($traits_idx, $traits);
171 if (($traits_idx = firstidx { ($traits) = /^traits=(\S*)\z/ } @args) != -1) {
172 my @traits = split /,/ => $traits;
174 $self->traits(\@traits);
176 $helper->{traits} = '['
177 .(join ',' => map { qq{'$_'} } ($self->traits->flatten))
180 splice @args, $traits_idx, 1, ();
183 if ($args[0] && $args[0] =~ /^create=(\S*)\z/) {
188 $self->_parse_loader_args(\@args);
190 $helper->{loader_args} = $self->_build_helper_loader_args;
193 if (first { ($dbi_dsn_part) = /^(dbi):/i } @args) {
195 qq{DSN must start with 'dbi:' not '$dbi_dsn_part' (case matters!)}
196 if $dbi_dsn_part ne 'dbi';
198 $helper->{setup_connect_info} = 1;
200 $helper->{connect_info} =
201 $self->_build_helper_connect_info(\@args);
203 $self->_parse_connect_info(\@args);
208 $helper->{generator} = ref $self;
209 $helper->{generator_version} = $VERSION;
214 Can be called on an instance to generate the files.
221 if ($self->create eq 'dynamic') {
222 $self->_print_dynamic_deprecation_warning;
223 $self->_gen_dynamic_schema;
224 } elsif ($self->create eq 'static') {
225 $self->_gen_static_schema;
231 sub _parse_loader_args {
232 my ($self, $args) = @_;
234 my %loader_args = $self->_read_loader_args($args);
236 while (my ($key, $val) = each %loader_args) {
237 next if $key =~ /^(?:components|constraint|exclude)\z/;
239 $loader_args{$key} = $self->_eval($val);
240 die "syntax error for loader args key '$key' with value '$val': $@"
245 $self->_build_loader_components(delete $loader_args{components});
247 $self->components(\@components);
249 for my $re_opt (qw/constraint exclude/) {
250 $loader_args{$re_opt} = qr/$loader_args{$re_opt}/
251 if exists $loader_args{$re_opt};
254 tie my %result, 'Tie::IxHash';
258 (%loader_args ? %loader_args : ()),
259 (!$self->old_schema ? (
263 components => \@components
267 $self->loader_args(\%result);
269 wantarray ? %result : \%result;
272 sub _read_loader_args {
273 my ($self, $args) = @_;
277 while (@$args && $args->[0] !~ /^dbi:/i) {
278 my ($key, $val) = split /=/, shift(@$args), 2;
280 if ($self->_is_struct($val)) {
281 $loader_args{$key} = $val;
282 } elsif ((my @vals = split /,/ => $val) > 1) {
283 $loader_args{$key} = \@vals;
285 $loader_args{$key} = $val;
289 wantarray ? %loader_args : \%loader_args;
292 sub _build_helper_loader_args {
295 my $args = $self->loader_args;
297 tie my %loader_args, 'Tie::IxHash';
299 while (my ($arg, $val) = each %$args) {
301 $loader_args{$arg} = $self->_data_struct_to_string($val);
303 $loader_args{$arg} = qq{'$val'};
310 sub _build_loader_components {
311 my ($self, $components) = @_;
313 my @components = $self->old_schema ? () : ('InflateColumn::DateTime');
316 $components = [ $components ] if !ref $components;
317 push @components, @$components;
320 wantarray ? @components : \@components;
323 sub _build_helper_connect_info {
324 my ($self, $connect_info) = @_;
326 my @connect_info = @$connect_info;
328 my ($dsn, $user, $password) = $self->_get_dsn_user_pass(\@connect_info);
330 tie my %helper_connect_info, 'Tie::IxHash';
332 %helper_connect_info = (
335 password => qq{'$password'}
338 for (@connect_info) {
339 if (/^\s*{.*}\s*\z/) {
340 my $hash = $self->_eval($_);
341 die "Syntax errorr in connect_info hash: $_: $@" if $@;
344 for my $key (keys %hash) {
345 my $val = $hash{$key};
348 $val = $self->_data_struct_to_string($val);
350 $val = $self->_quote($val);
353 $helper_connect_info{$key} = $val;
359 my ($key, $val) = split /=/, $_, 2;
361 if ($key eq 'quote_char') {
362 $helper_connect_info{$key} = length($val) == 1 ?
363 $self->_quote($val) :
364 $self->_data_struct_to_string([split //, $val]);
366 $helper_connect_info{$key} = $self->_quote_unless_struct($val);
370 \%helper_connect_info
373 sub _build_old_schema {
376 my @schema_pm = split '::', $self->schema_class;
377 $schema_pm[-1] .= '.pm';
379 File::Spec->catfile($self->helper->{base}, 'lib', @schema_pm);
381 if (-f $schema_file) {
382 my $schema_code = do { local (@ARGV, $/) = $schema_file; <> };
383 return 1 if $schema_code =~ /->load_classes/;
389 sub _data_struct_to_string {
390 my ($self, $data) = @_;
392 local $Data::Dumper::Terse = 1;
393 local $Data::Dumper::Quotekeys = 0;
394 local $Data::Dumper::Indent = 0;
395 local $Data::Dumper::Useqq = 1;
397 return Data::Dumper->Dump([$data]);
400 sub _get_dsn_user_pass {
401 my ($self, $connect_info) = @_;
403 my $dsn = shift @$connect_info;
404 my ($user, $password);
406 if ($dsn =~ /sqlite/i) {
407 ($user, $password) = ('', '');
408 shift @$connect_info while @$connect_info and $connect_info->[0] eq '';
410 ($user, $password) = splice @$connect_info, 0, 2;
413 ($dsn, $user, $password)
416 sub _parse_connect_info {
417 my ($self, $connect_info) = @_;
419 my @connect_info = @$connect_info;
421 my ($dsn, $user, $password) = $self->_get_dsn_user_pass(\@connect_info);
423 tie my %connect_info, 'Tie::IxHash';
424 @connect_info{qw/dsn user password/} = ($dsn, $user, $password);
426 for (@connect_info) {
427 if (/^\s*{.*}\s*\z/) {
428 my $hash = $self->_eval($_);
429 die "Syntax errorr in connect_info hash: $_: $@" if $@;
431 %connect_info = (%connect_info, %$hash);
436 my ($key, $val) = split /=/, $_, 2;
438 if ($key eq 'quote_char') {
439 $connect_info{$key} = length($val) == 1 ? $val : [split //, $val];
440 } elsif ($key =~ /^(?:name_sep|limit_dialect)\z/) {
441 $connect_info{$key} = $val;
443 $connect_info{$key} = $self->_eval($val);
446 die "syntax error for connect_info key '$key' with value '$val': $@"
450 $self->connect_info(\%connect_info);
456 my ($self, $val) = @_;
458 return $val =~ /^\s*[[{]/;
462 my ($self, $val) = @_;
464 return 'q{'.$val.'}';
467 sub _quote_unless_struct {
468 my ($self, $val) = @_;
470 $val = $self->_quote($val) if not $self->_is_struct($val);
476 my ($self, $code) = @_;
478 return $code if looks_like_number $code;
480 return $code if $code =~ m{^[\w;:/]*\z};
482 return eval "{no strict; $code}";
485 sub _gen_dynamic_schema {
488 my $helper = $self->helper;
490 my @schema_parts = split(/\:\:/, $self->schema_class);
491 my $schema_file_part = pop @schema_parts;
493 my $schema_dir = File::Spec->catfile(
494 $helper->{base}, 'lib', @schema_parts
496 my $schema_file = File::Spec->catfile(
497 $schema_dir, $schema_file_part . '.pm'
500 $helper->mk_dir($schema_dir);
501 $helper->render_file('schemaclass', $schema_file);
504 sub _gen_static_schema {
507 die "cannot load schema without connect info" unless $self->connect_info;
509 my $helper = $self->helper;
511 my $schema_dir = File::Spec->catfile($helper->{base}, 'lib');
513 eval { Class::MOP::load_class('DBIx::Class::Schema::Loader') };
514 die "Cannot load DBIx::Class::Schema::Loader: $@" if $@;
516 DBIx::Class::Schema::Loader->import(
517 "dump_to_dir:$schema_dir", 'make_schema_at'
523 [$self->connect_info]
529 my $helper = $self->helper;
531 $helper->render_file('compclass', $helper->{file} );
534 sub _print_dynamic_deprecation_warning {
536 ************************************ WARNING **********************************
537 * create=dynamic is DEPRECATED, please use create=static instead. *
538 *******************************************************************************
540 print "Continue? [y/n]: ";
541 chomp(my $response = <STDIN>);
542 exit 0 if $response =~ /^n(o)?\z/;
546 my ($self, $args) = @_;
548 # remove blanks, ie. someoned doing foo \ bar
549 my @res = grep !/^\s+\z/, @$args;
551 # remove leading whitespace, ie. foo \ bar
559 General Catalyst Stuff:
561 L<Catalyst::Manual>, L<Catalyst::Test>, L<Catalyst::Request>,
562 L<Catalyst::Response>, L<Catalyst::Helper>, L<Catalyst>,
564 Stuff related to DBIC and this Model style:
566 L<DBIx::Class>, L<DBIx::Class::Schema>,
567 L<DBIx::Class::Schema::Loader>, L<Catalyst::Model::DBIC::Schema>
571 Brandon L Black, C<blblack@gmail.com>
575 Rafael Kitover, C<rkitover at cpan.org>
579 This library is free software, you can redistribute it and/or modify
580 it under the same terms as Perl itself.
591 package [% schema_class %];
594 use base qw/DBIx::Class::Schema::Loader/;
596 __PACKAGE__->loader_options(
597 [%- FOREACH key = loader_args.keys %]
598 [% key %] => [% loader_args.${key} %],
605 [% schema_class %] - L<DBIx::Class::Schema::Loader> class
613 Dynamic L<DBIx::Class::Schema::Loader> schema for use in L<[% class %]>
617 [% generator %] - [% generator_version %]
621 [% author.replace(',+$', '') %]
625 This library is free software, you can redistribute it and/or modify
626 it under the same terms as Perl itself.
636 use base 'Catalyst::Model::DBIC::Schema';
639 schema_class => '[% schema_class %]',
640 [% IF traits %]traits => [% traits %],[% END %]
641 [% IF setup_connect_info %]connect_info => {
642 [%- FOREACH key = connect_info.keys %]
643 [% key %] => [% connect_info.${key} %],
651 [% class %] - Catalyst DBIC Schema Model
659 L<Catalyst::Model::DBIC::Schema> Model using schema L<[% schema_class %]>
663 [% generator %] - [% generator_version %]
667 [% author.replace(',+$', '') %]
671 This library is free software, you can redistribute it and/or modify
672 it under the same terms as Perl itself.