package Catalyst::Helper::Model::DBIC::Schema;
+use namespace::autoclean;
use Moose;
no warnings 'uninitialized';
-our $VERSION = '0.24';
+our $VERSION = '0.45';
+$VERSION = eval $VERSION;
use Carp;
use Tie::IxHash ();
use List::Util 'first';
use MooseX::Types::Moose qw/Str HashRef Bool ArrayRef/;
use Catalyst::Model::DBIC::Schema::Types 'CreateOption';
-use Moose::Autobox;
use List::MoreUtils 'firstidx';
-
-use namespace::clean -except => 'meta';
+use Scalar::Util 'looks_like_number';
+use File::Find 'finddepth';
+use Try::Tiny;
+use Cwd 'getcwd';
=head1 NAME
=head1 SYNOPSIS
script/create.pl model CatalystModelName DBIC::Schema MyApp::SchemaClass \
- [ create=dynamic | create=static ] [ roles=role1,role2... ] \
+ [ create=dynamic | create=static ] [ traits=trait1,trait2... ] \
[ Schema::Loader opts ] [ dsn user pass ] \
[ other connect_info args ]
adapt itself to changes in your database structure. You can edit
the generated classes by hand to refine them.
-C<roles> is the list of roles to apply to the model, see
+C<traits> is the list of traits to apply to the model, see
L<Catalyst::Model::DBIC::Schema> for details.
C<Schema::Loader opts> are described in L</TYPICAL EXAMPLES> below.
AutoCommit=1 cursor_class=DBIx::Class::Cursor::Cached \
on_connect_do='["select 1", "select 2"]' quote_char='"'
+If using a 2 character quote_char:
+
+ script/myapp_create.pl ... quote_char='[]'
+
B<ON WINDOWS COMMAND LINES QUOTING RULES ARE DIFFERENT>
In C<cmd.exe> the above example would be:
exclude='^(wibble|wobble)$' moniker_map='{ foo => "FOO" }' \
dbi:Pg:dbname=foodb myuname mypass
+Coderefs are also supported:
+
+ script/myapp_create.pl model CatalystModelName DBIC::Schema \
+ MyApp::SchemaClass create=static \
+ inflect_singular='sub { $_[0] =~ /\A(.+?)(_id)?\z/; $1 }' \
+ moniker_map='sub { join(q{}, map ucfirst, split(/[\W_]+/, lc $_[0])); }' \
+ dbi:mysql:foodb myuname mypass
+
See L<DBIx::Class::Schema::Loader::Base> for a list of options
Create a dynamic DBIx::Class::Schema::Loader-based Schema,
has helper => (is => 'ro', isa => 'Catalyst::Helper', required => 1);
has create => (is => 'rw', isa => CreateOption);
has args => (is => 'ro', isa => ArrayRef);
-has roles => (is => 'rw', isa => ArrayRef);
+has traits => (is => 'rw', isa => ArrayRef);
has schema_class => (is => 'ro', isa => Str, required => 1);
has loader_args => (is => 'rw', isa => HashRef);
has connect_info => (is => 'rw', isa => HashRef);
has old_schema => (is => 'rw', isa => Bool, lazy_build => 1);
+has is_moose_schema => (is => 'rw', isa => Bool, lazy_build => 1);
+has result_namespace => (is => 'rw', isa => Str, lazy_build => 1);
has components => (is => 'rw', isa => ArrayRef);
=head1 METHODS
sub BUILD {
my $self = shift;
my $helper = $self->helper;
- my @args = $self->args->flatten if $self->args;
+ my @args = @{ $self->args || [] };
$helper->{schema_class} = $self->schema_class;
@args = $self->_cleanup_args(\@args);
- my ($roles_idx, $roles);
- if (($roles_idx = firstidx { ($roles) = /^roles=(\S*)\z/ } @args) != -1) {
- my @roles = split /,/ => $roles;
+ my ($traits_idx, $traits);
+ if (($traits_idx = firstidx { ($traits) = /^traits=(\S*)\z/ } @args) != -1) {
+ my @traits = split /,/ => $traits;
- $self->roles(\@roles);
+ $self->traits(\@traits);
- $helper->{roles} = '['
- .(join ',' => map { qq{'$_'} } ($self->roles->flatten))
+ $helper->{traits} = '['
+ .(join ',' => map { qq{'$_'} } @traits)
.']';
- splice @args, $roles_idx, 1, ();
+ splice @args, $traits_idx, 1, ();
}
if ($args[0] && $args[0] =~ /^create=(\S*)\z/) {
$self->_parse_loader_args(\@args);
$helper->{loader_args} = $self->_build_helper_loader_args;
+ }
+ }
- if (first { /^dbi:/i } @args) {
- $helper->{setup_connect_info} = 1;
+ my $dbi_dsn_part;
+ if (first { ($dbi_dsn_part) = /^(dbi):/i } @args) {
+ die
+qq{DSN must start with 'dbi:' not '$dbi_dsn_part' (case matters!)}
+ if $dbi_dsn_part ne 'dbi';
- $helper->{connect_info} =
- $self->_build_helper_connect_info(\@args);
+ $helper->{setup_connect_info} = 1;
- $self->_parse_connect_info(\@args);
- }
- }
+ $helper->{connect_info} =
+ $self->_build_helper_connect_info(\@args);
+
+ $self->_parse_connect_info(\@args);
}
$helper->{generator} = ref $self;
while (my ($key, $val) = each %loader_args) {
next if $key =~ /^(?:components|constraint|exclude)\z/;
- $loader_args{$key} = eval $val;
+ $loader_args{$key} = $self->_eval($val);
die "syntax error for loader args key '$key' with value '$val': $@"
if $@;
}
- my @components =
- $self->_build_loader_components(delete $loader_args{components});
+ my @components = $self->_build_loader_components(
+ delete $loader_args{components},
+ $loader_args{use_namespaces},
+ );
$self->components(\@components);
%result = (
relationships => 1,
- (%loader_args ? %loader_args : ()),
+ use_moose => $self->is_moose_schema ? 1 : 0,
+ col_collision_map => 'column_%s',
(!$self->old_schema ? (
use_namespaces => 1
) : ()),
(@components ? (
components => \@components
- ) : ())
+ ) : ()),
+ (%loader_args ? %loader_args : ()),
);
$self->loader_args(\%result);
my %loader_args;
- while (@$args && $args->[0] !~ /^dbi:/) {
+ while (@$args && $args->[0] !~ /^dbi:/i) {
my ($key, $val) = split /=/, shift(@$args), 2;
if ($self->_is_struct($val)) {
}
sub _build_loader_components {
- my ($self, $components) = @_;
+ my ($self, $components, $use_namespaces) = @_;
- my @components = $self->old_schema ? () : ('InflateColumn::DateTime');
+ my @components = $self->old_schema && (not $use_namespaces) ? ()
+ : ('InflateColumn::DateTime');
if ($components) {
$components = [ $components ] if !ref $components;
for (@connect_info) {
if (/^\s*{.*}\s*\z/) {
- my $hash = eval $_;
+ my $hash = $self->_eval($_);
die "Syntax errorr in connect_info hash: $_: $@" if $@;
my %hash = %$hash;
if (ref $val) {
$val = $self->_data_struct_to_string($val);
} else {
- $val = 'q{'.$val.'}';
+ $val = $self->_quote($val);
}
$helper_connect_info{$key} = $val;
my ($key, $val) = split /=/, $_, 2;
- $helper_connect_info{$key} = $self->_quote_unless_struct($val);
+ if ($key eq 'quote_char') {
+ $helper_connect_info{$key} = length($val) == 1 ?
+ $self->_quote($val) :
+ $self->_data_struct_to_string([split //, $val]);
+ } else {
+ $helper_connect_info{$key} = $self->_quote_unless_struct($val);
+ }
}
\%helper_connect_info
sub _build_old_schema {
my $self = shift;
- my @schema_pm = split '::', $self->schema_class;
- $schema_pm[-1] .= '.pm';
- my $schema_file =
- File::Spec->catfile($self->helper->{base}, 'lib', @schema_pm);
+ return $self->result_namespace eq '' ? 1 : 0;
+}
+
+sub _build_is_moose_schema {
+ my $self = shift;
+
+ my @schema_parts = split '::', $self->schema_class;
+
+ my $result_dir = File::Spec->catfile(
+ $self->helper->{base}, 'lib', @schema_parts, $self->result_namespace
+ );
+
+ # assume yes for new schemas
+ return 1 if not -d $result_dir;
+
+ my $uses_moose = 1;
+
+ my $cwd = getcwd;
+
+ try {
+ finddepth(sub {
+ return if $File::Find::name !~ /\.pm\z/;
+
+ open my $fh, '<', $File::Find::name
+ or die "Could not open $File::Find::name: $!";
+
+ my $code = do { local $/; <$fh> };
+ close $fh;
+
+ $uses_moose = 0 if $code !~ /\nuse Moose;\n/;
+
+ die;
+ }, $result_dir);
+ };
+
+ chdir $cwd;
+
+ return $uses_moose;
+}
+
+sub _build_result_namespace {
+ my $self = shift;
+
+ my @schema_parts = split '::', $self->schema_class;
+ my $schema_pm =
+ File::Spec->catfile($self->helper->{base}, 'lib', @schema_parts) . '.pm';
+
+ if (not -f $schema_pm) {
+ try { Class::MOP::load_class('DBIx::Class::Schema::Loader') };
- if (-f $schema_file) {
- my $schema_code = do { local (@ARGV, $/) = $schema_file; <> };
- return 1 if $schema_code =~ /->load_classes/;
+ return 'Result' if $@;
+
+ return DBIx::Class::Schema::Loader->VERSION('0.05') ? 'Result' : '';
}
- 0;
+ open my $fh, '<', $schema_pm or die "Could not open $schema_pm: $!";
+ my $code = do { local $/; <$fh> };
+ close $fh;
+
+ my ($result_namespace) = $code =~ /result_namespace => '([^']+)'/;
+
+ if (not $result_namespace) {
+ if ($code =~ /->load_classes/) {
+ $result_namespace = '';
+ }
+ else {
+ $result_namespace = 'Result';
+ }
+ }
+
+ return $result_namespace;
}
sub _data_struct_to_string {
if ($dsn =~ /sqlite/i) {
($user, $password) = ('', '');
- shift @$connect_info while $connect_info->[0] eq '';
+ shift @$connect_info while @$connect_info and $connect_info->[0] eq '';
} else {
($user, $password) = splice @$connect_info, 0, 2;
}
for (@connect_info) {
if (/^\s*{.*}\s*\z/) {
- my $hash = eval $_;
+ my $hash = $self->_eval($_);
die "Syntax errorr in connect_info hash: $_: $@" if $@;
%connect_info = (%connect_info, %$hash);
my ($key, $val) = split /=/, $_, 2;
- if ($key =~ /^(?:quote_char|name_sep|limit_dialect)\z/) {
+ if ($key eq 'quote_char') {
+ $connect_info{$key} = length($val) == 1 ? $val : [split //, $val];
+ } elsif ($key =~ /^(?:name_sep|limit_dialect)\z/) {
$connect_info{$key} = $val;
} else {
- $connect_info{$key} = eval $val;
+ $connect_info{$key} = $self->_eval($val);
}
die "syntax error for connect_info key '$key' with value '$val': $@"
sub _is_struct {
my ($self, $val) = @_;
- return $val =~ /^\s*[[{]/;
+ return $val =~ /^\s*(?:sub|[[{])/;
+}
+
+sub _quote {
+ my ($self, $val) = @_;
+
+ return 'q{'.$val.'}';
}
sub _quote_unless_struct {
my ($self, $val) = @_;
- $val = 'q{'.$val.'}' if not $self->_is_struct($val);
+ $val = $self->_quote($val) if not $self->_is_struct($val);
+
+ return $val;
+}
+
+sub _eval {
+ my ($self, $code) = @_;
+
+ return $code if looks_like_number $code;
+
+ return $code if not $self->_is_struct($code);
- $val;
+ return eval "{no strict; $code}";
}
sub _gen_dynamic_schema {
my $schema_dir = File::Spec->catfile($helper->{base}, 'lib');
- eval { Class::MOP::load_class('DBIx::Class::Schema::Loader') };
+ try { Class::MOP::load_class('DBIx::Class::Schema::Loader') };
die "Cannot load DBIx::Class::Schema::Loader: $@" if $@;
DBIx::Class::Schema::Loader->import(
=head1 AUTHOR
-Brandon L Black, C<blblack@gmail.com>
+See L<Catalyst::Model::DBIC::Schema/AUTHOR> and
+L<Catalyst::Model::DBIC::Schema/CONTRIBUTORS>.
-Contributors:
+=head1 COPYRIGHT
-Rafael Kitover, C<<rkitover at cpan.org>>
+See L<Catalyst::Model::DBIC::Schema/COPYRIGHT>.
=head1 LICENSE
__PACKAGE__->config(
schema_class => '[% schema_class %]',
- [% IF roles %]roles => [% roles %],[% END %]
+ [% IF traits %]traits => [% traits %],[% END %]
[% IF setup_connect_info %]connect_info => {
[%- FOREACH key = connect_info.keys %]
[% key %] => [% connect_info.${key} %],