1 package DBIx::Class::Schema;
6 use Carp::Clan qw/^DBIx::Class/;
7 use Scalar::Util qw/weaken/;
9 use base qw/DBIx::Class/;
11 __PACKAGE__->mk_classdata('class_mappings' => {});
12 __PACKAGE__->mk_classdata('source_registrations' => {});
13 __PACKAGE__->mk_classdata('storage_type' => '::DBI');
14 __PACKAGE__->mk_classdata('storage');
18 DBIx::Class::Schema - composable schemas
22 package Library::Schema;
23 use base qw/DBIx::Class::Schema/;
25 # load Library::Schema::CD, Library::Schema::Book, Library::Schema::DVD
26 __PACKAGE__->load_classes(qw/CD Book DVD/);
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');
33 # Elsewhere in your code:
34 my $schema1 = Library::Schema->connect(
41 my $schema2 = Library::Schema->connect($coderef_returning_dbh);
43 # fetch objects using Library::Schema::DVD
44 my $resultset = $schema1->resultset('DVD')->search( ... );
45 my @dvd_objects = $schema2->resultset('DVD')->search( ... );
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
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.
63 =item Arguments: $moniker, $component_class
67 Registers a class which isa DBIx::Class::ResultSourceProxy. Equivalent to
70 $schema->register_source($moniker, $component_class->result_source_instance);
75 my ($self, $moniker, $to_register) = @_;
76 $self->register_source($moniker => $to_register->result_source_instance);
79 =head2 register_source
83 =item Arguments: $moniker, $result_source
87 Registers the L<DBIx::Class::ResultSource> in the schema with the given
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);
110 =item Arguments: $moniker
112 =item Return Value: $classname
116 Retrieves the result class name for the given moniker. For example:
118 my $class = $schema->class('CD');
123 my ($self, $moniker) = @_;
124 return $self->source($moniker)->result_class;
131 =item Arguments: $moniker
133 =item Return Value: $result_source
137 my $source = $schema->source('Book');
139 Returns the L<DBIx::Class::ResultSource> object for the registered moniker.
144 my ($self, $moniker) = @_;
145 my $sreg = $self->source_registrations;
146 return $sreg->{$moniker} if exists $sreg->{$moniker};
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};
159 =item Return Value: @source_monikers
163 Returns the source monikers of all source registrations on this schema.
166 my @source_monikers = $schema->sources;
170 sub sources { return keys %{shift->source_registrations}; }
176 =item Arguments: $moniker
178 =item Return Value: $result_set
182 my $rs = $schema->resultset('DVD');
184 Returns the L<DBIx::Class::ResultSet> object for the registered moniker.
189 my ($self, $moniker) = @_;
190 return $self->source($moniker)->resultset;
197 =item Arguments: @classes?, { $namespace => [ @classes ] }+
201 With no arguments, this method uses L<Module::Find> to find all classes under
202 the schema's namespace. Otherwise, this method loads the classes you specify
203 (using L<use>), and registers them (using L</"register_class">).
205 It is possible to comment out classes with a leading C<#>, but note that perl
206 will think it's a mistake (trying to use a comment in a qw list), so you'll
207 need to add C<no warnings 'qw';> before your load_classes call.
211 My::Schema->load_classes(); # loads My::Schema::CD, My::Schema::Artist,
212 # etc. (anything under the My::Schema namespace)
214 # loads My::Schema::CD, My::Schema::Artist, Other::Namespace::Producer but
215 # not Other::Namespace::LinerNotes nor My::Schema::Track
216 My::Schema->load_classes(qw/ CD Artist #Track /, {
217 Other::Namespace => [qw/ Producer #LinerNotes /],
223 my ($class, @params) = @_;
228 foreach my $param (@params) {
229 if (ref $param eq 'ARRAY') {
230 # filter out commented entries
231 my @modules = grep { $_ !~ /^#/ } @$param;
233 push (@{$comps_for{$class}}, @modules);
235 elsif (ref $param eq 'HASH') {
236 # more than one namespace possible
237 for my $comp ( keys %$param ) {
238 # filter out commented entries
239 my @modules = grep { $_ !~ /^#/ } @{$param->{$comp}};
241 push (@{$comps_for{$comp}}, @modules);
245 # filter out commented entries
246 push (@{$comps_for{$class}}, $param) if $param !~ /^#/;
250 eval "require Module::Find;";
251 $class->throw_exception(
252 "No arguments to load_classes and couldn't load Module::Find ($@)"
254 my @comp = map { substr $_, length "${class}::" }
255 Module::Find::findallmod($class);
256 $comps_for{$class} = \@comp;
261 no warnings qw/redefine/;
262 local *Class::C3::reinitialize = sub { };
263 foreach my $prefix (keys %comps_for) {
264 foreach my $comp (@{$comps_for{$prefix}||[]}) {
265 my $comp_class = "${prefix}::${comp}";
266 eval "use $comp_class"; # If it fails, assume the user fixed it
268 $comp_class =~ s/::/\//g;
269 die $@ unless $@ =~ /Can't locate.+$comp_class\.pm\sin\s\@INC/;
272 push(@to_register, [ $comp, $comp_class ]);
276 Class::C3->reinitialize;
278 foreach my $to (@to_register) {
279 $class->register_class(@$to);
280 # if $class->can('result_source_instance');
284 =head2 compose_connection
288 =item Arguments: $target_namespace, @db_info
290 =item Return Value: $new_schema
294 Calls L<DBIx::Class::Schema/"compose_namespace"> to the target namespace,
295 calls L<DBIx::Class::Schema/connection> with @db_info on the new schema,
296 then injects the L<DBix::Class::ResultSetProxy> component and a
297 resultset_instance classdata entry on all the new classes, in order to support
298 $target_namespaces::$class->search(...) method calls.
300 This is primarily useful when you have a specific need for class method access
301 to a connection. In normal usage it is preferred to call
302 L<DBIx::Class::Schema/connect> and use the resulting schema object to operate
303 on L<DBIx::Class::ResultSet> objects with L<DBIx::Class::Schema/resultset> for
308 sub compose_connection {
309 my ($self, $target, @info) = @_;
310 my $base = 'DBIx::Class::ResultSetProxy';
311 eval "require ${base};";
312 $self->throw_exception
313 ("No arguments to load_classes and couldn't load ${base} ($@)")
316 if ($self eq $target) {
317 # Pathological case, largely caused by the docs on early C::M::DBIC::Plain
318 foreach my $moniker ($self->sources) {
319 my $source = $self->source($moniker);
320 my $class = $source->result_class;
321 $self->inject_base($class, $base);
322 $class->mk_classdata(resultset_instance => $source->resultset);
323 $class->mk_classdata(class_resolver => $self);
325 $self->connection(@info);
329 my $schema = $self->compose_namespace($target, $base);
332 *{"${target}::schema"} = sub { $schema };
335 $schema->connection(@info);
336 foreach my $moniker ($schema->sources) {
337 my $source = $schema->source($moniker);
338 my $class = $source->result_class;
339 #warn "$moniker $class $source ".$source->storage;
340 $class->mk_classdata(result_source_instance => $source);
341 $class->mk_classdata(resultset_instance => $source->resultset);
342 $class->mk_classdata(class_resolver => $schema);
347 =head2 compose_namespace
351 =item Arguments: $target_namespace, $additional_base_class?
353 =item Return Value: $new_schema
357 For each L<DBIx::Class::ResultSource> in the schema, this method creates a
358 class in the target namespace (e.g. $target_namespace::CD,
359 $target_namespace::Artist) that inherits from the corresponding classes
360 attached to the current schema.
362 It also attaches a corresponding L<DBIx::Class::ResultSource> object to the
363 new $schema object. If C<$additional_base_class> is given, the new composed
364 classes will inherit from first the corresponding classe from the current
365 schema then the base class.
367 For example, for a schema with My::Schema::CD and My::Schema::Artist classes,
369 $schema->compose_namespace('My::DB', 'Base::Class');
370 print join (', ', @My::DB::CD::ISA) . "\n";
371 print join (', ', @My::DB::Artist::ISA) ."\n";
373 will produce the output
375 My::Schema::CD, Base::Class
376 My::Schema::Artist, Base::Class
380 sub compose_namespace {
381 my ($self, $target, $base) = @_;
382 my %reg = %{ $self->source_registrations };
385 my $schema = $self->clone;
387 no warnings qw/redefine/;
388 local *Class::C3::reinitialize = sub { };
389 foreach my $moniker ($schema->sources) {
390 my $source = $schema->source($moniker);
391 my $target_class = "${target}::${moniker}";
393 $target_class => $source->result_class, ($base ? $base : ())
395 $source->result_class($target_class);
398 Class::C3->reinitialize();
401 foreach my $meth (qw/class source resultset/) {
402 *{"${target}::${meth}"} =
403 sub { shift->schema->$meth(@_) };
409 =head2 setup_connection_class
413 =item Arguments: $target, @info
417 Sets up a database connection class to inject between the schema and the
418 subclasses that the schema creates.
422 sub setup_connection_class {
423 my ($class, $target, @info) = @_;
424 $class->inject_base($target => 'DBIx::Class::DB');
425 #$target->load_components('DB');
426 $target->connection(@info);
433 =item Arguments: @args
435 =item Return Value: $new_schema
439 Instantiates a new Storage object of type
440 L<DBIx::Class::Schema/"storage_type"> and passes the arguments to
441 $storage->connect_info. Sets the connection in-place on the schema. See
442 L<DBIx::Class::Storage::DBI/"connect_info"> for more information.
447 my ($self, @info) = @_;
448 return $self if !@info && $self->storage;
449 my $storage_class = $self->storage_type;
450 $storage_class = 'DBIx::Class::Storage'.$storage_class
451 if $storage_class =~ m/^::/;
452 eval "require ${storage_class};";
453 $self->throw_exception(
454 "No arguments to load_classes and couldn't load ${storage_class} ($@)"
456 my $storage = $storage_class->new;
457 $storage->connect_info(\@info);
458 $self->storage($storage);
466 =item Arguments: @info
468 =item Return Value: $new_schema
472 This is a convenience method. It is equivalent to calling
473 $schema->clone->connection(@info). See L</connection> and L</clone> for more
478 sub connect { shift->clone->connection(@_) }
482 Begins a transaction (does nothing if AutoCommit is off). Equivalent to
483 calling $schema->storage->txn_begin. See
484 L<DBIx::Class::Storage::DBI/"txn_begin"> for more information.
488 sub txn_begin { shift->storage->txn_begin }
492 Commits the current transaction. Equivalent to calling
493 $schema->storage->txn_commit. See L<DBIx::Class::Storage::DBI/"txn_commit">
494 for more information.
498 sub txn_commit { shift->storage->txn_commit }
502 Rolls back the current transaction. Equivalent to calling
503 $schema->storage->txn_rollback. See
504 L<DBIx::Class::Storage::DBI/"txn_rollback"> for more information.
508 sub txn_rollback { shift->storage->txn_rollback }
514 =item Arguments: C<$coderef>, @coderef_args?
516 =item Return Value: The return value of $coderef
520 Executes C<$coderef> with (optional) arguments C<@coderef_args> atomically,
521 returning its result (if any). If an exception is caught, a rollback is issued
522 and the exception is rethrown. If the rollback fails, (i.e. throws an
523 exception) an exception is thrown that includes a "Rollback failed" message.
527 my $author_rs = $schema->resultset('Author')->find(1);
530 my ($author, @titles) = @_;
532 # If any one of these fails, the entire transaction fails
533 $author->create_related('books', {
535 }) foreach (@titles);
537 return $author->books;
542 $rs = $schema->txn_do($coderef, $author_rs, qw/Night Day It/);
547 if ($error =~ /Rollback failed/) {
548 die "something terrible has happened!";
550 deal_with_failed_transaction();
554 In a nested transaction (calling txn_do() from within a txn_do() coderef) only
555 the outermost transaction will issue a L<DBIx::Class::Schema/"txn_commit"> on
556 the Schema's storage, and txn_do() can be called in void, scalar and list
557 context and it will behave as expected.
562 my ($self, $coderef, @args) = @_;
564 ref $self or $self->throw_exception
565 ('Cannot execute txn_do as a class method');
566 ref $coderef eq 'CODE' or $self->throw_exception
567 ('$coderef must be a CODE reference');
569 my (@return_values, $return_value);
571 $self->txn_begin; # If this throws an exception, no rollback is needed
573 my $wantarray = wantarray; # Need to save this since the context
574 # inside the eval{} block is independent
575 # of the context that called txn_do()
578 # Need to differentiate between scalar/list context to allow for
579 # returning a list in scalar context to get the size of the list
582 @return_values = $coderef->(@args);
583 } elsif (defined $wantarray) {
585 $return_value = $coderef->(@args);
601 my $rollback_error = $@;
602 my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
603 $self->throw_exception($error) # propagate nested rollback
604 if $rollback_error =~ /$exception_class/;
606 $self->throw_exception(
607 "Transaction aborted: $error. Rollback failed: ${rollback_error}"
610 $self->throw_exception($error); # txn failed but rollback succeeded
614 return $wantarray ? @return_values : $return_value;
621 =item Return Value: $new_schema
625 Clones the schema and its associated result_source objects and returns the
632 my $clone = bless({ (ref $self ? %$self : ()) }, ref $self || $self);
633 foreach my $moniker ($self->sources) {
634 my $source = $self->source($moniker);
635 my $new = $source->new($source);
636 $clone->register_source($moniker => $new);
645 =item Arguments: $moniker, \@data;
649 Populates the source registered with the given moniker with the supplied data.
650 @data should be a list of listrefs -- the first containing column names, the
651 second matching values.
655 $schema->populate('Artist', [
656 [ qw/artistid name/ ],
657 [ 1, 'Popular Band' ],
665 my ($self, $name, $data) = @_;
666 my $rs = $self->resultset($name);
667 my @names = @{shift(@$data)};
669 foreach my $item (@$data) {
671 @create{@names} = @$item;
672 push(@created, $rs->create(\%create));
677 =head2 throw_exception
681 =item Arguments: $message
685 Throws an exception. Defaults to using L<Carp::Clan> to report errors from
690 sub throw_exception {
695 =head2 deploy (EXPERIMENTAL)
699 =item Arguments: $sqlt_args
703 Attempts to deploy the schema to the current storage using L<SQL::Translator>.
705 Note that this feature is currently EXPERIMENTAL and may not work correctly
706 across all databases, or fully handle complex relationships.
711 my ($self, $sqltargs) = @_;
712 $self->throw_exception("Can't deploy without storage") unless $self->storage;
713 $self->storage->deploy($self, undef, $sqltargs);
720 Matt S. Trout <mst@shadowcatsystems.co.uk>
724 You may distribute this code under the same terms as Perl itself.