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