Cleanup debug output
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Admin.pm
CommitLineData
9f3849c3 1package DBIx::Class::Admin;
2
71ef99d5 3# check deps
4BEGIN {
a4a02f15 5 use Carp::Clan qw/^DBIx::Class/;
6 use DBIx::Class;
7 croak('The following modules are required for DBIx::Class::Admin ' . DBIx::Class::Optional::Dependencies->req_missing_for ('admin') )
8 unless DBIx::Class::Optional::Dependencies->req_ok_for ('admin');
71ef99d5 9}
585072bb 10
71ef99d5 11use Moose;
a62dec82 12use MooseX::Types::Moose qw/Int Str Any Bool/;
13use DBIx::Class::Admin::Types qw/DBICConnectInfo DBICHashRef/;
71ef99d5 14use MooseX::Types::JSON qw(JSON);
15use MooseX::Types::Path::Class qw(Dir File);
16use Try::Tiny;
cbde5b15 17use JSON::Any qw(DWIW XS JSON);
8aa16237 18use namespace::autoclean;
bb464677 19
595cb2c7 20=head1 NAME
21
22DBIx::Class::Admin - Administration object for schemas
23
24=head1 SYNOPSIS
25
47442cea 26 $ dbicadmin --help
27
28 $ dbicadmin --schema=MyApp::Schema \
29 --connect='["dbi:SQLite:my.db", "", ""]' \
30 --deploy
31
32 $ dbicadmin --schema=MyApp::Schema --class=Employee \
33 --connect='["dbi:SQLite:my.db", "", ""]' \
cbde5b15 34 --op=update --set='{ "name": "New_Employee" }'
47442cea 35
9c34993a 36 use DBIx::Class::Admin;
595cb2c7 37
9c34993a 38 # ddl manipulation
39 my $admin = DBIx::Class::Admin->new(
40 schema_class=> 'MY::Schema',
41 sql_dir=> $sql_dir,
42 connect_info => { dsn => $dsn, user => $user, password => $pass },
43 );
595cb2c7 44
9c34993a 45 # create SQLite sql
46 $admin->create('SQLite');
595cb2c7 47
9c34993a 48 # create SQL diff for an upgrade
49 $admin->create('SQLite', {} , "1.0");
595cb2c7 50
9c34993a 51 # upgrade a database
52 $admin->upgrade();
595cb2c7 53
9c34993a 54 # install a version for an unversioned schema
55 $admin->install("3.0");
9f3849c3 56
47442cea 57=head1 REQUIREMENTS
58
a4a02f15 59The Admin interface has additional requirements not currently part of
60L<DBIx::Class>. See L<DBIx::Class::Optional::Dependencies> for more details.
47442cea 61
a4a02f15 62=head1 ATTRIBUTES
9f3849c3 63
595cb2c7 64=head2 schema_class
9f3849c3 65
595cb2c7 66the class of the schema to load
e81f0fe2 67
595cb2c7 68=cut
e81f0fe2 69
9f3849c3 70has 'schema_class' => (
3b27cdac 71 is => 'ro',
72 isa => Str,
9f3849c3 73);
74
e81f0fe2 75
595cb2c7 76=head2 schema
9f3849c3 77
595cb2c7 78A pre-connected schema object can be provided for manipulation
e81f0fe2 79
595cb2c7 80=cut
e81f0fe2 81
9f3849c3 82has 'schema' => (
3b27cdac 83 is => 'ro',
84 isa => 'DBIx::Class::Schema',
a705b175 85 lazy_build => 1,
9f3849c3 86);
87
9f3849c3 88sub _build_schema {
a705b175 89 my ($self) = @_;
a77f5ab1 90 require Class::MOP;
b13aab4f 91 {
ab534c33 92 my @include_dirs = @{$self->include_dirs};
ab534c33 93 local @INC = (@include_dirs, @INC);
b13aab4f 94 Class::MOP::load_class($self->schema_class);
95 }
a705b175 96 $self->connect_info->[3]->{ignore_version} =1;
97 return $self->schema_class->connect(@{$self->connect_info()} ); # , $self->connect_info->[3], { ignore_version => 1} );
9f3849c3 98}
99
b13aab4f 100=head2 include_dirs
101
102Extra include directories to look when loading C<schema_class>
103
104=cut
105
106has 'include_dirs' => (
107 is => 'rw',
108 isa => 'ArrayRef',
109 default => sub {[]}
110);
e81f0fe2 111
bb464677 112=head2 resultset
113
114a resultset from the schema to operate on
e81f0fe2 115
bb464677 116=cut
e81f0fe2 117
bb464677 118has 'resultset' => (
3b27cdac 119 is => 'rw',
120 isa => Str,
bb464677 121);
122
e81f0fe2 123
bb464677 124=head2 where
125
126a hash ref or json string to be used for identifying data to manipulate
e81f0fe2 127
bb464677 128=cut
129
130has 'where' => (
a705b175 131 is => 'rw',
3b27cdac 132 isa => DBICHashRef,
133 coerce => 1,
bb464677 134);
135
e81f0fe2 136
bb464677 137=head2 set
e81f0fe2 138
bb464677 139a hash ref or json string to be used for inserting or updating data
e81f0fe2 140
bb464677 141=cut
142
143has 'set' => (
a705b175 144 is => 'rw',
3b27cdac 145 isa => DBICHashRef,
146 coerce => 1,
bb464677 147);
148
e81f0fe2 149
bb464677 150=head2 attrs
e81f0fe2 151
bb464677 152a hash ref or json string to be used for passing additonal info to the ->search call
e81f0fe2 153
bb464677 154=cut
e81f0fe2 155
bb464677 156has 'attrs' => (
3b27cdac 157 is => 'rw',
158 isa => DBICHashRef,
159 coerce => 1,
bb464677 160);
e81f0fe2 161
162
595cb2c7 163=head2 connect_info
164
165connect_info the arguments to provide to the connect call of the schema_class
bb464677 166
e81f0fe2 167=cut
bb464677 168
9f3849c3 169has 'connect_info' => (
3b27cdac 170 is => 'ro',
171 isa => DBICConnectInfo,
a705b175 172 lazy_build => 1,
3b27cdac 173 coerce => 1,
9f3849c3 174);
175
176sub _build_connect_info {
a705b175 177 my ($self) = @_;
178 return $self->_find_stanza($self->config, $self->config_stanza);
9f3849c3 179}
180
e81f0fe2 181
595cb2c7 182=head2 config_file
183
184config_file provide a config_file to read connect_info from, if this is provided
185config_stanze should also be provided to locate where the connect_info is in the config
186The config file should be in a format readable by Config::General
e81f0fe2 187
595cb2c7 188=cut
e81f0fe2 189
595cb2c7 190has config_file => (
a705b175 191 is => 'ro',
3b27cdac 192 isa => File,
193 coerce => 1,
595cb2c7 194);
195
e81f0fe2 196
595cb2c7 197=head2 config_stanza
198
199config_stanza for use with config_file should be a '::' deliminated 'path' to the connection information
200designed for use with catalyst config files
e81f0fe2 201
595cb2c7 202=cut
e81f0fe2 203
595cb2c7 204has 'config_stanza' => (
3b27cdac 205 is => 'ro',
206 isa => Str,
595cb2c7 207);
208
e81f0fe2 209
595cb2c7 210=head2 config
211
a03b396b 212Instead of loading from a file the configuration can be provided directly as a hash ref. Please note
595cb2c7 213config_stanza will still be required.
e81f0fe2 214
595cb2c7 215=cut
e81f0fe2 216
9f3849c3 217has config => (
3b27cdac 218 is => 'ro',
219 isa => DBICHashRef,
a705b175 220 lazy_build => 1,
9f3849c3 221);
222
223sub _build_config {
a705b175 224 my ($self) = @_;
71766122 225
9780718f 226 try { require Config::Any }
227 catch { die ("Config::Any is required to parse the config file.\n") };
9f3849c3 228
a705b175 229 my $cfg = Config::Any->load_files ( {files => [$self->config_file], use_ext =>1, flatten_to_hash=>1});
9f3849c3 230
a705b175 231 # just grab the config from the config file
232 $cfg = $cfg->{$self->config_file};
233 return $cfg;
9f3849c3 234}
235
e81f0fe2 236
595cb2c7 237=head2 sql_dir
9f3849c3 238
595cb2c7 239The location where sql ddl files should be created or found for an upgrade.
e81f0fe2 240
595cb2c7 241=cut
e81f0fe2 242
9f3849c3 243has 'sql_dir' => (
a705b175 244 is => 'ro',
3b27cdac 245 isa => Dir,
246 coerce => 1,
9f3849c3 247);
248
e81f0fe2 249
595cb2c7 250=head2 version
9f3849c3 251
595cb2c7 252Used for install, the version which will be 'installed' in the schema
e81f0fe2 253
595cb2c7 254=cut
e81f0fe2 255
9f3849c3 256has version => (
3b27cdac 257 is => 'rw',
258 isa => Str,
9f3849c3 259);
260
e81f0fe2 261
595cb2c7 262=head2 preversion
263
264Previouse 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
e81f0fe2 265
595cb2c7 266=cut
e81f0fe2 267
9f3849c3 268has preversion => (
3b27cdac 269 is => 'rw',
270 isa => Str,
9f3849c3 271);
272
e81f0fe2 273
595cb2c7 274=head2 force
275
276Try and force certain operations.
e81f0fe2 277
595cb2c7 278=cut
e81f0fe2 279
912e2d5a 280has force => (
3b27cdac 281 is => 'rw',
282 isa => Bool,
912e2d5a 283);
284
e81f0fe2 285
c57f1cf7 286=head2 quiet
595cb2c7 287
288Be less verbose about actions
e81f0fe2 289
595cb2c7 290=cut
e81f0fe2 291
64c012f4 292has quiet => (
3b27cdac 293 is => 'rw',
294 isa => Bool,
64c012f4 295);
296
912e2d5a 297has '_confirm' => (
3b27cdac 298 is => 'bare',
299 isa => Bool,
912e2d5a 300);
301
e81f0fe2 302
595cb2c7 303=head1 METHODS
304
305=head2 create
306
307=over 4
308
309=item Arguments: $sqlt_type, \%sqlt_args, $preversion
310
311=back
312
a03b396b 313L<create> will generate sql for the supplied schema_class in sql_dir. The flavour of sql to
314generate can be controlled by suppling a sqlt_type which should be a L<SQL::Translator> name.
595cb2c7 315
316Arguments for L<SQL::Translator> can be supplied in the sqlt_args hashref.
317
318Optional preversion can be supplied to generate a diff to be used by upgrade.
e81f0fe2 319
595cb2c7 320=cut
321
9f3849c3 322sub create {
a705b175 323 my ($self, $sqlt_type, $sqlt_args, $preversion) = @_;
595cb2c7 324
a705b175 325 $preversion ||= $self->preversion();
595cb2c7 326
a705b175 327 my $schema = $self->schema();
328 # create the dir if does not exist
329 $self->sql_dir->mkpath() if ( ! -d $self->sql_dir);
9f3849c3 330
a705b175 331 $schema->create_ddl_dir( $sqlt_type, (defined $schema->schema_version ? $schema->schema_version : ""), $self->sql_dir->stringify, $preversion, $sqlt_args );
9f3849c3 332}
333
e81f0fe2 334
595cb2c7 335=head2 upgrade
336
337=over 4
338
339=item Arguments: <none>
340
341=back
342
343upgrade will attempt to upgrade the connected database to the same version as the schema_class.
344B<MAKE SURE YOU BACKUP YOUR DB FIRST>
e81f0fe2 345
595cb2c7 346=cut
347
9f3849c3 348sub upgrade {
a705b175 349 my ($self) = @_;
350 my $schema = $self->schema();
15de9f06 351
a705b175 352 if (!$schema->get_db_version()) {
353 # schema is unversioned
b718fd0a 354 $schema->throw_exception ("Could not determin current schema version, please either install() or deploy().\n");
a705b175 355 } else {
356 my $ret = $schema->upgrade();
357 return $ret;
358 }
9f3849c3 359}
360
e81f0fe2 361
595cb2c7 362=head2 install
363
364=over 4
365
366=item Arguments: $version
367
368=back
369
a03b396b 370install is here to help when you want to move to L<DBIx::Class::Schema::Versioned> and have an existing
371database. install will take a version and add the version tracking tables and 'install' the version. No
372further ddl modification takes place. Setting the force attribute to a true value will allow overriding of
595cb2c7 373already versioned databases.
e81f0fe2 374
595cb2c7 375=cut
e81f0fe2 376
9f3849c3 377sub install {
a705b175 378 my ($self, $version) = @_;
379
380 my $schema = $self->schema();
381 $version ||= $self->version();
382 if (!$schema->get_db_version() ) {
383 # schema is unversioned
15de9f06 384 print "Going to install schema version\n" if (!$self->quiet);
a705b175 385 my $ret = $schema->install($version);
15de9f06 386 print "return is $ret\n" if (!$self->quiet);
a705b175 387 }
388 elsif ($schema->get_db_version() and $self->force ) {
585072bb 389 carp "Forcing install may not be a good idea";
a705b175 390 if($self->_confirm() ) {
a705b175 391 $self->schema->_set_db_version({ version => $version});
9c34993a 392 }
a705b175 393 }
394 else {
b718fd0a 395 $schema->throw_exception ("Schema already has a version. Try upgrade instead.\n");
a705b175 396 }
9f3849c3 397
398}
399
e81f0fe2 400
595cb2c7 401=head2 deploy
402
403=over 4
404
405=item Arguments: $args
406
407=back
408
a03b396b 409deploy will create the schema at the connected database. C<$args> are passed straight to
e81f0fe2 410L<DBIx::Class::Schema/deploy>.
411
595cb2c7 412=cut
e81f0fe2 413
9f3849c3 414sub deploy {
a705b175 415 my ($self, $args) = @_;
416 my $schema = $self->schema();
a03b396b 417 $schema->deploy( $args, $self->sql_dir );
9f3849c3 418}
419
bb464677 420=head2 insert
595cb2c7 421
422=over 4
423
424=item Arguments: $rs, $set
425
426=back
427
bb464677 428insert takes the name of a resultset from the schema_class and a hashref of data to insert
595cb2c7 429into that resultset
430
431=cut
e81f0fe2 432
bb464677 433sub insert {
a705b175 434 my ($self, $rs, $set) = @_;
bb464677 435
a705b175 436 $rs ||= $self->resultset();
437 $set ||= $self->set();
438 my $resultset = $self->schema->resultset($rs);
439 my $obj = $resultset->create( $set );
440 print ''.ref($resultset).' ID: '.join(',',$obj->id())."\n" if (!$self->quiet);
9f3849c3 441}
442
595cb2c7 443
bb464677 444=head2 update
595cb2c7 445
e81f0fe2 446=over 4
595cb2c7 447
448=item Arguments: $rs, $set, $where
449
450=back
451
e81f0fe2 452update takes the name of a resultset from the schema_class, a hashref of data to update and
453a where hash used to form the search for the rows to update.
454
595cb2c7 455=cut
e81f0fe2 456
bb464677 457sub update {
a705b175 458 my ($self, $rs, $set, $where) = @_;
882931aa 459
a705b175 460 $rs ||= $self->resultset();
461 $where ||= $self->where();
462 $set ||= $self->set();
463 my $resultset = $self->schema->resultset($rs);
464 $resultset = $resultset->search( ($where||{}) );
882931aa 465
a705b175 466 my $count = $resultset->count();
467 print "This action will modify $count ".ref($resultset)." records.\n" if (!$self->quiet);
882931aa 468
a705b175 469 if ( $self->force || $self->_confirm() ) {
470 $resultset->update_all( $set );
471 }
9f3849c3 472}
473
e81f0fe2 474
bb464677 475=head2 delete
595cb2c7 476
477=over 4
478
479=item Arguments: $rs, $where, $attrs
480
481=back
482
e81f0fe2 483delete takes the name of a resultset from the schema_class, a where hashref and a attrs to pass to ->search.
595cb2c7 484The found data is deleted and cannot be recovered.
e81f0fe2 485
595cb2c7 486=cut
e81f0fe2 487
bb464677 488sub delete {
a705b175 489 my ($self, $rs, $where, $attrs) = @_;
9f3849c3 490
a705b175 491 $rs ||= $self->resultset();
492 $where ||= $self->where();
493 $attrs ||= $self->attrs();
494 my $resultset = $self->schema->resultset($rs);
495 $resultset = $resultset->search( ($where||{}), ($attrs||()) );
9f3849c3 496
a705b175 497 my $count = $resultset->count();
498 print "This action will delete $count ".ref($resultset)." records.\n" if (!$self->quiet);
9f3849c3 499
a705b175 500 if ( $self->force || $self->_confirm() ) {
501 $resultset->delete_all();
502 }
9f3849c3 503}
504
e81f0fe2 505
bb464677 506=head2 select
595cb2c7 507
508=over 4
509
510=item Arguments: $rs, $where, $attrs
511
512=back
513
a03b396b 514select takes the name of a resultset from the schema_class, a where hashref and a attrs to pass to ->search.
595cb2c7 515The found data is returned in a array ref where the first row will be the columns list.
516
517=cut
e81f0fe2 518
bb464677 519sub select {
a705b175 520 my ($self, $rs, $where, $attrs) = @_;
521
522 $rs ||= $self->resultset();
523 $where ||= $self->where();
524 $attrs ||= $self->attrs();
525 my $resultset = $self->schema->resultset($rs);
526 $resultset = $resultset->search( ($where||{}), ($attrs||()) );
527
528 my @data;
529 my @columns = $resultset->result_source->columns();
a03b396b 530 push @data, [@columns];#
a705b175 531
532 while (my $row = $resultset->next()) {
533 my @fields;
534 foreach my $column (@columns) {
535 push( @fields, $row->get_column($column) );
9c34993a 536 }
a705b175 537 push @data, [@fields];
538 }
9c34993a 539
a705b175 540 return \@data;
9f3849c3 541}
542
595cb2c7 543sub _confirm {
a705b175 544 my ($self) = @_;
15de9f06 545
a705b175 546 # mainly here for testing
547 return 1 if ($self->meta->get_attribute('_confirm')->get_value($self));
15de9f06 548
549 print "Are you sure you want to do this? (type YES to confirm) \n";
a705b175 550 my $response = <STDIN>;
15de9f06 551
552 return ($response=~/^YES/);
9f3849c3 553}
554
595cb2c7 555sub _find_stanza {
a705b175 556 my ($self, $cfg, $stanza) = @_;
557 my @path = split /::/, $stanza;
558 while (my $path = shift @path) {
559 if (exists $cfg->{$path}) {
560 $cfg = $cfg->{$path};
561 }
562 else {
b718fd0a 563 die ("Could not find $stanza in config, $path does not seem to exist.\n");
9c34993a 564 }
a705b175 565 }
566 return $cfg;
595cb2c7 567}
bb464677 568
47442cea 569=head1 AUTHOR
bb464677 570
e81f0fe2 571See L<DBIx::Class/CONTRIBUTORS>.
bb464677 572
573=head1 LICENSE
574
e81f0fe2 575You may distribute this code under the same terms as Perl itself
576
bb464677 577=cut
e81f0fe2 578
9f3849c3 5791;