Merge 'trunk' into 'dbicadmin_refactor'
Peter Rabbitson [Sat, 13 Feb 2010 13:33:20 +0000 (13:33 +0000)]
r8691@Thesaurus (orig r8678):  ribasushi | 2010-02-13 10:07:15 +0100
Autogen comment for Dependencies.pod
r8692@Thesaurus (orig r8679):  ribasushi | 2010-02-13 10:11:24 +0100
Ask for newer M::I
r8698@Thesaurus (orig r8685):  ribasushi | 2010-02-13 11:11:10 +0100
Add author/license to pod
r8699@Thesaurus (orig r8686):  arcanez | 2010-02-13 13:43:22 +0100
fix typo per nuba on irc

Makefile.PL
lib/DBIx/Class.pm
lib/DBIx/Class/Admin.pm [new file with mode: 0644]
lib/DBIx/Class/Admin/Types.pm [new file with mode: 0644]
lib/DBIx/Class/Optional/Dependencies.pm
script/dbicadmin
t/admin/01load.t [new file with mode: 0644]
t/admin/02ddl.t [new file with mode: 0644]
t/admin/03data.t [new file with mode: 0644]
t/admin/10script.t [moved from t/89dbicadmin.t with 83% similarity]
t/lib/DBICTest/Schema/ForceForeign.pm

