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 my $schema1 = My::Schema->connect(
39 my $schema2 = My::Schema->connect( ... );
41 # fetch objects using My::Schema::Foo
42 my $resultset = $schema1->resultset('Foo')->search( ... );
43 my @objects = $schema2->resultset('Foo')->search( ... );
47 Creates database classes based on a schema. This is the recommended way to
48 use L<DBIx::Class> and allows you to use more than one concurrent connection
51 NB: If you're used to L<Class::DBI> it's worth reading the L</SYNOPSIS>
52 carefully as DBIx::Class does things a little differently. Note in
53 particular which module inherits off which.
57 =head2 register_class <moniker> <component_class>
59 Registers a class which isa ResultSourceProxy; equivalent to calling
61 $schema->register_source($moniker, $class->result_source_instance);
66 my ($self, $moniker, $to_register) = @_;
67 $self->register_source($moniker => $to_register->result_source_instance);
70 =head2 register_source <moniker> <result source>
72 Registers the result source in the schema with the given moniker
77 my ($self, $moniker, $source) = @_;
78 my %reg = %{$self->source_registrations};
79 $reg{$moniker} = $source;
80 $self->source_registrations(\%reg);
81 $source->schema($self);
82 if ($source->result_class) {
83 my %map = %{$self->class_mappings};
84 $map{$source->result_class} = $moniker;
85 $self->class_mappings(\%map);
91 my $class = $schema->class('Foo');
93 Retrieves the result class name for a given result source
98 my ($self, $moniker) = @_;
99 return $self->source($moniker)->result_class;
104 my $source = $schema->source('Foo');
106 Returns the result source object for the registered name
111 my ($self, $moniker) = @_;
112 my $sreg = $self->source_registrations;
113 return $sreg->{$moniker} if exists $sreg->{$moniker};
115 # if we got here, they probably passed a full class name
116 my $mapped = $self->class_mappings->{$moniker};
117 $self->throw_exception("Can't find source for ${moniker}")
118 unless $mapped && exists $sreg->{$mapped};
119 return $sreg->{$mapped};
124 my @source_monikers = $schema->sources;
126 Returns the source monikers of all source registrations on this schema
130 sub sources { return keys %{shift->source_registrations}; }
134 my $rs = $schema->resultset('Foo');
136 Returns the resultset for the registered moniker
141 my ($self, $moniker) = @_;
142 return $self->source($moniker)->resultset;
145 =head2 load_classes [<classes>, (<class>, <class>), {<namespace> => [<classes>]}]
147 Uses L<Module::Find> to find all classes under the database class' namespace,
148 or uses the classes you select. Then it loads the component (using L<use>),
149 and registers them (using B<register_class>);
151 It is possible to comment out classes with a leading '#', but note that perl
152 will think it's a mistake (trying to use a comment in a qw list) so you'll
153 need to add "no warnings 'qw';" before your load_classes call.
158 my ($class, @params) = @_;
163 foreach my $param (@params) {
164 if (ref $param eq 'ARRAY') {
165 # filter out commented entries
166 my @modules = grep { $_ !~ /^#/ } @$param;
168 push (@{$comps_for{$class}}, @modules);
170 elsif (ref $param eq 'HASH') {
171 # more than one namespace possible
172 for my $comp ( keys %$param ) {
173 # filter out commented entries
174 my @modules = grep { $_ !~ /^#/ } @{$param->{$comp}};
176 push (@{$comps_for{$comp}}, @modules);
180 # filter out commented entries
181 push (@{$comps_for{$class}}, $param) if $param !~ /^#/;
185 eval "require Module::Find;";
186 $class->throw_exception("No arguments to load_classes and couldn't load".
187 " Module::Find ($@)") if $@;
188 my @comp = map { substr $_, length "${class}::" } Module::Find::findallmod($class);
189 $comps_for{$class} = \@comp;
192 foreach my $prefix (keys %comps_for) {
193 foreach my $comp (@{$comps_for{$prefix}||[]}) {
194 my $comp_class = "${prefix}::${comp}";
195 eval "use $comp_class"; # If it fails, assume the user fixed it
197 die $@ unless $@ =~ /Can't locate/;
199 $class->register_class($comp => $comp_class);
200 # if $class->can('result_source_instance');
205 =head2 compose_connection <target> <@db_info>
207 This is the most important method in this class. it takes a target namespace,
208 as well as dbh connection info, and creates a L<DBIx::Class::DB> class as
209 well as subclasses for each of your database classes in this namespace, using
212 It will also setup a ->class method on the target class, which lets you
213 resolve database classes based on the schema component name, for example
215 MyApp::DB->class('Foo') # returns MyApp::DB::Foo,
216 # which ISA MyApp::Schema::Foo
218 This is the recommended API for accessing Schema generated classes, and
219 using it might give you instant advantages with future versions of DBIC.
221 WARNING: Loading components into Schema classes after compose_connection
222 may not cause them to be seen by the classes in your target namespace due
223 to the dispatch table approach used by Class::C3. If you do this you may find
224 you need to call Class::C3->reinitialize() afterwards to get the behaviour
229 sub compose_connection {
230 my ($self, $target, @info) = @_;
231 my $base = 'DBIx::Class::ResultSetProxy';
232 eval "require ${base};";
233 $self->throw_exception("No arguments to load_classes and couldn't load".
234 " ${base} ($@)") if $@;
236 if ($self eq $target) {
237 # Pathological case, largely caused by the docs on early C::M::DBIC::Plain
238 foreach my $moniker ($self->sources) {
239 my $source = $self->source($moniker);
240 my $class = $source->result_class;
241 $self->inject_base($class, $base);
242 $class->mk_classdata(resultset_instance => $source->resultset);
243 $class->mk_classdata(class_resolver => $self);
245 $self->connection(@info);
249 my $schema = $self->compose_namespace($target, $base);
252 *{"${target}::schema"} = sub { $schema };
255 $schema->connection(@info);
256 foreach my $moniker ($schema->sources) {
257 my $source = $schema->source($moniker);
258 my $class = $source->result_class;
259 #warn "$moniker $class $source ".$source->storage;
260 $class->mk_classdata(result_source_instance => $source);
261 $class->mk_classdata(resultset_instance => $source->resultset);
262 $class->mk_classdata(class_resolver => $schema);
267 sub compose_namespace {
268 my ($self, $target, $base) = @_;
269 my %reg = %{ $self->source_registrations };
272 my $schema = $self->clone;
273 foreach my $moniker ($schema->sources) {
274 my $source = $schema->source($moniker);
275 my $target_class = "${target}::${moniker}";
277 $target_class => $source->result_class, ($base ? $base : ())
279 $source->result_class($target_class);
283 foreach my $meth (qw/class source resultset/) {
284 *{"${target}::${meth}"} =
285 sub { shift->schema->$meth(@_) };
291 =head2 setup_connection_class <$target> <@info>
293 Sets up a database connection class to inject between the schema
294 and the subclasses the schema creates.
298 sub setup_connection_class {
299 my ($class, $target, @info) = @_;
300 $class->inject_base($target => 'DBIx::Class::DB');
301 #$target->load_components('DB');
302 $target->connection(@info);
305 =head2 connection(@args)
307 Instantiates a new Storage object of type storage_type and passes the
308 arguments to $storage->connect_info. Sets the connection in-place on
314 my ($self, @info) = @_;
315 my $storage_class = $self->storage_type;
316 $storage_class = 'DBIx::Class::Storage'.$storage_class
317 if $storage_class =~ m/^::/;
318 eval "require ${storage_class};";
319 $self->throw_exception("No arguments to load_classes and couldn't load".
320 " ${storage_class} ($@)") if $@;
321 my $storage = $storage_class->new;
322 $storage->connect_info(\@info);
323 $self->storage($storage);
327 =head2 connect(@info)
329 Conveneience method, equivalent to $schema->clone->connection(@info)
333 sub connect { shift->clone->connection(@_) }
337 Begins a transaction (does nothing if AutoCommit is off).
341 sub txn_begin { shift->storage->txn_begin }
345 Commits the current transaction.
349 sub txn_commit { shift->storage->txn_commit }
353 Rolls back the current transaction.
357 sub txn_rollback { shift->storage->txn_rollback }
361 Clones the schema and its associated result_source objects and returns the
368 my $clone = bless({ (ref $self ? %$self : ()) }, ref $self || $self);
369 foreach my $moniker ($self->sources) {
370 my $source = $self->source($moniker);
371 my $new = $source->new($source);
372 $clone->register_source($moniker => $new);
377 =head2 populate($moniker, \@data);
379 Populates the source registered with the given moniker with the supplied data.
380 @data should be a list of listrefs, the first containing column names, the
381 second matching values - i.e.
383 $schema->populate('Foo', [
384 [ qw/foo_id foo_string/ ],
393 my ($self, $name, $data) = @_;
394 my $rs = $self->resultset($name);
395 my @names = @{shift(@$data)};
396 foreach my $item (@$data) {
398 @create{@names} = @$item;
399 $rs->create(\%create);
403 =head2 throw_exception
405 Defaults to using Carp::Clan to report errors from user perspective.
409 sub throw_exception {
418 Matt S. Trout <mst@shadowcatsystems.co.uk>
422 You may distribute this code under the same terms as Perl itself.