bfc27cd9c6c7fb7fe8df75335cdddaf18d5cdd85
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Schema.pm
1 package DBIx::Class::Schema;
2
3 use strict;
4 use warnings;
5
6 use Carp qw/croak/;
7 use UNIVERSAL::require;
8
9 use base qw/DBIx::Class/;
10
11 __PACKAGE__->load_components(qw/Exception/);
12 __PACKAGE__->mk_classdata('class_mappings' => {});
13 __PACKAGE__->mk_classdata('source_registrations' => {});
14 __PACKAGE__->mk_classdata('storage_type' => '::DBI');
15 __PACKAGE__->mk_classdata('storage');
16
17 =head1 NAME
18
19 DBIx::Class::Schema - composable schemas
20
21 =head1 SYNOPSIS
22
23   package My::Schema;
24   use base qw/DBIx::Class::Schema/;
25   
26   # load My::Schema::Foo, My::Schema::Bar, My::Schema::Baz
27   __PACKAGE__->load_classes(qw/Foo Bar Baz/);
28
29   package My::Schema::Foo;
30   use base qw/DBIx::Class/;
31   __PACKAGE__->load_components(qw/PK::Auto::Pg Core/); # for example
32   __PACKAGE__->table('foo');
33
34   my $schema1 = My::Schema->connect(
35     $dsn,
36     $user,
37     $password,
38     $attrs
39   );
40
41   my $schema2 = My::Schema->connect( ... );
42
43   # fetch objects using My::Schema::Foo
44   my $resultset = $schema1->resultset('Foo')->search( ... );
45   my @objects = $schema2->resultset('Foo')->search( ... );
46
47 =head1 DESCRIPTION
48
49 Creates database classes based on a schema. This is the recommended way to
50 use L<DBIx::Class> and allows you to use more than one concurrent connection
51 with your classes.
52
53 NB: If you're used to L<Class::DBI> it's worth reading the L</SYNOPSIS>
54 carefully as DBIx::Class does things a little differently. Note in
55 particular which module inherits off which.
56
57 =head1 METHODS
58
59 =head2 register_class <moniker> <component_class>
60
61 Registers a class which isa ResultSourceProxy; equivalent to calling
62
63   $schema->register_source($moniker, $class->result_source_instance);
64
65 =cut
66
67 sub register_class {
68   my ($self, $moniker, $to_register) = @_;
69   $self->register_source($moniker => $to_register->result_source_instance);
70 }
71
72 =head2 register_source <moniker> <result source>
73
74 Registers the result source in the schema with the given moniker
75
76 =cut
77
78 sub register_source {
79   my ($self, $moniker, $source) = @_;
80   my %reg = %{$self->source_registrations};
81   $reg{$moniker} = $source;
82   $self->source_registrations(\%reg);
83   $source->schema($self);
84   if ($source->result_class) {
85     my %map = %{$self->class_mappings};
86     $map{$source->result_class} = $moniker;
87     $self->class_mappings(\%map);
88   }
89
90
91 =head2 class
92
93   my $class = $schema->class('Foo');
94
95 Retrieves the result class name for a given result source
96
97 =cut
98
99 sub class {
100   my ($self, $moniker) = @_;
101   return $self->source($moniker)->result_class;
102 }
103
104 =head2 source
105
106   my $source = $schema->source('Foo');
107
108 Returns the result source object for the registered name
109
110 =cut
111
112 sub source {
113   my ($self, $moniker) = @_;
114   my $sreg = $self->source_registrations;
115   return $sreg->{$moniker} if exists $sreg->{$moniker};
116
117   # if we got here, they probably passed a full class name
118   my $mapped = $self->class_mappings->{$moniker};
119   croak "Can't find source for ${moniker}"
120     unless $mapped && exists $sreg->{$mapped};
121   return $sreg->{$mapped};
122 }
123
124 =head2 sources
125
126   my @source_monikers = $schema->sources;
127
128 Returns the source monikers of all source registrations on this schema
129
130 =cut
131
132 sub sources { return keys %{shift->source_registrations}; }
133
134 =head2 resultset
135
136   my $rs = $schema->resultset('Foo');
137
138 Returns the resultset for the registered moniker
139
140 =cut
141
142 sub resultset {
143   my ($self, $moniker) = @_;
144   return $self->source($moniker)->resultset;
145 }
146
147 =head2  load_classes [<classes>, (<class>, <class>), {<namespace> => [<classes>]}]
148
149 Uses L<Module::Find> to find all classes under the database class' namespace,
150 or uses the classes you select.  Then it loads the component (using L<use>), 
151 and registers them (using B<register_class>);
152
153 It is possible to comment out classes with a leading '#', but note that perl
154 will think it's a mistake (trying to use a comment in a qw list) so you'll
155 need to add "no warnings 'qw';" before your load_classes call.
156
157 =cut
158
159 sub load_classes {
160   my ($class, @params) = @_;
161   
162   my %comps_for;
163   
164   if (@params) {
165     foreach my $param (@params) {
166       if (ref $param eq 'ARRAY') {
167         # filter out commented entries
168         my @modules = grep { $_ !~ /^#/ } @$param;
169         
170         push (@{$comps_for{$class}}, @modules);
171       }
172       elsif (ref $param eq 'HASH') {
173         # more than one namespace possible
174         for my $comp ( keys %$param ) {
175           # filter out commented entries
176           my @modules = grep { $_ !~ /^#/ } @{$param->{$comp}};
177
178           push (@{$comps_for{$comp}}, @modules);
179         }
180       }
181       else {
182         # filter out commented entries
183         push (@{$comps_for{$class}}, $param) if $param !~ /^#/;
184       }
185     }
186   } else {
187     eval "require Module::Find;";
188     $class->throw("No arguments to load_classes and couldn't load".
189       " Module::Find ($@)") if $@;
190     my @comp = map { substr $_, length "${class}::"  } Module::Find::findallmod($class);
191     $comps_for{$class} = \@comp;
192   }
193
194   foreach my $prefix (keys %comps_for) {
195     foreach my $comp (@{$comps_for{$prefix}||[]}) {
196       my $comp_class = "${prefix}::${comp}";
197       eval "use $comp_class"; # If it fails, assume the user fixed it
198       if ($@) {
199         die $@ unless $@ =~ /Can't locate/;
200       }
201       $class->register_class($comp => $comp_class);
202       #  if $class->can('result_source_instance');
203     }
204   }
205 }
206
207 =head2 compose_connection <target> <@db_info>
208
209 This is the most important method in this class. it takes a target namespace,
210 as well as dbh connection info, and creates a L<DBIx::Class::DB> class as
211 well as subclasses for each of your database classes in this namespace, using
212 this connection.
213
214 It will also setup a ->class method on the target class, which lets you
215 resolve database classes based on the schema component name, for example
216
217   MyApp::DB->class('Foo') # returns MyApp::DB::Foo, 
218                           # which ISA MyApp::Schema::Foo
219
220 This is the recommended API for accessing Schema generated classes, and 
221 using it might give you instant advantages with future versions of DBIC.
222
223 WARNING: Loading components into Schema classes after compose_connection
224 may not cause them to be seen by the classes in your target namespace due
225 to the dispatch table approach used by Class::C3. If you do this you may find
226 you need to call Class::C3->reinitialize() afterwards to get the behaviour
227 you expect.
228
229 =cut
230
231 sub compose_connection {
232   my ($self, $target, @info) = @_;
233   my $base = 'DBIx::Class::ResultSetProxy';
234   $base->require;
235
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);
244     }
245     return $self;
246   }
247
248   my $schema = $self->compose_namespace($target, $base);
249   $schema->connection(@info);
250   foreach my $moniker ($schema->sources) {
251     my $source = $schema->source($moniker);
252     my $class = $source->result_class;
253     #warn "$moniker $class $source ".$source->storage;
254     $class->mk_classdata(result_source_instance => $source);
255     $class->mk_classdata(resultset_instance => $source->resultset);
256     $class->mk_classdata(class_resolver => $schema);
257   }
258   return $schema;
259 }
260
261 sub compose_namespace {
262   my ($self, $target, $base) = @_;
263   my %reg = %{ $self->source_registrations };
264   my %target;
265   my %map;
266   my $schema = $self->clone;
267   foreach my $moniker ($schema->sources) {
268     my $source = $schema->source($moniker);
269     my $target_class = "${target}::${moniker}";
270     $self->inject_base(
271       $target_class => $source->result_class, ($base ? $base : ())
272     );
273     $source->result_class($target_class);
274   }
275   {
276     no strict 'refs';
277     *{"${target}::schema"} =
278       sub { $schema };
279     foreach my $meth (qw/class source resultset/) {
280       *{"${target}::${meth}"} =
281         sub { shift->schema->$meth(@_) };
282     }
283   }
284   return $schema;
285 }
286
287 =head2 setup_connection_class <$target> <@info>
288
289 Sets up a database connection class to inject between the schema
290 and the subclasses the schema creates.
291
292 =cut
293
294 sub setup_connection_class {
295   my ($class, $target, @info) = @_;
296   $class->inject_base($target => 'DBIx::Class::DB');
297   #$target->load_components('DB');
298   $target->connection(@info);
299 }
300
301 =head2 connection(@args)
302
303 Instantiates a new Storage object of type storage_type and passes the
304 arguments to $storage->connect_info. Sets the connection in-place on
305 the schema.
306
307 =cut
308
309 sub connection {
310   my ($self, @info) = @_;
311   my $storage_class = $self->storage_type;
312   $storage_class = 'DBIx::Class::Storage'.$storage_class
313     if $storage_class =~ m/^::/;
314   $storage_class->require;
315   my $storage = $storage_class->new;
316   $storage->connect_info(\@info);
317   $self->storage($storage);
318   return $self;
319 }
320
321 =head2 connect(@info)
322
323 Conveneience method, equivalent to $schema->clone->connection(@info)
324
325 =cut
326
327 sub connect { shift->clone->connection(@_) };
328
329 =head2 clone
330
331 Clones the schema and its associated result_source objects and returns the
332 copy.
333
334 =cut
335
336 sub clone {
337   my ($self) = @_;
338   my $clone = bless({ (ref $self ? %$self : ()) }, ref $self || $self);
339   foreach my $moniker ($self->sources) {
340     my $source = $self->source($moniker);
341     my $new = $source->new($source);
342     $clone->register_source($moniker => $new);
343   }
344   return $clone;
345 }
346
347 1;
348
349 =head1 AUTHORS
350
351 Matt S. Trout <mst@shadowcatsystems.co.uk>
352
353 =head1 LICENSE
354
355 You may distribute this code under the same terms as Perl itself.
356
357 =cut
358