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.
60 =head3 Arguments: ($moniker, $component_class)
62 Registers a class which isa L<DBIx::Class::ResultSourceProxy>. Equivalent to
65 $schema->register_source($moniker, $component_class->result_source_instance);
70 my ($self, $moniker, $to_register) = @_;
71 $self->register_source($moniker => $to_register->result_source_instance);
74 =head2 register_source
76 =head3 Arguments: ($moniker, $result_source)
78 Registers the L<DBIx::Class::ResultSource> in the schema with the given
84 my ($self, $moniker, $source) = @_;
85 my %reg = %{$self->source_registrations};
86 $reg{$moniker} = $source;
87 $self->source_registrations(\%reg);
88 $source->schema($self);
89 if ($source->result_class) {
90 my %map = %{$self->class_mappings};
91 $map{$source->result_class} = $moniker;
92 $self->class_mappings(\%map);
98 =head3 Arguments: ($moniker)
100 =head3 Returns: $classname
102 Retrieves the result class name for the given moniker.
106 my $class = $schema->class('CD');
111 my ($self, $moniker) = @_;
112 return $self->source($moniker)->result_class;
117 =head3 Arguments: ($moniker)
119 =head3 Returns: $result_source
121 my $source = $schema->source('Book');
123 Returns the L<DBIx::Class::ResultSource> object for the registered moniker.
128 my ($self, $moniker) = @_;
129 my $sreg = $self->source_registrations;
130 return $sreg->{$moniker} if exists $sreg->{$moniker};
132 # if we got here, they probably passed a full class name
133 my $mapped = $self->class_mappings->{$moniker};
134 $self->throw_exception("Can't find source for ${moniker}")
135 unless $mapped && exists $sreg->{$mapped};
136 return $sreg->{$mapped};
141 =head3 Returns: @source_monikers
143 Returns the source monikers of all source registrations on this schema.
147 my @source_monikers = $schema->sources;
151 sub sources { return keys %{shift->source_registrations}; }
155 =head3 Arguments: ($moniker)
157 =head3 Returns: $result_set
159 my $rs = $schema->resultset('DVD');
161 Returns the L<DBIx::Class::ResultSet> object for the registered moniker.
166 my ($self, $moniker) = @_;
167 return $self->source($moniker)->resultset;
172 =head3 Arguments: @classes?, { $namespace => [ @classes ] }+
174 With no arguments, this method uses L<Module::Find> to find all classes under
175 the schema's namespace. Otherwise, this method loads the classes you specify
176 (using L<use>), and registers them (using L</"register_class">).
178 It is possible to comment out classes with a leading '#', but note that perl
179 will think it's a mistake (trying to use a comment in a qw list) so you'll
180 need to add "no warnings 'qw';" before your load_classes call.
184 My::Schema->load_classes(); # loads My::Schema::CD, My::Schema::Artist,
185 # etc. (anything under the My::Schema namespace)
187 # loads My::Schema::CD, My::Schema::Artist, Other::Namespace::Producer but
188 # not Other::Namespace::LinerNotes nor My::Schema::Track
189 My::Schema->load_classes(qw/ CD Artist #Track /, {
190 Other::Namespace => [qw/ Producer #LinerNotes /],
196 my ($class, @params) = @_;
201 foreach my $param (@params) {
202 if (ref $param eq 'ARRAY') {
203 # filter out commented entries
204 my @modules = grep { $_ !~ /^#/ } @$param;
206 push (@{$comps_for{$class}}, @modules);
208 elsif (ref $param eq 'HASH') {
209 # more than one namespace possible
210 for my $comp ( keys %$param ) {
211 # filter out commented entries
212 my @modules = grep { $_ !~ /^#/ } @{$param->{$comp}};
214 push (@{$comps_for{$comp}}, @modules);
218 # filter out commented entries
219 push (@{$comps_for{$class}}, $param) if $param !~ /^#/;
223 eval "require Module::Find;";
224 $class->throw_exception(
225 "No arguments to load_classes and couldn't load Module::Find ($@)"
227 my @comp = map { substr $_, length "${class}::" }
228 Module::Find::findallmod($class);
229 $comps_for{$class} = \@comp;
234 no warnings qw/redefine/;
235 local *Class::C3::reinitialize = sub { };
236 foreach my $prefix (keys %comps_for) {
237 foreach my $comp (@{$comps_for{$prefix}||[]}) {
238 my $comp_class = "${prefix}::${comp}";
239 eval "use $comp_class"; # If it fails, assume the user fixed it
241 $comp_class =~ s/::/\//g;
242 die $@ unless $@ =~ /Can't locate.+$comp_class\.pm\sin\s\@INC/;
245 push(@to_register, [ $comp, $comp_class ]);
249 Class::C3->reinitialize;
251 foreach my $to (@to_register) {
252 $class->register_class(@$to);
253 # if $class->can('result_source_instance');
257 =head2 compose_connection
259 =head3 Arguments: ($target_namespace, @db_info)
261 =head3 Returns: $new_schema
263 Calls L<DBIx::Class::schema/"compose_namespace"> to the target namespace,
264 calls L<DBIx::Class::Schema/connection>(@db_info) on the new schema, then
265 injects the L<DBix::Class::ResultSetProxy> component and a resultset_instance
266 classdata entry on all the new classes in order to support
267 $target_namespaces::$class->search(...) method calls.
269 This is primarily useful when you have a specific need for class method access
270 to a connection. In normal usage it is preferred to call
271 L<DBIx::Class::Schema/connect> and use the resulting schema object to operate
272 on L<DBIx::Class::ResultSet> objects with L<DBIx::Class::Schema/resultset> for
277 sub compose_connection {
278 my ($self, $target, @info) = @_;
279 my $base = 'DBIx::Class::ResultSetProxy';
280 eval "require ${base};";
281 $self->throw_exception
282 ("No arguments to load_classes and couldn't load ${base} ($@)")
285 if ($self eq $target) {
286 # Pathological case, largely caused by the docs on early C::M::DBIC::Plain
287 foreach my $moniker ($self->sources) {
288 my $source = $self->source($moniker);
289 my $class = $source->result_class;
290 $self->inject_base($class, $base);
291 $class->mk_classdata(resultset_instance => $source->resultset);
292 $class->mk_classdata(class_resolver => $self);
294 $self->connection(@info);
298 my $schema = $self->compose_namespace($target, $base);
301 *{"${target}::schema"} = sub { $schema };
304 $schema->connection(@info);
305 foreach my $moniker ($schema->sources) {
306 my $source = $schema->source($moniker);
307 my $class = $source->result_class;
308 #warn "$moniker $class $source ".$source->storage;
309 $class->mk_classdata(result_source_instance => $source);
310 $class->mk_classdata(resultset_instance => $source->resultset);
311 $class->mk_classdata(class_resolver => $schema);
316 =head2 compose_namespace
318 =head3 Arguments: $target_namespace, $additional_base_class?
320 =head3 Returns: $new_schema
322 For each L<DBIx::Class::ResultSource> in the schema, this method creates a
323 class in the target namespace (e.g. $target_namespace::CD,
324 $target_namespace::Artist) that inherits from the corresponding classes
325 attached to the current schema.
327 It also attaches a corresponding L<DBIx::Class::ResultSource> object to the
328 new $schema object. If C<$additional_base_class> is given, the new composed
329 classes will inherit from first the corresponding classe from the current
330 schema then the base class.
332 e.g. (for a schema with My::Schema::CD and My::Schema::Artist classes),
334 $schema->compose_namespace('My::DB', 'Base::Class');
335 print join (', ', @My::DB::CD::ISA) . "\n";
336 print join (', ', @My::DB::Artist::ISA) ."\n";
338 Will produce the output
340 My::Schema::CD, Base::Class
341 My::Schema::Artist, Base::Class
345 sub compose_namespace {
346 my ($self, $target, $base) = @_;
347 my %reg = %{ $self->source_registrations };
350 my $schema = $self->clone;
352 no warnings qw/redefine/;
353 local *Class::C3::reinitialize = sub { };
354 foreach my $moniker ($schema->sources) {
355 my $source = $schema->source($moniker);
356 my $target_class = "${target}::${moniker}";
358 $target_class => $source->result_class, ($base ? $base : ())
360 $source->result_class($target_class);
363 Class::C3->reinitialize();
366 foreach my $meth (qw/class source resultset/) {
367 *{"${target}::${meth}"} =
368 sub { shift->schema->$meth(@_) };
374 =head2 setup_connection_class
376 =head3 Arguments: ($target, @info)
378 Sets up a database connection class to inject between the schema and the
379 subclasses that the schema creates.
383 sub setup_connection_class {
384 my ($class, $target, @info) = @_;
385 $class->inject_base($target => 'DBIx::Class::DB');
386 #$target->load_components('DB');
387 $target->connection(@info);
392 =head3 Arguments: (@args)
394 =head3 Returns: $new_schema
396 Instantiates a new Storage object of type
397 L<DBIx::Class::Schema/"storage_type"> and passes the arguments to
398 $storage->connect_info. Sets the connection in-place on the schema. See
399 L<DBIx::Class::Storage::DBI/"connect_info"> for more information.
404 my ($self, @info) = @_;
405 return $self if !@info && $self->storage;
406 my $storage_class = $self->storage_type;
407 $storage_class = 'DBIx::Class::Storage'.$storage_class
408 if $storage_class =~ m/^::/;
409 eval "require ${storage_class};";
410 $self->throw_exception(
411 "No arguments to load_classes and couldn't load ${storage_class} ($@)"
413 my $storage = $storage_class->new;
414 $storage->connect_info(\@info);
415 $self->storage($storage);
421 =head3 Arguments: (@info)
423 =head3 Returns: $new_schema
425 This is a convenience method. It is equivalent to calling
426 $schema->clone->connection(@info). See L</connection> and L</clone> for more
431 sub connect { shift->clone->connection(@_) }
435 Begins a transaction (does nothing if AutoCommit is off). Equivalent to
436 calling $schema->storage->txn_begin. See
437 L<DBIx::Class::Storage::DBI/"txn_begin"> for more information.
441 sub txn_begin { shift->storage->txn_begin }
445 Commits the current transaction. Equivalent to calling
446 $schema->storage->txn_commit. See L<DBIx::Class::Storage::DBI/"txn_commit">
447 for more information.
451 sub txn_commit { shift->storage->txn_commit }
455 Rolls back the current transaction. Equivalent to calling
456 $schema->storage->txn_rollback. See
457 L<DBIx::Class::Storage::DBI/"txn_rollback"> for more information.
461 sub txn_rollback { shift->storage->txn_rollback }
465 =head3 Arguments: (C<$coderef>, @coderef_args?)
467 =head3 Returns: (C<$return_value> | C<@return_values> | C<undef>) for scalar,
468 list and void contexts, respectively
470 Executes C<$coderef> with (optional) arguments C<@coderef_args> atomically,
471 returning its result (if any). If an exception is caught, a rollback is issued
472 and the exception is rethrown. If the rollback fails, (i.e. throws an
473 exception) an exception is thrown that includes a "Rollback failed" message.
477 my $author_rs = $schema->resultset('Author')->find(1);
480 my ($author, @titles) = @_;
482 # If any one of these fails, the entire transaction fails
483 $author->create_related('books', {
485 }) foreach (@titles);
487 return $author->books;
492 $rs = $schema->txn_do($coderef, $author_rs, qw/Night Day It/);
497 if ($error =~ /Rollback failed/) {
498 die "something terrible has happened!";
500 deal_with_failed_transaction();
504 In a nested transaction (calling txn_do() from within a txn_do() coderef) only
505 the outermost transaction will issue a L<DBIx::Class::Schema/"txn_commit"> on
506 the Schema's storage, and txn_do() can be called in void, scalar and list
507 context and it will behave as expected.
512 my ($self, $coderef, @args) = @_;
514 ref $self or $self->throw_exception
515 ('Cannot execute txn_do as a class method');
516 ref $coderef eq 'CODE' or $self->throw_exception
517 ('$coderef must be a CODE reference');
519 my (@return_values, $return_value);
521 $self->txn_begin; # If this throws an exception, no rollback is needed
523 my $wantarray = wantarray; # Need to save this since the context
524 # inside the eval{} block is independent
525 # of the context that called txn_do()
528 # Need to differentiate between scalar/list context to allow for
529 # returning a list in scalar context to get the size of the list
532 @return_values = $coderef->(@args);
533 } elsif (defined $wantarray) {
535 $return_value = $coderef->(@args);
551 my $rollback_error = $@;
552 my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
553 $self->throw_exception($error) # propagate nested rollback
554 if $rollback_error =~ /$exception_class/;
556 $self->throw_exception(
557 "Transaction aborted: $error. Rollback failed: ${rollback_error}"
560 $self->throw_exception($error); # txn failed but rollback succeeded
564 return $wantarray ? @return_values : $return_value;
569 =head3 Returns: $new_schema
571 Clones the schema and its associated result_source objects and returns the
578 my $clone = bless({ (ref $self ? %$self : ()) }, ref $self || $self);
579 foreach my $moniker ($self->sources) {
580 my $source = $self->source($moniker);
581 my $new = $source->new($source);
582 $clone->register_source($moniker => $new);
589 =head3 Arguments: ($moniker, \@data);
591 Populates the source registered with the given moniker with the supplied data.
592 @data should be a list of listrefs -- the first containing column names, the
593 second matching values.
597 $schema->populate('Artist', [
598 [ qw/artistid name/ ],
599 [ 1, 'Popular Band' ],
607 my ($self, $name, $data) = @_;
608 my $rs = $self->resultset($name);
609 my @names = @{shift(@$data)};
611 foreach my $item (@$data) {
613 @create{@names} = @$item;
614 push(@created, $rs->create(\%create));
619 =head2 throw_exception
623 =item Arguments: ($message)
627 Throws an exception. Defaults to using L<Carp::Clan> to report errors from
632 sub throw_exception {
637 =head2 deploy (EXPERIMENTAL)
641 =item Arguments: ($sqlt_args)
645 Attempts to deploy the schema to the current storage using L<SQL::Translator>.
647 Note that this feature is currently EXPERIMENTAL and may not work correctly
648 across all databases, or fully handle complex relationships.
653 my ($self, $sqltargs) = @_;
654 $self->throw_exception("Can't deploy without storage") unless $self->storage;
655 $self->storage->deploy($self, undef, $sqltargs);
662 Matt S. Trout <mst@shadowcatsystems.co.uk>
666 You may distribute this code under the same terms as Perl itself.