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