#!/nix/store/0kg70swgpg45ipcz3pr2siidq9fn6d77-coreutils-9.5/bin/env perl -I/nix/store/ww69rb7srifikvilg39q4v8n9h1zcssf-perl-5.38.2/lib/perl5/site_perl -I/nix/store/smjphqpfr93nf940qmxyx1mpcsp566dp-perl5.38.2-DBD-SQLite-1.74/lib/perl5/site_perl -I/nix/store/xma4dyxh029dzgfc429maqm1m4l1d5mx-perl5.38.2-DBI-1.644/lib/perl5/site_perl -I/nix/store/j6lh325fyplb2rq2mjkz4gfcrnc11m73-perl5.38.2-Test-Deep-1.204/lib/perl5/site_perl -I/nix/store/3idi7dma03lml9a16mi3zk8vbvlqp3pd-perl5.38.2-Test-Exception-0.43/lib/perl5/site_perl -I/nix/store/ia47vfc0mgfs4bkalbgipd34phwjdggf-perl5.38.2-Sub-Uplevel-0.2800/lib/perl5/site_perl -I/nix/store/js84vc8bff4vvy4z5k2z6v9qqhvk5v84-perl5.38.2-Test-Warn-0.37/lib/perl5/site_perl -I/nix/store/cawc9nln186c2qp1qqw3fr43ayfv3kpf-perl5.38.2-Class-Accessor-Grouped-0.10014/lib/perl5/site_perl -I/nix/store/ckx6kds6x86vsb90ck69xd1033dxc1xd-perl5.38.2-Module-Runtime-0.016/lib/perl5/site_perl -I/nix/store/wld6di999nmcyvk7jvgff5dqmf39gi80-perl5.38.2-Class-C3-Componentised-1.001002/lib/perl5/site_perl -I/nix/store/7g4fmgziw553hc42x9iwxwcj907c5yc1-perl5.38.2-Class-C3-0.35/lib/perl5/site_perl -I/nix/store/pjh4br3v99pgnazrf3s9442ag2k0vsya-perl5.38.2-Algorithm-C3-0.11/lib/perl5/site_perl -I/nix/store/71n823r7vpwq71xgfqbx6ri2x08252lv-perl5.38.2-Class-Inspector-1.36/lib/perl5/site_perl -I/nix/store/brklryclwzrhr7xfbgxrvl1akn9aq0hy-perl5.38.2-MRO-Compat-0.15/lib/perl5/site_perl -I/nix/store/39175w8jh9y01ylhjdgp0pimb9hrznmy-perl5.38.2-Config-Any-0.33/lib/perl5/site_perl -I/nix/store/k08lm1787j2gla5v5q9flsn0ac75q24a-perl5.38.2-Module-Pluggable-5.2/lib/perl5/site_perl -I/nix/store/qls20rz476gs3p7h0qxlrjaw02frrmzg-perl5.38.2-Context-Preserve-0.03/lib/perl5/site_perl -I/nix/store/g8gnhv14i28nasdascskh39biafghf5a-perl5.38.2-Data-Dumper-Concise-2.023/lib/perl5/site_perl -I/nix/store/gn90p9vd53amk9x53bi9fyxklbdqkkcr-perl5.38.2-Data-Page-2.03/lib/perl5/site_perl -I/nix/store/rj6lircl2njgxi4kba50w7a2vih3sfyc-perl5.38.2-Class-Accessor-Chained-0.01/lib/perl5/site_perl -I/nix/store/z2hg454k32bqs56vzrrxi9xscrprb45g-perl5.38.2-Class-Accessor-0.51/lib/perl5/site_perl -I/nix/store/09pzqy4mzjjdx5sxdgmsqrpi05zdhkqh-perl5.38.2-Devel-GlobalDestruction-0.14/lib/perl5/site_perl -I/nix/store/iijlyi71nqadvsk959nx9pjqrd34b8vb-perl5.38.2-Sub-Exporter-Progressive-0.001013/lib/perl5/site_perl -I/nix/store/g44fa6glp44ybscb2w0qvwcwz8xi3p10-perl5.38.2-Module-Find-0.16/lib/perl5/site_perl -I/nix/store/pq3c2lhwfbmrrhnxfncx7dz20p1ffb7d-perl5.38.2-Path-Class-0.37/lib/perl5/site_perl -I/nix/store/g3inj93bsga64qxvais21iyl6l71xkbz-perl5.38.2-SQL-Abstract-Classic-1.91/lib/perl5/site_perl -I/nix/store/57rg48c4j4xd5i64zxd53ca2cg9p678d-perl5.38.2-SQL-Abstract-2.000001/lib/perl5/site_perl -I/nix/store/i4nak3f5r44hj0an2bg7k69i260wcw63-perl5.38.2-Hash-Merge-0.302/lib/perl5/site_perl -I/nix/store/p34w9n22rz0nyz8w846g9f2bd4d473zm-perl5.38.2-Clone-Choose-0.010/lib/perl5/site_perl -I/nix/store/g6ss7ghrbz1l650jgkc9yp0h3abkqsq1-perl5.38.2-Moo-2.005005/lib/perl5/site_perl -I/nix/store/8mfb2d8d0syb74gibizs8cyf33lljjf2-perl5.38.2-Class-Method-Modifiers-2.15/lib/perl5/site_perl -I/nix/store/25v0v6r0swabiqw3imjvwjf6bz53j67k-perl5.38.2-Role-Tiny-2.002004/lib/perl5/site_perl -I/nix/store/i2ba8s01blyl5r3k0hm3z6ihrasdv2fc-perl5.38.2-Sub-Quote-2.006008/lib/perl5/site_perl -I/nix/store/s77wldkzrra80xm1kag0qxrpshqdd2sn-perl5.38.2-Scope-Guard-0.21/lib/perl5/site_perl -I/nix/store/q2mivq8q8hg400hrq4al7yanx658mfbd-perl5.38.2-Sub-Name-0.27/lib/perl5/site_perl -I/nix/store/zn3s3frnixy2ljxnkwji3a6i53zhbwlk-perl5.38.2-namespace-clean-0.27/lib/perl5/site_perl -I/nix/store/ckbnlgj989m24yp7cmk31173qvnjjiyn-perl5.38.2-B-Hooks-EndOfScope-0.26/lib/perl5/site_perl -I/nix/store/9ssbmqcmw4ix0xks6x3ccxmf4i52azr9-perl5.38.2-Module-Implementation-0.09/lib/perl5/site_perl -I/nix/store/k9bj7v2acm0ksvsyv0j79pyv338fpdb6-perl5.38.2-Try-Tiny-0.31/lib/perl5/site_perl -I/nix/store/hs9n6idzxd1cz22hizicasljq46hsy36-perl5.38.2-Package-Stash-0.40/lib/perl5/site_perl -I/nix/store/dkfk5rb2wl6bldgghq99nfax9wvfhp00-perl5.38.2-Dist-CheckConflicts-0.11/lib/perl5/site_perl -I/nix/store/2q87hbw9nygj4mzfc4zmzfpq7kv2wqjn-perl5.38.2-DBIx-Class-0.082843/lib/perl5/site_perl

