Make compose_namespace and install_model_shortcut configurable.
[catagits/Catalyst-Model-DBIC-Schema.git] / lib / Catalyst / Helper / Model / DBIC / Schema.pm
index 8cdea7e..f50b2e5 100644 (file)
@@ -1,22 +1,24 @@
 package Catalyst::Helper::Model::DBIC::Schema;
 
-use strict;
-use warnings;
+use namespace::autoclean;
+use Moose;
 no warnings 'uninitialized';
 
-our $VERSION = '0.24';
-
-use parent 'Class::Accessor::Fast';
+our $VERSION = '0.65';
+$VERSION = eval $VERSION;
 
 use Carp;
-use UNIVERSAL::require;
 use Tie::IxHash ();
 use Data::Dumper ();
-use List::Util ();
-
-__PACKAGE__->mk_accessors(qw/
-  helper schema_class loader_args connect_info _old_schema
-/);
+use List::Util 'first';
+use MooseX::Types::Moose qw/Str HashRef Bool ArrayRef/;
+use Catalyst::Model::DBIC::Schema::Types 'CreateOption';
+use List::MoreUtils 'firstidx';
+use Scalar::Util 'looks_like_number';
+use File::Find 'finddepth';
+use Try::Tiny;
+use Cwd 'getcwd';
+use Module::Runtime 'use_module';
 
 =head1 NAME
 
@@ -25,8 +27,9 @@ Catalyst::Helper::Model::DBIC::Schema - Helper for DBIC Schema Models
 =head1 SYNOPSIS
 
   script/create.pl model CatalystModelName DBIC::Schema MyApp::SchemaClass \
-    [ create=dynamic | create=static ] [ Schema::Loader opts ] \
-    [ dsn user pass ] [ other connect_info arguments ]
+    [ create=dynamic | create=static ] [ traits=trait1,trait2... ] \
+    [ Schema::Loader opts ] [ dsn user pass ] \
+    [ other connect_info args ]
 
 =head1 DESCRIPTION
 
@@ -56,49 +59,95 @@ L<DBIx::Class::Schema::Loader> at runtime, and will not automatically
 adapt itself to changes in your database structure.  You can edit
 the generated classes by hand to refine them.
 
-C<connect_info> arguments are the same as what
-DBIx::Class::Schema::connect expects, and are storage_type-specific.
-For DBI-based storage, these arguments are the dsn, username,
-password, and connect options, respectively.  These are optional for
-existing Schemas, but required if you use either of the C<create=>
-options.
+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 documented in L<DBIx::Class::Schema::Loader::Base>
+and some examples are given in L</TYPICAL EXAMPLES> below.
+
+C<connect_info> arguments are the same as what L<DBIx::Class::Schema/connect>
+expects, and are storage_type-specific. They are documented in
+L<DBIx::Class::Storage::DBI/connect_info>. For DBI-based storage, these
+arguments are the dsn, username, password, and connect options, respectively.
+These are optional for existing Schemas, but required if you use either of the
+C<create=> options.
+
+username and password can be omitted for C<SQLite> dsns.
 
 Use of either of the C<create=> options requires L<DBIx::Class::Schema::Loader>.
 
 =head1 TYPICAL EXAMPLES
 
-  # Use DBIx::Class::Schema::Loader to create a static DBIx::Class::Schema,
-  #  and a Model which references it:
+Use DBIx::Class::Schema::Loader to create a static DBIx::Class::Schema,
+and a Model which references it:
+
   script/myapp_create.pl model CatalystModelName DBIC::Schema \
     MyApp::SchemaClass create=static dbi:mysql:foodb myuname mypass
 
-  # Same, with extra connect_info args
+Same, with extra connect_info args
+user and pass can be omitted for sqlite, since they are always empty
+
+  script/myapp_create.pl model CatalystModelName DBIC::Schema \
+    MyApp::SchemaClass create=static dbi:SQLite:foo.db \
+    AutoCommit=1 cursor_class=DBIx::Class::Cursor::Cached \
+    on_connect_do='["select 1", "select 2"]' quote_names=1
+
+B<ON WINDOWS COMMAND LINES QUOTING RULES ARE DIFFERENT>
+
+In C<cmd.exe> the above example would be:
+
   script/myapp_create.pl model CatalystModelName DBIC::Schema \
