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';
17 use namespace::clean -except => 'meta';
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 ] [ roles=role1,role2... ] \
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<roles> is the list of roles 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 B<ON WINDOWS COMMAND LINES QUOTING RULES ARE DIFFERENT>
92 In C<cmd.exe> the above example would be:
94 script/myapp_create.pl model CatalystModelName DBIC::Schema \
95 MyApp::SchemaClass create=static dbi:SQLite:foo.db \
96 AutoCommit=1 cursor_class=DBIx::Class::Cursor::Cached \
97 on_connect_do="[\"select 1\", \"select 2\"]" quote_char="\""
99 Same, but with extra Schema::Loader args (separate multiple values by commas):
101 script/myapp_create.pl model CatalystModelName DBIC::Schema \
102 MyApp::SchemaClass create=static db_schema=foodb components=Foo,Bar \
103 exclude='^(wibble|wobble)$' moniker_map='{ foo => "FOO" }' \
104 dbi:Pg:dbname=foodb myuname mypass
106 See L<DBIx::Class::Schema::Loader::Base> for a list of options
108 Create a dynamic DBIx::Class::Schema::Loader-based Schema,
109 and a Model which references it (B<DEPRECATED>):
111 script/myapp_create.pl model CatalystModelName DBIC::Schema \
112 MyApp::SchemaClass create=dynamic dbi:mysql:foodb myuname mypass
114 Reference an existing Schema of any kind, and provide some connection information for ->config:
116 script/myapp_create.pl model CatalystModelName DBIC::Schema \
117 MyApp::SchemaClass dbi:mysql:foodb myuname mypass
119 Same, but don't supply connect information yet (you'll need to do this
120 in your app config, or [not recommended] in the schema itself).
122 script/myapp_create.pl model ModelName DBIC::Schema My::SchemaClass
126 has helper => (is => 'ro', isa => 'Catalyst::Helper', required => 1);
127 has create => (is => 'rw', isa => CreateOption);
128 has args => (is => 'ro', isa => ArrayRef);
129 has roles => (is => 'rw', isa => ArrayRef);
130 has schema_class => (is => 'ro', isa => Str, required => 1);
131 has loader_args => (is => 'rw', isa => HashRef);
132 has connect_info => (is => 'rw', isa => HashRef);
133 has old_schema => (is => 'rw', isa => Bool, lazy_build => 1);
134 has components => (is => 'rw', isa => ArrayRef);
140 This is called by L<Catalyst::Helper> with the commandline args to generate the
146 my ($package, $helper, $schema_class, @args) = @_;
148 my $self = $package->new(
150 schema_class => $schema_class,
159 my $helper = $self->helper;
160 my @args = $self->args->flatten if $self->args;
162 $helper->{schema_class} = $self->schema_class;
164 @args = $self->_cleanup_args(\@args);
166 my ($roles_idx, $roles);
167 if (($roles_idx = firstidx { ($roles) = /^roles=(\S*)\z/ } @args) != -1) {
168 my @roles = split /,/ => $roles;
170 $self->roles(\@roles);
172 $helper->{roles} = '['
173 .(join ',' => map { qq{'$_'} } ($self->roles->flatten))
176 splice @args, $roles_idx, 1, ();
179 if ($args[0] && $args[0] =~ /^create=(\S*)\z/) {
184 $self->_parse_loader_args(\@args);
186 $helper->{loader_args} = $self->_build_helper_loader_args;
188 if (first { /^dbi:/i } @args) {
189 $helper->{setup_connect_info} = 1;
191 $helper->{connect_info} =
192 $self->_build_helper_connect_info(\@args);
194 $self->_parse_connect_info(\@args);
199 $helper->{generator} = ref $self;
200 $helper->{generator_version} = $VERSION;
206 if ($self->create eq 'dynamic') {
207 $self->_print_dynamic_deprecation_warning;
208 $self->_gen_dynamic_schema;
209 } elsif ($self->create eq 'static') {
210 $self->_gen_static_schema;
216 sub _parse_loader_args {
217 my ($self, $args) = @_;
219 my %loader_args = $self->_read_loader_args($args);
221 while (my ($key, $val) = each %loader_args) {
222 next if $key =~ /^(?:components|constraint|exclude)\z/;
224 $loader_args{$key} = eval $val;
225 die "syntax error for loader args key '$key' with value '$val': $@"
230 $self->_build_loader_components(delete $loader_args{components});
232 $self->components(\@components);
234 for my $re_opt (qw/constraint exclude/) {
235 $loader_args{$re_opt} = qr/$loader_args{$re_opt}/
236 if exists $loader_args{$re_opt};
239 tie my %result, 'Tie::IxHash';
243 (%loader_args ? %loader_args : ()),
244 (!$self->old_schema ? (
248 components => \@components
252 $self->loader_args(\%result);
254 wantarray ? %result : \%result;
257 sub _read_loader_args {
258 my ($self, $args) = @_;
262 while (@$args && $args->[0] !~ /^dbi:/) {
263 my ($key, $val) = split /=/, shift(@$args), 2;
265 if ($self->_is_struct($val)) {
266 $loader_args{$key} = $val;
267 } elsif ((my @vals = split /,/ => $val) > 1) {
268 $loader_args{$key} = \@vals;
270 $loader_args{$key} = $val;
274 wantarray ? %loader_args : \%loader_args;
277 sub _build_helper_loader_args {
280 my $args = $self->loader_args;
282 tie my %loader_args, 'Tie::IxHash';
284 while (my ($arg, $val) = each %$args) {
286 $loader_args{$arg} = $self->_data_struct_to_string($val);
288 $loader_args{$arg} = qq{'$val'};
295 sub _build_loader_components {
296 my ($self, $components) = @_;
298 my @components = $self->old_schema ? () : ('InflateColumn::DateTime');
301 $components = [ $components ] if !ref $components;
302 push @components, @$components;
305 wantarray ? @components : \@components;
308 sub _build_helper_connect_info {
309 my ($self, $connect_info) = @_;
311 my @connect_info = @$connect_info;
313 my ($dsn, $user, $password) = $self->_get_dsn_user_pass(\@connect_info);
315 tie my %helper_connect_info, 'Tie::IxHash';
317 %helper_connect_info = (
320 password => qq{'$password'}
323 for (@connect_info) {
324 if (/^\s*{.*}\s*\z/) {
326 die "Syntax errorr in connect_info hash: $_: $@" if $@;
329 for my $key (keys %hash) {
330 my $val = $hash{$key};
333 $val = $self->_data_struct_to_string($val);
335 $val = 'q{'.$val.'}';
338 $helper_connect_info{$key} = $val;
344 my ($key, $val) = split /=/, $_, 2;
346 $helper_connect_info{$key} = $self->_quote_unless_struct($val);
349 \%helper_connect_info
352 sub _build_old_schema {
355 my @schema_pm = split '::', $self->schema_class;
356 $schema_pm[-1] .= '.pm';
358 File::Spec->catfile($self->helper->{base}, 'lib', @schema_pm);
360 if (-f $schema_file) {
361 my $schema_code = do { local (@ARGV, $/) = $schema_file; <> };
362 return 1 if $schema_code =~ /->load_classes/;
368 sub _data_struct_to_string {
369 my ($self, $data) = @_;
371 local $Data::Dumper::Terse = 1;
372 local $Data::Dumper::Quotekeys = 0;
373 local $Data::Dumper::Indent = 0;
374 local $Data::Dumper::Useqq = 1;
376 return Data::Dumper->Dump([$data]);
379 sub _get_dsn_user_pass {
380 my ($self, $connect_info) = @_;
382 my $dsn = shift @$connect_info;
383 my ($user, $password);
385 if ($dsn =~ /sqlite/i) {
386 ($user, $password) = ('', '');
387 shift @$connect_info while $connect_info->[0] eq '';
389 ($user, $password) = splice @$connect_info, 0, 2;
392 ($dsn, $user, $password)
395 sub _parse_connect_info {
396 my ($self, $connect_info) = @_;
398 my @connect_info = @$connect_info;
400 my ($dsn, $user, $password) = $self->_get_dsn_user_pass(\@connect_info);
402 tie my %connect_info, 'Tie::IxHash';
403 @connect_info{qw/dsn user password/} = ($dsn, $user, $password);
405 for (@connect_info) {
406 if (/^\s*{.*}\s*\z/) {
408 die "Syntax errorr in connect_info hash: $_: $@" if $@;
410 %connect_info = (%connect_info, %$hash);
415 my ($key, $val) = split /=/, $_, 2;
417 if ($key =~ /^(?:quote_char|name_sep)\z/) {
418 $connect_info{$key} = $val;
420 $connect_info{$key} = eval $val;
423 die "syntax error for connect_info key '$key' with value '$val': $@"
427 $self->connect_info(\%connect_info);
433 my ($self, $val) = @_;
435 return $val =~ /^\s*[[{]/;
438 sub _quote_unless_struct {
439 my ($self, $val) = @_;
441 $val = 'q{'.$val.'}' if not $self->_is_struct($val);
446 sub _gen_dynamic_schema {
449 my $helper = $self->helper;
451 my @schema_parts = split(/\:\:/, $self->schema_class);
452 my $schema_file_part = pop @schema_parts;
454 my $schema_dir = File::Spec->catfile(
455 $helper->{base}, 'lib', @schema_parts
457 my $schema_file = File::Spec->catfile(
458 $schema_dir, $schema_file_part . '.pm'
461 $helper->mk_dir($schema_dir);
462 $helper->render_file('schemaclass', $schema_file);
465 sub _gen_static_schema {
468 die "cannot load schema without connect info" unless $self->connect_info;
470 my $helper = $self->helper;
472 my $schema_dir = File::Spec->catfile($helper->{base}, 'lib');
474 eval { Class::MOP::load_class('DBIx::Class::Schema::Loader') };
475 die "Cannot load DBIx::Class::Schema::Loader: $@" if $@;
477 DBIx::Class::Schema::Loader->import(
478 "dump_to_dir:$schema_dir", 'make_schema_at'
484 [$self->connect_info]
490 my $helper = $self->helper;
492 $helper->render_file('compclass', $helper->{file} );
495 sub _print_dynamic_deprecation_warning {
497 ************************************ WARNING **********************************
498 * create=dynamic is DEPRECATED, please use create=static instead. *
499 *******************************************************************************
501 print "Continue? [y/n]: ";
502 chomp(my $response = <STDIN>);
503 exit 0 if $response =~ /^n(o)?\z/;
507 my ($self, $args) = @_;
509 # remove blanks, ie. someoned doing foo \ bar
510 my @res = grep !/^\s+\z/, @$args;
512 # remove leading whitespace, ie. foo \ bar
520 General Catalyst Stuff:
522 L<Catalyst::Manual>, L<Catalyst::Test>, L<Catalyst::Request>,
523 L<Catalyst::Response>, L<Catalyst::Helper>, L<Catalyst>,
525 Stuff related to DBIC and this Model style:
527 L<DBIx::Class>, L<DBIx::Class::Schema>,
528 L<DBIx::Class::Schema::Loader>, L<Catalyst::Model::DBIC::Schema>
532 Brandon L Black, C<blblack@gmail.com>
536 Rafael Kitover, C<<rkitover at cpan.org>>
540 This library is free software, you can redistribute it and/or modify
541 it under the same terms as Perl itself.
552 package [% schema_class %];
555 use base qw/DBIx::Class::Schema::Loader/;
557 __PACKAGE__->loader_options(
558 [%- FOREACH key = loader_args.keys %]
559 [% key %] => [% loader_args.${key} %],
566 [% schema_class %] - L<DBIx::Class::Schema::Loader> class
574 Dynamic L<DBIx::Class::Schema::Loader> schema for use in L<[% class %]>
578 [% generator %] - [% generator_version %]
582 [% author.replace(',+$', '') %]
586 This library is free software, you can redistribute it and/or modify
587 it under the same terms as Perl itself.
597 use base 'Catalyst::Model::DBIC::Schema';
600 schema_class => '[% schema_class %]',
601 [% IF roles %]roles => [% roles %],[% END %]
602 [% IF setup_connect_info %]connect_info => {
603 [%- FOREACH key = connect_info.keys %]
604 [% key %] => [% connect_info.${key} %],
612 [% class %] - Catalyst DBIC Schema Model
620 L<Catalyst::Model::DBIC::Schema> Model using schema L<[% schema_class %]>
624 [% generator %] - [% generator_version %]
628 [% author.replace(',+$', '') %]
632 This library is free software, you can redistribute it and/or modify
633 it under the same terms as Perl itself.