index 010c3ba..b69ec9f 100644 (file)
@@ -44,7 +44,6 @@ my $runtime_requires = {
   'Class::Inspector'         => '1.24',
   'Data::Page'               => '2.00',
   'DBI'                      => '1.609',
-  'JSON::Any'                => '1.18',
   'MRO::Compat'              => '0.09',
   'Module::Find'             => '0.06',
   'Path::Class'              => '0.16',
index 9f5bdd0..76b4490 100644 (file)
@@ -259,6 +259,8 @@ dyfrgi: Michael Leuchtenburg <michael@slashhome.org>
 
 frew: Arthur Axel "fREW" Schmidt <frioux@gmail.com>
 
+goraxe: Gordon Irving <goraxe@cpan.org>
+
 gphat: Cory G Watson <gphat@cpan.org>
 
 groditi: Guillermo Roditi <groditi@cpan.org>
diff --git a/lib/DBIx/Class/Admin.pm b/lib/DBIx/Class/Admin.pm
new file mode 100644 (file)
index 0000000..e47e93b
--- /dev/null
@@ -0,0 +1,569 @@
+package DBIx::Class::Admin;
+
+# check deps
+BEGIN {
+  use Carp::Clan qw/^DBIx::Class/;
+  use DBIx::Class;
+  croak('The following modules are required for DBIx::Class::Admin ' . DBIx::Class::Optional::Dependencies->req_missing_for ('admin') )
+    unless DBIx::Class::Optional::Dependencies->req_ok_for ('admin');
+}
+
+use Moose;
+use parent 'DBIx::Class::Schema';
+
+use MooseX::Types::Moose qw/Int Str Any Bool/;
+use DBIx::Class::Admin::Types qw/DBICConnectInfo DBICHashRef/;
+use MooseX::Types::JSON qw(JSON);
+use MooseX::Types::Path::Class qw(Dir File);
+use Try::Tiny;
+use JSON::Any qw(DWIW XS JSON);
+use namespace::autoclean;
+
+=head1 NAME
+
+DBIx::Class::Admin - Administration object for schemas
+
+=head1 SYNOPSIS
+
+  $ dbicadmin --help
+
+  $ dbicadmin --schema=MyApp::Schema \
+    --connect='["dbi:SQLite:my.db", "", ""]' \
+    --deploy
+
+  $ dbicadmin --schema=MyApp::Schema --class=Employee \
+    --connect='["dbi:SQLite:my.db", "", ""]' \
+    --op=update --set='{ "name": "New_Employee" }'
+
+  use DBIx::Class::Admin;
+
+  # ddl manipulation
+  my $admin = DBIx::Class::Admin->new(
+    schema_class=> 'MY::Schema',
+    sql_dir=> $sql_dir,
+    connect_info => { dsn => $dsn, user => $user, password => $pass },
+  );
+
+  # create SQLite sql
+  $admin->create('SQLite');
+
+  # create SQL diff for an upgrade
+  $admin->create('SQLite', {} , "1.0");
+
+  # upgrade a database
+  $admin->upgrade();
+
+  # install a version for an unversioned schema
+  $admin->install("3.0");
+
+=head1 REQUIREMENTS
+
+The Admin interface has additional requirements not currently part of
+L<DBIx::Class>. See L<DBIx::Class::Optional::Dependencies> for more details.
+
+=head1 ATTRIBUTES
+
+=head2 schema_class
+
+the class of the schema to load
+
+=cut
+
+has 'schema_class' => (
+  is    => 'ro',
+  isa    => Str,
+);
+
+
+=head2 schema
+
+A pre-connected schema object can be provided for manipulation
+
+=cut
+
+has 'schema' => (
+  is      => 'ro',
+  isa      => 'DBIx::Class::Schema',
+  lazy_build  => 1,
+);
+
+sub _build_schema {
+  my ($self)  = @_;
+  $self->ensure_class_loaded($self->schema_class);
+
+  $self->connect_info->[3]->{ignore_version} =1;
+  return $self->schema_class->connect(@{$self->connect_info()} ); # ,  $self->connect_info->[3], { ignore_version => 1} );
+}
+
+
+=head2 resultset
+
+a resultset from the schema to operate on
+
+=cut
+
+has 'resultset' => (
+  is      => 'rw',
+  isa      => Str,
+);
+
+
+=head2 where
+
+a hash ref or json string to be used for identifying data to manipulate
+
+=cut
+
+has 'where' => (
+  is      => 'rw',
+  isa      => DBICHashRef,
+  coerce    => 1,
+);
+
+
+=head2 set
+
+a hash ref or json string to be used for inserting or updating data
+
+=cut
+
+has 'set' => (
+  is      => 'rw',
+  isa      => DBICHashRef,
+  coerce    => 1,
+);
+
+
+=head2 attrs
+
+a hash ref or json string to be used for passing additonal info to the ->search call
+
+=cut
+
+has 'attrs' => (
+  is       => 'rw',
+  isa      => DBICHashRef,
+  coerce    => 1,
+);
+
+
+=head2 connect_info
+
+connect_info the arguments to provide to the connect call of the schema_class
+
+=cut
+
+has 'connect_info' => (
+  is      => 'ro',
+  isa      => DBICConnectInfo,
+  lazy_build  => 1,
+  coerce    => 1,
+);
+
+sub _build_connect_info {
+  my ($self) = @_;
+  return $self->_find_stanza($self->config, $self->config_stanza);
+}
+
+
+=head2 config_file
+
+config_file provide a config_file to read connect_info from, if this is provided
+config_stanze should also be provided to locate where the connect_info is in the config
+The config file should be in a format readable by Config::General
+
+=cut
+
+has config_file => (
+  is      => 'ro',
+  isa      => File,
+  coerce    => 1,
+);
+
+
+=head2 config_stanza
+
+config_stanza for use with config_file should be a '::' deliminated 'path' to the connection information
+designed for use with catalyst config files
+
+=cut
+
+has 'config_stanza' => (
+  is      => 'ro',
+  isa      => Str,
+);
+
+
+=head2 config
+
+Instead of loading from a file the configuration can be provided directly as a hash ref.  Please note 
+config_stanza will still be required.
+
+=cut
+
+has config => (
+  is      => 'ro',
+  isa      => DBICHashRef,
+  lazy_build  => 1,
+);
+
+sub _build_config {
+  my ($self) = @_;
+
+  eval { require Config::Any }
+    or $self->throw_exception( "Config::Any is required to parse the config file");
+
+  my $cfg = Config::Any->load_files ( {files => [$self->config_file], use_ext =>1, flatten_to_hash=>1});
+
+  # just grab the config from the config file
+  $cfg = $cfg->{$self->config_file};
+  return $cfg;
+}
+
+
+=head2 sql_dir
+
+The location where sql ddl files should be created or found for an upgrade.
+
+=cut
+
+has 'sql_dir' => (
+  is      => 'ro',
+  isa      => Dir,
+  coerce    => 1,
+);
+
+
+=head2 version
+
+Used for install, the version which will be 'installed' in the schema
+
+=cut
+
+has version => (
+  is      => 'rw',
+  isa      => Str,
+);
+
+
+=head2 preversion
+
+Previouse version of the schema to create an upgrade diff for, the full sql for that version of the sql must be in the sql_dir
+
+=cut
+
+has preversion => (
+  is      => 'rw',
+  isa      => Str,
+);
+
+
+=head2 force
+
+Try and force certain operations.
+
+=cut
+
+has force => (
+  is      => 'rw',
+  isa      => Bool,
+);
+
+
+=head2 quiet
+
+Be less verbose about actions
+
+=cut
+
+has quiet => (
+  is      => 'rw',
+  isa      => Bool,
+);
+
+has '_confirm' => (
+  is    => 'bare',
+  isa    => Bool,
+);
+
+
+=head1 METHODS
+
+=head2 create
+
+=over 4
+
+=item Arguments: $sqlt_type, \%sqlt_args, $preversion
+
+=back
+
+L<create> will generate sql for the supplied schema_class in sql_dir.  The flavour of sql to 
+generate can be controlled by suppling a sqlt_type which should be a L<SQL::Translator> name.  
+
+Arguments for L<SQL::Translator> can be supplied in the sqlt_args hashref.
+
+Optional preversion can be supplied to generate a diff to be used by upgrade.
+
+=cut
+
+sub create {
+  my ($self, $sqlt_type, $sqlt_args, $preversion) = @_;
+
+  $preversion ||= $self->preversion();
+
+  my $schema = $self->schema();
+  # create the dir if does not exist
+  $self->sql_dir->mkpath() if ( ! -d $self->sql_dir);
+
+  $schema->create_ddl_dir( $sqlt_type, (defined $schema->schema_version ? $schema->schema_version : ""), $self->sql_dir->stringify, $preversion, $sqlt_args );
+}
+
+
+=head2 upgrade
+
+=over 4
+
+=item Arguments: <none>
+
+=back
+
+upgrade will attempt to upgrade the connected database to the same version as the schema_class.
+B<MAKE SURE YOU BACKUP YOUR DB FIRST>
+
+=cut
+
+sub upgrade {
+  my ($self) = @_;
+  my $schema = $self->schema();
+  if (!$schema->get_db_version()) {
+    # schema is unversioned
+    $self->throw_exception ("could not determin current schema version, please either install or deploy");
+  } else {
+    my $ret = $schema->upgrade();
+    return $ret;
+  }
+}
+
+
+=head2 install
+
+=over 4
+
+=item Arguments: $version
+
+=back
+
+install is here to help when you want to move to L<DBIx::Class::Schema::Versioned> and have an existing 
+database.  install will take a version and add the version tracking tables and 'install' the version.  No 
+further ddl modification takes place.  Setting the force attribute to a true value will allow overriding of 
+already versioned databases.
+
+=cut
+
+sub install {
+  my ($self, $version) = @_;
+
+  my $schema = $self->schema();
+  $version ||= $self->version();
+  if (!$schema->get_db_version() ) {
+    # schema is unversioned
+    print "Going to install schema version\n";
+    my $ret = $schema->install($version);
+    print "retun is $ret\n";
+  }
+  elsif ($schema->get_db_version() and $self->force ) {
+    carp "Forcing install may not be a good idea";
+    if($self->_confirm() ) {
+      $self->schema->_set_db_version({ version => $version});
+    }
+  }
+  else {
+    $self->throw_exception ("schema already has a version not installing, try upgrade instead");
+  }
+
+}
+
+
+=head2 deploy
+
+=over 4
+
+=item Arguments: $args
+
+=back
+
+deploy will create the schema at the connected database.  C<$args> are passed straight to 
+L<DBIx::Class::Schema/deploy>.
+
+=cut
+
+sub deploy {
+  my ($self, $args) = @_;
+  my $schema = $self->schema();
+  if (!$schema->get_db_version() ) {
+    # schema is unversioned
+    $schema->deploy( $args, $self->sql_dir)
+      or $self->throw_exception ("could not deploy schema");
+  } else {
+    $self->throw_exception("there already is a database with a version here, try upgrade instead");
+  }
+}
+
+=head2 insert
+
+=over 4
+
+=item Arguments: $rs, $set
+
+=back
+
+insert takes the name of a resultset from the schema_class and a hashref of data to insert
+into that resultset
+
+=cut
+
+sub insert {
+  my ($self, $rs, $set) = @_;
+
+  $rs ||= $self->resultset();
+  $set ||= $self->set();
+  my $resultset = $self->schema->resultset($rs);
+  my $obj = $resultset->create( $set );
+  print ''.ref($resultset).' ID: '.join(',',$obj->id())."\n" if (!$self->quiet);
+}
+
+
+=head2 update
+
+=over 4
+
+=item Arguments: $rs, $set, $where
+
+=back
+
+update takes the name of a resultset from the schema_class, a hashref of data to update and
+a where hash used to form the search for the rows to update.
+
+=cut
+
+sub update {
+  my ($self, $rs, $set, $where) = @_;
+
+  $rs ||= $self->resultset();
+  $where ||= $self->where();
+  $set ||= $self->set();
+  my $resultset = $self->schema->resultset($rs);
+  $resultset = $resultset->search( ($where||{}) );
+
+  my $count = $resultset->count();
+  print "This action will modify $count ".ref($resultset)." records.\n" if (!$self->quiet);
+
+  if ( $self->force || $self->_confirm() ) {
+    $resultset->update_all( $set );
+  }
+}
+
+
+=head2 delete
+
+=over 4
+
+=item Arguments: $rs, $where, $attrs
+
+=back
+
+delete takes the name of a resultset from the schema_class, a where hashref and a attrs to pass to ->search.
+The found data is deleted and cannot be recovered.
+
+=cut
+
+sub delete {
+  my ($self, $rs, $where, $attrs) = @_;
+
+  $rs ||= $self->resultset();
+  $where ||= $self->where();
+  $attrs ||= $self->attrs();
+  my $resultset = $self->schema->resultset($rs);
+  $resultset = $resultset->search( ($where||{}), ($attrs||()) );
+
+  my $count = $resultset->count();
+  print "This action will delete $count ".ref($resultset)." records.\n" if (!$self->quiet);
+
+  if ( $self->force || $self->_confirm() ) {
+    $resultset->delete_all();
+  }
+}
+
+
+=head2 select
+
+=over 4
+
+=item Arguments: $rs, $where, $attrs
+
+=back
+
+select takes the name of a resultset from the schema_class, a where hashref and a attrs to pass to ->search. 
+The found data is returned in a array ref where the first row will be the columns list.
+
+=cut
+
+sub select {
+  my ($self, $rs, $where, $attrs) = @_;
+
+  $rs ||= $self->resultset();
+  $where ||= $self->where();
+  $attrs ||= $self->attrs();
+  my $resultset = $self->schema->resultset($rs);
+  $resultset = $resultset->search( ($where||{}), ($attrs||()) );
+
+  my @data;
+  my @columns = $resultset->result_source->columns();
+  push @data, [@columns];# 
+
+  while (my $row = $resultset->next()) {
+    my @fields;
+    foreach my $column (@columns) {
+      push( @fields, $row->get_column($column) );
+    }
+    push @data, [@fields];
+  }
+
+  return \@data;
+}
+
+sub _confirm {
+  my ($self) = @_;
+  print "Are you sure you want to do this? (type YES to confirm) \n";
+  # mainly here for testing
+  return 1 if ($self->meta->get_attribute('_confirm')->get_value($self));
+  my $response = <STDIN>;
+  return 1 if ($response=~/^YES/);
+  return;
+}
+
+sub _find_stanza {
+  my ($self, $cfg, $stanza) = @_;
+  my @path = split /::/, $stanza;
+  while (my $path = shift @path) {
+    if (exists $cfg->{$path}) {
+      $cfg = $cfg->{$path};
+    }
+    else {
+      $self->throw_exception("could not find $stanza in config, $path did not seem to exist");
+    }
+  }
+  return $cfg;
+}
+
+=head1 AUTHOR
+
+See L<DBIx::Class/CONTRIBUTORS>.
+
+=head1 LICENSE
+
+You may distribute this code under the same terms as Perl itself
+
+=cut
+
+1;
diff --git a/lib/DBIx/Class/Admin/Types.pm b/lib/DBIx/Class/Admin/Types.pm
new file mode 100644 (file)
index 0000000..23af292
--- /dev/null
@@ -0,0 +1,48 @@
+package # hide from PAUSE
+    DBIx::Class::Admin::Types;
+
+use MooseX::Types -declare => [qw(
+    DBICConnectInfo
+    DBICArrayRef
+    DBICHashRef
+)];
+use MooseX::Types::Moose qw/Int HashRef ArrayRef Str Any Bool/;
+use MooseX::Types::JSON qw(JSON);
+
+subtype DBICArrayRef,
+    as ArrayRef;
+
+subtype DBICHashRef,
+    as HashRef;
+
+coerce DBICArrayRef,
+  from JSON,
+  via { _json_to_data ($_) };
+
+coerce DBICHashRef,
+  from JSON,
+  via { _json_to_data($_) };
+
+subtype DBICConnectInfo,
+  as ArrayRef;
+
+coerce DBICConnectInfo,
+  from JSON,
+   via { return _json_to_data($_) } ;
+
+coerce DBICConnectInfo,
+  from Str,
+    via { return _json_to_data($_) };
+
+coerce DBICConnectInfo,
+  from HashRef,
+   via { [ $_ ] };
+
+sub _json_to_data {
+  my ($json_str) = @_;
+  my $json = JSON::Any->new(allow_barekey => 1, allow_singlequote => 1, relaxed=>1);
+  my $ret = $json->jsonToObj($json_str);
+  return $ret;
+}
+
+1;
index dd5265e..6870714 100644 (file)
@@ -11,6 +11,19 @@ use Carp;
 # POD is generated automatically by calling _gen_pod from the
 # Makefile.PL in $AUTHOR mode
 
+my $moose_basic = {
+  'Moose'                      => '0.98',
+  'MooseX::Types'              => '0.21',
+};
+
+my $admin_basic = {
+  %$moose_basic,
+  'MooseX::Types::Path::Class' => '0.05',
+  'MooseX::Types::JSON'        => '0.02',
+  'namespace::autoclean'       => '0.09',
+  'parent'                     => '0.223',
+};
+
 my $reqs = {
   dist => {
     #'Module::Install::Pod::Inherit' => '0.01',
@@ -18,8 +31,7 @@ my $reqs = {
 
   replicated => {
     req => {
-      'Moose'                     => '0.98',
-      'MooseX::Types'             => '0.21',
+      %$moose_basic,
       'namespace::clean'          => '0.11',
       'Hash::Merge'               => '0.11',
     },
@@ -30,6 +42,27 @@ my $reqs = {
   },
 
   admin => {
+    req => {
+      %$admin_basic,
+    },
+    pod => {
+      title => 'DBIx::Class::Admin',
+      desc => 'Modules required for the DBIx::Class administrative library',
+    },
+  },
+
+  admin_script => {
+    req => {
+      %$moose_basic,
+      %$admin_basic,
+      'Getopt::Long::Descriptive' => '0.081',
+      'JSON::Any'                 => '1.22',
+      'Text::CSV'                 => '1.16',
+    },
+    pod => {
+      title => 'dbicadmin',
+      desc => 'Modules required for the CLI DBIx::Class interface dbicadmin',
+    },
   },
 
   deploy => {
index d6c8ecd..2b6a456 100755 (executable)
 #!/usr/bin/perl
+
 use strict;
 use warnings;
 
-use Getopt::Long;
-use Pod::Usage;
-use JSON::Any;
-
-
-my $json = JSON::Any->new(allow_barekey => 1, allow_singlequote => 1);
-
-GetOptions(
-    'schema=s'  => \my $schema_class,
-    'class=s'   => \my $resultset_class,
-    'connect=s' => \my $connect,
-    'op=s'      => \my $op,
-    'set=s'     => \my $set,
-    'where=s'   => \my $where,
-    'attrs=s'   => \my $attrs,
-    'format=s'  => \my $format,
-    'force'     => \my $force,
-    'trace'     => \my $trace,
-    'quiet'     => \my $quiet,
-    'help'      => \my $help,
-    'tlibs'      => \my $t_libs,
-);
-
-if ($t_libs) {
-    unshift( @INC, 't/lib', 'lib' );
+BEGIN {
+  use DBIx::Class;
+  die (  "The following modules are required for the dbicadmin utility\n"
+       . DBIx::Class::Optional::Dependencies->req_missing_for ('admin_script')
+  ) unless DBIx::Class::Optional::Dependencies->req_ok_for ('admin_script');
 }
 
-pod2usage(1) if ($help);
-$ENV{DBIC_TRACE} = 1 if ($trace);
-
-die('No op specified') if(!$op);
-die('Invalid op') if ($op!~/^insert|update|delete|select$/s);
-my $csv_class;
-if ($op eq 'select') {
-    $format ||= 'tsv';
-    die('Invalid format') if ($format!~/^tsv|csv$/s);
-    $csv_class = 'Text::CSV_XS';
-    eval{ require Text::CSV_XS };
-    if ($@) {
-        $csv_class = 'Text::CSV_PP';
-        eval{ require Text::CSV_PP };
-        die('The select op requires either the Text::CSV_XS or the Text::CSV_PP module') if ($@);
-    }
-}
-
-die('No schema specified') if(!$schema_class);
-eval("require $schema_class");
-die('Unable to load schema') if ($@);
-$connect = $json->jsonToObj( $connect ) if ($connect);
-my $schema = $schema_class->connect(
-    ( $connect ? @$connect : () )
+use Getopt::Long::Descriptive;
+use DBIx::Class::Admin;
+
+my ($opts, $usage) = describe_options(
+  "%c: %o",
+  (
+    ['Actions'],
+    ["action" => hidden => { one_of => [
+      ['create|c' => 'Create version diffs needs preversion',],
+      ['upgrade|u' => 'Upgrade the database to the current schema '],
+      ['install|i' => 'Install the schema to the database',],
+      ['deploy|d' => 'Deploy the schema to the database',],
+      ['select|s'   => 'Select data from the schema', ],
+      ['insert|i'   => 'Insert data into the schema', ],
+      ['update|u'   => 'Update data in the schema', ], 
+      ['delete|D'   => 'Delete data from the schema',],
+      ['op:s' => 'compatiblity option all of the above can be suppied as --op=<action>'],
+      ['help|h' => 'display this help'],
+    ], required=> 1 }],
+    ['Options'],
+    ['schema-class|schema|C:s' => 'The class of the schema to load', { required => 1 } ],
+    ['resultset|resultset_class|class|r:s' => 'The resultset to operate on for data manipulation' ],
+    ['config-stanza|S:s' => 'Where in the config to find the connection_info, supply in form MyApp::Model::DB',],
+    ['config|f:s' => 'Supply the config file for parsing by Config::Any', { depends => 'config_stanza'} ],
+    ['connect-info|n:s%' => 'Supply the connect info as additonal options ie -I dsn=<dsn> user=<user> password=<pass> '],
+    ['connect:s' => 'Supply the connect info as a json string' ],
+    ['sql-dir|q:s' => 'The directory where sql diffs will be created'],
+    ['sql-type|t:s' => 'The RDBMs flavour you wish to use'],
+    ['version|v:i' => 'Supply a version install'],
+    ['preversion|p:s' => 'The previous version to diff against',],
+    ['set:s' => 'JSON data used to perform data operations' ],
+    ['lib|I:s' => 'Additonal library path to search in'], 
+    ['attrs:s' => 'JSON string to be used for the second argument for search'],
+    ['where:s' => 'JSON string to be used for the where clause of search'],
+    ['force' => 'Be forceful with some operations'],
+    ['trace' => 'Turn on DBIx::Class trace output'],
+    ['quiet' => 'Be less verbose'],
+  )
 );
 
-die('No class specified') if(!$resultset_class);
-my $resultset = eval{ $schema->resultset($resultset_class) };
-die('Unable to load the class with the schema') if ($@);
-
-$set = $json->jsonToObj( $set ) if ($set);
-$where = $json->jsonToObj( $where ) if ($where);
-$attrs = $json->jsonToObj( $attrs ) if ($attrs);
+die "please only use one of --config or --connect-info\n" if ($opts->{config} and $opts->{connect_info});
 
-if ($op eq 'insert') {
-    die('Do not use the where option with the insert op') if ($where);
-    die('Do not use the attrs option with the insert op') if ($attrs);
-    my $obj = $resultset->create( $set );
-    print ''.ref($resultset).' ID: '.join(',',$obj->id())."\n" if (!$quiet);
+# option compatability mangle
+if($opts->{connect}) {
+  $opts->{connect_info} = delete $opts->{connect};
 }
-elsif ($op eq 'update') {
-    $resultset = $resultset->search( ($where||{}) );
-    my $count = $resultset->count();
-    print "This action will modify $count ".ref($resultset)." records.\n" if (!$quiet);
-    if ( $force || confirm() ) {
-        $resultset->update_all( $set );
-    }
-}
-elsif ($op eq 'delete') {
-    die('Do not use the set option with the delete op') if ($set);
-    $resultset = $resultset->search( ($where||{}), ($attrs||()) );
-    my $count = $resultset->count();
-    print "This action will delete $count ".ref($resultset)." records.\n" if (!$quiet);
-    if ( $force || confirm() ) {
-        $resultset->delete_all();
-    }
-}
-elsif ($op eq 'select') {
-    die('Do not use the set option with the select op') if ($set);
-    my $csv = $csv_class->new({
-        sep_char => ( $format eq 'tsv' ? "\t" : ',' ),
-    });
-    $resultset = $resultset->search( ($where||{}), ($attrs||()) );
-    my @columns = $resultset->result_source->columns();
-    $csv->combine( @columns );
-    print $csv->string()."\n";
-    while (my $row = $resultset->next()) {
-        my @fields;
-        foreach my $column (@columns) {
-            push( @fields, $row->get_column($column) );
-        }
-        $csv->combine( @fields );
-        print $csv->string()."\n";
-    }
-}
-
-sub confirm {
-    print "Are you sure you want to do this? (type YES to confirm) ";
-    my $response = <STDIN>;
-    return 1 if ($response=~/^YES/);
-    return;
-}
-
-__END__
-
-=head1 NAME
-
-dbicadmin - Execute operations upon DBIx::Class objects.
-
-=head1 SYNOPSIS
-
-  dbicadmin --op=insert --schema=My::Schema --class=Class --set=JSON
-  dbicadmin --op=update --schema=My::Schema --class=Class --set=JSON --where=JSON
-  dbicadmin --op=delete --schema=My::Schema --class=Class --where=JSON
-  dbicadmin --op=select --schema=My::Schema --class=Class --where=JSON --format=tsv
-
-=head1 DESCRIPTION
-
-This utility provides the ability to run INSERTs, UPDATEs, 
-DELETEs, and SELECTs on any DBIx::Class object.
-
-=head1 OPTIONS
-
-=head2 op
 
-The type of operation.  Valid values are insert, update, delete, 
-and select.
+my $admin = DBIx::Class::Admin->new( %$opts );
 
-=head2 schema
 
-The name of your schema class.
+my $action = $opts->{action};
 
-=head2 class
+$action = $opts->{op} if ($action eq 'op');
 
-The name of the class, within your schema, that you want to run 
-the operation on.
+print "Performig action $action...\n";
 
-=head2 connect
+my $res = $admin->$action();
+if ($action eq 'select') {
 
-A JSON array to be passed to your schema class upon connecting.  
-The array will need to be compatible with whatever the DBIC 
-->connect() method requires.
+  my $format = $opts->{format} || 'tsv';
+  die('Invalid format') if ($format!~/^tsv|csv$/s);
 
-=head2 set
+  require Text::CSV;
 
-This option must be valid JSON data string and is passed in to 
-the DBIC update() method.  Use this option with the update 
-and insert ops.
+  my $csv = Text::CSV->new({
+    sep_char => ( $format eq 'tsv' ? "\t" : ',' ),
+  });
 
-=head2 where
-
-This option must be valid JSON data string and is passed in as 
-the first argument to the DBIC search() method.  Use this 
-option with the update, delete, and select ops.
-
-=head2 attrs
-
-This option must be valid JSON data string and is passed in as 
-the second argument to the DBIC search() method.  Use this 
-option with the update, delete, and select ops.
-
-=head2 help
-
-Display this help page.
-
-=head2 force
-
-Suppresses the confirmation dialogues that are usually displayed 
-when someone runs a DELETE or UPDATE action.
-
-=head2 quiet
-
-Do not display status messages.
-
-=head2 trace
-
-Turns on tracing on the DBI storage, thus printing SQL as it is 
-executed.
-
-=head2 tlibs
-
-This option is purely for testing during the DBIC installation.  Do 
-not use it.
-
-=head1 JSON
-
-JSON is a lightweight data-interchange format.  It allows you 
-to express complex data structures for use in the where and 
-set options.
-
-This module turns on L<JSON>'s BareKey and QuotApos options so 
-that your data can look a bit more readable.
-
-  --where={"this":"that"} # generic JSON
-  --where={this:'that'}   # with BareKey and QuoteApos
-
-Consider wrapping your JSON in outer quotes so that you don't 
-have to escape your inner quotes.
-
-  --where={this:\"that\"} # no outer quote
-  --where='{this:"that"}' # outer quoted
+  foreach my $row (@$res) {
+    $csv->combine( @$row );
+    print $csv->string()."\n";
+  }
+}
 
 =head1 AUTHOR
 
-Aran Deltac <bluefeet@cpan.org>
+See L<DBIx::Class/CONTRIBUTORS>.
 
 =head1 LICENSE
 
-You may distribute this code under the same terms as Perl itself.
+You may distribute this code under the same terms as Perl itself
 
+=cut
diff --git a/t/admin/01load.t b/t/admin/01load.t
new file mode 100644 (file)
index 0000000..2089607
--- /dev/null
@@ -0,0 +1,15 @@
+use strict;
+use warnings;
+
+use Test::More;
+
+BEGIN {
+    require DBIx::Class;
+    plan skip_all => 'Test needs ' . DBIx::Class::Optional::Dependencies->req_missing_for('admin')
+      unless DBIx::Class::Optional::Dependencies->req_ok_for('admin');
+}
+
+use_ok 'DBIx::Class::Admin';
+
+
+done_testing;
diff --git a/t/admin/02ddl.t b/t/admin/02ddl.t
new file mode 100644 (file)
index 0000000..d7d9d28
--- /dev/null
@@ -0,0 +1,130 @@
+use strict;
+use warnings;
+
+use Test::More;
+use Test::Exception;
+use Test::Warn;
+
+BEGIN {
+    require DBIx::Class;
+    plan skip_all => 'Test needs ' . DBIx::Class::Optional::Dependencies->req_missing_for('admin')
+      unless DBIx::Class::Optional::Dependencies->req_ok_for('admin');
+
+    plan skip_all => 'Test needs ' . DBIx::Class::Optional::Dependencies->req_missing_for('deploy')
+      unless DBIx::Class::Optional::Dependencies->req_ok_for('deploy');
+}
+
+use lib qw(t/lib);
+use DBICTest;
+
+use Path::Class;
+
+use ok 'DBIx::Class::Admin';
+
+
+my $sql_dir = dir(qw/t var/);
+my @connect_info = DBICTest->_database(
+  no_deploy=>1,
+  no_populate=>1,
+  sqlite_use_file  => 1,
+);
+{ # create the schema
+
+#  make sure we are  clean
+clean_dir($sql_dir);
+
+
+my $admin = DBIx::Class::Admin->new(
+  schema_class=> "DBICTest::Schema",
+  sql_dir=> $sql_dir,
+  connect_info => \@connect_info, 
+);
+isa_ok ($admin, 'DBIx::Class::Admin', 'create the admin object');
+lives_ok { $admin->create('MySQL'); } 'Can create MySQL sql';
+lives_ok { $admin->create('SQLite'); } 'Can Create SQLite sql';
+}
+
+{ # upgrade schema
+
+#my $schema = DBICTest->init_schema(
+#  no_deploy    => 1,
+#  no_populat    => 1,
+#  sqlite_use_file  => 1,
+#);
+
+clean_dir($sql_dir);
+require DBICVersion_v1;
+
+my $admin = DBIx::Class::Admin->new(
+  schema_class => 'DBICVersion::Schema', 
+  sql_dir =>  $sql_dir,
+  connect_info => \@connect_info,
+);
+
+my $schema = $admin->schema();
+
+lives_ok { $admin->create($schema->storage->sqlt_type(), {add_drop_table=>0}); } 'Can create DBICVersionOrig sql in ' . $schema->storage->sqlt_type;
+lives_ok { $admin->deploy(  ) } 'Can Deploy schema';
+
+# connect to now deployed schema
+lives_ok { $schema = DBICVersion::Schema->connect(@{$schema->storage->connect_info()}); } 'Connect to deployed Database';
+
+is($schema->get_db_version, $DBICVersion::Schema::VERSION, 'Schema deployed and versions match');
+
+
+require DBICVersion_v2;
+
+$admin = DBIx::Class::Admin->new(
+  schema_class => 'DBICVersion::Schema', 
+  sql_dir =>  $sql_dir,
+  connect_info => \@connect_info
+);
+
+lives_ok { $admin->create($schema->storage->sqlt_type(), {}, "1.0" ); } 'Can create diff for ' . $schema->storage->sqlt_type;
+{
+  local $SIG{__WARN__} = sub { warn $_[0] unless $_[0] =~ /DB version .+? is lower than the schema version/ };
+  lives_ok {$admin->upgrade();} 'upgrade the schema';
+}
+
+is($schema->get_db_version, $DBICVersion::Schema::VERSION, 'Schema and db versions match');
+
+}
+
+{ # install
+
+clean_dir($sql_dir);
+
+my $admin = DBIx::Class::Admin->new(
+  schema_class  => 'DBICVersion::Schema', 
+  sql_dir      => $sql_dir,
+  _confirm    => 1,
+  connect_info  => \@connect_info,
+);
+
+$admin->version("3.0");
+lives_ok { $admin->install(); } 'install schema version 3.0';
+is($admin->schema->get_db_version, "3.0", 'db thinks its version 3.0');
+dies_ok { $admin->install("4.0"); } 'cannot install to allready existing version';
+
+$admin->force(1);
+warnings_exist ( sub {
+  lives_ok { $admin->install("4.0") } 'can force install to allready existing version'
+}, qr/Forcing install may not be a good idea/, 'Force warning emitted' );
+is($admin->schema->get_db_version, "4.0", 'db thinks its version 4.0');
+#clean_dir($sql_dir);
+}
+
+sub clean_dir {
+  my ($dir) = @_;
+  $dir = $dir->resolve;
+  if ( ! -d $dir ) {
+    $dir->mkpath();
+  }
+  foreach my $file ($dir->children) {
+    # skip any hidden files
+    next if ($file =~ /^\./); 
+    unlink $file;
+  }
+}
+
+done_testing;
diff --git a/t/admin/03data.t b/t/admin/03data.t
new file mode 100644 (file)
index 0000000..8bdd562
--- /dev/null
@@ -0,0 +1,65 @@
+use strict;
+use warnings;
+
+use Test::More;
+
+use Test::Exception;
+use Test::Deep;
+
+BEGIN {
+    require DBIx::Class;
+    plan skip_all => 'Test needs ' . DBIx::Class::Optional::Dependencies->req_missing_for('admin')
+      unless DBIx::Class::Optional::Dependencies->req_ok_for('admin');
+}
+
+use lib 't/lib';
+use DBICTest;
+
+use ok 'DBIx::Class::Admin';
+
+
+{ # test data maniplulation functions
+
+  # create a DBICTest so we can steal its connect info
+  my $schema = DBICTest->init_schema(
+    sqlite_use_file => 1,
+  );
+
+  my $admin = DBIx::Class::Admin->new(
+    schema_class=> "DBICTest::Schema",
+    connect_info => $schema->storage->connect_info(),
+    quiet  => 1,
+    _confirm=>1,
+  );
+  isa_ok ($admin, 'DBIx::Class::Admin', 'create the admin object');
+
+  $admin->insert('Employee', { name => 'Matt' });
+  my $employees = $schema->resultset('Employee');
+  is ($employees->count(), 1, "insert okay" );
+
+  my $employee = $employees->find(1);
+  is($employee->name(),  'Matt', "insert valid" );
+
+  $admin->update('Employee', {name => 'Trout'}, {name => 'Matt'});
+
+  $employee = $employees->find(1);
+  is($employee->name(),  'Trout', "update Matt to Trout" );
+
+  $admin->insert('Employee', {name =>'Aran'});
+
+  my $expected_data = [ 
+    [$employee->result_source->columns() ],
+    [1,1,undef,undef,undef,'Trout'],
+    [2,2,undef,undef,undef,'Aran']
+  ];
+  my $data;
+  lives_ok { $data = $admin->select('Employee')} 'can retrive data from database';
+  cmp_deeply($data, $expected_data, 'DB matches whats expected');
+
+  $admin->delete('Employee', {name=>'Trout'});
+  my $del_rs  = $employees->search({name => 'Trout'});
+  is($del_rs->count(), 0, "delete Trout" );
+  is ($employees->count(), 1, "left Aran" );
+}
+
+done_testing;
similarity index 83%
rename from t/89dbicadmin.t
rename to t/admin/10script.t
index 1729d2d..7718b34 100644 (file)
@@ -1,19 +1,18 @@
 # vim: filetype=perl
 use strict;
-use warnings;  
+use warnings;
 
 use Test::More;
+use Config;
 use lib qw(t/lib);
+$ENV{PERL5LIB} = join ($Config{path_sep}, @INC);
 use DBICTest;
 
 
-eval 'require JSON::Any';
-plan skip_all => 'Install JSON::Any to run this test' if ($@);
-
-eval 'require Text::CSV_XS';
-if ($@) {
-    eval 'require Text::CSV_PP';
-    plan skip_all => 'Install Text::CSV_XS or Text::CSV_PP to run this test' if ($@);
+BEGIN {
+    require DBIx::Class;
+    plan skip_all => 'Test needs ' . DBIx::Class::Optional::Dependencies->req_missing_for('admin_script')
+      unless DBIx::Class::Optional::Dependencies->req_ok_for('admin_script');
 }
 
 my @json_backends = qw/XS JSON DWIW/;
@@ -56,7 +55,9 @@ sub test_dbicadmin {
         open(my $fh, "-|",  _prepare_system_args( qw|--op=select --attrs={"order_by":"name"}| ) ) or die $!;
         my $data = do { local $/; <$fh> };
         close($fh);
-        ok( ($data=~/Aran.*Trout/s), "$ENV{JSON_ANY_ORDER}: select with attrs" );
+        if (!ok( ($data=~/Aran.*Trout/s), "$ENV{JSON_ANY_ORDER}: select with attrs" )) {
+          diag ("data from select is $data")
+        };
     }
 
     system( _prepare_system_args( qw|--op=delete --where={"name":"Trout"}| ) );
@@ -71,10 +72,11 @@ sub test_dbicadmin {
 #
 sub _prepare_system_args {
     my $perl = $^X;
+
     my @args = (
-        qw|script/dbicadmin --quiet --schema=DBICTest::Schema --class=Employee --tlibs|,
+        qw|script/dbicadmin --quiet --schema=DBICTest::Schema --class=Employee|,
         q|--connect=["dbi:SQLite:dbname=t/var/DBIxClass.db","","",{"AutoCommit":1}]|,
-        qw|--force --tlibs|,
+        qw|--force|,
         @_,
     );
 
index 8e2daeb..c340d8b 100644 (file)
@@ -12,30 +12,21 @@ __PACKAGE__->set_primary_key(qw/artist/);
 
 # Normally this would not appear as a FK constraint
 # since it uses the PK
-__PACKAGE__->might_have(
-                       'artist_1', 'DBICTest::Schema::Artist', {
-                           'foreign.artistid' => 'self.artist',
-                       }, {
-                           is_foreign_key_constraint => 1,
-                       },
+__PACKAGE__->might_have('artist_1', 'DBICTest::Schema::Artist',
+  { 'foreign.artistid' => 'self.artist' },
+  { is_foreign_key_constraint => 1 },
 );
 
 # Normally this would appear as a FK constraint
-__PACKAGE__->might_have(
-                       'cd_1', 'DBICTest::Schema::CD', {
-                           'foreign.cdid' => 'self.cd',
-                       }, {
-                           is_foreign_key_constraint => 0,
-                       },
+__PACKAGE__->might_have('cd_1', 'DBICTest::Schema::CD',
+  { 'foreign.cdid' => 'self.cd' },
+  { is_foreign_key_constraint => 0 },
 );
 
 # Normally this would appear as a FK constraint
-__PACKAGE__->belongs_to(
-                       'cd_3', 'DBICTest::Schema::CD', {
-                           'foreign.cdid' => 'self.cd',
-                       }, {
-                           is_foreign_key_constraint => 0,
-                       },
+__PACKAGE__->belongs_to('cd_3', 'DBICTest::Schema::CD',
+  { 'foreign.cdid' => 'self.cd' },
+  { is_foreign_key_constraint => 0 },
 );
 
 1;