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