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