1 package DBIx::Class::Schema;
6 use Carp::Clan qw/^DBIx::Class/;
8 use base qw/DBIx::Class/;
10 __PACKAGE__->mk_classdata('class_mappings' => {});
11 __PACKAGE__->mk_classdata('source_registrations' => {});
12 __PACKAGE__->mk_classdata('storage_type' => '::DBI');
13 __PACKAGE__->mk_classdata('storage');
17 DBIx::Class::Schema - composable schemas
21 package Library::Schema;
22 use base qw/DBIx::Class::Schema/;
24 # load Library::Schema::CD, Library::Schema::Book, Library::Schema::DVD
25 __PACKAGE__->load_classes(qw/CD Book DVD/);
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');
32 # Elsewhere in your code:
33 my $schema1 = Library::Schema->connect(
40 my $schema2 = Library::Schema->connect($coderef_returning_dbh);
42 # fetch objects using Library::Schema::DVD
43 my $resultset = $schema1->resultset('DVD')->search( ... );
44 my @dvd_objects = $schema2->resultset('DVD')->search( ... );
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
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.
62 =item Arguments: $moniker, $component_class
66 Registers a class which isa L<DBIx::Class::ResultSourceProxy>. Equivalent to
69 $schema->register_source($moniker, $component_class->result_source_instance);
74 my ($self, $moniker, $to_register) = @_;
75 $self->register_source($moniker => $to_register->result_source_instance);
78 =head2 register_source
82 =item Arguments: $moniker, $result_source
86 Registers the L<DBIx::Class::ResultSource> in the schema with the given
92 my ($self, $moniker, $source) = @_;
93 my %reg = %{$self->source_registrations};
94 $reg{$moniker} = $source;
95 $self->source_registrations(\%reg);
96 $source->schema($self);
97 if ($source->result_class) {
98 my %map = %{$self->class_mappings};
99 $map{$source->result_class} = $moniker;
100 $self->class_mappings(\%map);
108 =item Arguments: $moniker
110 =item Return Value: $classname
114 Retrieves the result class name for the given moniker. For example:
116 my $class = $schema->class('CD');
121 my ($self, $moniker) = @_;
122 return $self->source($moniker)->result_class;
129 =item Arguments: $moniker
131 =item Return Value: $result_source
135 my $source = $schema->source('Book');
137 Returns the L<DBIx::Class::ResultSource> object for the registered moniker.
142 my ($self, $moniker) = @_;
143 my $sreg = $self->source_registrations;
144 return $sreg->{$moniker} if exists $sreg->{$moniker};
146 # if we got here, they probably passed a full class name
147 my $mapped = $self->class_mappings->{$moniker};
148 $self->throw_exception("Can't find source for ${moniker}")
149 unless $mapped && exists $sreg->{$mapped};
150 return $sreg->{$mapped};
157 =item Return Value: @source_monikers
161 Returns the source monikers of all source registrations on this schema.
164 my @source_monikers = $schema->sources;
168 sub sources { return keys %{shift->source_registrations}; }
174 =item Arguments: $moniker
176 =item Return Value: $result_set
180 my $rs = $schema->resultset('DVD');
182 Returns the L<DBIx::Class::ResultSet> object for the registered moniker.
187 my ($self, $moniker) = @_;
188 return $self->source($moniker)->resultset;
195 =item Arguments: @classes?, { $namespace => [ @classes ] }+
199 With no arguments, this method uses L<Module::Find> to find all classes under
200 the schema's namespace. Otherwise, this method loads the classes you specify
201 (using L<use>), and registers them (using L</"register_class">).
203 It is possible to comment out classes with a leading C<#>, but note that perl
204 will think it's a mistake (trying to use a comment in a qw list), so you'll
205 need to add C<no warnings 'qw';> before your load_classes call.
209 My::Schema->load_classes(); # loads My::Schema::CD, My::Schema::Artist,
210 # etc. (anything under the My::Schema namespace)
212 # loads My::Schema::CD, My::Schema::Artist, Other::Namespace::Producer but
213 # not Other::Namespace::LinerNotes nor My::Schema::Track
214 My::Schema->load_classes(qw/ CD Artist #Track /, {
215 Other::Namespace => [qw/ Producer #LinerNotes /],
221 my ($class, @params) = @_;
226 foreach my $param (@params) {
227 if (ref $param eq 'ARRAY') {
228 # filter out commented entries
229 my @modules = grep { $_ !~ /^#/ } @$param;
231 push (@{$comps_for{$class}}, @modules);
233 elsif (ref $param eq 'HASH') {
234 # more than one namespace possible
235 for my $comp ( keys %$param ) {
236 # filter out commented entries
237 my @modules = grep { $_ !~ /^#/ } @{$param->{$comp}};
239 push (@{$comps_for{$comp}}, @modules);
243 # filter out commented entries
244 push (@{$comps_for{$class}}, $param) if $param !~ /^#/;
248 eval "require Module::Find;";
249 $class->throw_exception(
250 "No arguments to load_classes and couldn't load Module::Find ($@)"
252 my @comp = map { substr $_, length "${class}::" }
253 Module::Find::findallmod($class);
254 $comps_for{$class} = \@comp;
259 no warnings qw/redefine/;
260 local *Class::C3::reinitialize = sub { };
261 foreach my $prefix (keys %comps_for) {
262 foreach my $comp (@{$comps_for{$prefix}||[]}) {
263 my $comp_class = "${prefix}::${comp}";
264 eval "use $comp_class"; # If it fails, assume the user fixed it
266 $comp_class =~ s/::/\//g;
267 die $@ unless $@ =~ /Can't locate.+$comp_class\.pm\sin\s\@INC/;
270 push(@to_register, [ $comp, $comp_class ]);
274 Class::C3->reinitialize;
276 foreach my $to (@to_register) {
277 $class->register_class(@$to);
278 # if $class->can('result_source_instance');
282 =head2 compose_connection
286 =item Arguments: $target_namespace, @db_info
288 =item Return Value: $new_schema
292 Calls L<DBIx::Class::Schema/"compose_namespace"> to the target namespace,
293 calls L<DBIx::Class::Schema/connection> with @db_info on the new schema,
294 then injects the L<DBix::Class::ResultSetProxy> component and a
295 resultset_instance classdata entry on all the new classes, in order to support
296 $target_namespaces::$class->search(...) method calls.
298 This is primarily useful when you have a specific need for class method access
299 to a connection. In normal usage it is preferred to call
300 L<DBIx::Class::Schema/connect> and use the resulting schema object to operate
301 on L<DBIx::Class::ResultSet> objects with L<DBIx::Class::Schema/resultset> for
306 sub compose_connection {
307 my ($self, $target, @info) = @_;
308 my $base = 'DBIx::Class::ResultSetProxy';
309 eval "require ${base};";
310 $self->throw_exception
311 ("No arguments to load_classes and couldn't load ${base} ($@)")
314 if ($self eq $target) {
315 # Pathological case, largely caused by the docs on early C::M::DBIC::Plain
316 foreach my $moniker ($self->sources) {
317 my $source = $self->source($moniker);
318 my $class = $source->result_class;
319 $self->inject_base($class, $base);
320 $class->mk_classdata(resultset_instance => $source->resultset);
321 $class->mk_classdata(class_resolver => $self);
323 $self->connection(@info);
327 my $schema = $self->compose_namespace($target, $base);
330 *{"${target}::schema"} = sub { $schema };
333 $schema->connection(@info);
334 foreach my $moniker ($schema->sources) {
335 my $source = $schema->source($moniker);
336 my $class = $source->result_class;
337 #warn "$moniker $class $source ".$source->storage;
338 $class->mk_classdata(result_source_instance => $source);
339 $class->mk_classdata(resultset_instance => $source->resultset);
340 $class->mk_classdata(class_resolver => $schema);
345 =head2 compose_namespace
349 =item Arguments: $target_namespace, $additional_base_class?
351 =item Return Value: $new_schema
355 For each L<DBIx::Class::ResultSource> in the schema, this method creates a
356 class in the target namespace (e.g. $target_namespace::CD,
357 $target_namespace::Artist) that inherits from the corresponding classes
358 attached to the current schema.
360 It also attaches a corresponding L<DBIx::Class::ResultSource> object to the
361 new $schema object. If C<$additional_base_class> is given, the new composed
362 classes will inherit from first the corresponding classe from the current
363 schema then the base class.
365 For example, for a schema with My::Schema::CD and My::Schema::Artist classes,
367 $schema->compose_namespace('My::DB', 'Base::Class');
368 print join (', ', @My::DB::CD::ISA) . "\n";
369 print join (', ', @My::DB::Artist::ISA) ."\n";
371 will produce the output
373 My::Schema::CD, Base::Class
374 My::Schema::Artist, Base::Class
378 sub compose_namespace {
379 my ($self, $target, $base) = @_;
380 my %reg = %{ $self->source_registrations };
383 my $schema = $self->clone;
385 no warnings qw/redefine/;
386 local *Class::C3::reinitialize = sub { };
387 foreach my $moniker ($schema->sources) {
388 my $source = $schema->source($moniker);
389 my $target_class = "${target}::${moniker}";
391 $target_class => $source->result_class, ($base ? $base : ())
393 $source->result_class($target_class);
396 Class::C3->reinitialize();
399 foreach my $meth (qw/class source resultset/) {
400 *{"${target}::${meth}"} =
401 sub { shift->schema->$meth(@_) };
407 =head2 setup_connection_class
411 =item Arguments: $target, @info
415 Sets up a database connection class to inject between the schema and the
416 subclasses that the schema creates.
420 sub setup_connection_class {
421 my ($class, $target, @info) = @_;
422 $class->inject_base($target => 'DBIx::Class::DB');
423 #$target->load_components('DB');
424 $target->connection(@info);
431 =item Arguments: @args
433 =item Return Value: $new_schema
437 Instantiates a new Storage object of type
438 L<DBIx::Class::Schema/"storage_type"> and passes the arguments to
439 $storage->connect_info. Sets the connection in-place on the schema. See
440 L<DBIx::Class::Storage::DBI/"connect_info"> for more information.
445 my ($self, @info) = @_;
446 return $self if !@info && $self->storage;
447 my $storage_class = $self->storage_type;
448 $storage_class = 'DBIx::Class::Storage'.$storage_class
449 if $storage_class =~ m/^::/;
450 eval "require ${storage_class};";
451 $self->throw_exception(
452 "No arguments to load_classes and couldn't load ${storage_class} ($@)"
454 my $storage = $storage_class->new;
455 $storage->connect_info(\@info);
456 $self->storage($storage);
464 =item Arguments: @info
466 =item Return Value: $new_schema
470 This is a convenience method. It is equivalent to calling
471 $schema->clone->connection(@info). See L</connection> and L</clone> for more
476 sub connect { shift->clone->connection(@_) }
480 Begins a transaction (does nothing if AutoCommit is off). Equivalent to
481 calling $schema->storage->txn_begin. See
482 L<DBIx::Class::Storage::DBI/"txn_begin"> for more information.
486 sub txn_begin { shift->storage->txn_begin }
490 Commits the current transaction. Equivalent to calling
491 $schema->storage->txn_commit. See L<DBIx::Class::Storage::DBI/"txn_commit">
492 for more information.
496 sub txn_commit { shift->storage->txn_commit }
500 Rolls back the current transaction. Equivalent to calling
501 $schema->storage->txn_rollback. See
502 L<DBIx::Class::Storage::DBI/"txn_rollback"> for more information.
506 sub txn_rollback { shift->storage->txn_rollback }
512 =item Arguments: C<$coderef>, @coderef_args?
514 =item Return Value: The return value of $coderef
518 Executes C<$coderef> with (optional) arguments C<@coderef_args> atomically,
519 returning its result (if any). If an exception is caught, a rollback is issued
520 and the exception is rethrown. If the rollback fails, (i.e. throws an
521 exception) an exception is thrown that includes a "Rollback failed" message.
525 my $author_rs = $schema->resultset('Author')->find(1);
528 my ($author, @titles) = @_;
530 # If any one of these fails, the entire transaction fails
531 $author->create_related('books', {
533 }) foreach (@titles);
535 return $author->books;
540 $rs = $schema->txn_do($coderef, $author_rs, qw/Night Day It/);
545 if ($error =~ /Rollback failed/) {
546 die "something terrible has happened!";
548 deal_with_failed_transaction();
552 In a nested transaction (calling txn_do() from within a txn_do() coderef) only
553 the outermost transaction will issue a L<DBIx::Class::Schema/"txn_commit"> on
554 the Schema's storage, and txn_do() can be called in void, scalar and list
555 context and it will behave as expected.
560 my ($self, $coderef, @args) = @_;
562 ref $self or $self->throw_exception
563 ('Cannot execute txn_do as a class method');
564 ref $coderef eq 'CODE' or $self->throw_exception
565 ('$coderef must be a CODE reference');
567 my (@return_values, $return_value);
569 $self->txn_begin; # If this throws an exception, no rollback is needed
571 my $wantarray = wantarray; # Need to save this since the context
572 # inside the eval{} block is independent
573 # of the context that called txn_do()
576 # Need to differentiate between scalar/list context to allow for
577 # returning a list in scalar context to get the size of the list
580 @return_values = $coderef->(@args);
581 } elsif (defined $wantarray) {
583 $return_value = $coderef->(@args);
599 my $rollback_error = $@;
600 my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
601 $self->throw_exception($error) # propagate nested rollback
602 if $rollback_error =~ /$exception_class/;
604 $self->throw_exception(
605 "Transaction aborted: $error. Rollback failed: ${rollback_error}"
608 $self->throw_exception($error); # txn failed but rollback succeeded
612 return $wantarray ? @return_values : $return_value;
619 =item Return Value: $new_schema
623 Clones the schema and its associated result_source objects and returns the
630 my $clone = bless({ (ref $self ? %$self : ()) }, ref $self || $self);
631 foreach my $moniker ($self->sources) {
632 my $source = $self->source($moniker);
633 my $new = $source->new($source);
634 $clone->register_source($moniker => $new);
643 =item Arguments: $moniker, \@data;
647 Populates the source registered with the given moniker with the supplied data.
648 @data should be a list of listrefs -- the first containing column names, the
649 second matching values.
653 $schema->populate('Artist', [
654 [ qw/artistid name/ ],
655 [ 1, 'Popular Band' ],
663 my ($self, $name, $data) = @_;
664 my $rs = $self->resultset($name);
665 my @names = @{shift(@$data)};
667 foreach my $item (@$data) {
669 @create{@names} = @$item;
670 push(@created, $rs->create(\%create));
675 =head2 throw_exception
679 =item Arguments: $message
683 Throws an exception. Defaults to using L<Carp::Clan> to report errors from
688 sub throw_exception {
693 =head2 deploy (EXPERIMENTAL)
697 =item Arguments: $sqlt_args
701 Attempts to deploy the schema to the current storage using L<SQL::Translator>.
703 Note that this feature is currently EXPERIMENTAL and may not work correctly
704 across all databases, or fully handle complex relationships.
709 my ($self, $sqltargs) = @_;
710 $self->throw_exception("Can't deploy without storage") unless $self->storage;
711 $self->storage->deploy($self, undef, $sqltargs);
718 Matt S. Trout <mst@shadowcatsystems.co.uk>
722 You may distribute this code under the same terms as Perl itself.