-    MyApp::SchemaClass create=static dbi:SQLite:foo.db '' '' \
+    MyApp::SchemaClass create=static dbi:SQLite:foo.db \
     AutoCommit=1 cursor_class=DBIx::Class::Cursor::Cached \
-    on_connect_do='["select 1", "select 2"]'
+    on_connect_do="[\"select 1\", \"select 2\"]" quote_names=1
+
+Same, but with extra Schema::Loader args (separate multiple values by commas):
 
-  # Same, but with extra Schema::Loader args (separate multiple values by commas):
   script/myapp_create.pl model CatalystModelName DBIC::Schema \
     MyApp::SchemaClass create=static db_schema=foodb components=Foo,Bar \
-    exclude='^wibble|wobble$' moniker_map='{ foo => "FFFFUUUU" }' \
+    exclude='^(wibble|wobble)$' moniker_map='{ foo => "FOO" }' \
     dbi:Pg:dbname=foodb myuname mypass
 
-  # See DBIx::Class::Schema::Loader::Base for list of options
+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,
+and a Model which references it (B<DEPRECATED>):
 
-  # Create a dynamic DBIx::Class::Schema::Loader-based Schema,
-  #  and a Model which references it:
   script/myapp_create.pl model CatalystModelName DBIC::Schema \
     MyApp::SchemaClass create=dynamic dbi:mysql:foodb myuname mypass
 
-  # Reference an existing Schema of any kind, and provide some connection information for ->config:
+Reference an existing Schema of any kind, and provide some connection information for ->config:
+
   script/myapp_create.pl model CatalystModelName DBIC::Schema \
     MyApp::SchemaClass dbi:mysql:foodb myuname mypass
 
-  # Same, but don't supply connect information yet (you'll need to do this
-  #  in your app config, or [not recommended] in the schema itself).
+Same, but don't supply connect information yet (you'll need to do this
+in your app config, or [not recommended] in the schema itself).
+
   script/myapp_create.pl model ModelName DBIC::Schema My::SchemaClass
 
