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