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