use strict;
use warnings;

BEGIN {
  use DBIx::Class;
  die (  'The following modules are required for the dbicadmin utility: '
       . DBIx::Class::Optional::Dependencies->req_missing_for ('admin_script')
       . "\n"
  ) unless DBIx::Class::Optional::Dependencies->req_ok_for ('admin_script');
}

use DBIx::Class::Admin::Descriptive;
#use Getopt::Long::Descriptive;
use DBIx::Class::Admin;

my $short_description = "utility for administrating DBIx::Class schemata";
my $synopsis_text =q|
  deploy a schema to a database
  %c --schema=MyApp::Schema \
    --connect='["dbi:SQLite:my.db", "", ""]' \
    --deploy

  update an existing record
  %c --schema=MyApp::Schema --class=Employee \
    --connect='["dbi:SQLite:my.db", "", ""]' \
    --op=update --set='{ "name": "New_Employee" }'
|;

my ($opts, $usage) = describe_options(
    "%c: %o",
  (
    ['Actions'],
    ["action" => hidden => { one_of => [
      ['create' => 'Create version diffs needs preversion'],
      ['upgrade' => 'Upgrade the database to the current schema'],
      ['install' => 'Install the schema version tables to an existing database'],
      ['deploy' => 'Deploy the schema to the database'],
      ['select'   => 'Select data from the schema'],
      ['insert'   => 'Insert data into the schema'],
      ['update'   => 'Update data in the schema'],
      ['delete'   => 'Delete data from the schema'],
      ['op:s' => 'compatibility option all of the above can be supplied as --op=<action>'],
      ['help' => 'display this help', { implies => { schema_class => '__dummy__' } } ],
      ['documentation-as-pod:s' => 'hidden', { implies => { schema_class => '__dummy__' } } ],
    ], required => 1 }],
    ['Arguments'],
    ["configuration" => hidden => { one_of => [
      ['config-file|config:s' => 'Supply the config file for parsing by Config::Any', { depends => 'config_stanza'} ],
      ['connect-info:s%' => 'Supply the connect info as trailing options e.g. --connect-info dsn=<dsn> user=<user> password=<pass>' ],
      ['connect:s' => 'Supply the connect info as a JSON-encoded structure, e.g. an --connect=["dsn","user","pass"]'],
    ] }],
    ['schema-class:s' => 'The class of the schema to load', { required => 1 } ],
    ['config-stanza:s' => 'Where in the config to find the connection_info, supply in form MyApp::Model::DB',],
    ['resultset|resultset-class|class:s' => 'The resultset to operate on for data manipulation' ],
    ['sql-dir:s' => 'The directory where sql diffs will be created'],
    ['sql-type:s' => 'The RDBMs flavour you wish to use'],
    ['version:i' => 'Supply a version install'],
    ['preversion:s' => 'The previous version to diff against',],
    ['set:s' => 'JSON data used to perform data operations' ],
    ['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'],
    ['I:s@' => 'Same as perl\'s -I, prepended to current @INC'],
  )
);

