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