test fixups, Schema optimisation tweaks
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Schema.pm
CommitLineData
a02675cd 1package DBIx::Class::Schema;
2
3use strict;
4use warnings;
aa562407 5
701da8c4 6use Carp::Clan qw/^DBIx::Class/;
a02675cd 7
41a6f8c0 8use base qw/DBIx::Class/;
a02675cd 9
0dc79249 10__PACKAGE__->mk_classdata('class_mappings' => {});
11__PACKAGE__->mk_classdata('source_registrations' => {});
1e10a11d 12__PACKAGE__->mk_classdata('storage_type' => '::DBI');
d7156e50 13__PACKAGE__->mk_classdata('storage');
a02675cd 14
c2da098a 15=head1 NAME
16
17DBIx::Class::Schema - composable schemas
18
19=head1 SYNOPSIS
20
c2da098a 21 package My::Schema;
c2da098a 22 use base qw/DBIx::Class::Schema/;
a3d93194 23
24 # load My::Schema::Foo, My::Schema::Bar, My::Schema::Baz
c2da098a 25 __PACKAGE__->load_classes(qw/Foo Bar Baz/);
26
c2da098a 27 package My::Schema::Foo;
03312470 28 use base qw/DBIx::Class/;
54540863 29 __PACKAGE__->load_components(qw/PK::Auto::Pg Core/); # for example
c2da098a 30 __PACKAGE__->table('foo');
c2da098a 31
5d9076f2 32 # Elsewhere in your code:
a3d93194 33 my $schema1 = My::Schema->connect(
34 $dsn,
35 $user,
36 $password,
37 $attrs
38 );
90ec6cad 39
40 my $schema2 = My::Schema->connect($coderef_returning_dbh);
c2da098a 41
a3d93194 42 # fetch objects using My::Schema::Foo
43 my $resultset = $schema1->resultset('Foo')->search( ... );
44 my @objects = $schema2->resultset('Foo')->search( ... );
c2da098a 45
46=head1 DESCRIPTION
47
a3d93194 48Creates database classes based on a schema. This is the recommended way to
49use L<DBIx::Class> and allows you to use more than one concurrent connection
50with your classes.
429bd4f1 51
03312470 52NB: If you're used to L<Class::DBI> it's worth reading the L</SYNOPSIS>
53carefully as DBIx::Class does things a little differently. Note in
54particular which module inherits off which.
55
c2da098a 56=head1 METHODS
57
87c4e602 58=head2 register_class
59
60=head3 Arguments: <moniker> <component_class>
076652e8 61
80c90f5d 62Registers a class which isa ResultSourceProxy; equivalent to calling
66d9ef6b 63
181a28f4 64 $schema->register_source($moniker, $component_class->result_source_instance);
076652e8 65
c2da098a 66=cut
67
a02675cd 68sub register_class {
0dc79249 69 my ($self, $moniker, $to_register) = @_;
70 $self->register_source($moniker => $to_register->result_source_instance);
74b92d9a 71}
72
87c4e602 73=head2 register_source
74
75=head3 Arguments: <moniker> <result source>
076652e8 76
0dc79249 77Registers the result source in the schema with the given moniker
076652e8 78
79=cut
80
0dc79249 81sub 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}
a02675cd 93
bfb2bd4f 94=head2 class
95
96 my $class = $schema->class('Foo');
97
0dc79249 98Retrieves the result class name for a given result source
bfb2bd4f 99
100=cut
101
102sub class {
0dc79249 103 my ($self, $moniker) = @_;
104 return $self->source($moniker)->result_class;
bfb2bd4f 105}
106
ea20d0fd 107=head2 source
108
109 my $source = $schema->source('Foo');
110
111Returns the result source object for the registered name
112
113=cut
114
115sub source {
0dc79249 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};
701da8c4 122 $self->throw_exception("Can't find source for ${moniker}")
0dc79249 123 unless $mapped && exists $sreg->{$mapped};
124 return $sreg->{$mapped};
ea20d0fd 125}
126
0dc79249 127=head2 sources
128
129 my @source_monikers = $schema->sources;
130
131Returns the source monikers of all source registrations on this schema
132
133=cut
134
135sub sources { return keys %{shift->source_registrations}; }
136
ea20d0fd 137=head2 resultset
138
139 my $rs = $schema->resultset('Foo');
140
0dc79249 141Returns the resultset for the registered moniker
ea20d0fd 142
143=cut
144
145sub resultset {
0dc79249 146 my ($self, $moniker) = @_;
147 return $self->source($moniker)->resultset;
ea20d0fd 148}
149
87c4e602 150=head2 load_classes
151
152=head3 Arguments: [<classes>, (<class>, <class>), {<namespace> => [<classes>]}]
076652e8 153
429bd4f1 154Uses L<Module::Find> to find all classes under the database class' namespace,
155or uses the classes you select. Then it loads the component (using L<use>),
156and registers them (using B<register_class>);
076652e8 157
5ce32fc1 158It is possible to comment out classes with a leading '#', but note that perl
159will think it's a mistake (trying to use a comment in a qw list) so you'll
160need to add "no warnings 'qw';" before your load_classes call.
161
076652e8 162=cut
163
a02675cd 164sub load_classes {
5ce32fc1 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 {
41a6f8c0 192 eval "require Module::Find;";
701da8c4 193 $class->throw_exception("No arguments to load_classes and couldn't load".
41a6f8c0 194 " Module::Find ($@)") if $@;
5ce32fc1 195 my @comp = map { substr $_, length "${class}::" } Module::Find::findallmod($class);
196 $comps_for{$class} = \@comp;
41a6f8c0 197 }
5ce32fc1 198
e6efde04 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 ]);
bfb2bd4f 211 }
5ce32fc1 212 }
a02675cd 213 }
e6efde04 214 Class::C3->reinitialize;
215
216 foreach my $to (@to_register) {
217 $class->register_class(@$to);
218 # if $class->can('result_source_instance');
219 }
a02675cd 220}
221
87c4e602 222=head2 compose_connection
223
224=head3 Arguments: <target> <@db_info>
429bd4f1 225
226This is the most important method in this class. it takes a target namespace,
227as well as dbh connection info, and creates a L<DBIx::Class::DB> class as
228well as subclasses for each of your database classes in this namespace, using
229this connection.
076652e8 230
54540863 231It will also setup a ->class method on the target class, which lets you
8c130052 232resolve database classes based on the schema component name, for example
233
54540863 234 MyApp::DB->class('Foo') # returns MyApp::DB::Foo,
8c130052 235 # which ISA MyApp::Schema::Foo
236
237This is the recommended API for accessing Schema generated classes, and
238using it might give you instant advantages with future versions of DBIC.
239
54540863 240WARNING: Loading components into Schema classes after compose_connection
241may not cause them to be seen by the classes in your target namespace due
242to the dispatch table approach used by Class::C3. If you do this you may find
243you need to call Class::C3->reinitialize() afterwards to get the behaviour
244you expect.
245
076652e8 246=cut
247
a02675cd 248sub compose_connection {
ea20d0fd 249 my ($self, $target, @info) = @_;
80c90f5d 250 my $base = 'DBIx::Class::ResultSetProxy';
8ef144ff 251 eval "require ${base};";
252 $self->throw_exception("No arguments to load_classes and couldn't load".
253 " ${base} ($@)") if $@;
be381829 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 }
50041f3c 264 $self->connection(@info);
be381829 265 return $self;
266 }
267
66d9ef6b 268 my $schema = $self->compose_namespace($target, $base);
ecceadff 269 {
270 no strict 'refs';
271 *{"${target}::schema"} = sub { $schema };
272 }
273
66d9ef6b 274 $schema->connection(@info);
0dc79249 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;
8c49f629 279 $class->mk_classdata(result_source_instance => $source);
ea20d0fd 280 $class->mk_classdata(resultset_instance => $source->resultset);
66d9ef6b 281 $class->mk_classdata(class_resolver => $schema);
bfb2bd4f 282 }
283 return $schema;
e678398e 284}
285
286sub compose_namespace {
66d9ef6b 287 my ($self, $target, $base) = @_;
288 my %reg = %{ $self->source_registrations };
11b78bd6 289 my %target;
290 my %map;
66d9ef6b 291 my $schema = $self->clone;
e9100ff7 292 {
293 no warnings qw/redefine/;
294 local *Class::C3::reinitialize = sub { };
295 foreach my $moniker ($schema->sources) {
296 my $source = $schema->source($moniker);
297 my $target_class = "${target}::${moniker}";
298 $self->inject_base(
299 $target_class => $source->result_class, ($base ? $base : ())
300 );
301 $source->result_class($target_class);
302 }
b7951443 303 }
e9100ff7 304 Class::C3->reinitialize();
11b78bd6 305 {
306 no strict 'refs';
1edaf6fe 307 foreach my $meth (qw/class source resultset/) {
308 *{"${target}::${meth}"} =
309 sub { shift->schema->$meth(@_) };
310 }
11b78bd6 311 }
bfb2bd4f 312 return $schema;
b7951443 313}
314
87c4e602 315=head2 setup_connection_class
316
317=head3 Arguments: <$target> <@info>
076652e8 318
429bd4f1 319Sets up a database connection class to inject between the schema
320and the subclasses the schema creates.
321
076652e8 322=cut
323
b7951443 324sub setup_connection_class {
325 my ($class, $target, @info) = @_;
63e9583a 326 $class->inject_base($target => 'DBIx::Class::DB');
327 #$target->load_components('DB');
b7951443 328 $target->connection(@info);
329}
330
87c4e602 331=head2 connection
332
333=head3 Arguments: (@args)
66d9ef6b 334
335Instantiates a new Storage object of type storage_type and passes the
19feb86b 336arguments to $storage->connect_info. Sets the connection in-place on
66d9ef6b 337the schema.
338
339=cut
340
341sub connection {
342 my ($self, @info) = @_;
1e10a11d 343 my $storage_class = $self->storage_type;
344 $storage_class = 'DBIx::Class::Storage'.$storage_class
345 if $storage_class =~ m/^::/;
8ef144ff 346 eval "require ${storage_class};";
347 $self->throw_exception("No arguments to load_classes and couldn't load".
348 " ${storage_class} ($@)") if $@;
66d9ef6b 349 my $storage = $storage_class->new;
350 $storage->connect_info(\@info);
351 $self->storage($storage);
352 return $self;
353}
354
87c4e602 355=head2 connect
356
357=head3 Arguments: (@info)
66d9ef6b 358
359Conveneience method, equivalent to $schema->clone->connection(@info)
360
361=cut
362
08b515f1 363sub connect { shift->clone->connection(@_) }
364
365=head2 txn_begin
366
367Begins a transaction (does nothing if AutoCommit is off).
368
369=cut
370
371sub txn_begin { shift->storage->txn_begin }
372
373=head2 txn_commit
374
375Commits the current transaction.
376
377=cut
378
379sub txn_commit { shift->storage->txn_commit }
380
381=head2 txn_rollback
382
383Rolls back the current transaction.
384
385=cut
386
387sub txn_rollback { shift->storage->txn_rollback }
66d9ef6b 388
a62cf8d4 389=head2 txn_do
390
181a28f4 391=head3 Arguments: <$coderef>, [@coderef_args]
a62cf8d4 392
181a28f4 393Executes C<$coderef> with (optional) arguments C<@coderef_args>
394transactionally, returning its result (if any). If an exception is
395caught, a rollback is issued and the exception is rethrown. If the
396rollback fails, (i.e. throws an exception) an exception is thrown that
397includes a "Rollback failed" message.
a62cf8d4 398
399For example,
400
401 my $foo = $schema->resultset('foo')->find(1);
402
403 my $coderef = sub {
404 my ($foo, @bars) = @_;
405
406 # If any one of these fails, the entire transaction fails
407 $foo->create_related('bars', {
408 col => $_
409 }) foreach (@bars);
410
411 return $foo->bars;
412 };
413
414 my $rs;
415 eval {
416 $rs = $schema->txn_do($coderef, $foo, qw/foo bar baz/);
417 };
418
419 if ($@) {
420 my $error = $@;
421 if ($error =~ /Rollback failed/) {
422 die "something terrible has happened!";
423 } else {
424 deal_with_failed_transaction();
425 die $error;
426 }
427 }
428
181a28f4 429Nested transactions work as expected (i.e. only the outermost
a62cf8d4 430transaction will issue a txn_commit on the Schema's storage)
431
432=cut
433
434sub txn_do {
435 my ($self, $coderef, @args) = @_;
436
171dadd7 437 ref $self or $self->throw_exception
438 ('Cannot execute txn_do as a class method');
439 ref $coderef eq 'CODE' or $self->throw_exception
440 ('$coderef must be a CODE reference');
a62cf8d4 441
442 my (@return_values, $return_value);
443
444 $self->txn_begin; # If this throws an exception, no rollback is needed
445
446 my $wantarray = wantarray; # Need to save this since it's reset in eval{}
447
448 eval {
449 # Need to differentiate between scalar/list context to allow for returning
450 # a list in scalar context to get the size of the list
451 if ($wantarray) {
452 @return_values = $coderef->(@args);
453 } else {
454 $return_value = $coderef->(@args);
455 }
456 $self->txn_commit;
457 };
458
459 if ($@) {
460 my $error = $@;
461
462 eval {
463 $self->txn_rollback;
464 };
465
466 if ($@) {
467 my $rollback_error = $@;
468 my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
469 $self->throw_exception($error) # propagate nested rollback
470 if $rollback_error =~ /$exception_class/;
471
472 $self->throw_exception("Transaction aborted: $error. Rollback failed: ".
473 $rollback_error);
474 } else {
475 $self->throw_exception($error); # txn failed but rollback succeeded
476 }
477 }
478
479 return $wantarray ? @return_values : $return_value;
480}
481
66d9ef6b 482=head2 clone
483
484Clones the schema and its associated result_source objects and returns the
485copy.
486
487=cut
488
489sub clone {
490 my ($self) = @_;
491 my $clone = bless({ (ref $self ? %$self : ()) }, ref $self || $self);
492 foreach my $moniker ($self->sources) {
493 my $source = $self->source($moniker);
494 my $new = $source->new($source);
495 $clone->register_source($moniker => $new);
496 }
497 return $clone;
498}
499
87c4e602 500=head2 populate
501
502=head3 Arguments: ($moniker, \@data);
a37a4697 503
504Populates the source registered with the given moniker with the supplied data.
505@data should be a list of listrefs, the first containing column names, the
506second matching values - i.e.
507
a62cf8d4 508 $schema->populate('Foo', [
509 [ qw/foo_id foo_string/ ],
510 [ 1, 'One' ],
511 [ 2, 'Two' ],
512 ...
513 ]);
a37a4697 514
515=cut
516
517sub populate {
518 my ($self, $name, $data) = @_;
519 my $rs = $self->resultset($name);
520 my @names = @{shift(@$data)};
521 foreach my $item (@$data) {
522 my %create;
523 @create{@names} = @$item;
524 $rs->create(\%create);
525 }
526}
527
5160b401 528=head2 throw_exception
701da8c4 529
530Defaults to using Carp::Clan to report errors from user perspective.
531
532=cut
533
534sub throw_exception {
535 my ($self) = shift;
536 croak @_;
537}
538
1c339d71 539=head2 deploy
540
541Attempts to deploy the schema to the current storage
542
543=cut
544
545sub deploy {
546 my ($self) = shift;
547 $self->throw_exception("Can't deploy without storage") unless $self->storage;
548 $self->storage->deploy($self);
549}
550
a02675cd 5511;
c2da098a 552
c2da098a 553=head1 AUTHORS
554
daec44b8 555Matt S. Trout <mst@shadowcatsystems.co.uk>
c2da098a 556
557=head1 LICENSE
558
559You may distribute this code under the same terms as Perl itself.
560
561=cut
562