if(defined (my $fn = $opts->{documentation_as_pod}) ) {
  $usage->synopsis($synopsis_text);
  $usage->short_description($short_description);

  if ($fn) {
    require File::Spec;
    require File::Path;
    my $dir = File::Spec->catpath( (File::Spec->splitpath($fn))[0,1] );
    File::Path::mkpath([$dir]);
  }

  local *STDOUT if $fn;
  open (STDOUT, '>', $fn) or die "Unable to open $fn: $!\n" if $fn;

  print STDOUT "\n";
  print STDOUT $usage->pod;
  print STDOUT "\n";

  close STDOUT if $fn;
  exit 0;
}

# FIXME - lowercasing will eventually go away when Getopt::Long::Descriptive is fixed
if($opts->{i}) {
  require lib;
  lib->import( @{delete $opts->{i}} );
}

if($opts->{help}) {
  $usage->die();
}

# option compatibility mangle
# (can not be joined in the spec, one is s% the other is s)
if($opts->{connect}) {
  $opts->{connect_info} = delete $opts->{connect};
}

my $admin = DBIx::Class::Admin->new( %$opts );

my $action = $opts->{action};

$action = $opts->{op} if ($action eq 'op');

print "Performing action $action...\n";

my $res = $admin->$action();
if ($action eq 'select') {

  my $format = $opts->{format} || 'tsv';
  die('Invalid format') if ($format!~/^tsv|csv$/s);

  require Text::CSV;

  my $csv = Text::CSV->new({
    sep_char => ( $format eq 'tsv' ? "\t" : ',' ),
  });

  foreach my $row (@$res) {
    $csv->combine( @$row );
    print $csv->string()."\n";
  }
}

1;

__END__

=head1 NAME

dbicadmin - utility for administrating DBIx::Class schemata

=head1 SYNOPSIS

dbicadmin: [-I] [long options...]

  deploy a schema to a database
  dbicadmin --schema=MyApp::Schema \
    --connect='["dbi:SQLite:my.db", "", ""]' \
    --deploy

  update an existing record
  dbicadmin --schema=MyApp::Schema --class=Employee \
    --connect='["dbi:SQLite:my.db", "", ""]' \
    --op=update --set='{ "name": "New_Employee" }'



=head1 OPTIONS

=over

=back

=head2 Actions

=cut

=over

=item B<--create>

Create version diffs needs preversion

=cut

=item B<--upgrade>

Upgrade the database to the current schema

=cut

=item B<--install>

Install the schema version tables to an existing database

=cut

=item B<--deploy>

Deploy the schema to the database

=cut

=item B<--select>

Select data from the schema

=cut

=item B<--insert>

Insert data into the schema

=cut

=item B<--update>

Update data in the schema

=cut

=item B<--delete>

Delete data from the schema

=cut

=item B<--op>

compatibility option all of the above can be supplied as --op=<action>

=cut

=item B<--help>

display this help

=cut

=back

=head2 Arguments

=cut

=over

=item B<--config-file> or B<--config>

Supply the config file for parsing by Config::Any

=cut

=item B<--connect-info>

Supply the connect info as trailing options e.g. --connect-info dsn=<dsn> user=<user> password=<pass>

=cut

=item B<--connect>

Supply the connect info as a JSON-encoded structure, e.g. an --connect=["dsn","user","pass"]

=cut

=item B<--schema-class>

The class of the schema to load

=cut

=item B<--config-stanza>

Where in the config to find the connection_info, supply in form MyApp::Model::DB

=cut

=item B<--resultset> or B<--resultset-class> or B<--class>

The resultset to operate on for data manipulation

=cut

=item B<--sql-dir>

The directory where sql diffs will be created

=cut

=item B<--sql-type>

The RDBMs flavour you wish to use

=cut

=item B<--version>

Supply a version install

=cut

=item B<--preversion>

The previous version to diff against

=cut

=item B<--set>

JSON data used to perform data operations

=cut

=item B<--attrs>

JSON string to be used for the second argument for search

=cut

=item B<--where>

JSON string to be used for the where clause of search

=cut

=item B<--force>

Be forceful with some operations

=cut

=item B<--trace>

Turn on DBIx::Class trace output

=cut

=item B<--quiet>

Be less verbose

=cut

=item B<-I>

Same as perl's -I, prepended to current @INC

=cut

=back


=head1 AUTHORS

See L<DBIx::Class/AUTHORS>

=head1 LICENSE

You may distribute this code under the same terms as Perl itself

=cut
