Fix RT#57732
[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 {
23737393 356 $schema->upgrade_directory ($self->sql_dir) if $self->sql_dir; # this will override whatever default the schema has
a705b175 357 my $ret = $schema->upgrade();
358 return $ret;
359 }
9f3849c3 360}
361
e81f0fe2 362
595cb2c7 363=head2 install
364
365=over 4
366
367=item Arguments: $version
368
369=back
370
a03b396b 371install is here to help when you want to move to L<DBIx::Class::Schema::Versioned> and have an existing
372database. install will take a version and add the version tracking tables and 'install' the version. No
373further ddl modification takes place. Setting the force attribute to a true value will allow overriding of
595cb2c7 374already versioned databases.
e81f0fe2 375
595cb2c7 376=cut
e81f0fe2 377
9f3849c3 378sub install {
a705b175 379 my ($self, $version) = @_;
380
381 my $schema = $self->schema();
382 $version ||= $self->version();
383 if (!$schema->get_db_version() ) {
384 # schema is unversioned
15de9f06 385 print "Going to install schema version\n" if (!$self->quiet);
a705b175 386 my $ret = $schema->install($version);
15de9f06 387 print "return is $ret\n" if (!$self->quiet);
a705b175 388 }
389 elsif ($schema->get_db_version() and $self->force ) {
585072bb 390 carp "Forcing install may not be a good idea";
a705b175 391 if($self->_confirm() ) {
a705b175 392 $self->schema->_set_db_version({ version => $version});
9c34993a 393 }
a705b175 394 }
395 else {
b718fd0a 396 $schema->throw_exception ("Schema already has a version. Try upgrade instead.\n");
a705b175 397 }
9f3849c3 398
399}
400
e81f0fe2 401
595cb2c7 402=head2 deploy
403
404=over 4
405
406=item Arguments: $args
407
408=back
409
a03b396b 410deploy will create the schema at the connected database. C<$args> are passed straight to
e81f0fe2 411L<DBIx::Class::Schema/deploy>.
412
595cb2c7 413=cut
e81f0fe2 414
9f3849c3 415sub deploy {
a705b175 416 my ($self, $args) = @_;
417 my $schema = $self->schema();
a03b396b 418 $schema->deploy( $args, $self->sql_dir );
9f3849c3 419}
420
bb464677 421=head2 insert
595cb2c7 422
423=over 4
424
425=item Arguments: $rs, $set
426
427=back
428
bb464677 429insert takes the name of a resultset from the schema_class and a hashref of data to insert
595cb2c7 430into that resultset
431
432=cut
e81f0fe2 433
bb464677 434sub insert {
a705b175 435 my ($self, $rs, $set) = @_;
bb464677 436
a705b175 437 $rs ||= $self->resultset();
438 $set ||= $self->set();
439 my $resultset = $self->schema->resultset($rs);
440 my $obj = $resultset->create( $set );
441 print ''.ref($resultset).' ID: '.join(',',$obj->id())."\n" if (!$self->quiet);
9f3849c3 442}
443
595cb2c7 444
bb464677 445=head2 update
595cb2c7 446
e81f0fe2 447=over 4
595cb2c7 448
449=item Arguments: $rs, $set, $where
450
451=back
452
e81f0fe2 453update takes the name of a resultset from the schema_class, a hashref of data to update and
454a where hash used to form the search for the rows to update.
455
595cb2c7 456=cut
e81f0fe2 457
bb464677 458sub update {
a705b175 459 my ($self, $rs, $set, $where) = @_;
882931aa 460
a705b175 461 $rs ||= $self->resultset();
462 $where ||= $self->where();
463 $set ||= $self->set();
464 my $resultset = $self->schema->resultset($rs);
465 $resultset = $resultset->search( ($where||{}) );
882931aa 466
a705b175 467 my $count = $resultset->count();
468 print "This action will modify $count ".ref($resultset)." records.\n" if (!$self->quiet);
882931aa 469
a705b175 470 if ( $self->force || $self->_confirm() ) {
471 $resultset->update_all( $set );
472 }
9f3849c3 473}
474
e81f0fe2 475
bb464677 476=head2 delete
595cb2c7 477
478=over 4
479
480=item Arguments: $rs, $where, $attrs
481
482=back
483
e81f0fe2 484delete takes the name of a resultset from the schema_class, a where hashref and a attrs to pass to ->search.
595cb2c7 485The found data is deleted and cannot be recovered.
e81f0fe2 486
595cb2c7 487=cut
e81f0fe2 488
bb464677 489sub delete {
a705b175 490 my ($self, $rs, $where, $attrs) = @_;
9f3849c3 491
a705b175 492 $rs ||= $self->resultset();
493 $where ||= $self->where();
494 $attrs ||= $self->attrs();
495 my $resultset = $self->schema->resultset($rs);
496 $resultset = $resultset->search( ($where||{}), ($attrs||()) );
9f3849c3 497
a705b175 498 my $count = $resultset->count();
499 print "This action will delete $count ".ref($resultset)." records.\n" if (!$self->quiet);
9f3849c3 500
a705b175 501 if ( $self->force || $self->_confirm() ) {
502 $resultset->delete_all();
503 }
9f3849c3 504}
505
e81f0fe2 506
bb464677 507=head2 select
595cb2c7 508
509=over 4
510
511=item Arguments: $rs, $where, $attrs
512
513=back
514
a03b396b 515select takes the name of a resultset from the schema_class, a where hashref and a attrs to pass to ->search.
595cb2c7 516The found data is returned in a array ref where the first row will be the columns list.
517
518=cut
e81f0fe2 519
bb464677 520sub select {
a705b175 521 my ($self, $rs, $where, $attrs) = @_;
522
523 $rs ||= $self->resultset();
524 $where ||= $self->where();
525 $attrs ||= $self->attrs();
526 my $resultset = $self->schema->resultset($rs);
527 $resultset = $resultset->search( ($where||{}), ($attrs||()) );
528
529 my @data;
530 my @columns = $resultset->result_source->columns();
a03b396b 531 push @data, [@columns];#
a705b175 532
533 while (my $row = $resultset->next()) {
534 my @fields;
535 foreach my $column (@columns) {
536 push( @fields, $row->get_column($column) );
9c34993a 537 }
a705b175 538 push @data, [@fields];
539 }
9c34993a 540
a705b175 541 return \@data;
9f3849c3 542}
543
595cb2c7 544sub _confirm {
a705b175 545 my ($self) = @_;
15de9f06 546
a705b175 547 # mainly here for testing
548 return 1 if ($self->meta->get_attribute('_confirm')->get_value($self));
15de9f06 549
550 print "Are you sure you want to do this? (type YES to confirm) \n";
a705b175 551 my $response = <STDIN>;
15de9f06 552
553 return ($response=~/^YES/);
9f3849c3 554}
555
595cb2c7 556sub _find_stanza {
a705b175 557 my ($self, $cfg, $stanza) = @_;
558 my @path = split /::/, $stanza;
559 while (my $path = shift @path) {
560 if (exists $cfg->{$path}) {
561 $cfg = $cfg->{$path};
562 }
563 else {
b718fd0a 564 die ("Could not find $stanza in config, $path does not seem to exist.\n");
9c34993a 565 }
a705b175 566 }
567 return $cfg;
595cb2c7 568}
bb464677 569
47442cea 570=head1 AUTHOR
bb464677 571
e81f0fe2 572See L<DBIx::Class/CONTRIBUTORS>.
bb464677 573
574=head1 LICENSE
575
e81f0fe2 576You may distribute this code under the same terms as Perl itself
577
bb464677 578=cut
e81f0fe2 579
9f3849c3 5801;