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