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?, { $namespace => [ $class+ ] }+
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(
194 "No arguments to load_classes and couldn't load Module::Find ($@)"
196 my @comp = map { substr $_, length "${class}::" }
197 Module::Find::findallmod($class);
198 $comps_for{$class} = \@comp;
203 no warnings qw/redefine/;
204 local *Class::C3::reinitialize = sub { };
205 foreach my $prefix (keys %comps_for) {
206 foreach my $comp (@{$comps_for{$prefix}||[]}) {
207 my $comp_class = "${prefix}::${comp}";
208 eval "use $comp_class"; # If it fails, assume the user fixed it
210 $comp_class =~ s/::/\//g;
211 die $@ unless $@ =~ /Can't locate.+$comp_class\.pm\sin\s\@INC/;
214 push(@to_register, [ $comp, $comp_class ]);
218 Class::C3->reinitialize;
220 foreach my $to (@to_register) {
221 $class->register_class(@$to);
222 # if $class->can('result_source_instance');
226 =head2 compose_connection
228 =head3 Arguments: $target_ns, @db_info
230 =head3 Return value: $new_schema
232 Calls compose_namespace to the $target_ns, calls ->connection(@db_info) on
233 the new schema, then injects the ResultSetProxy component and a
234 resultset_instance classdata entry on all the new classes in order to support
235 $target_ns::Class->search(...) method calls. Primarily useful when you have
236 a specific need for classmethod access to a connection - in normal usage
237 ->connect is preferred.
241 sub compose_connection {
242 my ($self, $target, @info) = @_;
243 my $base = 'DBIx::Class::ResultSetProxy';
244 eval "require ${base};";
245 $self->throw_exception
246 ("No arguments to load_classes and couldn't load ${base} ($@)")
249 if ($self eq $target) {
250 # Pathological case, largely caused by the docs on early C::M::DBIC::Plain
251 foreach my $moniker ($self->sources) {
252 my $source = $self->source($moniker);
253 my $class = $source->result_class;
254 $self->inject_base($class, $base);
255 $class->mk_classdata(resultset_instance => $source->resultset);
256 $class->mk_classdata(class_resolver => $self);
258 $self->connection(@info);
262 my $schema = $self->compose_namespace($target, $base);
265 *{"${target}::schema"} = sub { $schema };
268 $schema->connection(@info);
269 foreach my $moniker ($schema->sources) {
270 my $source = $schema->source($moniker);
271 my $class = $source->result_class;
272 #warn "$moniker $class $source ".$source->storage;
273 $class->mk_classdata(result_source_instance => $source);
274 $class->mk_classdata(resultset_instance => $source->resultset);
275 $class->mk_classdata(class_resolver => $schema);
280 =head2 compose_namespace
282 =head3 Arguments: $target_ns, $additional_base_class?
284 =head3 Return value: $new_schema
286 For each result source in the schema, creates a class in the target
287 namespace (e.g. $target_ns::CD, $target_ns::Artist) inheriting from the
288 corresponding classes attached to the current schema and a result source
289 to match attached to the new $schema object. If an additional base class is
290 given, injects this immediately behind the corresponding classes from the
291 current schema in the created classes' @ISA.
295 sub compose_namespace {
296 my ($self, $target, $base) = @_;
297 my %reg = %{ $self->source_registrations };
300 my $schema = $self->clone;
302 no warnings qw/redefine/;
303 local *Class::C3::reinitialize = sub { };
304 foreach my $moniker ($schema->sources) {
305 my $source = $schema->source($moniker);
306 my $target_class = "${target}::${moniker}";
308 $target_class => $source->result_class, ($base ? $base : ())
310 $source->result_class($target_class);
313 Class::C3->reinitialize();
316 foreach my $meth (qw/class source resultset/) {
317 *{"${target}::${meth}"} =
318 sub { shift->schema->$meth(@_) };
324 =head2 setup_connection_class
326 =head3 Arguments: <$target> <@info>
328 Sets up a database connection class to inject between the schema
329 and the subclasses the schema creates.
333 sub setup_connection_class {
334 my ($class, $target, @info) = @_;
335 $class->inject_base($target => 'DBIx::Class::DB');
336 #$target->load_components('DB');
337 $target->connection(@info);
342 =head3 Arguments: (@args)
344 Instantiates a new Storage object of type storage_type and passes the
345 arguments to $storage->connect_info. Sets the connection in-place on
351 my ($self, @info) = @_;
352 return $self if !@info && $self->storage;
353 my $storage_class = $self->storage_type;
354 $storage_class = 'DBIx::Class::Storage'.$storage_class
355 if $storage_class =~ m/^::/;
356 eval "require ${storage_class};";
357 $self->throw_exception(
358 "No arguments to load_classes and couldn't load ${storage_class} ($@)"
360 my $storage = $storage_class->new;
361 $storage->connect_info(\@info);
362 $self->storage($storage);
368 =head3 Arguments: (@info)
370 Conveneience method, equivalent to $schema->clone->connection(@info)
374 sub connect { shift->clone->connection(@_) }
378 Begins a transaction (does nothing if AutoCommit is off).
382 sub txn_begin { shift->storage->txn_begin }
386 Commits the current transaction.
390 sub txn_commit { shift->storage->txn_commit }
394 Rolls back the current transaction.
398 sub txn_rollback { shift->storage->txn_rollback }
402 =head3 Arguments: $coderef, @coderef_args?
404 Executes C<$coderef> with (optional) arguments C<@coderef_args>
405 transactionally, returning its result (if any). If an exception is
406 caught, a rollback is issued and the exception is rethrown. If the
407 rollback fails, (i.e. throws an exception) an exception is thrown that
408 includes a "Rollback failed" message.
412 my $author_rs = $schema->resultset('Author')->find(1);
415 my ($author, @titles) = @_;
417 # If any one of these fails, the entire transaction fails
418 $author->create_related('books', {
420 }) foreach (@titles);
422 return $author->books;
427 $rs = $schema->txn_do($coderef, $author_rs, qw/Night Day It/);
432 if ($error =~ /Rollback failed/) {
433 die "something terrible has happened!";
435 deal_with_failed_transaction();
439 Nested transactions work as expected (i.e. only the outermost
440 transaction will issue a txn_commit on the Schema's storage), and
441 txn_do() can be called in void, scalar and list context and it will
447 my ($self, $coderef, @args) = @_;
449 ref $self or $self->throw_exception
450 ('Cannot execute txn_do as a class method');
451 ref $coderef eq 'CODE' or $self->throw_exception
452 ('$coderef must be a CODE reference');
454 my (@return_values, $return_value);
456 $self->txn_begin; # If this throws an exception, no rollback is needed
458 my $wantarray = wantarray; # Need to save this since the context
459 # inside the eval{} block is independent
460 # of the context that called txn_do()
463 # Need to differentiate between scalar/list context to allow for
464 # returning a list in scalar context to get the size of the list
468 @return_values = $coderef->(@args);
469 } elsif (defined $wantarray) {
471 $return_value = $coderef->(@args);
487 my $rollback_error = $@;
488 my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
489 $self->throw_exception($error) # propagate nested rollback
490 if $rollback_error =~ /$exception_class/;
492 $self->throw_exception(
493 "Transaction aborted: $error. Rollback failed: ${rollback_error}"
496 $self->throw_exception($error); # txn failed but rollback succeeded
500 return $wantarray ? @return_values : $return_value;
505 Clones the schema and its associated result_source objects and returns the
512 my $clone = bless({ (ref $self ? %$self : ()) }, ref $self || $self);
513 foreach my $moniker ($self->sources) {
514 my $source = $self->source($moniker);
515 my $new = $source->new($source);
516 $clone->register_source($moniker => $new);
523 =head3 Arguments: ($moniker, \@data);
525 Populates the source registered with the given moniker with the supplied data.
526 @data should be a list of listrefs, the first containing column names, the
527 second matching values - i.e.
529 $schema->populate('Artist', [
530 [ qw/artistid name/ ],
531 [ 1, 'Popular Band' ],
539 my ($self, $name, $data) = @_;
540 my $rs = $self->resultset($name);
541 my @names = @{shift(@$data)};
543 foreach my $item (@$data) {
545 @create{@names} = @$item;
546 push(@created, $rs->create(\%create));
551 =head2 throw_exception
553 Defaults to using Carp::Clan to report errors from user perspective.
557 sub throw_exception {
562 =head2 deploy (EXPERIMENTAL)
564 Attempts to deploy the schema to the current storage using SQL::Translator.
566 Note that this feature is currently EXPERIMENTAL and may not work correctly
567 across all databases, or fully handle complex relationships.
572 my ($self, $sqltargs) = @_;
573 $self->throw_exception("Can't deploy without storage") unless $self->storage;
574 $self->storage->deploy($self, undef, $sqltargs);
581 Matt S. Trout <mst@shadowcatsystems.co.uk>
585 You may distribute this code under the same terms as Perl itself.