Doc updates to remove PK::Auto::<db> references and miscellaneous trinkets.
[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 ResultSourceProxy; equivalent to calling
63
64   $schema->register_source($moniker, $component_class->result_source_instance);
65
66 =cut
67
68 sub register_class {
69   my ($self, $moniker, $to_register) = @_;
70   $self->register_source($moniker => $to_register->result_source_instance);
71 }
72
73 =head2 register_source
74
75 =head3 Arguments: <moniker> <result source>
76
77 Registers the result source in the schema with the given moniker
78
79 =cut
80
81 sub register_source {
82   my ($self, $moniker, $source) = @_;
83   my %reg = %{$self->source_registrations};
84   $reg{$moniker} = $source;
85   $self->source_registrations(\%reg);
86   $source->schema($self);
87   if ($source->result_class) {
88     my %map = %{$self->class_mappings};
89     $map{$source->result_class} = $moniker;
90     $self->class_mappings(\%map);
91   }
92
93
94 =head2 class
95
96   my $class = $schema->class('CD');
97
98 Retrieves the result class name for a given result source
99
100 =cut
101
102 sub class {
103   my ($self, $moniker) = @_;
104   return $self->source($moniker)->result_class;
105 }
106
107 =head2 source
108
109   my $source = $schema->source('Book');
110
111 Returns the result source object for the registered name
112
113 =cut
114
115 sub source {
116   my ($self, $moniker) = @_;
117   my $sreg = $self->source_registrations;
118   return $sreg->{$moniker} if exists $sreg->{$moniker};
119
120   # if we got here, they probably passed a full class name
121   my $mapped = $self->class_mappings->{$moniker};
122   $self->throw_exception("Can't find source for ${moniker}")
123     unless $mapped && exists $sreg->{$mapped};
124   return $sreg->{$mapped};
125 }
126
127 =head2 sources
128
129   my @source_monikers = $schema->sources;
130
131 Returns the source monikers of all source registrations on this schema
132
133 =cut
134
135 sub sources { return keys %{shift->source_registrations}; }
136
137 =head2 resultset
138
139   my $rs = $schema->resultset('DVD');
140
141 Returns the resultset for the registered moniker
142
143 =cut
144
145 sub resultset {
146   my ($self, $moniker) = @_;
147   return $self->source($moniker)->resultset;
148 }
149
150 =head2 load_classes
151
152 =head3 Arguments: [<classes>, (<class>, <class>), {<namespace> => [<classes>]}]
153
154 Uses L<Module::Find> to find all classes under the database class' namespace,
155 or uses the classes you select.  Then it loads the component (using L<use>), 
156 and registers them (using B<register_class>);
157
158 It is possible to comment out classes with a leading '#', but note that perl
159 will think it's a mistake (trying to use a comment in a qw list) so you'll
160 need to add "no warnings 'qw';" before your load_classes call.
161
162 =cut
163
164 sub load_classes {
165   my ($class, @params) = @_;
166   
167   my %comps_for;
168   
169   if (@params) {
170     foreach my $param (@params) {
171       if (ref $param eq 'ARRAY') {
172         # filter out commented entries
173         my @modules = grep { $_ !~ /^#/ } @$param;
174         
175         push (@{$comps_for{$class}}, @modules);
176       }
177       elsif (ref $param eq 'HASH') {
178         # more than one namespace possible
179         for my $comp ( keys %$param ) {
180           # filter out commented entries
181           my @modules = grep { $_ !~ /^#/ } @{$param->{$comp}};
182
183           push (@{$comps_for{$comp}}, @modules);
184         }
185       }
186       else {
187         # filter out commented entries
188         push (@{$comps_for{$class}}, $param) if $param !~ /^#/;
189       }
190     }
191   } else {
192     eval "require Module::Find;";
193     $class->throw_exception("No arguments to load_classes and couldn't load".
194       " Module::Find ($@)") if $@;
195     my @comp = map { substr $_, length "${class}::"  } Module::Find::findallmod($class);
196     $comps_for{$class} = \@comp;
197   }
198
199   my @to_register;
200   {
201     no warnings qw/redefine/;
202     local *Class::C3::reinitialize = sub { };
203     foreach my $prefix (keys %comps_for) {
204       foreach my $comp (@{$comps_for{$prefix}||[]}) {
205         my $comp_class = "${prefix}::${comp}";
206         eval "use $comp_class"; # If it fails, assume the user fixed it
207         if ($@) {
208           $comp_class =~ s/::/\//g;
209           die $@ unless $@ =~ /Can't locate.+$comp_class\.pm\sin\s\@INC/;
210           warn $@ if $@;
211         }
212         push(@to_register, [ $comp, $comp_class ]);
213       }
214     }
215   }
216   Class::C3->reinitialize;
217
218   foreach my $to (@to_register) {
219     $class->register_class(@$to);
220     #  if $class->can('result_source_instance');
221   }
222 }
223
224 =head2 compose_connection
225
226 =head3 Arguments: <target> <@db_info>
227
228 This method takes a target namespace, as well as dbh connection info, 
229 and creates a L<DBIx::Class::DB> class as well as subclasses for each of
230 your database classes in this namespace, using this connection.
231
232 It will also setup a ->class method on the target class, which lets you
233 resolve database classes based on the schema component name, for example
234
235   Library::Model::DB->class('Book') # returns Library::Model::Book, 
236                                     # which ISA Library::Schema::Book
237
238 This is the recommended API for accessing Schema generated classes, and 
239 using it might give you instant advantages with future versions of DBIC.
240
241 WARNING: Loading components into Schema classes after compose_connection
242 may not cause them to be seen by the classes in your target namespace due
243 to the dispatch table approach used by Class::C3. If you do this you may find
244 you need to call Class::C3->reinitialize() afterwards to get the behaviour
245 you expect.
246
247 =cut
248
249 sub compose_connection {
250   my ($self, $target, @info) = @_;
251   my $base = 'DBIx::Class::ResultSetProxy';
252   eval "require ${base};";
253   $self->throw_exception("No arguments to load_classes and couldn't load".
254       " ${base} ($@)") if $@;
255
256   if ($self eq $target) {
257     # Pathological case, largely caused by the docs on early C::M::DBIC::Plain
258     foreach my $moniker ($self->sources) {
259       my $source = $self->source($moniker);
260       my $class = $source->result_class;
261       $self->inject_base($class, $base);
262       $class->mk_classdata(resultset_instance => $source->resultset);
263       $class->mk_classdata(class_resolver => $self);
264     }
265     $self->connection(@info);
266     return $self;
267   }
268
269   my $schema = $self->compose_namespace($target, $base);
270   {
271     no strict 'refs';
272     *{"${target}::schema"} = sub { $schema };
273   }
274
275   $schema->connection(@info);
276   foreach my $moniker ($schema->sources) {
277     my $source = $schema->source($moniker);
278     my $class = $source->result_class;
279     #warn "$moniker $class $source ".$source->storage;
280     $class->mk_classdata(result_source_instance => $source);
281     $class->mk_classdata(resultset_instance => $source->resultset);
282     $class->mk_classdata(class_resolver => $schema);
283   }
284   return $schema;
285 }
286
287 =head2 compose_namespace
288
289 =head3 Arguments: <target> <base>
290
291 Translates <base> namespace into the specified <target> namespace. 
292
293 =cut
294
295 sub compose_namespace {
296   my ($self, $target, $base) = @_;
297   my %reg = %{ $self->source_registrations };
298   my %target;
299   my %map;
300   my $schema = $self->clone;
301   {
302     no warnings qw/redefine/;
303     local *Class::C3::reinitialize = sub { };
304     foreach my $moniker ($schema->sources) {
305       my $source = $schema->source($moniker);
306       my $target_class = "${target}::${moniker}";
307       $self->inject_base(
308         $target_class => $source->result_class, ($base ? $base : ())
309       );
310       $source->result_class($target_class);
311     }
312   }
313   Class::C3->reinitialize();
314   {
315     no strict 'refs';
316     foreach my $meth (qw/class source resultset/) {
317       *{"${target}::${meth}"} =
318         sub { shift->schema->$meth(@_) };
319     }
320   }
321   return $schema;
322 }
323
324 =head2 setup_connection_class
325
326 =head3 Arguments: <$target> <@info>
327
328 Sets up a database connection class to inject between the schema
329 and the subclasses the schema creates.
330
331 =cut
332
333 sub setup_connection_class {
334   my ($class, $target, @info) = @_;
335   $class->inject_base($target => 'DBIx::Class::DB');
336   #$target->load_components('DB');
337   $target->connection(@info);
338 }
339
340 =head2 connection
341
342 =head3 Arguments: (@args)
343
344 Instantiates a new Storage object of type storage_type and passes the
345 arguments to $storage->connect_info. Sets the connection in-place on
346 the schema.
347
348 =cut
349
350 sub connection {
351   my ($self, @info) = @_;
352   return $self if !@info && $self->storage;
353   my $storage_class = $self->storage_type;
354   $storage_class = 'DBIx::Class::Storage'.$storage_class
355     if $storage_class =~ m/^::/;
356   eval "require ${storage_class};";
357   $self->throw_exception("No arguments to load_classes and couldn't load".
358       " ${storage_class} ($@)") if $@;
359   my $storage = $storage_class->new;
360   $storage->connect_info(\@info);
361   $self->storage($storage);
362   return $self;
363 }
364
365 =head2 connect
366
367 =head3 Arguments: (@info)
368
369 Conveneience method, equivalent to $schema->clone->connection(@info)
370
371 =cut
372
373 sub connect { shift->clone->connection(@_) }
374
375 =head2 txn_begin
376
377 Begins a transaction (does nothing if AutoCommit is off).
378
379 =cut
380
381 sub txn_begin { shift->storage->txn_begin }
382
383 =head2 txn_commit
384
385 Commits the current transaction.
386
387 =cut
388
389 sub txn_commit { shift->storage->txn_commit }
390
391 =head2 txn_rollback
392
393 Rolls back the current transaction.
394
395 =cut
396
397 sub txn_rollback { shift->storage->txn_rollback }
398
399 =head2 txn_do
400
401 =head3 Arguments: <$coderef>, [@coderef_args]
402
403 Executes C<$coderef> with (optional) arguments C<@coderef_args>
404 transactionally, returning its result (if any). If an exception is
405 caught, a rollback is issued and the exception is rethrown. If the
406 rollback fails, (i.e. throws an exception) an exception is thrown that
407 includes a "Rollback failed" message.
408
409 For example,
410
411   my $author_rs = $schema->resultset('Author')->find(1);
412
413   my $coderef = sub {
414     my ($author, @titles) = @_;
415
416     # If any one of these fails, the entire transaction fails
417     $author->create_related('books', {
418       title => $_
419     }) foreach (@titles);
420
421     return $author->books;
422   };
423
424   my $rs;
425   eval {
426     $rs = $schema->txn_do($coderef, $author_rs, qw/Night Day It/);
427   };
428
429   if ($@) {
430     my $error = $@;
431     if ($error =~ /Rollback failed/) {
432       die "something terrible has happened!";
433     } else {
434       deal_with_failed_transaction();
435     }
436   }
437
438 Nested transactions work as expected (i.e. only the outermost
439 transaction will issue a txn_commit on the Schema's storage), and
440 txn_do() can be called in void, scalar and list context and it will
441 behave as expected.
442
443 =cut
444
445 sub txn_do {
446   my ($self, $coderef, @args) = @_;
447
448   ref $self or $self->throw_exception
449     ('Cannot execute txn_do as a class method');
450   ref $coderef eq 'CODE' or $self->throw_exception
451     ('$coderef must be a CODE reference');
452
453   my (@return_values, $return_value);
454
455   $self->txn_begin; # If this throws an exception, no rollback is needed
456
457   my $wantarray = wantarray; # Need to save this since it's reset in eval{}
458
459   eval {
460     # Need to differentiate between scalar/list context to allow for
461     # returning a list in scalar context to get the size of the list
462
463     if ($wantarray) {
464       # list context
465       @return_values = $coderef->(@args);
466     } elsif (defined $wantarray) {
467       # scalar context
468       $return_value = $coderef->(@args);
469     } else {
470       # void context
471       $coderef->(@args);
472     }
473     $self->txn_commit;
474   };
475
476   if ($@) {
477     my $error = $@;
478
479     eval {
480       $self->txn_rollback;
481     };
482
483     if ($@) {
484       my $rollback_error = $@;
485       my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
486       $self->throw_exception($error)  # propagate nested rollback
487         if $rollback_error =~ /$exception_class/;
488
489       $self->throw_exception("Transaction aborted: $error. Rollback failed: ".
490                              $rollback_error);
491     } else {
492       $self->throw_exception($error); # txn failed but rollback succeeded
493     }
494   }
495
496   return $wantarray ? @return_values : $return_value;
497 }
498
499 =head2 clone
500
501 Clones the schema and its associated result_source objects and returns the
502 copy.
503
504 =cut
505
506 sub clone {
507   my ($self) = @_;
508   my $clone = bless({ (ref $self ? %$self : ()) }, ref $self || $self);
509   foreach my $moniker ($self->sources) {
510     my $source = $self->source($moniker);
511     my $new = $source->new($source);
512     $clone->register_source($moniker => $new);
513   }
514   return $clone;
515 }
516
517 =head2 populate
518
519 =head3 Arguments: ($moniker, \@data);
520
521 Populates the source registered with the given moniker with the supplied data.
522 @data should be a list of listrefs, the first containing column names, the
523 second matching values - i.e.
524
525   $schema->populate('Artist', [
526     [ qw/artistid name/ ],
527     [ 1, 'Popular Band' ],
528     [ 2, 'Indie Band' ],
529     ...
530   ]);
531
532 =cut
533
534 sub populate {
535   my ($self, $name, $data) = @_;
536   my $rs = $self->resultset($name);
537   my @names = @{shift(@$data)};
538   my @created;
539   foreach my $item (@$data) {
540     my %create;
541     @create{@names} = @$item;
542     push(@created, $rs->create(\%create));
543   }
544   return @created;
545 }
546
547 =head2 throw_exception
548
549 Defaults to using Carp::Clan to report errors from user perspective.
550
551 =cut
552
553 sub throw_exception {
554   my ($self) = shift;
555   croak @_;
556 }
557
558 =head2 deploy (EXPERIMENTAL)
559
560 Attempts to deploy the schema to the current storage using SQL::Translator.
561
562 Note that this feature is currently EXPERIMENTAL and may not work correctly
563 across all databases, or fully handle complex relationships.
564
565 =cut
566
567 sub deploy {
568   my ($self, $sqltargs) = @_;
569   $self->throw_exception("Can't deploy without storage") unless $self->storage;
570   $self->storage->deploy($self, undef, $sqltargs);
571 }
572
573 1;
574
575 =head1 AUTHORS
576
577 Matt S. Trout <mst@shadowcatsystems.co.uk>
578
579 =head1 LICENSE
580
581 You may distribute this code under the same terms as Perl itself.
582
583 =cut
584