I hate you all.
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Schema.pm
1 package DBIx::Class::Schema;
2
3 use strict;
4 use warnings;
5
6 use Carp::Clan qw/^DBIx::Class/;
7 use Scalar::Util qw/weaken/;
8
9 use base qw/DBIx::Class/;
10
11 __PACKAGE__->mk_classdata('class_mappings' => {});
12 __PACKAGE__->mk_classdata('source_registrations' => {});
13 __PACKAGE__->mk_classdata('storage_type' => '::DBI');
14 __PACKAGE__->mk_classdata('storage');
15
16 =head1 NAME
17
18 DBIx::Class::Schema - composable schemas
19
20 =head1 SYNOPSIS
21
22   package Library::Schema;
23   use base qw/DBIx::Class::Schema/;
24
25   # load Library::Schema::CD, Library::Schema::Book, Library::Schema::DVD
26   __PACKAGE__->load_classes(qw/CD Book DVD/);
27
28   package Library::Schema::CD;
29   use base qw/DBIx::Class/;
30   __PACKAGE__->load_components(qw/PK::Auto Core/); # for example
31   __PACKAGE__->table('cd');
32
33   # Elsewhere in your code:
34   my $schema1 = Library::Schema->connect(
35     $dsn,
36     $user,
37     $password,
38     { AutoCommit => 0 },
39   );
40
41   my $schema2 = Library::Schema->connect($coderef_returning_dbh);
42
43   # fetch objects using Library::Schema::DVD
44   my $resultset = $schema1->resultset('DVD')->search( ... );
45   my @dvd_objects = $schema2->resultset('DVD')->search( ... );
46
47 =head1 DESCRIPTION
48
49 Creates database classes based on a schema. This is the recommended way to
50 use L<DBIx::Class> and allows you to use more than one concurrent connection
51 with your classes.
52
53 NB: If you're used to L<Class::DBI> it's worth reading the L</SYNOPSIS>
54 carefully, as DBIx::Class does things a little differently. Note in
55 particular which module inherits off which.
56
57 =head1 METHODS
58
59 =head2 register_class
60
61 =over 4
62
63 =item Arguments: $moniker, $component_class
64
65 =back
66
67 Registers a class which isa DBIx::Class::ResultSourceProxy. Equivalent to
68 calling:
69
70   $schema->register_source($moniker, $component_class->result_source_instance);
71
72 =cut
73
74 sub register_class {
75   my ($self, $moniker, $to_register) = @_;
76   $self->register_source($moniker => $to_register->result_source_instance);
77 }
78
79 =head2 register_source
80
81 =over 4
82
83 =item Arguments: $moniker, $result_source
84
85 =back
86
87 Registers the L<DBIx::Class::ResultSource> in the schema with the given
88 moniker.
89
90 =cut
91
92 sub register_source {
93   my ($self, $moniker, $source) = @_;
94   my %reg = %{$self->source_registrations};
95   $reg{$moniker} = $source;
96   $self->source_registrations(\%reg);
97   $source->schema($self);
98   weaken($source->{schema}) if ref($self);
99   if ($source->result_class) {
100     my %map = %{$self->class_mappings};
101     $map{$source->result_class} = $moniker;
102     $self->class_mappings(\%map);
103   }
104 }
105
106 =head2 class
107
108 =over 4
109
110 =item Arguments: $moniker
111
112 =item Return Value: $classname
113
114 =back
115
116 Retrieves the result class name for the given moniker. For example:
117
118   my $class = $schema->class('CD');
119
120 =cut
121
122 sub class {
123   my ($self, $moniker) = @_;
124   return $self->source($moniker)->result_class;
125 }
126
127 =head2 source
128
129 =over 4
130
131 =item Arguments: $moniker
132
133 =item Return Value: $result_source
134
135 =back
136
137   my $source = $schema->source('Book');
138
139 Returns the L<DBIx::Class::ResultSource> object for the registered moniker.
140
141 =cut
142
143 sub source {
144   my ($self, $moniker) = @_;
145   my $sreg = $self->source_registrations;
146   return $sreg->{$moniker} if exists $sreg->{$moniker};
147
148   # if we got here, they probably passed a full class name
149   my $mapped = $self->class_mappings->{$moniker};
150   $self->throw_exception("Can't find source for ${moniker}")
151     unless $mapped && exists $sreg->{$mapped};
152   return $sreg->{$mapped};
153 }
154
155 =head2 sources
156
157 =over 4
158
159 =item Return Value: @source_monikers
160
161 =back
162
163 Returns the source monikers of all source registrations on this schema.
164 For example:
165
166   my @source_monikers = $schema->sources;
167
168 =cut
169
170 sub sources { return keys %{shift->source_registrations}; }
171
172 =head2 storage
173
174   my $storage = $schema->storage;
175
176 Returns the L<DBIx::Class::Storage> object for this Schema.
177
178 =head2 resultset
179
180 =over 4
181
182 =item Arguments: $moniker
183
184 =item Return Value: $result_set
185
186 =back
187
188   my $rs = $schema->resultset('DVD');
189
190 Returns the L<DBIx::Class::ResultSet> object for the registered moniker.
191
192 =cut
193
194 sub resultset {
195   my ($self, $moniker) = @_;
196   return $self->source($moniker)->resultset;
197 }
198
199 =head2 load_classes
200
201 =over 4
202
203 =item Arguments: @classes?, { $namespace => [ @classes ] }+
204
205 =back
206
207 With no arguments, this method uses L<Module::Find> to find all classes under
208 the schema's namespace. Otherwise, this method loads the classes you specify
209 (using L<use>), and registers them (using L</"register_class">).
210
211 It is possible to comment out classes with a leading C<#>, but note that perl
212 will think it's a mistake (trying to use a comment in a qw list), so you'll
213 need to add C<no warnings 'qw';> before your load_classes call.
214
215 Example:
216
217   My::Schema->load_classes(); # loads My::Schema::CD, My::Schema::Artist,
218                               # etc. (anything under the My::Schema namespace)
219
220   # loads My::Schema::CD, My::Schema::Artist, Other::Namespace::Producer but
221   # not Other::Namespace::LinerNotes nor My::Schema::Track
222   My::Schema->load_classes(qw/ CD Artist #Track /, {
223     Other::Namespace => [qw/ Producer #LinerNotes /],
224   });
225
226 =cut
227
228 sub load_classes {
229   my ($class, @params) = @_;
230
231   my %comps_for;
232
233   if (@params) {
234     foreach my $param (@params) {
235       if (ref $param eq 'ARRAY') {
236         # filter out commented entries
237         my @modules = grep { $_ !~ /^#/ } @$param;
238
239         push (@{$comps_for{$class}}, @modules);
240       }
241       elsif (ref $param eq 'HASH') {
242         # more than one namespace possible
243         for my $comp ( keys %$param ) {
244           # filter out commented entries
245           my @modules = grep { $_ !~ /^#/ } @{$param->{$comp}};
246
247           push (@{$comps_for{$comp}}, @modules);
248         }
249       }
250       else {
251         # filter out commented entries
252         push (@{$comps_for{$class}}, $param) if $param !~ /^#/;
253       }
254     }
255   } else {
256     eval "require Module::Find;";
257     $class->throw_exception(
258       "No arguments to load_classes and couldn't load Module::Find ($@)"
259     ) if $@;
260     my @comp = map { substr $_, length "${class}::"  }
261                  Module::Find::findallmod($class);
262     $comps_for{$class} = \@comp;
263   }
264
265   my @to_register;
266   {
267     no warnings qw/redefine/;
268     local *Class::C3::reinitialize = sub { };
269     foreach my $prefix (keys %comps_for) {
270       foreach my $comp (@{$comps_for{$prefix}||[]}) {
271         my $comp_class = "${prefix}::${comp}";
272         { # try to untaint module name. mods where this fails
273           # are left alone so we don't have to change the old behavior
274           no locale; # localized \w doesn't untaint expression
275           if ( $comp_class =~ m/^( (?:\w+::)* \w+ )$/x ) {
276             $comp_class = $1;
277           }
278         }
279         $class->ensure_class_loaded($comp_class);
280         $comp_class->source_name($comp) unless $comp_class->source_name;
281
282         push(@to_register, [ $comp_class->source_name, $comp_class ]);
283       }
284     }
285   }
286   Class::C3->reinitialize;
287
288   foreach my $to (@to_register) {
289     $class->register_class(@$to);
290     #  if $class->can('result_source_instance');
291   }
292 }
293
294 =head2 compose_connection
295
296 =over 4
297
298 =item Arguments: $target_namespace, @db_info
299
300 =item Return Value: $new_schema
301
302 =back
303
304 Calls L<DBIx::Class::Schema/"compose_namespace"> to the target namespace,
305 calls L<DBIx::Class::Schema/connection> with @db_info on the new schema,
306 then injects the L<DBix::Class::ResultSetProxy> component and a
307 resultset_instance classdata entry on all the new classes, in order to support
308 $target_namespaces::$class->search(...) method calls.
309
310 This is primarily useful when you have a specific need for class method access
311 to a connection. In normal usage it is preferred to call
312 L<DBIx::Class::Schema/connect> and use the resulting schema object to operate
313 on L<DBIx::Class::ResultSet> objects with L<DBIx::Class::Schema/resultset> for
314 more information.
315
316 =cut
317
318 sub compose_connection {
319   my ($self, $target, @info) = @_;
320   my $base = 'DBIx::Class::ResultSetProxy';
321   eval "require ${base};";
322   $self->throw_exception
323     ("No arguments to load_classes and couldn't load ${base} ($@)")
324       if $@;
325
326   if ($self eq $target) {
327     # Pathological case, largely caused by the docs on early C::M::DBIC::Plain
328     foreach my $moniker ($self->sources) {
329       my $source = $self->source($moniker);
330       my $class = $source->result_class;
331       $self->inject_base($class, $base);
332       $class->mk_classdata(resultset_instance => $source->resultset);
333       $class->mk_classdata(class_resolver => $self);
334     }
335     $self->connection(@info);
336     return $self;
337   }
338
339   my $schema = $self->compose_namespace($target, $base);
340   {
341     no strict 'refs';
342     *{"${target}::schema"} = sub { $schema };
343   }
344
345   $schema->connection(@info);
346   foreach my $moniker ($schema->sources) {
347     my $source = $schema->source($moniker);
348     my $class = $source->result_class;
349     #warn "$moniker $class $source ".$source->storage;
350     $class->mk_classdata(result_source_instance => $source);
351     $class->mk_classdata(resultset_instance => $source->resultset);
352     $class->mk_classdata(class_resolver => $schema);
353   }
354   return $schema;
355 }
356
357 =head2 compose_namespace
358
359 =over 4
360
361 =item Arguments: $target_namespace, $additional_base_class?
362
363 =item Return Value: $new_schema
364
365 =back
366
367 For each L<DBIx::Class::ResultSource> in the schema, this method creates a
368 class in the target namespace (e.g. $target_namespace::CD,
369 $target_namespace::Artist) that inherits from the corresponding classes
370 attached to the current schema.
371
372 It also attaches a corresponding L<DBIx::Class::ResultSource> object to the
373 new $schema object. If C<$additional_base_class> is given, the new composed
374 classes will inherit from first the corresponding classe from the current
375 schema then the base class.
376
377 For example, for a schema with My::Schema::CD and My::Schema::Artist classes,
378
379   $schema->compose_namespace('My::DB', 'Base::Class');
380   print join (', ', @My::DB::CD::ISA) . "\n";
381   print join (', ', @My::DB::Artist::ISA) ."\n";
382
383 will produce the output
384
385   My::Schema::CD, Base::Class
386   My::Schema::Artist, Base::Class
387
388 =cut
389
390 sub compose_namespace {
391   my ($self, $target, $base) = @_;
392   my %reg = %{ $self->source_registrations };
393   my %target;
394   my %map;
395   my $schema = $self->clone;
396   {
397     no warnings qw/redefine/;
398     local *Class::C3::reinitialize = sub { };
399     foreach my $moniker ($schema->sources) {
400       my $source = $schema->source($moniker);
401       my $target_class = "${target}::${moniker}";
402       $self->inject_base(
403         $target_class => $source->result_class, ($base ? $base : ())
404       );
405       $source->result_class($target_class);
406       $target_class->result_source_instance($source)
407         if $target_class->can('result_source_instance');
408     }
409   }
410   Class::C3->reinitialize();
411   {
412     no strict 'refs';
413     foreach my $meth (qw/class source resultset/) {
414       *{"${target}::${meth}"} =
415         sub { shift->schema->$meth(@_) };
416     }
417   }
418   return $schema;
419 }
420
421 =head2 setup_connection_class
422
423 =over 4
424
425 =item Arguments: $target, @info
426
427 =back
428
429 Sets up a database connection class to inject between the schema and the
430 subclasses that the schema creates.
431
432 =cut
433
434 sub setup_connection_class {
435   my ($class, $target, @info) = @_;
436   $class->inject_base($target => 'DBIx::Class::DB');
437   #$target->load_components('DB');
438   $target->connection(@info);
439 }
440
441 =head2 storage_type
442
443 =over 4
444
445 =item Arguments: $storage_type
446
447 =item Return Value: $storage_type
448
449 =back
450
451 Set the storage class that will be instantiated when L</connect> is called.
452 If the classname starts with C<::>, the prefix C<DBIx::Class::Storage> is
453 assumed by L</connect>.  Defaults to C<::DBI>,
454 which is L<DBIx::Class::Storage::DBI>.
455
456 You want to use this to hardcoded subclasses of L<DBIx::Class::Storage::DBI>
457 in cases where the appropriate subclass is not autodetected, such as when
458 dealing with MSSQL via L<DBD::Sybase>, in which case you'd set it to
459 C<::DBI::Sybase::MSSQL>.
460
461 =head2 connection
462
463 =over 4
464
465 =item Arguments: @args
466
467 =item Return Value: $new_schema
468
469 =back
470
471 Instantiates a new Storage object of type
472 L<DBIx::Class::Schema/"storage_type"> and passes the arguments to
473 $storage->connect_info. Sets the connection in-place on the schema. See
474 L<DBIx::Class::Storage::DBI/"connect_info"> for more information.
475
476 =cut
477
478 sub connection {
479   my ($self, @info) = @_;
480   return $self if !@info && $self->storage;
481   my $storage_class = $self->storage_type;
482   $storage_class = 'DBIx::Class::Storage'.$storage_class
483     if $storage_class =~ m/^::/;
484   eval "require ${storage_class};";
485   $self->throw_exception(
486     "No arguments to load_classes and couldn't load ${storage_class} ($@)"
487   ) if $@;
488   my $storage = $storage_class->new;
489   $storage->connect_info(\@info);
490   $self->storage($storage);
491   return $self;
492 }
493
494 =head2 connect
495
496 =over 4
497
498 =item Arguments: @info
499
500 =item Return Value: $new_schema
501
502 =back
503
504 This is a convenience method. It is equivalent to calling
505 $schema->clone->connection(@info). See L</connection> and L</clone> for more
506 information.
507
508 =cut
509
510 sub connect { shift->clone->connection(@_) }
511
512 =head2 txn_begin
513
514 Begins a transaction (does nothing if AutoCommit is off). Equivalent to
515 calling $schema->storage->txn_begin. See
516 L<DBIx::Class::Storage::DBI/"txn_begin"> for more information.
517
518 =cut
519
520 sub txn_begin { shift->storage->txn_begin }
521
522 =head2 txn_commit
523
524 Commits the current transaction. Equivalent to calling
525 $schema->storage->txn_commit. See L<DBIx::Class::Storage::DBI/"txn_commit">
526 for more information.
527
528 =cut
529
530 sub txn_commit { shift->storage->txn_commit }
531
532 =head2 txn_rollback
533
534 Rolls back the current transaction. Equivalent to calling
535 $schema->storage->txn_rollback. See
536 L<DBIx::Class::Storage::DBI/"txn_rollback"> for more information.
537
538 =cut
539
540 sub txn_rollback { shift->storage->txn_rollback }
541
542 =head2 txn_do
543
544 =over 4
545
546 =item Arguments: C<$coderef>, @coderef_args?
547
548 =item Return Value: The return value of $coderef
549
550 =back
551
552 Executes C<$coderef> with (optional) arguments C<@coderef_args> atomically,
553 returning its result (if any). If an exception is caught, a rollback is issued
554 and the exception is rethrown. If the rollback fails, (i.e. throws an
555 exception) an exception is thrown that includes a "Rollback failed" message.
556
557 For example,
558
559   my $author_rs = $schema->resultset('Author')->find(1);
560   my @titles = qw/Night Day It/;
561
562   my $coderef = sub {
563     # If any one of these fails, the entire transaction fails
564     $author_rs->create_related('books', {
565       title => $_
566     }) foreach (@titles);
567
568     return $author->books;
569   };
570
571   my $rs;
572   eval {
573     $rs = $schema->txn_do($coderef);
574   };
575
576   if ($@) {                                  # Transaction failed
577     die "something terrible has happened!"   #
578       if ($@ =~ /Rollback failed/);          # Rollback failed
579
580     deal_with_failed_transaction();
581   }
582
583 In a nested transaction (calling txn_do() from within a txn_do() coderef) only
584 the outermost transaction will issue a L<DBIx::Class::Schema/"txn_commit"> on
585 the Schema's storage, and txn_do() can be called in void, scalar and list
586 context and it will behave as expected.
587
588 =cut
589
590 sub txn_do {
591   my ($self, $coderef, @args) = @_;
592
593   $self->storage or $self->throw_exception
594     ('txn_do called on $schema without storage');
595   ref $coderef eq 'CODE' or $self->throw_exception
596     ('$coderef must be a CODE reference');
597
598   my (@return_values, $return_value);
599
600   $self->txn_begin; # If this throws an exception, no rollback is needed
601
602   my $wantarray = wantarray; # Need to save this since the context
603                              # inside the eval{} block is independent
604                              # of the context that called txn_do()
605   eval {
606
607     # Need to differentiate between scalar/list context to allow for
608     # returning a list in scalar context to get the size of the list
609     if ($wantarray) {
610       # list context
611       @return_values = $coderef->(@args);
612     } elsif (defined $wantarray) {
613       # scalar context
614       $return_value = $coderef->(@args);
615     } else {
616       # void context
617       $coderef->(@args);
618     }
619     $self->txn_commit;
620   };
621
622   if ($@) {
623     my $error = $@;
624
625     eval {
626       $self->txn_rollback;
627     };
628
629     if ($@) {
630       my $rollback_error = $@;
631       my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
632       $self->throw_exception($error)  # propagate nested rollback
633         if $rollback_error =~ /$exception_class/;
634
635       $self->throw_exception(
636         "Transaction aborted: $error. Rollback failed: ${rollback_error}"
637       );
638     } else {
639       $self->throw_exception($error); # txn failed but rollback succeeded
640     }
641   }
642
643   return $wantarray ? @return_values : $return_value;
644 }
645
646 =head2 clone
647
648 =over 4
649
650 =item Return Value: $new_schema
651
652 =back
653
654 Clones the schema and its associated result_source objects and returns the
655 copy.
656
657 =cut
658
659 sub clone {
660   my ($self) = @_;
661   my $clone = { (ref $self ? %$self : ()) };
662   bless $clone, (ref $self || $self);
663
664   foreach my $moniker ($self->sources) {
665     my $source = $self->source($moniker);
666     my $new = $source->new($source);
667     $clone->register_source($moniker => $new);
668   }
669   return $clone;
670 }
671
672 =head2 populate
673
674 =over 4
675
676 =item Arguments: $source_name, \@data;
677
678 =back
679
680 Pass this method a resultsource name, and an arrayref of
681 arrayrefs. The arrayrefs should contain a list of column names,
682 followed by one or many sets of matching data for the given columns. 
683
684 Each set of data is inserted into the database using
685 L<DBIx::Class::ResultSet/create>, and a arrayref of the resulting row
686 objects is returned.
687
688 i.e.,
689
690   $schema->populate('Artist', [
691     [ qw/artistid name/ ],
692     [ 1, 'Popular Band' ],
693     [ 2, 'Indie Band' ],
694     ...
695   ]);
696
697 =cut
698
699 sub populate {
700   my ($self, $name, $data) = @_;
701   my $rs = $self->resultset($name);
702   my @names = @{shift(@$data)};
703   my @created;
704   foreach my $item (@$data) {
705     my %create;
706     @create{@names} = @$item;
707     push(@created, $rs->create(\%create));
708   }
709   return @created;
710 }
711
712 =head2 throw_exception
713
714 =over 4
715
716 =item Arguments: $message
717
718 =back
719
720 Throws an exception. Defaults to using L<Carp::Clan> to report errors from
721 user's perspective.
722
723 =cut
724
725 sub throw_exception {
726   my ($self) = shift;
727   croak @_;
728 }
729
730 =head2 deploy (EXPERIMENTAL)
731
732 =over 4
733
734 =item Arguments: $sqlt_args, $dir
735
736 =back
737
738 Attempts to deploy the schema to the current storage using L<SQL::Translator>.
739
740 Note that this feature is currently EXPERIMENTAL and may not work correctly
741 across all databases, or fully handle complex relationships.
742
743 See L<SQL::Translator/METHODS> for a list of values for C<$sqlt_args>. The most
744 common value for this would be C<< { add_drop_table => 1, } >> to have the SQL
745 produced include a DROP TABLE statement for each table created.
746
747 =cut
748
749 sub deploy {
750   my ($self, $sqltargs, $dir) = @_;
751   $self->throw_exception("Can't deploy without storage") unless $self->storage;
752   $self->storage->deploy($self, undef, $sqltargs, $dir);
753 }
754
755 =head2 create_ddl_dir (EXPERIMENTAL)
756
757 =over 4
758
759 =item Arguments: \@databases, $version, $directory, $sqlt_args
760
761 =back
762
763 Creates an SQL file based on the Schema, for each of the specified
764 database types, in the given directory.
765
766 Note that this feature is currently EXPERIMENTAL and may not work correctly
767 across all databases, or fully handle complex relationships.
768
769 =cut
770
771 sub create_ddl_dir {
772   my $self = shift;
773
774   $self->throw_exception("Can't create_ddl_dir without storage") unless $self->storage;
775   $self->storage->create_ddl_dir($self, @_);
776 }
777
778 =head2 ddl_filename (EXPERIMENTAL)
779
780   my $filename = $table->ddl_filename($type, $dir, $version)
781
782 Creates a filename for a SQL file based on the table class name.  Not
783 intended for direct end user use.
784
785 =cut
786
787 sub ddl_filename {
788     my ($self, $type, $dir, $version) = @_;
789
790     my $filename = ref($self);
791     $filename =~ s/::/-/;
792     $filename = "$dir$filename-$version-$type.sql";
793
794     return $filename;
795 }
796
797 1;
798
799 =head1 AUTHORS
800
801 Matt S. Trout <mst@shadowcatsystems.co.uk>
802
803 =head1 LICENSE
804
805 You may distribute this code under the same terms as Perl itself.
806
807 =cut