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 ResultSourceProxy; equivalent to calling
64 $schema->register_source($moniker, $component_class->result_source_instance);
69 my ($self, $moniker, $to_register) = @_;
70 $self->register_source($moniker => $to_register->result_source_instance);
73 =head2 register_source
75 =head3 Arguments: <moniker> <result source>
77 Registers the result source in the schema with the given moniker
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);
96 my $class = $schema->class('CD');
98 Retrieves the result class name for a given result source
103 my ($self, $moniker) = @_;
104 return $self->source($moniker)->result_class;
109 my $source = $schema->source('Book');
111 Returns the result source object for the registered name
116 my ($self, $moniker) = @_;
117 my $sreg = $self->source_registrations;
118 return $sreg->{$moniker} if exists $sreg->{$moniker};
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};
129 my @source_monikers = $schema->sources;
131 Returns the source monikers of all source registrations on this schema
135 sub sources { return keys %{shift->source_registrations}; }
139 my $rs = $schema->resultset('DVD');
141 Returns the resultset for the registered moniker
146 my ($self, $moniker) = @_;
147 return $self->source($moniker)->resultset;
152 =head3 Arguments: [<classes>, (<class>, <class>), {<namespace> => [<classes>]}]
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>);
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.
165 my ($class, @params) = @_;
170 foreach my $param (@params) {
171 if (ref $param eq 'ARRAY') {
172 # filter out commented entries
173 my @modules = grep { $_ !~ /^#/ } @$param;
175 push (@{$comps_for{$class}}, @modules);
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}};
183 push (@{$comps_for{$comp}}, @modules);
187 # filter out commented entries
188 push (@{$comps_for{$class}}, $param) if $param !~ /^#/;
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;
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
208 $comp_class =~ s/::/\//g;
209 die $@ unless $@ =~ /Can't locate.+$comp_class\.pm\sin\s\@INC/;
212 push(@to_register, [ $comp, $comp_class ]);
216 Class::C3->reinitialize;
218 foreach my $to (@to_register) {
219 $class->register_class(@$to);
220 # if $class->can('result_source_instance');
224 =head2 compose_connection
226 =head3 Arguments: <target> <@db_info>
228 This method takes a target namespace, as well as dbh connection info,
229 and creates a L<DBIx::Class::DB> class as well as subclasses for each of
230 your database classes in this namespace, using this connection.
232 It will also setup a ->class method on the target class, which lets you
233 resolve database classes based on the schema component name, for example
235 Library::Model::DB->class('Book') # returns Library::Model::Book,
236 # which ISA Library::Schema::Book
238 This is the recommended API for accessing Schema generated classes, and
239 using it might give you instant advantages with future versions of DBIC.
241 WARNING: Loading components into Schema classes after compose_connection
242 may not cause them to be seen by the classes in your target namespace due
243 to the dispatch table approach used by Class::C3. If you do this you may find
244 you need to call Class::C3->reinitialize() afterwards to get the behaviour
249 sub compose_connection {
250 my ($self, $target, @info) = @_;
251 my $base = 'DBIx::Class::ResultSetProxy';
252 eval "require ${base};";
253 $self->throw_exception("No arguments to load_classes and couldn't load".
254 " ${base} ($@)") if $@;
256 if ($self eq $target) {
257 # Pathological case, largely caused by the docs on early C::M::DBIC::Plain
258 foreach my $moniker ($self->sources) {
259 my $source = $self->source($moniker);
260 my $class = $source->result_class;
261 $self->inject_base($class, $base);
262 $class->mk_classdata(resultset_instance => $source->resultset);
263 $class->mk_classdata(class_resolver => $self);
265 $self->connection(@info);
269 my $schema = $self->compose_namespace($target, $base);
272 *{"${target}::schema"} = sub { $schema };
275 $schema->connection(@info);
276 foreach my $moniker ($schema->sources) {
277 my $source = $schema->source($moniker);
278 my $class = $source->result_class;
279 #warn "$moniker $class $source ".$source->storage;
280 $class->mk_classdata(result_source_instance => $source);
281 $class->mk_classdata(resultset_instance => $source->resultset);
282 $class->mk_classdata(class_resolver => $schema);
287 =head2 compose_namespace
289 =head3 Arguments: <target> <base>
291 Translates <base> namespace into the specified <target> namespace.
294 My::Schema->compose_connection('A::B::C', @conn_info);
296 My::Schema::Tableclasses would become A::B::C::Tableclasses.
300 sub compose_namespace {
301 my ($self, $target, $base) = @_;
302 my %reg = %{ $self->source_registrations };
305 my $schema = $self->clone;
307 no warnings qw/redefine/;
308 local *Class::C3::reinitialize = sub { };
309 foreach my $moniker ($schema->sources) {
310 my $source = $schema->source($moniker);
311 my $target_class = "${target}::${moniker}";
313 $target_class => $source->result_class, ($base ? $base : ())
315 $source->result_class($target_class);
318 Class::C3->reinitialize();
321 foreach my $meth (qw/class source resultset/) {
322 *{"${target}::${meth}"} =
323 sub { shift->schema->$meth(@_) };
329 =head2 setup_connection_class
331 =head3 Arguments: <$target> <@info>
333 Sets up a database connection class to inject between the schema
334 and the subclasses the schema creates.
338 sub setup_connection_class {
339 my ($class, $target, @info) = @_;
340 $class->inject_base($target => 'DBIx::Class::DB');
341 #$target->load_components('DB');
342 $target->connection(@info);
347 =head3 Arguments: (@args)
349 Instantiates a new Storage object of type storage_type and passes the
350 arguments to $storage->connect_info. Sets the connection in-place on
356 my ($self, @info) = @_;
357 return $self if !@info && $self->storage;
358 my $storage_class = $self->storage_type;
359 $storage_class = 'DBIx::Class::Storage'.$storage_class
360 if $storage_class =~ m/^::/;
361 eval "require ${storage_class};";
362 $self->throw_exception("No arguments to load_classes and couldn't load".
363 " ${storage_class} ($@)") if $@;
364 my $storage = $storage_class->new;
365 $storage->connect_info(\@info);
366 $self->storage($storage);
372 =head3 Arguments: (@info)
374 Conveneience method, equivalent to $schema->clone->connection(@info)
378 sub connect { shift->clone->connection(@_) }
382 Begins a transaction (does nothing if AutoCommit is off).
386 sub txn_begin { shift->storage->txn_begin }
390 Commits the current transaction.
394 sub txn_commit { shift->storage->txn_commit }
398 Rolls back the current transaction.
402 sub txn_rollback { shift->storage->txn_rollback }
406 =head3 Arguments: <$coderef>, [@coderef_args]
408 Executes C<$coderef> with (optional) arguments C<@coderef_args>
409 transactionally, returning its result (if any). If an exception is
410 caught, a rollback is issued and the exception is rethrown. If the
411 rollback fails, (i.e. throws an exception) an exception is thrown that
412 includes a "Rollback failed" message.
416 my $author_rs = $schema->resultset('Author')->find(1);
419 my ($author, @titles) = @_;
421 # If any one of these fails, the entire transaction fails
422 $author->create_related('books', {
424 }) foreach (@titles);
426 return $author->books;
431 $rs = $schema->txn_do($coderef, $author_rs, qw/Night Day It/);
436 if ($error =~ /Rollback failed/) {
437 die "something terrible has happened!";
439 deal_with_failed_transaction();
443 Nested transactions work as expected (i.e. only the outermost
444 transaction will issue a txn_commit on the Schema's storage), and
445 txn_do() can be called in void, scalar and list context and it will
451 my ($self, $coderef, @args) = @_;
453 ref $self or $self->throw_exception
454 ('Cannot execute txn_do as a class method');
455 ref $coderef eq 'CODE' or $self->throw_exception
456 ('$coderef must be a CODE reference');
458 my (@return_values, $return_value);
460 $self->txn_begin; # If this throws an exception, no rollback is needed
462 my $wantarray = wantarray; # Need to save this since it's reset in eval{}
465 # Need to differentiate between scalar/list context to allow for
466 # returning a list in scalar context to get the size of the list
470 @return_values = $coderef->(@args);
471 } elsif (defined $wantarray) {
473 $return_value = $coderef->(@args);
489 my $rollback_error = $@;
490 my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
491 $self->throw_exception($error) # propagate nested rollback
492 if $rollback_error =~ /$exception_class/;
494 $self->throw_exception("Transaction aborted: $error. Rollback failed: ".
497 $self->throw_exception($error); # txn failed but rollback succeeded
501 return $wantarray ? @return_values : $return_value;
506 Clones the schema and its associated result_source objects and returns the
513 my $clone = bless({ (ref $self ? %$self : ()) }, ref $self || $self);
514 foreach my $moniker ($self->sources) {
515 my $source = $self->source($moniker);
516 my $new = $source->new($source);
517 $clone->register_source($moniker => $new);
524 =head3 Arguments: ($moniker, \@data);
526 Populates the source registered with the given moniker with the supplied data.
527 @data should be a list of listrefs, the first containing column names, the
528 second matching values - i.e.
530 $schema->populate('Artist', [
531 [ qw/artistid name/ ],
532 [ 1, 'Popular Band' ],
540 my ($self, $name, $data) = @_;
541 my $rs = $self->resultset($name);
542 my @names = @{shift(@$data)};
544 foreach my $item (@$data) {
546 @create{@names} = @$item;
547 push(@created, $rs->create(\%create));
552 =head2 throw_exception
554 Defaults to using Carp::Clan to report errors from user perspective.
558 sub throw_exception {
563 =head2 deploy (EXPERIMENTAL)
565 Attempts to deploy the schema to the current storage using SQL::Translator.
567 Note that this feature is currently EXPERIMENTAL and may not work correctly
568 across all databases, or fully handle complex relationships.
573 my ($self, $sqltargs) = @_;
574 $self->throw_exception("Can't deploy without storage") unless $self->storage;
575 $self->storage->deploy($self, undef, $sqltargs);
582 Matt S. Trout <mst@shadowcatsystems.co.uk>
586 You may distribute this code under the same terms as Perl itself.