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