Commit | Line | Data |
a02675cd |
1 | package DBIx::Class::Schema; |
2 | |
3 | use strict; |
4 | use warnings; |
aa562407 |
5 | |
701da8c4 |
6 | use Carp::Clan qw/^DBIx::Class/; |
a02675cd |
7 | |
41a6f8c0 |
8 | use 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 | |
17 | DBIx::Class::Schema - composable schemas |
18 | |
19 | =head1 SYNOPSIS |
20 | |
24d67825 |
21 | package Library::Schema; |
c2da098a |
22 | use base qw/DBIx::Class::Schema/; |
a3d93194 |
23 | |
24d67825 |
24 | # load Library::Schema::CD, Library::Schema::Book, Library::Schema::DVD |
25 | __PACKAGE__->load_classes(qw/CD Book DVD/); |
c2da098a |
26 | |
24d67825 |
27 | package Library::Schema::CD; |
03312470 |
28 | use base qw/DBIx::Class/; |
77254782 |
29 | __PACKAGE__->load_components(qw/PK::Auto Core/); # for example |
24d67825 |
30 | __PACKAGE__->table('cd'); |
c2da098a |
31 | |
5d9076f2 |
32 | # Elsewhere in your code: |
24d67825 |
33 | my $schema1 = Library::Schema->connect( |
a3d93194 |
34 | $dsn, |
35 | $user, |
36 | $password, |
24d67825 |
37 | { AutoCommit => 0 }, |
a3d93194 |
38 | ); |
90ec6cad |
39 | |
24d67825 |
40 | my $schema2 = Library::Schema->connect($coderef_returning_dbh); |
c2da098a |
41 | |
24d67825 |
42 | # fetch objects using Library::Schema::DVD |
43 | my $resultset = $schema1->resultset('DVD')->search( ... ); |
44 | my @dvd_objects = $schema2->resultset('DVD')->search( ... ); |
c2da098a |
45 | |
46 | =head1 DESCRIPTION |
47 | |
a3d93194 |
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. |
429bd4f1 |
51 | |
03312470 |
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 | |
c2da098a |
56 | =head1 METHODS |
57 | |
87c4e602 |
58 | =head2 register_class |
59 | |
60 | =head3 Arguments: <moniker> <component_class> |
076652e8 |
61 | |
80c90f5d |
62 | Registers a class which isa ResultSourceProxy; equivalent to calling |
66d9ef6b |
63 | |
181a28f4 |
64 | $schema->register_source($moniker, $component_class->result_source_instance); |
076652e8 |
65 | |
c2da098a |
66 | =cut |
67 | |
a02675cd |
68 | sub register_class { |
0dc79249 |
69 | my ($self, $moniker, $to_register) = @_; |
70 | $self->register_source($moniker => $to_register->result_source_instance); |
74b92d9a |
71 | } |
72 | |
87c4e602 |
73 | =head2 register_source |
74 | |
75 | =head3 Arguments: <moniker> <result source> |
076652e8 |
76 | |
0dc79249 |
77 | Registers the result source in the schema with the given moniker |
076652e8 |
78 | |
79 | =cut |
80 | |
0dc79249 |
81 | sub register_source { |
82 | my ($self, $moniker, $source) = @_; |
83 | my %reg = %{$self->source_registrations}; |
84 | $reg{$moniker} = $source; |
85 | $self->source_registrations(\%reg); |
86 | $source->schema($self); |
87 | if ($source->result_class) { |
88 | my %map = %{$self->class_mappings}; |
89 | $map{$source->result_class} = $moniker; |
90 | $self->class_mappings(\%map); |
91 | } |
92 | } |
a02675cd |
93 | |
bfb2bd4f |
94 | =head2 class |
95 | |
24d67825 |
96 | my $class = $schema->class('CD'); |
bfb2bd4f |
97 | |
0dc79249 |
98 | Retrieves the result class name for a given result source |
bfb2bd4f |
99 | |
100 | =cut |
101 | |
102 | sub class { |
0dc79249 |
103 | my ($self, $moniker) = @_; |
104 | return $self->source($moniker)->result_class; |
bfb2bd4f |
105 | } |
106 | |
ea20d0fd |
107 | =head2 source |
108 | |
24d67825 |
109 | my $source = $schema->source('Book'); |
ea20d0fd |
110 | |
111 | Returns the result source object for the registered name |
112 | |
113 | =cut |
114 | |
115 | sub source { |
0dc79249 |
116 | my ($self, $moniker) = @_; |
117 | my $sreg = $self->source_registrations; |
118 | return $sreg->{$moniker} if exists $sreg->{$moniker}; |
119 | |
120 | # if we got here, they probably passed a full class name |
121 | my $mapped = $self->class_mappings->{$moniker}; |
701da8c4 |
122 | $self->throw_exception("Can't find source for ${moniker}") |
0dc79249 |
123 | unless $mapped && exists $sreg->{$mapped}; |
124 | return $sreg->{$mapped}; |
ea20d0fd |
125 | } |
126 | |
0dc79249 |
127 | =head2 sources |
128 | |
129 | my @source_monikers = $schema->sources; |
130 | |
131 | Returns the source monikers of all source registrations on this schema |
132 | |
133 | =cut |
134 | |
135 | sub sources { return keys %{shift->source_registrations}; } |
136 | |
ea20d0fd |
137 | =head2 resultset |
138 | |
24d67825 |
139 | my $rs = $schema->resultset('DVD'); |
ea20d0fd |
140 | |
0dc79249 |
141 | Returns the resultset for the registered moniker |
ea20d0fd |
142 | |
143 | =cut |
144 | |
145 | sub resultset { |
0dc79249 |
146 | my ($self, $moniker) = @_; |
147 | return $self->source($moniker)->resultset; |
ea20d0fd |
148 | } |
149 | |
87c4e602 |
150 | =head2 load_classes |
151 | |
152 | =head3 Arguments: [<classes>, (<class>, <class>), {<namespace> => [<classes>]}] |
076652e8 |
153 | |
429bd4f1 |
154 | Uses L<Module::Find> to find all classes under the database class' namespace, |
155 | or uses the classes you select. Then it loads the component (using L<use>), |
156 | and registers them (using B<register_class>); |
076652e8 |
157 | |
5ce32fc1 |
158 | It is possible to comment out classes with a leading '#', but note that perl |
159 | will think it's a mistake (trying to use a comment in a qw list) so you'll |
160 | need to add "no warnings 'qw';" before your load_classes call. |
161 | |
076652e8 |
162 | =cut |
163 | |
a02675cd |
164 | sub load_classes { |
5ce32fc1 |
165 | my ($class, @params) = @_; |
166 | |
167 | my %comps_for; |
168 | |
169 | if (@params) { |
170 | foreach my $param (@params) { |
171 | if (ref $param eq 'ARRAY') { |
172 | # filter out commented entries |
173 | my @modules = grep { $_ !~ /^#/ } @$param; |
174 | |
175 | push (@{$comps_for{$class}}, @modules); |
176 | } |
177 | elsif (ref $param eq 'HASH') { |
178 | # more than one namespace possible |
179 | for my $comp ( keys %$param ) { |
180 | # filter out commented entries |
181 | my @modules = grep { $_ !~ /^#/ } @{$param->{$comp}}; |
182 | |
183 | push (@{$comps_for{$comp}}, @modules); |
184 | } |
185 | } |
186 | else { |
187 | # filter out commented entries |
188 | push (@{$comps_for{$class}}, $param) if $param !~ /^#/; |
189 | } |
190 | } |
191 | } else { |
41a6f8c0 |
192 | eval "require Module::Find;"; |
701da8c4 |
193 | $class->throw_exception("No arguments to load_classes and couldn't load". |
41a6f8c0 |
194 | " Module::Find ($@)") if $@; |
5ce32fc1 |
195 | my @comp = map { substr $_, length "${class}::" } Module::Find::findallmod($class); |
196 | $comps_for{$class} = \@comp; |
41a6f8c0 |
197 | } |
5ce32fc1 |
198 | |
e6efde04 |
199 | my @to_register; |
200 | { |
201 | no warnings qw/redefine/; |
202 | local *Class::C3::reinitialize = sub { }; |
203 | foreach my $prefix (keys %comps_for) { |
204 | foreach my $comp (@{$comps_for{$prefix}||[]}) { |
205 | my $comp_class = "${prefix}::${comp}"; |
206 | eval "use $comp_class"; # If it fails, assume the user fixed it |
207 | if ($@) { |
3b24f6ea |
208 | $comp_class =~ s/::/\//g; |
209 | die $@ unless $@ =~ /Can't locate.+$comp_class\.pm\sin\s\@INC/; |
210 | warn $@ if $@; |
e6efde04 |
211 | } |
212 | push(@to_register, [ $comp, $comp_class ]); |
bfb2bd4f |
213 | } |
5ce32fc1 |
214 | } |
a02675cd |
215 | } |
e6efde04 |
216 | Class::C3->reinitialize; |
217 | |
218 | foreach my $to (@to_register) { |
219 | $class->register_class(@$to); |
220 | # if $class->can('result_source_instance'); |
221 | } |
a02675cd |
222 | } |
223 | |
87c4e602 |
224 | =head2 compose_connection |
225 | |
13765dad |
226 | =head3 Arguments: $target_ns, @db_info |
429bd4f1 |
227 | |
13765dad |
228 | =head3 Return value: $new_schema |
076652e8 |
229 | |
13765dad |
230 | Calls compose_namespace to the $target_ns, calls ->connection(@db_info) on |
231 | the new schema, then injects the ResultSetProxy component and a |
232 | resultset_instance classdata entry on all the new classes in order to support |
233 | $target_ns::Class->search(...) method calls. Primarily useful when you have |
234 | a specific need for classmethod access to a connection - in normal usage |
235 | ->connect is preferred. |
54540863 |
236 | |
076652e8 |
237 | =cut |
238 | |
a02675cd |
239 | sub compose_connection { |
ea20d0fd |
240 | my ($self, $target, @info) = @_; |
80c90f5d |
241 | my $base = 'DBIx::Class::ResultSetProxy'; |
8ef144ff |
242 | eval "require ${base};"; |
243 | $self->throw_exception("No arguments to load_classes and couldn't load". |
244 | " ${base} ($@)") if $@; |
be381829 |
245 | |
246 | if ($self eq $target) { |
247 | # Pathological case, largely caused by the docs on early C::M::DBIC::Plain |
248 | foreach my $moniker ($self->sources) { |
249 | my $source = $self->source($moniker); |
250 | my $class = $source->result_class; |
251 | $self->inject_base($class, $base); |
252 | $class->mk_classdata(resultset_instance => $source->resultset); |
253 | $class->mk_classdata(class_resolver => $self); |
254 | } |
50041f3c |
255 | $self->connection(@info); |
be381829 |
256 | return $self; |
257 | } |
258 | |
66d9ef6b |
259 | my $schema = $self->compose_namespace($target, $base); |
ecceadff |
260 | { |
261 | no strict 'refs'; |
262 | *{"${target}::schema"} = sub { $schema }; |
263 | } |
264 | |
66d9ef6b |
265 | $schema->connection(@info); |
0dc79249 |
266 | foreach my $moniker ($schema->sources) { |
267 | my $source = $schema->source($moniker); |
268 | my $class = $source->result_class; |
269 | #warn "$moniker $class $source ".$source->storage; |
8c49f629 |
270 | $class->mk_classdata(result_source_instance => $source); |
ea20d0fd |
271 | $class->mk_classdata(resultset_instance => $source->resultset); |
66d9ef6b |
272 | $class->mk_classdata(class_resolver => $schema); |
bfb2bd4f |
273 | } |
274 | return $schema; |
e678398e |
275 | } |
276 | |
77254782 |
277 | =head2 compose_namespace |
278 | |
13765dad |
279 | =head3 Arguments: $target_ns, $additional_base_class? |
280 | |
281 | =head3 Return value: $new_schema |
77254782 |
282 | |
13765dad |
283 | For each result source in the schema, creates a class in the target |
284 | namespace (e.g. $target_ns::CD, $target_ns::Artist) inheriting from the |
285 | corresponding classes attached to the current schema and a result source |
286 | to match attached to the new $schema object. If an additional base class is |
287 | given, injects this immediately behind the corresponding classes from the |
288 | current schema in the created classes' @ISA. |
77254782 |
289 | |
290 | =cut |
291 | |
e678398e |
292 | sub compose_namespace { |
66d9ef6b |
293 | my ($self, $target, $base) = @_; |
294 | my %reg = %{ $self->source_registrations }; |
11b78bd6 |
295 | my %target; |
296 | my %map; |
66d9ef6b |
297 | my $schema = $self->clone; |
e9100ff7 |
298 | { |
299 | no warnings qw/redefine/; |
300 | local *Class::C3::reinitialize = sub { }; |
301 | foreach my $moniker ($schema->sources) { |
302 | my $source = $schema->source($moniker); |
303 | my $target_class = "${target}::${moniker}"; |
304 | $self->inject_base( |
305 | $target_class => $source->result_class, ($base ? $base : ()) |
306 | ); |
307 | $source->result_class($target_class); |
308 | } |
b7951443 |
309 | } |
e9100ff7 |
310 | Class::C3->reinitialize(); |
11b78bd6 |
311 | { |
312 | no strict 'refs'; |
1edaf6fe |
313 | foreach my $meth (qw/class source resultset/) { |
314 | *{"${target}::${meth}"} = |
315 | sub { shift->schema->$meth(@_) }; |
316 | } |
11b78bd6 |
317 | } |
bfb2bd4f |
318 | return $schema; |
b7951443 |
319 | } |
320 | |
87c4e602 |
321 | =head2 setup_connection_class |
322 | |
323 | =head3 Arguments: <$target> <@info> |
076652e8 |
324 | |
429bd4f1 |
325 | Sets up a database connection class to inject between the schema |
326 | and the subclasses the schema creates. |
327 | |
076652e8 |
328 | =cut |
329 | |
b7951443 |
330 | sub setup_connection_class { |
331 | my ($class, $target, @info) = @_; |
63e9583a |
332 | $class->inject_base($target => 'DBIx::Class::DB'); |
333 | #$target->load_components('DB'); |
b7951443 |
334 | $target->connection(@info); |
335 | } |
336 | |
87c4e602 |
337 | =head2 connection |
338 | |
339 | =head3 Arguments: (@args) |
66d9ef6b |
340 | |
341 | Instantiates a new Storage object of type storage_type and passes the |
19feb86b |
342 | arguments to $storage->connect_info. Sets the connection in-place on |
66d9ef6b |
343 | the schema. |
344 | |
345 | =cut |
346 | |
347 | sub connection { |
348 | my ($self, @info) = @_; |
e59d3e5b |
349 | return $self if !@info && $self->storage; |
1e10a11d |
350 | my $storage_class = $self->storage_type; |
351 | $storage_class = 'DBIx::Class::Storage'.$storage_class |
352 | if $storage_class =~ m/^::/; |
8ef144ff |
353 | eval "require ${storage_class};"; |
354 | $self->throw_exception("No arguments to load_classes and couldn't load". |
355 | " ${storage_class} ($@)") if $@; |
66d9ef6b |
356 | my $storage = $storage_class->new; |
357 | $storage->connect_info(\@info); |
358 | $self->storage($storage); |
359 | return $self; |
360 | } |
361 | |
87c4e602 |
362 | =head2 connect |
363 | |
364 | =head3 Arguments: (@info) |
66d9ef6b |
365 | |
366 | Conveneience method, equivalent to $schema->clone->connection(@info) |
367 | |
368 | =cut |
369 | |
08b515f1 |
370 | sub connect { shift->clone->connection(@_) } |
371 | |
372 | =head2 txn_begin |
373 | |
374 | Begins a transaction (does nothing if AutoCommit is off). |
375 | |
376 | =cut |
377 | |
378 | sub txn_begin { shift->storage->txn_begin } |
379 | |
380 | =head2 txn_commit |
381 | |
382 | Commits the current transaction. |
383 | |
384 | =cut |
385 | |
386 | sub txn_commit { shift->storage->txn_commit } |
387 | |
388 | =head2 txn_rollback |
389 | |
390 | Rolls back the current transaction. |
391 | |
392 | =cut |
393 | |
394 | sub txn_rollback { shift->storage->txn_rollback } |
66d9ef6b |
395 | |
a62cf8d4 |
396 | =head2 txn_do |
397 | |
3b24f6ea |
398 | =head3 Arguments: <$coderef>, [@coderef_args] |
a62cf8d4 |
399 | |
3b24f6ea |
400 | Executes C<$coderef> with (optional) arguments C<@coderef_args> |
401 | transactionally, returning its result (if any). If an exception is |
402 | caught, a rollback is issued and the exception is rethrown. If the |
403 | rollback fails, (i.e. throws an exception) an exception is thrown that |
404 | includes a "Rollback failed" message. |
a62cf8d4 |
405 | |
406 | For example, |
407 | |
24d67825 |
408 | my $author_rs = $schema->resultset('Author')->find(1); |
a62cf8d4 |
409 | |
410 | my $coderef = sub { |
24d67825 |
411 | my ($author, @titles) = @_; |
a62cf8d4 |
412 | |
413 | # If any one of these fails, the entire transaction fails |
24d67825 |
414 | $author->create_related('books', { |
415 | title => $_ |
416 | }) foreach (@titles); |
a62cf8d4 |
417 | |
24d67825 |
418 | return $author->books; |
a62cf8d4 |
419 | }; |
420 | |
421 | my $rs; |
422 | eval { |
24d67825 |
423 | $rs = $schema->txn_do($coderef, $author_rs, qw/Night Day It/); |
a62cf8d4 |
424 | }; |
425 | |
426 | if ($@) { |
427 | my $error = $@; |
428 | if ($error =~ /Rollback failed/) { |
429 | die "something terrible has happened!"; |
430 | } else { |
431 | deal_with_failed_transaction(); |
a62cf8d4 |
432 | } |
433 | } |
434 | |
3b24f6ea |
435 | Nested transactions work as expected (i.e. only the outermost |
24d67825 |
436 | transaction will issue a txn_commit on the Schema's storage), and |
437 | txn_do() can be called in void, scalar and list context and it will |
438 | behave as expected. |
a62cf8d4 |
439 | |
440 | =cut |
441 | |
442 | sub txn_do { |
443 | my ($self, $coderef, @args) = @_; |
444 | |
171dadd7 |
445 | ref $self or $self->throw_exception |
446 | ('Cannot execute txn_do as a class method'); |
447 | ref $coderef eq 'CODE' or $self->throw_exception |
448 | ('$coderef must be a CODE reference'); |
a62cf8d4 |
449 | |
450 | my (@return_values, $return_value); |
451 | |
452 | $self->txn_begin; # If this throws an exception, no rollback is needed |
453 | |
454 | my $wantarray = wantarray; # Need to save this since it's reset in eval{} |
455 | |
456 | eval { |
24d67825 |
457 | # Need to differentiate between scalar/list context to allow for |
458 | # returning a list in scalar context to get the size of the list |
eeb34228 |
459 | |
a62cf8d4 |
460 | if ($wantarray) { |
eeb34228 |
461 | # list context |
a62cf8d4 |
462 | @return_values = $coderef->(@args); |
eeb34228 |
463 | } elsif (defined $wantarray) { |
464 | # scalar context |
a62cf8d4 |
465 | $return_value = $coderef->(@args); |
eeb34228 |
466 | } else { |
467 | # void context |
468 | $coderef->(@args); |
a62cf8d4 |
469 | } |
470 | $self->txn_commit; |
471 | }; |
472 | |
473 | if ($@) { |
474 | my $error = $@; |
475 | |
476 | eval { |
477 | $self->txn_rollback; |
478 | }; |
479 | |
480 | if ($@) { |
481 | my $rollback_error = $@; |
482 | my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION"; |
483 | $self->throw_exception($error) # propagate nested rollback |
484 | if $rollback_error =~ /$exception_class/; |
485 | |
486 | $self->throw_exception("Transaction aborted: $error. Rollback failed: ". |
487 | $rollback_error); |
488 | } else { |
489 | $self->throw_exception($error); # txn failed but rollback succeeded |
490 | } |
491 | } |
492 | |
493 | return $wantarray ? @return_values : $return_value; |
494 | } |
495 | |
66d9ef6b |
496 | =head2 clone |
497 | |
498 | Clones the schema and its associated result_source objects and returns the |
499 | copy. |
500 | |
501 | =cut |
502 | |
503 | sub clone { |
504 | my ($self) = @_; |
505 | my $clone = bless({ (ref $self ? %$self : ()) }, ref $self || $self); |
506 | foreach my $moniker ($self->sources) { |
507 | my $source = $self->source($moniker); |
508 | my $new = $source->new($source); |
509 | $clone->register_source($moniker => $new); |
510 | } |
511 | return $clone; |
512 | } |
513 | |
87c4e602 |
514 | =head2 populate |
515 | |
516 | =head3 Arguments: ($moniker, \@data); |
a37a4697 |
517 | |
518 | Populates the source registered with the given moniker with the supplied data. |
519 | @data should be a list of listrefs, the first containing column names, the |
520 | second matching values - i.e. |
521 | |
24d67825 |
522 | $schema->populate('Artist', [ |
523 | [ qw/artistid name/ ], |
524 | [ 1, 'Popular Band' ], |
525 | [ 2, 'Indie Band' ], |
a62cf8d4 |
526 | ... |
527 | ]); |
a37a4697 |
528 | |
529 | =cut |
530 | |
531 | sub populate { |
532 | my ($self, $name, $data) = @_; |
533 | my $rs = $self->resultset($name); |
534 | my @names = @{shift(@$data)}; |
84e3c114 |
535 | my @created; |
a37a4697 |
536 | foreach my $item (@$data) { |
537 | my %create; |
538 | @create{@names} = @$item; |
84e3c114 |
539 | push(@created, $rs->create(\%create)); |
a37a4697 |
540 | } |
84e3c114 |
541 | return @created; |
a37a4697 |
542 | } |
543 | |
5160b401 |
544 | =head2 throw_exception |
701da8c4 |
545 | |
546 | Defaults to using Carp::Clan to report errors from user perspective. |
547 | |
548 | =cut |
549 | |
550 | sub throw_exception { |
551 | my ($self) = shift; |
552 | croak @_; |
553 | } |
554 | |
ec6704d4 |
555 | =head2 deploy (EXPERIMENTAL) |
1c339d71 |
556 | |
ec6704d4 |
557 | Attempts to deploy the schema to the current storage using SQL::Translator. |
558 | |
559 | Note that this feature is currently EXPERIMENTAL and may not work correctly |
560 | across all databases, or fully handle complex relationships. |
1c339d71 |
561 | |
562 | =cut |
563 | |
564 | sub deploy { |
cb561d1a |
565 | my ($self, $sqltargs) = @_; |
1c339d71 |
566 | $self->throw_exception("Can't deploy without storage") unless $self->storage; |
cb561d1a |
567 | $self->storage->deploy($self, undef, $sqltargs); |
1c339d71 |
568 | } |
569 | |
a02675cd |
570 | 1; |
c2da098a |
571 | |
c2da098a |
572 | =head1 AUTHORS |
573 | |
daec44b8 |
574 | Matt S. Trout <mst@shadowcatsystems.co.uk> |
c2da098a |
575 | |
576 | =head1 LICENSE |
577 | |
578 | You may distribute this code under the same terms as Perl itself. |
579 | |
580 | =cut |
581 | |