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