C3 loading speedup
[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 My::Schema;
22   use base qw/DBIx::Class::Schema/;
23   
24   # load My::Schema::Foo, My::Schema::Bar, My::Schema::Baz
25   __PACKAGE__->load_classes(qw/Foo Bar Baz/);
26
27   package My::Schema::Foo;
28   use base qw/DBIx::Class/;
29   __PACKAGE__->load_components(qw/PK::Auto::Pg Core/); # for example
30   __PACKAGE__->table('foo');
31
32   # Elsewhere in your code:
33   my $schema1 = My::Schema->connect(
34     $dsn,
35     $user,
36     $password,
37     $attrs
38   );
39   
40   my $schema2 = My::Schema->connect($coderef_returning_dbh);
41
42   # fetch objects using My::Schema::Foo
43   my $resultset = $schema1->resultset('Foo')->search( ... );
44   my @objects = $schema2->resultset('Foo')->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('Foo');
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('Foo');
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('Foo');
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           die $@ unless $@ =~ /Can't locate/;
209         }
210         push(@to_register, [ $comp, $comp_class ]);
211       }
212     }
213   }
214   Class::C3->reinitialize;
215
216   foreach my $to (@to_register) {
217     $class->register_class(@$to);
218     #  if $class->can('result_source_instance');
219   }
220 }
221
222 =head2 compose_connection
223
224 =head3 Arguments: <target> <@db_info>
225
226 This is the most important method in this class. it takes a target namespace,
227 as well as dbh connection info, and creates a L<DBIx::Class::DB> class as
228 well as subclasses for each of your database classes in this namespace, using
229 this connection.
230
231 It will also setup a ->class method on the target class, which lets you
232 resolve database classes based on the schema component name, for example
233
234   MyApp::DB->class('Foo') # returns MyApp::DB::Foo, 
235                           # which ISA MyApp::Schema::Foo
236
237 This is the recommended API for accessing Schema generated classes, and 
238 using it might give you instant advantages with future versions of DBIC.
239
240 WARNING: Loading components into Schema classes after compose_connection
241 may not cause them to be seen by the classes in your target namespace due
242 to the dispatch table approach used by Class::C3. If you do this you may find
243 you need to call Class::C3->reinitialize() afterwards to get the behaviour
244 you expect.
245
246 =cut
247
248 sub compose_connection {
249   my ($self, $target, @info) = @_;
250   my $base = 'DBIx::Class::ResultSetProxy';
251   eval "require ${base};";
252   $self->throw_exception("No arguments to load_classes and couldn't load".
253       " ${base} ($@)") if $@;
254
255   if ($self eq $target) {
256     # Pathological case, largely caused by the docs on early C::M::DBIC::Plain
257     foreach my $moniker ($self->sources) {
258       my $source = $self->source($moniker);
259       my $class = $source->result_class;
260       $self->inject_base($class, $base);
261       $class->mk_classdata(resultset_instance => $source->resultset);
262       $class->mk_classdata(class_resolver => $self);
263     }
264     $self->connection(@info);
265     return $self;
266   }
267
268   my $schema = $self->compose_namespace($target, $base);
269   {
270     no strict 'refs';
271     *{"${target}::schema"} = sub { $schema };
272   }
273
274   $schema->connection(@info);
275   foreach my $moniker ($schema->sources) {
276     my $source = $schema->source($moniker);
277     my $class = $source->result_class;
278     #warn "$moniker $class $source ".$source->storage;
279     $class->mk_classdata(result_source_instance => $source);
280     $class->mk_classdata(resultset_instance => $source->resultset);
281     $class->mk_classdata(class_resolver => $schema);
282   }
283   return $schema;
284 }
285
286 sub compose_namespace {
287   my ($self, $target, $base) = @_;
288   my %reg = %{ $self->source_registrations };
289   my %target;
290   my %map;
291   my $schema = $self->clone;
292   foreach my $moniker ($schema->sources) {
293     my $source = $schema->source($moniker);
294     my $target_class = "${target}::${moniker}";
295     $self->inject_base(
296       $target_class => $source->result_class, ($base ? $base : ())
297     );
298     $source->result_class($target_class);
299   }
300   {
301     no strict 'refs';
302     foreach my $meth (qw/class source resultset/) {
303       *{"${target}::${meth}"} =
304         sub { shift->schema->$meth(@_) };
305     }
306   }
307   return $schema;
308 }
309
310 =head2 setup_connection_class
311
312 =head3 Arguments: <$target> <@info>
313
314 Sets up a database connection class to inject between the schema
315 and the subclasses the schema creates.
316
317 =cut
318
319 sub setup_connection_class {
320   my ($class, $target, @info) = @_;
321   $class->inject_base($target => 'DBIx::Class::DB');
322   #$target->load_components('DB');
323   $target->connection(@info);
324 }
325
326 =head2 connection
327
328 =head3 Arguments: (@args)
329
330 Instantiates a new Storage object of type storage_type and passes the
331 arguments to $storage->connect_info. Sets the connection in-place on
332 the schema.
333
334 =cut
335
336 sub connection {
337   my ($self, @info) = @_;
338   my $storage_class = $self->storage_type;
339   $storage_class = 'DBIx::Class::Storage'.$storage_class
340     if $storage_class =~ m/^::/;
341   eval "require ${storage_class};";
342   $self->throw_exception("No arguments to load_classes and couldn't load".
343       " ${storage_class} ($@)") if $@;
344   my $storage = $storage_class->new;
345   $storage->connect_info(\@info);
346   $self->storage($storage);
347   return $self;
348 }
349
350 =head2 connect
351
352 =head3 Arguments: (@info)
353
354 Conveneience method, equivalent to $schema->clone->connection(@info)
355
356 =cut
357
358 sub connect { shift->clone->connection(@_) }
359
360 =head2 txn_begin
361
362 Begins a transaction (does nothing if AutoCommit is off).
363
364 =cut
365
366 sub txn_begin { shift->storage->txn_begin }
367
368 =head2 txn_commit
369
370 Commits the current transaction.
371
372 =cut
373
374 sub txn_commit { shift->storage->txn_commit }
375
376 =head2 txn_rollback
377
378 Rolls back the current transaction.
379
380 =cut
381
382 sub txn_rollback { shift->storage->txn_rollback }
383
384 =head2 txn_do
385
386 =head3 Arguments: <$coderef>, [@coderef_args]
387
388 Executes C<$coderef> with (optional) arguments C<@coderef_args>
389 transactionally, returning its result (if any). If an exception is
390 caught, a rollback is issued and the exception is rethrown. If the
391 rollback fails, (i.e. throws an exception) an exception is thrown that
392 includes a "Rollback failed" message.
393
394 For example,
395
396   my $foo = $schema->resultset('foo')->find(1);
397
398   my $coderef = sub {
399     my ($foo, @bars) = @_;
400
401     # If any one of these fails, the entire transaction fails
402     $foo->create_related('bars', {
403       col => $_
404     }) foreach (@bars);
405
406     return $foo->bars;
407   };
408
409   my $rs;
410   eval {
411     $rs = $schema->txn_do($coderef, $foo, qw/foo bar baz/);
412   };
413
414   if ($@) {
415     my $error = $@;
416     if ($error =~ /Rollback failed/) {
417       die "something terrible has happened!";
418     } else {
419       deal_with_failed_transaction();
420       die $error;
421     }
422   }
423
424 Nested transactions work as expected (i.e. only the outermost
425 transaction will issue a txn_commit on the Schema's storage)
426
427 =cut
428
429 sub txn_do {
430   my ($self, $coderef, @args) = @_;
431
432   ref $self or $self->throw_exception
433     ('Cannot execute txn_do as a class method');
434   ref $coderef eq 'CODE' or $self->throw_exception
435     ('$coderef must be a CODE reference');
436
437   my (@return_values, $return_value);
438
439   $self->txn_begin; # If this throws an exception, no rollback is needed
440
441   my $wantarray = wantarray; # Need to save this since it's reset in eval{}
442
443   eval {
444     # Need to differentiate between scalar/list context to allow for returning
445     # a list in scalar context to get the size of the list
446     if ($wantarray) {
447       @return_values = $coderef->(@args);
448     } else {
449       $return_value = $coderef->(@args);
450     }
451     $self->txn_commit;
452   };
453
454   if ($@) {
455     my $error = $@;
456
457     eval {
458       $self->txn_rollback;
459     };
460
461     if ($@) {
462       my $rollback_error = $@;
463       my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
464       $self->throw_exception($error)  # propagate nested rollback
465         if $rollback_error =~ /$exception_class/;
466
467       $self->throw_exception("Transaction aborted: $error. Rollback failed: ".
468                              $rollback_error);
469     } else {
470       $self->throw_exception($error); # txn failed but rollback succeeded
471     }
472   }
473
474   return $wantarray ? @return_values : $return_value;
475 }
476
477 =head2 clone
478
479 Clones the schema and its associated result_source objects and returns the
480 copy.
481
482 =cut
483
484 sub clone {
485   my ($self) = @_;
486   my $clone = bless({ (ref $self ? %$self : ()) }, ref $self || $self);
487   foreach my $moniker ($self->sources) {
488     my $source = $self->source($moniker);
489     my $new = $source->new($source);
490     $clone->register_source($moniker => $new);
491   }
492   return $clone;
493 }
494
495 =head2 populate
496
497 =head3 Arguments: ($moniker, \@data);
498
499 Populates the source registered with the given moniker with the supplied data.
500 @data should be a list of listrefs, the first containing column names, the
501 second matching values - i.e.
502
503   $schema->populate('Foo', [
504     [ qw/foo_id foo_string/ ],
505     [ 1, 'One' ],
506     [ 2, 'Two' ],
507     ...
508   ]);
509
510 =cut
511
512 sub populate {
513   my ($self, $name, $data) = @_;
514   my $rs = $self->resultset($name);
515   my @names = @{shift(@$data)};
516   foreach my $item (@$data) {
517     my %create;
518     @create{@names} = @$item;
519     $rs->create(\%create);
520   }
521 }
522
523 =head2 throw_exception
524
525 Defaults to using Carp::Clan to report errors from user perspective.
526
527 =cut
528
529 sub throw_exception {
530   my ($self) = shift;
531   croak @_;
532 }
533
534 =head2 deploy
535
536 Attempts to deploy the schema to the current storage
537
538 =cut
539
540 sub deploy {
541   my ($self) = shift;
542   $self->throw_exception("Can't deploy without storage") unless $self->storage;
543   $self->storage->deploy($self);
544 }
545
546 1;
547
548 =head1 AUTHORS
549
550 Matt S. Trout <mst@shadowcatsystems.co.uk>
551
552 =head1 LICENSE
553
554 You may distribute this code under the same terms as Perl itself.
555
556 =cut
557