change warns/dies -> carp/throw_exception
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Admin.pm
1 #
2 #===============================================================================
3 #
4 #         FILE:  Admin.pm
5 #
6 #  DESCRIPTION:  Administrative functions for DBIx::Class Schemata
7 #
8 #        FILES:  ---
9 #         BUGS:  ---
10 #        NOTES:  ---
11 #       AUTHOR:  Gordon Irving (), <Gordon.irving@sophos.com>
12 #      VERSION:  1.0
13 #      CREATED:  28/11/09 12:27:15 GMT
14 #     REVISION:  ---
15 #===============================================================================
16
17 package DBIx::Class::Admin;
18
19 use Moose;
20 use MooseX::Types -declare => [qw( DBICConnectInfo )];
21 use MooseX::Types::Moose qw/Int HashRef ArrayRef Str Any/;
22 use MooseX::Types::JSON qw(JSON);
23 use MooseX::Types::Path::Class qw(Dir File);
24 use Try::Tiny;
25
26 use Carp::Clan qw/^DBIx::Class/;
27
28 use parent 'Class::C3::Componentised';
29 use parent 'DBIx::Class::Schema';
30
31 use JSON::Any;
32
33 use namespace::autoclean;
34
35 my @_deps = qw(Moose MooseX::Types MooseX::Types::JSON MooseX::Types::Path::Class Try::Tiny parent JSON::Any Class::C3::Componentised namespace::autoclean);
36
37 coerce ArrayRef,
38   from JSON,
39   via { _json_to_data ($_) };
40
41 coerce HashRef,
42   from JSON,
43   via { _json_to_data($_) };
44
45 subtype DBICConnectInfo,
46   as ArrayRef;
47
48 coerce DBICConnectInfo,
49   from JSON,
50    via { return _json_to_data($_) } ;
51
52 coerce DBICConnectInfo,
53   from Str,
54     via { return _json_to_data($_) };
55
56 coerce DBICConnectInfo,
57   from HashRef,
58    via { [ $_->{dsn}, $_->{user}, $_->{password} ]  };
59
60
61 =head1 NAME
62
63 DBIx::Class::Admin - Administration object for schemas
64
65 =head1 SYNOPSIS
66
67   use DBIx::Class::Admin;
68
69   # ddl manipulation
70   my $admin = DBIx::Class::Admin->new(
71     schema_class=> 'MY::Schema',
72     sql_dir=> $sql_dir,
73     connect_info => { dsn => $dsn, user => $user, password => $pass },
74   );
75
76   # create SQLite sql
77   $admin->create('SQLite');
78
79   # create SQL diff for an upgrade
80   $admin->create('SQLite', {} , "1.0");
81
82   # upgrade a database
83   $admin->upgrade();
84
85   # install a version for an unversioned schema
86   $admin->install("3.0");
87
88 =head1 Attributes
89
90 =head2 schema_class
91
92 the class of the schema to load
93
94 =cut
95
96 has 'schema_class' => (
97   is    => 'ro',
98   isa    => 'Str',
99   coerce  => 1,
100 );
101
102
103 =head2 schema
104
105 A pre-connected schema object can be provided for manipulation
106
107 =cut
108
109 has 'schema' => (
110   is      => 'ro',
111   isa      => 'DBIx::Class::Schema',
112   lazy_build  => 1,
113 );
114
115 sub _build_schema {
116   my ($self)  = @_;
117   $self->ensure_class_loaded($self->schema_class);
118
119   $self->connect_info->[3]->{ignore_version} =1;
120   return $self->schema_class->connect(@{$self->connect_info()} ); # ,  $self->connect_info->[3], { ignore_version => 1} );
121 }
122
123
124 =head2 resultset
125
126 a resultset from the schema to operate on
127
128 =cut
129
130 has 'resultset' => (
131   is      => 'rw',
132   isa      => Str,
133 );
134
135
136 =head2 where
137
138 a hash ref or json string to be used for identifying data to manipulate
139
140 =cut
141
142 has 'where' => (
143   is      => 'rw',
144   isa      => HashRef,
145   coerce    => 1,
146 );
147
148
149 =head2 set
150
151 a hash ref or json string to be used for inserting or updating data
152
153 =cut
154
155 has 'set' => (
156   is      => 'rw',
157   isa      => HashRef,
158   coerce    => 1,
159 );
160
161
162 =head2 attrs
163
164 a hash ref or json string to be used for passing additonal info to the ->search call
165
166 =cut
167
168 has 'attrs' => (
169   is       => 'rw',
170   isa      => HashRef,
171   coerce    => 1,
172 );
173
174
175 =head2 connect_info
176
177 connect_info the arguments to provide to the connect call of the schema_class
178
179 =cut
180
181 has 'connect_info' => (
182   is      => 'ro',
183   isa      => DBICConnectInfo,
184   lazy_build  => 1,
185   coerce    => 1,
186 );
187
188 sub _build_connect_info {
189   my ($self) = @_;
190   return $self->_find_stanza($self->config, $self->config_stanza);
191 }
192
193
194 =head2 config_file
195
196 config_file provide a config_file to read connect_info from, if this is provided
197 config_stanze should also be provided to locate where the connect_info is in the config
198 The config file should be in a format readable by Config::General
199
200 =cut
201
202 has config_file => (
203   is      => 'ro',
204   isa      => File,
205   coerce    => 1,
206 );
207
208
209 =head2 config_stanza
210
211 config_stanza for use with config_file should be a '::' deliminated 'path' to the connection information
212 designed for use with catalyst config files
213
214 =cut
215
216 has 'config_stanza' => (
217   is      => 'ro',
218   isa      => 'Str',
219 );
220
221
222 =head2 config
223
224 Instead of loading from a file the configuration can be provided directly as a hash ref.  Please note 
225 config_stanza will still be required.
226
227 =cut
228
229 has config => (
230   is      => 'ro',
231   isa      => HashRef,
232   lazy_build  => 1,
233 );
234
235 sub _build_config {
236   my ($self) = @_;
237   try { require Config::Any } catch { $self->throw_exception( "Config::Any is required to parse the config file"); };
238
239   my $cfg = Config::Any->load_files ( {files => [$self->config_file], use_ext =>1, flatten_to_hash=>1});
240
241   # just grab the config from the config file
242   $cfg = $cfg->{$self->config_file};
243   return $cfg;
244 }
245
246
247 =head2 sql_dir
248
249 The location where sql ddl files should be created or found for an upgrade.
250
251 =cut
252
253 has 'sql_dir' => (
254   is      => 'ro',
255   isa      => Dir,
256   coerce    => 1,
257 );
258
259
260 =head2 version
261
262 Used for install, the version which will be 'installed' in the schema
263
264 =cut
265
266 has version => (
267   is      => 'rw',
268   isa      => 'Str',
269 );
270
271
272 =head2 preversion
273
274 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
275
276 =cut
277
278 has preversion => (
279   is      => 'rw',
280   isa      => 'Str',
281 );
282
283
284 =head2 force
285
286 Try and force certain operations.
287
288 =cut
289
290 has force => (
291   is      => 'rw',
292   isa      => 'Bool',
293 );
294
295
296 =head2 quiet
297
298 Be less verbose about actions
299
300 =cut
301
302 has quiet => (
303   is      => 'rw',
304   isa      => 'Bool',
305 );
306
307 has '_confirm' => (
308   is    => 'bare',
309   isa    => 'Bool',
310 );
311
312
313 =head1 METHODS
314
315 =head2 create
316
317 =over 4
318
319 =item Arguments: $sqlt_type, \%sqlt_args, $preversion
320
321 =back
322
323 L<create> will generate sql for the supplied schema_class in sql_dir.  The flavour of sql to 
324 generate can be controlled by suppling a sqlt_type which should be a L<SQL::Translator> name.  
325
326 Arguments for L<SQL::Translator> can be supplied in the sqlt_args hashref.
327
328 Optional preversion can be supplied to generate a diff to be used by upgrade.
329
330 =cut
331
332 sub create {
333   my ($self, $sqlt_type, $sqlt_args, $preversion) = @_;
334
335   $preversion ||= $self->preversion();
336
337   my $schema = $self->schema();
338   # create the dir if does not exist
339   $self->sql_dir->mkpath() if ( ! -d $self->sql_dir);
340
341   $schema->create_ddl_dir( $sqlt_type, (defined $schema->schema_version ? $schema->schema_version : ""), $self->sql_dir->stringify, $preversion, $sqlt_args );
342 }
343
344
345 =head2 upgrade
346
347 =over 4
348
349 =item Arguments: <none>
350
351 =back
352
353 upgrade will attempt to upgrade the connected database to the same version as the schema_class.
354 B<MAKE SURE YOU BACKUP YOUR DB FIRST>
355
356 =cut
357
358 sub upgrade {
359   my ($self) = @_;
360   my $schema = $self->schema();
361   if (!$schema->get_db_version()) {
362     # schema is unversioned
363     $self->throw_exception ("could not determin current schema version, please either install or deploy");
364   } else {
365     my $ret = $schema->upgrade();
366     return $ret;
367   }
368 }
369
370
371 =head2 install
372
373 =over 4
374
375 =item Arguments: $version
376
377 =back
378
379 install is here to help when you want to move to L<DBIx::Class::Schema::Versioned> and have an existing 
380 database.  install will take a version and add the version tracking tables and 'install' the version.  No 
381 further ddl modification takes place.  Setting the force attribute to a true value will allow overriding of 
382 already versioned databases.
383
384 =cut
385
386 sub install {
387   my ($self, $version) = @_;
388
389   my $schema = $self->schema();
390   $version ||= $self->version();
391   if (!$schema->get_db_version() ) {
392     # schema is unversioned
393     print "Going to install schema version\n";
394     my $ret = $schema->install($version);
395     print "retun is $ret\n";
396   }
397   elsif ($schema->get_db_version() and $self->force ) {
398     carp "Forcing install may not be a good idea";
399     if($self->_confirm() ) {
400       $self->schema->_set_db_version({ version => $version});
401     }
402   }
403   else {
404     $self->throw_exception ("schema already has a version not installing, try upgrade instead");
405   }
406
407 }
408
409
410 =head2 deploy
411
412 =over 4
413
414 =item Arguments: $args
415
416 =back
417
418 deploy will create the schema at the connected database.  C<$args> are passed straight to 
419 L<DBIx::Class::Schema/deploy>.
420
421 =cut
422
423 sub deploy {
424   my ($self, $args) = @_;
425   my $schema = $self->schema();
426   if (!$schema->get_db_version() ) {
427     # schema is unversioned
428     $schema->deploy( $args, $self->sql_dir)
429       or $self->throw_exception ("could not deploy schema");
430   } else {
431     $self->throw_exception("there already is a database with a version here, try upgrade instead");
432   }
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       $self->throw_exception("could not find $stanza in config, $path did not seem to exist");
577     }
578   }
579   return $cfg;
580 }
581
582 sub _json_to_data {
583   my ($json_str) = @_;
584   my $json = JSON::Any->new(allow_barekey => 1, allow_singlequote => 1, relaxed=>1);
585   my $ret = $json->jsonToObj($json_str);
586   return $ret;
587 }
588
589
590 {  # deps check
591
592 my @_missing_deps;
593 foreach my $dep (@_deps) {
594   eval "require $dep";
595   if ($@) {
596     push @_missing_deps, $dep;
597   }
598 }
599
600 if (@_missing_deps > 0) {
601   die "The following dependecies are missing " . join ",", @_missing_deps;
602 }
603
604
605 }
606
607
608 =head1 AUTHORS
609
610 See L<DBIx::Class/CONTRIBUTORS>.
611
612 =head1 LICENSE
613
614 You may distribute this code under the same terms as Perl itself
615
616 =cut
617
618 1;