+=cut
+
+has helper => (is => 'ro', isa => 'Catalyst::Helper', required => 1);
+has create => (is => 'rw', isa => CreateOption);
+has args => (is => 'ro', 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
 
 =head2 mk_compclass
@@ -111,40 +160,79 @@ files.
 sub mk_compclass {
     my ($package, $helper, $schema_class, @args) = @_;
 
-    my $self = $package->new;
+    my $self = $package->new(
+        helper => $helper,
+        schema_class => $schema_class,
+        args => \@args
+    );
+
+    $self->run;
+}
+
+sub BUILD {
+    my $self   = shift;
+    my $helper = $self->helper;
+    my @args   = @{ $self->args || [] };
+
+    $helper->{schema_class} = $self->schema_class;
+
+    @args = $self->_cleanup_args(\@args);
 
-    $helper->{schema_class} = $schema_class
-        or croak "Must supply schema class name";
+    my ($traits_idx, $traits);
+    if (($traits_idx = firstidx { ($traits) = /^traits=(\S*)\z/ } @args) != -1) {
+        my @traits = split /,/ => $traits;
 
-    $self->schema_class($schema_class);
-    $self->helper($helper);
+        $self->traits(\@traits);
 
-    my $create = '';
-    if ($args[0] && $args[0] =~ /^create=(dynamic|static)$/) {
-        $create = $1;
+        $helper->{traits} = '['
+            .(join ',' => map { qq{'$_'} } @traits)
+            .']';
+
+        splice @args, $traits_idx, 1, ();
+    }
+
+    if ($args[0] && $args[0] =~ /^create=(\S*)\z/) {
+        $self->create($1);
         shift @args;
 
         if (@args) {
             $self->_parse_loader_args(\@args);
 
-            if (List::Util::first { /dbi:/ } @args) {
-                $helper->{setup_connect_info} = 1;
+            $helper->{loader_args} = $self->_build_helper_loader_args;
+        }
+    }
 
-                $helper->{connect_info} =
-                $self->_build_helper_connect_info(\@args);
+    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';
 
-                $self->_parse_connect_info(\@args) if $create eq 'static';
-            }
-        }
+        $helper->{setup_connect_info} = 1;
+
+        $helper->{connect_info} =
+            $self->_build_helper_connect_info(\@args);
+
+        $self->_parse_connect_info(\@args);
     }
 
     $helper->{generator} = ref $self;
     $helper->{generator_version} = $VERSION;
+}
+
+=head2 run
+
+Can be called on an instance to generate the files.
+
+=cut
+
+sub run {
+    my $self = shift;
 
-    if ($create eq 'dynamic') {
-        $self->helper->{loader_args} = $self->_build_helper_loader_args;
+    if ($self->create eq 'dynamic') {
+        $self->_print_dynamic_deprecation_warning;
         $self->_gen_dynamic_schema;
-    } elsif ($create eq 'static') {
+    } elsif ($self->create eq 'static') {
         $self->_gen_static_schema;
     }
 
@@ -159,13 +247,17 @@ sub _parse_loader_args {
     while (my ($key, $val) = each %loader_args) {
         next if $key =~ /^(?:components|constraint|exclude)\z/;
 
-        $loader_args{$key} = eval $val;
-        croak "syntax error for loader args key '$key' with value '$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);
 
     for my $re_opt (qw/constraint exclude/) {
         $loader_args{$re_opt} = qr/$loader_args{$re_opt}/
@@ -176,13 +268,15 @@ sub _parse_loader_args {
 
     %result = (
         relationships => 1,
-        (%loader_args ? %loader_args : ()),
-        (!$self->_is_old_schema ? (
+        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);
@@ -195,16 +289,59 @@ sub _read_loader_args {
 
     my %loader_args;
 
-    while (@$args && $args->[0] !~ /^dbi:/) {
+    while (@$args && $args->[0] !~ /^dbi:/i) {
         my ($key, $val) = split /=/, shift(@$args), 2;
 
-        if ((my @vals = split /,/ => $val) > 1) {
+        if ($self->_is_struct($val)) {
+            $loader_args{$key} = $val;
+        } elsif ((my @vals = split /,/ => $val) > 1) {
             $loader_args{$key} = \@vals;
         } else {
             $loader_args{$key} = $val;
         }
     }
 
+    # Use args after connect_info as loader args as well, because people always
+    # get the order confused.
+    my $i = 1;
+    if ($args->[0] =~ /sqlite/i) {
+        $i++ if $args->[$i] eq '';
+        $i++ if $args->[$i] eq '';
+    }
+    else {
+        $i += 2;
+    }
+
+    my $have_loader = try {
+        use_module('DBIx::Class::Schema::Loader::Base');
+        1;
+    };
+
+    if ($have_loader) {
+        while (defined $args->[$i]) {
+            $i++ while $self->_is_struct($args->[$i]);
+
+            last if not defined $args->[$i];
+
+            my ($key, $val) = split /=/, $args->[$i], 2;
+
+            if (not DBIx::Class::Schema::Loader::Base->can($key)) {
+                $i++;
+                next;
+            }
+
+            if ($self->_is_struct($val)) {
+                $loader_args{$key} = $val;
+            } elsif ((my @vals = split /,/ => $val) > 1) {
+                $loader_args{$key} = \@vals;
+            } else {
+                $loader_args{$key} = $val;
+            }
+
+            splice @$args, $i, 1;
+        }
+    }
+
     wantarray ? %loader_args : \%loader_args;
 }
 
@@ -227,9 +364,10 @@ sub _build_helper_loader_args {
 }
 
 sub _build_loader_components {
-    my ($self, $components) = @_;
+    my ($self, $components, $use_namespaces) = @_;
 
-    my @components = $self->_is_old_schema ? () : ('InflateColumn::DateTime');
+    my @components = $self->old_schema && (not $use_namespaces) ? ()
+        : ('InflateColumn::DateTime');
 
     if ($components) {
         $components = [ $components ] if !ref $components;
@@ -244,7 +382,7 @@ sub _build_helper_connect_info {
 
     my @connect_info = @$connect_info;
 
-    my ($dsn, $user, $password) = splice @connect_info, 0, 3;
+    my ($dsn, $user, $password) = $self->_get_dsn_user_pass(\@connect_info);
 
     tie my %helper_connect_info, 'Tie::IxHash';
 
@@ -256,8 +394,8 @@ sub _build_helper_connect_info {
 
     for (@connect_info) {
         if (/^\s*{.*}\s*\z/) {
-            my $hash = eval $_;
-            croak "Syntax errorr in connect_info hash: $_: $@" if $@;
+            my $hash = $self->_eval($_);
+            die "Syntax errorr in connect_info hash: $_: $@" if $@;
             my %hash = %$hash;
 
             for my $key (keys %hash) {
@@ -266,7 +404,7 @@ sub _build_helper_connect_info {
                 if (ref $val) {
                     $val = $self->_data_struct_to_string($val);
                 } else {
-                    $val = qq{'$val'};
+                    $val = $self->_quote($val);
                 }
 
                 $helper_connect_info{$key} = $val;
@@ -277,37 +415,131 @@ sub _build_helper_connect_info {
 
         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;
+
+    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) {
+        eval { use_module('DBIx::Class::Schema::Loader') };
+
+        return 'Result' if $@;
+
+        return (try { DBIx::Class::Schema::Loader->VERSION('0.05') }) ? 'Result' : '';
+    }
+
+    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 => '([^']+)'/;
+
+    return $result_namespace if $result_namespace;
+
+    return '' if $code =~ /->load_classes/;
+
+    return 'Result';
+}
+
 sub _data_struct_to_string {
     my ($self, $data) = @_;
 
     local $Data::Dumper::Terse = 1;
     local $Data::Dumper::Quotekeys = 0;
+    local $Data::Dumper::Sortkeys = 1;
     local $Data::Dumper::Indent = 0;
     local $Data::Dumper::Useqq = 1;
 
     return Data::Dumper->Dump([$data]);
 }
 
+sub _get_dsn_user_pass {
+    my ($self, $connect_info) = @_;
+
+    my $dsn = shift @$connect_info;
+    my ($user, $password);
+
+    if ($dsn =~ /sqlite/i) {
+        ($user, $password) = ('', '');
+        shift @$connect_info while @$connect_info and $connect_info->[0] eq '';
+    } else {
+        ($user, $password) = splice @$connect_info, 0, 2;
+    }
+    
+    ($dsn, $user, $password)
+}
+
 sub _parse_connect_info {
     my ($self, $connect_info) = @_;
 
     my @connect_info = @$connect_info;
 
-    my ($dsn, $user, $password) = splice @connect_info, 0, 3;
+    my ($dsn, $user, $password) = $self->_get_dsn_user_pass(\@connect_info);
 
     tie my %connect_info, 'Tie::IxHash';
     @connect_info{qw/dsn user password/} = ($dsn, $user, $password);
 
     for (@connect_info) {
         if (/^\s*{.*}\s*\z/) {
-            my $hash = eval $_;
-            croak "Syntax errorr in connect_info hash: $_: $@" if $@;
+            my $hash = $self->_eval($_);
+            die "Syntax errorr in connect_info hash: $_: $@" if $@;
 
             %connect_info = (%connect_info, %$hash);
 
@@ -316,8 +548,15 @@ sub _parse_connect_info {
 
         my ($key, $val) = split /=/, $_, 2;
 
-        $connect_info{$key} = eval $val;
-        croak "syntax error for connect_info key '$key' with value '$val': $@"
+        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} = $self->_eval($val);
+        }
+
+        die "syntax error for connect_info key '$key' with value '$val': $@"
             if $@;
     }
 
@@ -326,12 +565,34 @@ sub _parse_connect_info {
     \%connect_info
 }
 
+sub _is_struct {
+    my ($self, $val) = @_;
+
+    return $val =~ /^\s*(?:sub|[[{])/;
+}
+
+sub _quote {
+    my ($self, $val) = @_;
+
+    return 'q{'.$val.'}';
+}
+
 sub _quote_unless_struct {
     my ($self, $val) = @_;
 
-    $val = qq{'$val'} if $val !~ /^\s*[[{]/;
+    $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 {
@@ -356,41 +617,41 @@ sub _gen_dynamic_schema {
 sub _gen_static_schema {
     my $self = shift;
 
-    croak "cannot load schema without connect info" unless $self->connect_info;
+    die "cannot load schema without connect info" unless $self->connect_info;
 
     my $helper = $self->helper;
 
     my $schema_dir = File::Spec->catfile($helper->{base}, 'lib');
 
-    DBIx::Class::Schema::Loader->use(
+    try {
+        use_module('DBIx::Class::Schema::Loader')
+    }
+    catch {
+        die "Cannot load DBIx::Class::Schema::Loader: $_";
+    };
+
+    DBIx::Class::Schema::Loader->import(
         "dump_to_dir:$schema_dir", 'make_schema_at'
-    ) or croak "Cannot load DBIx::Class::Schema::Loader: $@";
+    );
 
     make_schema_at(
         $self->schema_class,
         $self->loader_args,
         [$self->connect_info]
     );
-}
 
-sub _is_old_schema {
-    my $self = shift;
+    require lib;
+    lib->import($schema_dir);
 
-    return $self->_old_schema if defined $self->_old_schema;
+    use_module($self->schema_class);
 
-    my @schema_pm   = split '::', $self->schema_class;
-    $schema_pm[-1] .= '.pm';
-    my $schema_file =
-    File::Spec->catfile($self->helper->{base}, 'lib', @schema_pm);
+    my @sources = $self->schema_class->sources;
 
-    if (-f $schema_file) {
-        my $schema_code = do { local (@ARGV, $/) = $schema_file; <> };
-        $self->_old_schema(1) if $schema_code =~ /->load_classes/;
-    } else {
-        $self->_old_schema(0);
+    if (not @sources) {
+        warn <<'EOF';
+WARNING: No tables found, did you forget to specify db_schema?
+EOF
     }
-
-    return $self->_old_schema;
 }
 
 sub _gen_model {
@@ -400,6 +661,29 @@ sub _gen_model {
     $helper->render_file('compclass', $helper->{file} );
 }
 
+sub _print_dynamic_deprecation_warning {
+    warn <<EOF;
+************************************ WARNING **********************************
+* create=dynamic is DEPRECATED, please use create=static instead.             *
+*******************************************************************************
+EOF
+    print "Continue? [y/n]: ";
+    chomp(my $response = <STDIN>);
+    exit 0 if $response =~ /^n(o)?\z/;
+}
+
+sub _cleanup_args {
+    my ($self, $args) = @_;
+
+# remove blanks, ie. someoned doing foo \  bar
+    my @res = grep !/^\s+\z/, @$args;
+
+# remove leading whitespace, ie. foo \ bar
+    s/^\s*// for @res;
+
+    @res
+}
+
 =head1 SEE ALSO
 
 General Catalyst Stuff:
@@ -414,7 +698,12 @@ L<DBIx::Class::Schema::Loader>, L<Catalyst::Model::DBIC::Schema>
 
 =head1 AUTHOR
 
-Brandon L Black, C<blblack@gmail.com>
+See L<Catalyst::Model::DBIC::Schema/AUTHOR> and
+L<Catalyst::Model::DBIC::Schema/CONTRIBUTORS>.
+
+=head1 COPYRIGHT
+
+See L<Catalyst::Model::DBIC::Schema/COPYRIGHT>.
 
 =head1 LICENSE
 
@@ -479,6 +768,7 @@ use base 'Catalyst::Model::DBIC::Schema';
 
 __PACKAGE__->config(
     schema_class => '[% schema_class %]',
+    [% IF traits %]traits => [% traits %],[% END %]
     [% IF setup_connect_info %]connect_info => {
         [%- FOREACH key = connect_info.keys %]
         [% key %] => [% connect_info.${key} %],
@@ -515,3 +805,5 @@ it under the same terms as Perl itself.
 =cut
 
 1;
+__END__
+# vim:sts=4 sw=4: