Minor documentation
[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::Clan qw/^DBIx::Class/;
7
8 use base qw/DBIx::Class/;
9
10 __PACKAGE__->mk_classdata('class_mappings' => {});
11 __PACKAGE__->mk_classdata('source_registrations' => {});
12 __PACKAGE__->mk_classdata('storage_type' => '::DBI');
13 __PACKAGE__->mk_classdata('storage');
14
15 =head1 NAME
16
17 DBIx::Class::Schema - composable schemas
18
19 =head1 SYNOPSIS
20
21   package My::Schema;
22   use base qw/DBIx::Class::Schema/;
23   
24   # load My::Schema::Foo, My::Schema::Bar, My::Schema::Baz
25   __PACKAGE__->load_classes(qw/Foo Bar Baz/);
26
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');
31
32   # Elsewhere in your code:
33   my $schema1 = My::Schema->connect(
34     $dsn,
35     $user,
36     $password,
37     $attrs
38   );
39
40   my $schema2 = My::Schema->connect( ... );
41
42   # fetch objects using My::Schema::Foo
43   my $resultset = $schema1->resultset('Foo')->search( ... );
44   my @objects = $schema2->resultset('Foo')->search( ... );
45
46 =head1 DESCRIPTION
47
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
50 with your classes.
51
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.
55
56 =head1 METHODS
57
58 =head2 register_class <moniker> <component_class>
59
60 Registers a class which isa ResultSourceProxy; equivalent to calling
61
62   $schema->register_source($moniker, $class->result_source_instance);
63
64 =cut
65
66 sub register_class {
67   my ($self, $moniker, $to_register) = @_;
68   $self->register_source($moniker => $to_register->result_source_instance);
69 }
70
71 =head2 register_source <moniker> <result source>
72
73 Registers the result source in the schema with the given moniker
74
75 =cut
76
77 sub register_source {
78   my ($self, $moniker, $source) = @_;
79   my %reg = %{$self->source_registrations};
80   $reg{$moniker} = $source;
81   $self->source_registrations(\%reg);
82   $source->schema($self);
83   if ($source->result_class) {
84     my %map = %{$self->class_mappings};
85     $map{$source->result_class} = $moniker;
86     $self->class_mappings(\%map);
87   }
88
89
90 =head2 class
91
92   my $class = $schema->class('Foo');
93
94 Retrieves the result class name for a given result source
95
96 =cut
97
98 sub class {
99   my ($self, $moniker) = @_;
100   return $self->source($moniker)->result_class;
101 }
102
103 =head2 source
104
105   my $source = $schema->source('Foo');
106
107 Returns the result source object for the registered name
108
109 =cut
110
111 sub source {
112   my ($self, $moniker) = @_;
113   my $sreg = $self->source_registrations;
114   return $sreg->{$moniker} if exists $sreg->{$moniker};
115
116   # if we got here, they probably passed a full class name
117   my $mapped = $self->class_mappings->{$moniker};
118   $self->throw_exception("Can't find source for ${moniker}")
119     unless $mapped && exists $sreg->{$mapped};
120   return $sreg->{$mapped};
121 }
122
123 =head2 sources
124
125   my @source_monikers = $schema->sources;
126
127 Returns the source monikers of all source registrations on this schema
128
129 =cut
130
131 sub sources { return keys %{shift->source_registrations}; }
132
133 =head2 resultset
134
135   my $rs = $schema->resultset('Foo');
136
137 Returns the resultset for the registered moniker
138
139 =cut
140
141 sub resultset {
142   my ($self, $moniker) = @_;
143   return $self->source($moniker)->resultset;
144 }
145
146 =head2  load_classes [<classes>, (<class>, <class>), {<namespace> => [<classes>]}]
147
148 Uses L<Module::Find> to find all classes under the database class' namespace,
149 or uses the classes you select.  Then it loads the component (using L<use>), 
150 and registers them (using B<register_class>);
151
152 It is possible to comment out classes with a leading '#', but note that perl
153 will think it's a mistake (trying to use a comment in a qw list) so you'll
154 need to add "no warnings 'qw';" before your load_classes call.
155
156 =cut
157
158 sub load_classes {
159   my ($class, @params) = @_;
160   
161   my %comps_for;
162   
163   if (@params) {
164     foreach my $param (@params) {
165       if (ref $param eq 'ARRAY') {
166         # filter out commented entries
167         my @modules = grep { $_ !~ /^#/ } @$param;
168         
169         push (@{$comps_for{$class}}, @modules);
170       }
171       elsif (ref $param eq 'HASH') {
172         # more than one namespace possible
173         for my $comp ( keys %$param ) {
174           # filter out commented entries
175           my @modules = grep { $_ !~ /^#/ } @{$param->{$comp}};
176
177           push (@{$comps_for{$comp}}, @modules);
178         }
179       }
180       else {
181         # filter out commented entries
182         push (@{$comps_for{$class}}, $param) if $param !~ /^#/;
183       }
184     }
185   } else {
186     eval "require Module::Find;";
187     $class->throw_exception("No arguments to load_classes and couldn't load".
188       " Module::Find ($@)") if $@;
189     my @comp = map { substr $_, length "${class}::"  } Module::Find::findallmod($class);
190     $comps_for{$class} = \@comp;
191   }
192
193   foreach my $prefix (keys %comps_for) {
194     foreach my $comp (@{$comps_for{$prefix}||[]}) {
195       my $comp_class = "${prefix}::${comp}";
196       eval "use $comp_class"; # If it fails, assume the user fixed it
197       if ($@) {
198         die $@ unless $@ =~ /Can't locate/;
199       }
200       $class->register_class($comp => $comp_class);
201       #  if $class->can('result_source_instance');
202     }
203   }
204 }
205
206 =head2 compose_connection <target> <@db_info>
207
208 This is the most important method in this class. it takes a target namespace,
209 as well as dbh connection info, and creates a L<DBIx::Class::DB> class as
210 well as subclasses for each of your database classes in this namespace, using
211 this connection.
212
213 It will also setup a ->class method on the target class, which lets you
214 resolve database classes based on the schema component name, for example
215
216   MyApp::DB->class('Foo') # returns MyApp::DB::Foo, 
217                           # which ISA MyApp::Schema::Foo
218
219 This is the recommended API for accessing Schema generated classes, and 
220 using it might give you instant advantages with future versions of DBIC.
221
222 WARNING: Loading components into Schema classes after compose_connection
223 may not cause them to be seen by the classes in your target namespace due
224 to the dispatch table approach used by Class::C3. If you do this you may find
225 you need to call Class::C3->reinitialize() afterwards to get the behaviour
226 you expect.
227
228 =cut
229
230 sub compose_connection {
231   my ($self, $target, @info) = @_;
232   my $base = 'DBIx::Class::ResultSetProxy';
233   eval "require ${base};";
234   $self->throw_exception("No arguments to load_classes and couldn't load".
235       " ${base} ($@)") if $@;
236
237   if ($self eq $target) {
238     # Pathological case, largely caused by the docs on early C::M::DBIC::Plain
239     foreach my $moniker ($self->sources) {
240       my $source = $self->source($moniker);
241       my $class = $source->result_class;
242       $self->inject_base($class, $base);
243       $class->mk_classdata(resultset_instance => $source->resultset);
244       $class->mk_classdata(class_resolver => $self);
245     }
246     $self->connection(@info);
247     return $self;
248   }
249
250   my $schema = $self->compose_namespace($target, $base);
251   {
252     no strict 'refs';
253     *{"${target}::schema"} = sub { $schema };
254   }
255
256   $schema->connection(@info);
257   foreach my $moniker ($schema->sources) {
258     my $source = $schema->source($moniker);
259     my $class = $source->result_class;
260     #warn "$moniker $class $source ".$source->storage;
261     $class->mk_classdata(result_source_instance => $source);
262     $class->mk_classdata(resultset_instance => $source->resultset);
263     $class->mk_classdata(class_resolver => $schema);
264   }
265   return $schema;
266 }
267
268 sub compose_namespace {
269   my ($self, $target, $base) = @_;
270   my %reg = %{ $self->source_registrations };
271   my %target;
272   my %map;
273   my $schema = $self->clone;
274   foreach my $moniker ($schema->sources) {
275     my $source = $schema->source($moniker);
276     my $target_class = "${target}::${moniker}";
277     $self->inject_base(
278       $target_class => $source->result_class, ($base ? $base : ())
279     );
280     $source->result_class($target_class);
281   }
282   {
283     no strict 'refs';
284     foreach my $meth (qw/class source resultset/) {
285       *{"${target}::${meth}"} =
286         sub { shift->schema->$meth(@_) };
287     }
288   }
289   return $schema;
290 }
291
292 =head2 setup_connection_class <$target> <@info>
293
294 Sets up a database connection class to inject between the schema
295 and the subclasses the schema creates.
296
297 =cut
298
299 sub setup_connection_class {
300   my ($class, $target, @info) = @_;
301   $class->inject_base($target => 'DBIx::Class::DB');
302   #$target->load_components('DB');
303   $target->connection(@info);
304 }
305
306 =head2 connection(@args)
307
308 Instantiates a new Storage object of type storage_type and passes the
309 arguments to $storage->connect_info. Sets the connection in-place on
310 the schema.
311
312 =cut
313
314 sub connection {
315   my ($self, @info) = @_;
316   my $storage_class = $self->storage_type;
317   $storage_class = 'DBIx::Class::Storage'.$storage_class
318     if $storage_class =~ m/^::/;
319   eval "require ${storage_class};";
320   $self->throw_exception("No arguments to load_classes and couldn't load".
321       " ${storage_class} ($@)") if $@;
322   my $storage = $storage_class->new;
323   $storage->connect_info(\@info);
324   $self->storage($storage);
325   return $self;
326 }
327
328 =head2 connect(@info)
329
330 Conveneience method, equivalent to $schema->clone->connection(@info)
331
332 =cut
333
334 sub connect { shift->clone->connection(@_) }
335
336 =head2 txn_begin
337
338 Begins a transaction (does nothing if AutoCommit is off).
339
340 =cut
341
342 sub txn_begin { shift->storage->txn_begin }
343
344 =head2 txn_commit
345
346 Commits the current transaction.
347
348 =cut
349
350 sub txn_commit { shift->storage->txn_commit }
351
352 =head2 txn_rollback
353
354 Rolls back the current transaction.
355
356 =cut
357
358 sub txn_rollback { shift->storage->txn_rollback }
359
360 =head2 clone
361
362 Clones the schema and its associated result_source objects and returns the
363 copy.
364
365 =cut
366
367 sub clone {
368   my ($self) = @_;
369   my $clone = bless({ (ref $self ? %$self : ()) }, ref $self || $self);
370   foreach my $moniker ($self->sources) {
371     my $source = $self->source($moniker);
372     my $new = $source->new($source);
373     $clone->register_source($moniker => $new);
374   }
375   return $clone;
376 }
377
378 =head2 populate($moniker, \@data);
379
380 Populates the source registered with the given moniker with the supplied data.
381 @data should be a list of listrefs, the first containing column names, the
382 second matching values - i.e.
383
384 $schema->populate('Foo', [
385   [ qw/foo_id foo_string/ ],
386   [ 1, 'One' ],
387   [ 2, 'Two' ],
388   ...
389 ]);
390
391 =cut
392
393 sub populate {
394   my ($self, $name, $data) = @_;
395   my $rs = $self->resultset($name);
396   my @names = @{shift(@$data)};
397   foreach my $item (@$data) {
398     my %create;
399     @create{@names} = @$item;
400     $rs->create(\%create);
401   }
402 }
403
404 =head2 throw_exception
405
406 Defaults to using Carp::Clan to report errors from user perspective.
407
408 =cut
409
410 sub throw_exception {
411   my ($self) = shift;
412   croak @_;
413 }
414
415 1;
416
417 =head1 AUTHORS
418
419 Matt S. Trout <mst@shadowcatsystems.co.uk>
420
421 =head1 LICENSE
422
423 You may distribute this code under the same terms as Perl itself.
424
425 =cut
426