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
22 use base qw/DBIx::Class::Schema/;
24 # load My::Schema::Foo, My::Schema::Bar, My::Schema::Baz
25 __PACKAGE__->load_classes(qw/Foo Bar Baz/);
27 package My::Schema::Foo;
28 use base qw/DBIx::Class/;
29 __PACKAGE__->load_components(qw/PK::Auto::Pg Core/); # for example
30 __PACKAGE__->table('foo');
32 # Elsewhere in your code:
33 my $schema1 = My::Schema->connect(
40 my $schema2 = My::Schema->connect( ... );
42 # fetch objects using My::Schema::Foo
43 my $resultset = $schema1->resultset('Foo')->search( ... );
44 my @objects = $schema2->resultset('Foo')->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, $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('Foo');
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('Foo');
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('Foo');
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;
199 foreach my $prefix (keys %comps_for) {
200 foreach my $comp (@{$comps_for{$prefix}||[]}) {
201 my $comp_class = "${prefix}::${comp}";
202 eval "use $comp_class"; # If it fails, assume the user fixed it
204 die $@ unless $@ =~ /Can't locate/;
206 $class->register_class($comp => $comp_class);
207 # if $class->can('result_source_instance');
212 =head2 compose_connection
214 =head3 Arguments: <target> <@db_info>
216 This is the most important method in this class. it takes a target namespace,
217 as well as dbh connection info, and creates a L<DBIx::Class::DB> class as
218 well as subclasses for each of your database classes in this namespace, using
221 It will also setup a ->class method on the target class, which lets you
222 resolve database classes based on the schema component name, for example
224 MyApp::DB->class('Foo') # returns MyApp::DB::Foo,
225 # which ISA MyApp::Schema::Foo
227 This is the recommended API for accessing Schema generated classes, and
228 using it might give you instant advantages with future versions of DBIC.
230 WARNING: Loading components into Schema classes after compose_connection
231 may not cause them to be seen by the classes in your target namespace due
232 to the dispatch table approach used by Class::C3. If you do this you may find
233 you need to call Class::C3->reinitialize() afterwards to get the behaviour
238 sub compose_connection {
239 my ($self, $target, @info) = @_;
240 my $base = 'DBIx::Class::ResultSetProxy';
241 eval "require ${base};";
242 $self->throw_exception("No arguments to load_classes and couldn't load".
243 " ${base} ($@)") if $@;
245 if ($self eq $target) {
246 # Pathological case, largely caused by the docs on early C::M::DBIC::Plain
247 foreach my $moniker ($self->sources) {
248 my $source = $self->source($moniker);
249 my $class = $source->result_class;
250 $self->inject_base($class, $base);
251 $class->mk_classdata(resultset_instance => $source->resultset);
252 $class->mk_classdata(class_resolver => $self);
254 $self->connection(@info);
258 my $schema = $self->compose_namespace($target, $base);
261 *{"${target}::schema"} = sub { $schema };
264 $schema->connection(@info);
265 foreach my $moniker ($schema->sources) {
266 my $source = $schema->source($moniker);
267 my $class = $source->result_class;
268 #warn "$moniker $class $source ".$source->storage;
269 $class->mk_classdata(result_source_instance => $source);
270 $class->mk_classdata(resultset_instance => $source->resultset);
271 $class->mk_classdata(class_resolver => $schema);
276 sub compose_namespace {
277 my ($self, $target, $base) = @_;
278 my %reg = %{ $self->source_registrations };
281 my $schema = $self->clone;
282 foreach my $moniker ($schema->sources) {
283 my $source = $schema->source($moniker);
284 my $target_class = "${target}::${moniker}";
286 $target_class => $source->result_class, ($base ? $base : ())
288 $source->result_class($target_class);
292 foreach my $meth (qw/class source resultset/) {
293 *{"${target}::${meth}"} =
294 sub { shift->schema->$meth(@_) };
300 =head2 setup_connection_class
302 =head3 Arguments: <$target> <@info>
304 Sets up a database connection class to inject between the schema
305 and the subclasses the schema creates.
309 sub setup_connection_class {
310 my ($class, $target, @info) = @_;
311 $class->inject_base($target => 'DBIx::Class::DB');
312 #$target->load_components('DB');
313 $target->connection(@info);
318 =head3 Arguments: (@args)
320 Instantiates a new Storage object of type storage_type and passes the
321 arguments to $storage->connect_info. Sets the connection in-place on
327 my ($self, @info) = @_;
328 my $storage_class = $self->storage_type;
329 $storage_class = 'DBIx::Class::Storage'.$storage_class
330 if $storage_class =~ m/^::/;
331 eval "require ${storage_class};";
332 $self->throw_exception("No arguments to load_classes and couldn't load".
333 " ${storage_class} ($@)") if $@;
334 my $storage = $storage_class->new;
335 $storage->connect_info(\@info);
336 $self->storage($storage);
342 =head3 Arguments: (@info)
344 Conveneience method, equivalent to $schema->clone->connection(@info)
348 sub connect { shift->clone->connection(@_) }
352 Begins a transaction (does nothing if AutoCommit is off).
356 sub txn_begin { shift->storage->txn_begin }
360 Commits the current transaction.
364 sub txn_commit { shift->storage->txn_commit }
368 Rolls back the current transaction.
372 sub txn_rollback { shift->storage->txn_rollback }
376 =head3 Arguments: <coderef>, [@coderef_args]
378 Executes <coderef> with (optional) arguments <@coderef_args> transactionally,
379 returning its result (if any). If an exception is caught, a rollback is issued
380 and the exception is rethrown. If the rollback fails, (i.e. throws an
381 exception) an exception is thrown that includes a "Rollback failed" message.
385 my $foo = $schema->resultset('foo')->find(1);
388 my ($foo, @bars) = @_;
390 # If any one of these fails, the entire transaction fails
391 $foo->create_related('bars', {
400 $rs = $schema->txn_do($coderef, $foo, qw/foo bar baz/);
405 if ($error =~ /Rollback failed/) {
406 die "something terrible has happened!";
408 deal_with_failed_transaction();
413 Nested transactions should work as expected (i.e. only the outermost
414 transaction will issue a txn_commit on the Schema's storage)
419 my ($self, $coderef, @args) = @_;
421 ref $self or $self->throw_exception
422 ('Cannot execute txn_do as a class method');
423 ref $coderef eq 'CODE' or $self->throw_exception
424 ('$coderef must be a CODE reference');
426 my (@return_values, $return_value);
428 $self->txn_begin; # If this throws an exception, no rollback is needed
430 my $wantarray = wantarray; # Need to save this since it's reset in eval{}
433 # Need to differentiate between scalar/list context to allow for returning
434 # a list in scalar context to get the size of the list
436 @return_values = $coderef->(@args);
438 $return_value = $coderef->(@args);
451 my $rollback_error = $@;
452 my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
453 $self->throw_exception($error) # propagate nested rollback
454 if $rollback_error =~ /$exception_class/;
456 $self->throw_exception("Transaction aborted: $error. Rollback failed: ".
459 $self->throw_exception($error); # txn failed but rollback succeeded
463 return $wantarray ? @return_values : $return_value;
468 Clones the schema and its associated result_source objects and returns the
475 my $clone = bless({ (ref $self ? %$self : ()) }, ref $self || $self);
476 foreach my $moniker ($self->sources) {
477 my $source = $self->source($moniker);
478 my $new = $source->new($source);
479 $clone->register_source($moniker => $new);
486 =head3 Arguments: ($moniker, \@data);
488 Populates the source registered with the given moniker with the supplied data.
489 @data should be a list of listrefs, the first containing column names, the
490 second matching values - i.e.
492 $schema->populate('Foo', [
493 [ qw/foo_id foo_string/ ],
502 my ($self, $name, $data) = @_;
503 my $rs = $self->resultset($name);
504 my @names = @{shift(@$data)};
505 foreach my $item (@$data) {
507 @create{@names} = @$item;
508 $rs->create(\%create);
512 =head2 throw_exception
514 Defaults to using Carp::Clan to report errors from user perspective.
518 sub throw_exception {
527 Matt S. Trout <mst@shadowcatsystems.co.uk>
531 You may distribute this code under the same terms as Perl itself.