19434b4cfaeb39d1ce64aac38f69bb5bada31631
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Schema.pm
1 package DBIx::Class::Schema;
2
3 use strict;
4 use warnings;
5
6 use base 'DBIx::Class';
7
8 use DBIx::Class::Carp;
9 use Try::Tiny;
10 use Scalar::Util qw( weaken blessed refaddr );
11 use DBIx::Class::_Util qw(
12   false emit_loud_diag refdesc
13   refcount quote_sub scope_guard
14   is_exception dbic_internal_try
15   fail_on_internal_call emit_loud_diag
16 );
17 use Devel::GlobalDestruction;
18 use namespace::clean;
19
20 __PACKAGE__->mk_group_accessors( inherited => qw( storage exception_action ) );
21 __PACKAGE__->mk_classaccessor('storage_type' => '::DBI');
22 __PACKAGE__->mk_classaccessor('stacktrace' => $ENV{DBIC_TRACE} || 0);
23 __PACKAGE__->mk_classaccessor('default_resultset_attributes' => {});
24
25 # These two should have been private from the start but too late now
26 # Undocumented on purpose, hopefully it won't ever be necessary to
27 # screw with them
28 __PACKAGE__->mk_classaccessor('class_mappings' => {});
29 __PACKAGE__->mk_classaccessor('source_registrations' => {});
30
31 __PACKAGE__->mk_group_accessors( component_class => 'schema_sanity_checker' );
32 __PACKAGE__->schema_sanity_checker(
33   'DBIx::Class::Schema::SanityChecker'
34 );
35
36 =head1 NAME
37
38 DBIx::Class::Schema - composable schemas
39
40 =head1 SYNOPSIS
41
42   package Library::Schema;
43   use base qw/DBIx::Class::Schema/;
44
45   # load all Result classes in Library/Schema/Result/
46   __PACKAGE__->load_namespaces();
47
48   package Library::Schema::Result::CD;
49   use base qw/DBIx::Class::Core/;
50
51   __PACKAGE__->load_components(qw/InflateColumn::DateTime/); # for example
52   __PACKAGE__->table('cd');
53
54   # Elsewhere in your code:
55   my $schema1 = Library::Schema->connect(
56     $dsn,
57     $user,
58     $password,
59     { AutoCommit => 1 },
60   );
61
62   my $schema2 = Library::Schema->connect($coderef_returning_dbh);
63
64   # fetch objects using Library::Schema::Result::DVD
65   my $resultset = $schema1->resultset('DVD')->search( ... );
66   my @dvd_objects = $schema2->resultset('DVD')->search( ... );
67
68 =head1 DESCRIPTION
69
70 Creates database classes based on a schema. This is the recommended way to
71 use L<DBIx::Class> and allows you to use more than one concurrent connection
72 with your classes.
73
74 NB: If you're used to L<Class::DBI> it's worth reading the L</SYNOPSIS>
75 carefully, as DBIx::Class does things a little differently. Note in
76 particular which module inherits off which.
77
78 =head1 SETUP METHODS
79
80 =head2 load_namespaces
81
82 =over 4
83
84 =item Arguments: %options?
85
86 =back
87
88   package MyApp::Schema;
89   __PACKAGE__->load_namespaces();
90
91   __PACKAGE__->load_namespaces(
92      result_namespace => 'Res',
93      resultset_namespace => 'RSet',
94      default_resultset_class => '+MyApp::Othernamespace::RSet',
95   );
96
97 With no arguments, this method uses L<Module::Find> to load all of the
98 Result and ResultSet classes under the namespace of the schema from
99 which it is called.  For example, C<My::Schema> will by default find
100 and load Result classes named C<My::Schema::Result::*> and ResultSet
101 classes named C<My::Schema::ResultSet::*>.
102
103 ResultSet classes are associated with Result class of the same name.
104 For example, C<My::Schema::Result::CD> will get the ResultSet class
105 C<My::Schema::ResultSet::CD> if it is present.
106
107 Both Result and ResultSet namespaces are configurable via the
108 C<result_namespace> and C<resultset_namespace> options.
109
110 Another option, C<default_resultset_class> specifies a custom default
111 ResultSet class for Result classes with no corresponding ResultSet.
112
113 All of the namespace and classname options are by default relative to
114 the schema classname.  To specify a fully-qualified name, prefix it
115 with a literal C<+>.  For example, C<+Other::NameSpace::Result>.
116
117 =head3 Warnings
118
119 You will be warned if ResultSet classes are discovered for which there
120 are no matching Result classes like this:
121
122   load_namespaces found ResultSet class $classname with no corresponding Result class
123
124 If a ResultSource instance is found to already have a ResultSet class set
125 using L<resultset_class|DBIx::Class::ResultSource/resultset_class> to some
126 other class, you will be warned like this:
127
128   We found ResultSet class '$rs_class' for '$result_class', but it seems
129   that you had already set '$result_class' to use '$rs_set' instead
130
131 =head3 Examples
132
133   # load My::Schema::Result::CD, My::Schema::Result::Artist,
134   #    My::Schema::ResultSet::CD, etc...
135   My::Schema->load_namespaces;
136
137   # Override everything to use ugly names.
138   # In this example, if there is a My::Schema::Res::Foo, but no matching
139   #   My::Schema::RSets::Foo, then Foo will have its
140   #   resultset_class set to My::Schema::RSetBase
141   My::Schema->load_namespaces(
142     result_namespace => 'Res',
143     resultset_namespace => 'RSets',
144     default_resultset_class => 'RSetBase',
145   );
146
147   # Put things in other namespaces
148   My::Schema->load_namespaces(
149     result_namespace => '+Some::Place::Results',
150     resultset_namespace => '+Another::Place::RSets',
151   );
152
153 To search multiple namespaces for either Result or ResultSet classes,
154 use an arrayref of namespaces for that option.  In the case that the
155 same result (or resultset) class exists in multiple namespaces, later
156 entries in the list of namespaces will override earlier ones.
157
158   My::Schema->load_namespaces(
159     # My::Schema::Results_C::Foo takes precedence over My::Schema::Results_B::Foo :
160     result_namespace => [ 'Results_A', 'Results_B', 'Results_C' ],
161     resultset_namespace => [ '+Some::Place::RSets', 'RSets' ],
162   );
163
164 =cut
165
166 # Pre-pends our classname to the given relative classname or
167 #   class namespace, unless there is a '+' prefix, which will
168 #   be stripped.
169 sub _expand_relative_name {
170   my ($class, $name) = @_;
171   $name =~ s/^\+// or $name = "${class}::${name}";
172   return $name;
173 }
174
175 # Finds all modules in the supplied namespace, or if omitted in the
176 # namespace of $class. Untaints all findings as they can be assumed
177 # to be safe
178 sub _findallmod {
179   require Module::Find;
180   return map
181     { $_ =~ /(.+)/ }   # untaint result
182     Module::Find::findallmod( $_[1] || ref $_[0] || $_[0] )
183   ;
184 }
185
186 # returns a hash of $shortname => $fullname for every package
187 # found in the given namespaces ($shortname is with the $fullname's
188 # namespace stripped off)
189 sub _map_namespaces {
190   my ($me, $namespaces) = @_;
191
192   my %res;
193   for my $ns (@$namespaces) {
194     $res{ substr($_, length "${ns}::") } = $_
195       for $me->_findallmod($ns);
196   }
197
198   \%res;
199 }
200
201 # returns the result_source_instance for the passed class/object,
202 # or dies with an informative message (used by load_namespaces)
203 sub _ns_get_rsrc_instance {
204   my $me = shift;
205   my $rs_class = ref ($_[0]) || $_[0];
206
207   return dbic_internal_try {
208     $rs_class->result_source
209   } catch {
210     $me->throw_exception (
211       "Attempt to load_namespaces() class $rs_class failed - are you sure this is a real Result Class?: $_"
212     );
213   };
214 }
215
216 sub load_namespaces {
217   my ($class, %args) = @_;
218
219   my $result_namespace = delete $args{result_namespace} || 'Result';
220   my $resultset_namespace = delete $args{resultset_namespace} || 'ResultSet';
221
222   my $default_resultset_class = delete $args{default_resultset_class};
223
224   $default_resultset_class = $class->_expand_relative_name($default_resultset_class)
225     if $default_resultset_class;
226
227   $class->throw_exception('load_namespaces: unknown option(s): '
228     . join(q{,}, map { qq{'$_'} } keys %args))
229       if scalar keys %args;
230
231   for my $arg ($result_namespace, $resultset_namespace) {
232     $arg = [ $arg ] if ( $arg and ! ref $arg );
233
234     $class->throw_exception('load_namespaces: namespace arguments must be '
235       . 'a simple string or an arrayref')
236         if ref($arg) ne 'ARRAY';
237
238     $_ = $class->_expand_relative_name($_) for (@$arg);
239   }
240
241   my $results_by_source_name = $class->_map_namespaces($result_namespace);
242   my $resultsets_by_source_name = $class->_map_namespaces($resultset_namespace);
243
244   my @to_register;
245   {
246     # ensure classes are loaded and attached in inheritance order
247     for my $result_class (values %$results_by_source_name) {
248       $class->ensure_class_loaded($result_class);
249     }
250     my %inh_idx;
251     my @source_names_by_subclass_last = sort {
252
253       ($inh_idx{$a} ||=
254         scalar @{mro::get_linear_isa( $results_by_source_name->{$a} )}
255       )
256
257           <=>
258
259       ($inh_idx{$b} ||=
260         scalar @{mro::get_linear_isa( $results_by_source_name->{$b} )}
261       )
262
263     } keys(%$results_by_source_name);
264
265     foreach my $source_name (@source_names_by_subclass_last) {
266       my $result_class = $results_by_source_name->{$source_name};
267
268       my $preset_resultset_class = $class->_ns_get_rsrc_instance ($result_class)->resultset_class;
269       my $found_resultset_class = delete $resultsets_by_source_name->{$source_name};
270
271       if($preset_resultset_class && $preset_resultset_class ne 'DBIx::Class::ResultSet') {
272         if($found_resultset_class && $found_resultset_class ne $preset_resultset_class) {
273           carp "We found ResultSet class '$found_resultset_class' matching '$results_by_source_name->{$source_name}', but it seems "
274              . "that you had already set the '$results_by_source_name->{$source_name}' resultet to '$preset_resultset_class' instead";
275         }
276       }
277       # elsif - there may be *no* default_resultset_class, in which case we fallback to
278       # DBIx::Class::Resultset and there is nothing to check
279       elsif($found_resultset_class ||= $default_resultset_class) {
280         $class->ensure_class_loaded($found_resultset_class);
281         if(!$found_resultset_class->isa("DBIx::Class::ResultSet")) {
282             carp "load_namespaces found ResultSet class '$found_resultset_class' that does not subclass DBIx::Class::ResultSet";
283         }
284
285         $class->_ns_get_rsrc_instance ($result_class)->resultset_class($found_resultset_class);
286       }
287
288       my $source_name = $class->_ns_get_rsrc_instance ($result_class)->source_name || $source_name;
289
290       push(@to_register, [ $source_name, $result_class ]);
291     }
292   }
293
294   foreach (sort keys %$resultsets_by_source_name) {
295     carp "load_namespaces found ResultSet class '$resultsets_by_source_name->{$_}' "
296         .'with no corresponding Result class';
297   }
298
299   $class->register_class(@$_) for (@to_register);
300
301   return;
302 }
303
304 =head2 load_classes
305
306 =over 4
307
308 =item Arguments: @classes?, { $namespace => [ @classes ] }+
309
310 =back
311
312 L</load_classes> is an alternative method to L</load_namespaces>, both of
313 which serve similar purposes, each with different advantages and disadvantages.
314 In the general case you should use L</load_namespaces>, unless you need to
315 be able to specify that only specific classes are loaded at runtime.
316
317 With no arguments, this method uses L<Module::Find> to find all classes under
318 the schema's namespace. Otherwise, this method loads the classes you specify
319 (using L<use>), and registers them (using L</"register_class">).
320
321 It is possible to comment out classes with a leading C<#>, but note that perl
322 will think it's a mistake (trying to use a comment in a qw list), so you'll
323 need to add C<no warnings 'qw';> before your load_classes call.
324
325 If any classes found do not appear to be Result class files, you will
326 get the following warning:
327
328    Failed to load $comp_class. Can't find source_name method. Is
329    $comp_class really a full DBIC result class? Fix it, move it elsewhere,
330    or make your load_classes call more specific.
331
332 Example:
333
334   My::Schema->load_classes(); # loads My::Schema::CD, My::Schema::Artist,
335                               # etc. (anything under the My::Schema namespace)
336
337   # loads My::Schema::CD, My::Schema::Artist, Other::Namespace::Producer but
338   # not Other::Namespace::LinerNotes nor My::Schema::Track
339   My::Schema->load_classes(qw/ CD Artist #Track /, {
340     Other::Namespace => [qw/ Producer #LinerNotes /],
341   });
342
343 =cut
344
345 sub load_classes {
346   my ($class, @params) = @_;
347
348   my %comps_for;
349
350   if (@params) {
351     foreach my $param (@params) {
352       if (ref $param eq 'ARRAY') {
353         # filter out commented entries
354         my @modules = grep { $_ !~ /^#/ } @$param;
355
356         push (@{$comps_for{$class}}, @modules);
357       }
358       elsif (ref $param eq 'HASH') {
359         # more than one namespace possible
360         for my $comp ( keys %$param ) {
361           # filter out commented entries
362           my @modules = grep { $_ !~ /^#/ } @{$param->{$comp}};
363
364           push (@{$comps_for{$comp}}, @modules);
365         }
366       }
367       else {
368         # filter out commented entries
369         push (@{$comps_for{$class}}, $param) if $param !~ /^#/;
370       }
371     }
372   } else {
373     my @comp = map { substr $_, length "${class}::"  }
374                  $class->_findallmod($class);
375     $comps_for{$class} = \@comp;
376   }
377
378   my @to_register;
379   {
380     foreach my $prefix (keys %comps_for) {
381       foreach my $comp (@{$comps_for{$prefix}||[]}) {
382         my $comp_class = "${prefix}::${comp}";
383         $class->ensure_class_loaded($comp_class);
384
385         my $snsub = $comp_class->can('source_name');
386         if(! $snsub ) {
387           carp "Failed to load $comp_class. Can't find source_name method. Is $comp_class really a full DBIC result class? Fix it, move it elsewhere, or make your load_classes call more specific.";
388           next;
389         }
390         $comp = $snsub->($comp_class) || $comp;
391
392         push(@to_register, [ $comp, $comp_class ]);
393       }
394     }
395   }
396
397   foreach my $to (@to_register) {
398     $class->register_class(@$to);
399   }
400 }
401
402 =head2 storage_type
403
404 =over 4
405
406 =item Arguments: $storage_type|{$storage_type, \%args}
407
408 =item Return Value: $storage_type|{$storage_type, \%args}
409
410 =item Default value: DBIx::Class::Storage::DBI
411
412 =back
413
414 Set the storage class that will be instantiated when L</connect> is called.
415 If the classname starts with C<::>, the prefix C<DBIx::Class::Storage> is
416 assumed by L</connect>.
417
418 You want to use this to set subclasses of L<DBIx::Class::Storage::DBI>
419 in cases where the appropriate subclass is not autodetected.
420
421 If your storage type requires instantiation arguments, those are
422 defined as a second argument in the form of a hashref and the entire
423 value needs to be wrapped into an arrayref or a hashref.  We support
424 both types of refs here in order to play nice with your
425 Config::[class] or your choice. See
426 L<DBIx::Class::Storage::DBI::Replicated> for an example of this.
427
428 =head2 default_resultset_attributes
429
430 =over 4
431
432 =item Arguments: L<\%attrs|DBIx::Class::ResultSet/ATTRIBUTES>
433
434 =item Return Value: L<\%attrs|DBIx::Class::ResultSet/ATTRIBUTES>
435
436 =item Default value: None
437
438 =back
439
440 Like L<DBIx::Class::ResultSource/resultset_attributes> stores a collection
441 of resultset attributes, to be used as defaults for B<every> ResultSet
442 instance schema-wide. The same list of CAVEATS and WARNINGS applies, with
443 the extra downside of these defaults being practically inescapable: you will
444 B<not> be able to derive a ResultSet instance with these attributes unset.
445
446 Example:
447
448    package My::Schema;
449    use base qw/DBIx::Class::Schema/;
450    __PACKAGE__->default_resultset_attributes( { software_limit => 1 } );
451
452 =head2 schema_sanity_checker
453
454 =over 4
455
456 =item Arguments: L<perform_schema_sanity_checks()|DBIx::Class::Schema::SanityChecker/perform_schema_sanity_checks> provider
457
458 =item Return Value: L<perform_schema_sanity_checks()|DBIx::Class::Schema::SanityChecker/perform_schema_sanity_checks> provider
459
460 =item Default value: L<DBIx::Class::Schema::SanityChecker>
461
462 =back
463
464 On every call to L</connection> if the value of this attribute evaluates to
465 true, DBIC will invoke
466 C<< L<$schema_sanity_checker|/schema_sanity_checker>->L<perform_schema_sanity_checks|DBIx::Class::Schema::SanityChecker/perform_schema_sanity_checks>($schema) >>
467 before returning. The return value of this invocation is ignored.
468
469 B<YOU ARE STRONGLY URGED> to
470 L<learn more about the reason|DBIx::Class::Schema::SanityChecker/WHY> this
471 feature was introduced. Blindly disabling the checker on existing projects
472 B<may result in data corruption> after upgrade to C<< DBIC >= v0.082900 >>.
473
474 Example:
475
476    package My::Schema;
477    use base qw/DBIx::Class::Schema/;
478    __PACKAGE__->schema_sanity_checker('My::Schema::SanityChecker');
479
480    # or to disable all checks:
481    __PACKAGE__->schema_sanity_checker('');
482
483 Note: setting the value to C<undef> B<will not> have the desired effect,
484 due to an implementation detail of L<Class::Accessor::Grouped> inherited
485 accessors. In order to disable any and all checks you must set this
486 attribute to an empty string as shown in the second example above.
487
488 =head2 exception_action
489
490 =over 4
491
492 =item Arguments: $code_reference
493
494 =item Return Value: $code_reference
495
496 =item Default value: None
497
498 =back
499
500 When L</throw_exception> is invoked and L</exception_action> is set to a code
501 reference, this reference will be called instead of
502 L<DBIx::Class::Exception/throw>, with the exception message passed as the only
503 argument.
504
505 Your custom throw code B<must> rethrow the exception, as L</throw_exception> is
506 an integral part of DBIC's internal execution control flow.
507
508 Example:
509
510    package My::Schema;
511    use base qw/DBIx::Class::Schema/;
512    use My::ExceptionClass;
513    __PACKAGE__->exception_action(sub { My::ExceptionClass->throw(@_) });
514    __PACKAGE__->load_classes;
515
516    # or:
517    my $schema_obj = My::Schema->connect( .... );
518    $schema_obj->exception_action(sub { My::ExceptionClass->throw(@_) });
519
520 =head2 stacktrace
521
522 =over 4
523
524 =item Arguments: boolean
525
526 =back
527
528 Whether L</throw_exception> should include stack trace information.
529 Defaults to false normally, but defaults to true if C<$ENV{DBIC_TRACE}>
530 is true.
531
532 =head2 sqlt_deploy_hook
533
534 =over
535
536 =item Arguments: $sqlt_schema
537
538 =back
539
540 An optional sub which you can declare in your own Schema class that will get
541 passed the L<SQL::Translator::Schema> object when you deploy the schema via
542 L</create_ddl_dir> or L</deploy>.
543
544 For an example of what you can do with this, see
545 L<DBIx::Class::Manual::Cookbook/Adding Indexes And Functions To Your SQL>.
546
547 Note that sqlt_deploy_hook is called by L</deployment_statements>, which in turn
548 is called before L</deploy>. Therefore the hook can be used only to manipulate
549 the L<SQL::Translator::Schema> object before it is turned into SQL fed to the
550 database. If you want to execute post-deploy statements which can not be generated
551 by L<SQL::Translator>, the currently suggested method is to overload L</deploy>
552 and use L<dbh_do|DBIx::Class::Storage::DBI/dbh_do>.
553
554 =head1 METHODS
555
556 =head2 connect
557
558 =over 4
559
560 =item Arguments: @connectinfo
561
562 =item Return Value: $new_schema
563
564 =back
565
566 Creates and returns a new Schema object. The connection info set on it
567 is used to create a new instance of the storage backend and set it on
568 the Schema object.
569
570 See L<DBIx::Class::Storage::DBI/"connect_info"> for DBI-specific
571 syntax on the C<@connectinfo> argument, or L<DBIx::Class::Storage> in
572 general.
573
574 Note that C<connect_info> expects an arrayref of arguments, but
575 C<connect> does not. C<connect> wraps its arguments in an arrayref
576 before passing them to C<connect_info>.
577
578 =head3 Overloading
579
580 C<connect> is a convenience method. It is equivalent to calling
581 $schema->clone->connection(@connectinfo). To write your own overloaded
582 version, overload L</connection> instead.
583
584 =cut
585
586 sub connect :DBIC_method_is_indirect_sugar {
587   DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
588   shift->clone->connection(@_);
589 }
590
591 =head2 resultset
592
593 =over 4
594
595 =item Arguments: L<$source_name|DBIx::Class::ResultSource/source_name>
596
597 =item Return Value: L<$resultset|DBIx::Class::ResultSet>
598
599 =back
600
601   my $rs = $schema->resultset('DVD');
602
603 Returns the L<DBIx::Class::ResultSet> object for the registered source
604 name.
605
606 =cut
607
608 sub resultset {
609   my ($self, $source_name) = @_;
610   $self->throw_exception('resultset() expects a source name')
611     unless defined $source_name;
612   return $self->source($source_name)->resultset;
613 }
614
615 =head2 sources
616
617 =over 4
618
619 =item Return Value: L<@source_names|DBIx::Class::ResultSource/source_name>
620
621 =back
622
623   my @source_names = $schema->sources;
624
625 Lists names of all the sources registered on this Schema object.
626
627 =cut
628
629 sub sources { keys %{shift->source_registrations} }
630
631 =head2 source
632
633 =over 4
634
635 =item Arguments: L<$source_name|DBIx::Class::ResultSource/source_name>
636
637 =item Return Value: L<$result_source|DBIx::Class::ResultSource>
638
639 =back
640
641   my $source = $schema->source('Book');
642
643 Returns the L<DBIx::Class::ResultSource> object for the registered
644 source name.
645
646 =cut
647
648 sub source {
649   my ($self, $source_name) = @_;
650
651   $self->throw_exception("source() expects a source name")
652     unless $source_name;
653
654   my $source_registrations;
655
656   my $rsrc =
657     ( $source_registrations = $self->source_registrations )->{$source_name}
658       ||
659     # if we got here, they probably passed a full class name
660     $source_registrations->{ $self->class_mappings->{$source_name} || '' }
661       ||
662     $self->throw_exception( "Can't find source for ${source_name}" )
663   ;
664
665   # DO NOT REMOVE:
666   # We need to prevent alterations of pre-existing $@ due to where this call
667   # sits in the overall stack ( *unless* of course there is an actual error
668   # to report ). set_mro does alter $@ (and yes - it *can* throw an exception)
669   # We do not use local because set_mro *can* throw an actual exception
670   # We do not use a try/catch either, as on one hand it would slow things
671   # down for no reason (we would always rethrow), but also because adding *any*
672   # try/catch block below will segfault various threading tests on older perls
673   # ( which in itself is a FIXME but ENOTIMETODIG )
674   my $old_dollarat = $@;
675
676   no strict 'refs';
677   mro::set_mro($_, 'c3') for
678     grep
679       {
680         # some pseudo-sources do not have a result/resultset yet
681         defined $_
682           and
683         (
684           (
685             ${"${_}::__INITIAL_MRO_UPON_DBIC_LOAD__"}
686               ||= mro::get_mro($_)
687           )
688             ne
689           'c3'
690         )
691       }
692       map
693         { length ref $_ ? ref $_ : $_ }
694         ( $rsrc, $rsrc->result_class, $rsrc->resultset_class )
695   ;
696
697   # DO NOT REMOVE - see comment above
698   $@ = $old_dollarat;
699
700   $rsrc;
701 }
702
703 =head2 class
704
705 =over 4
706
707 =item Arguments: L<$source_name|DBIx::Class::ResultSource/source_name>
708
709 =item Return Value: $classname
710
711 =back
712
713   my $class = $schema->class('CD');
714
715 Retrieves the Result class name for the given source name.
716
717 =cut
718
719 sub class {
720   return shift->source(shift)->result_class;
721 }
722
723 =head2 txn_do
724
725 =over 4
726
727 =item Arguments: C<$coderef>, @coderef_args?
728
729 =item Return Value: The return value of $coderef
730
731 =back
732
733 Executes C<$coderef> with (optional) arguments C<@coderef_args> atomically,
734 returning its result (if any). Equivalent to calling $schema->storage->txn_do.
735 See L<DBIx::Class::Storage/"txn_do"> for more information.
736
737 This interface is preferred over using the individual methods L</txn_begin>,
738 L</txn_commit>, and L</txn_rollback> below.
739
740 WARNING: If you are connected with C<< AutoCommit => 0 >> the transaction is
741 considered nested, and you will still need to call L</txn_commit> to write your
742 changes when appropriate. You will also want to connect with C<< auto_savepoint =>
743 1 >> to get partial rollback to work, if the storage driver for your database
744 supports it.
745
746 Connecting with C<< AutoCommit => 1 >> is recommended.
747
748 =cut
749
750 sub txn_do {
751   my $self = shift;
752
753   $self->storage or $self->throw_exception
754     ('txn_do called on $schema without storage');
755
756   $self->storage->txn_do(@_);
757 }
758
759 =head2 txn_scope_guard
760
761 Runs C<txn_scope_guard> on the schema's storage. See
762 L<DBIx::Class::Storage/txn_scope_guard>.
763
764 =cut
765
766 sub txn_scope_guard {
767   my $self = shift;
768
769   $self->storage or $self->throw_exception
770     ('txn_scope_guard called on $schema without storage');
771
772   $self->storage->txn_scope_guard(@_);
773 }
774
775 =head2 txn_begin
776
777 Begins a transaction (does nothing if AutoCommit is off). Equivalent to
778 calling $schema->storage->txn_begin. See
779 L<DBIx::Class::Storage/"txn_begin"> for more information.
780
781 =cut
782
783 sub txn_begin {
784   my $self = shift;
785
786   $self->storage or $self->throw_exception
787     ('txn_begin called on $schema without storage');
788
789   $self->storage->txn_begin;
790 }
791
792 =head2 txn_commit
793
794 Commits the current transaction. Equivalent to calling
795 $schema->storage->txn_commit. See L<DBIx::Class::Storage/"txn_commit">
796 for more information.
797
798 =cut
799
800 sub txn_commit {
801   my $self = shift;
802
803   $self->storage or $self->throw_exception
804     ('txn_commit called on $schema without storage');
805
806   $self->storage->txn_commit;
807 }
808
809 =head2 txn_rollback
810
811 Rolls back the current transaction. Equivalent to calling
812 $schema->storage->txn_rollback. See
813 L<DBIx::Class::Storage/"txn_rollback"> for more information.
814
815 =cut
816
817 sub txn_rollback {
818   my $self = shift;
819
820   $self->storage or $self->throw_exception
821     ('txn_rollback called on $schema without storage');
822
823   $self->storage->txn_rollback;
824 }
825
826 =head2 storage
827
828   my $storage = $schema->storage;
829
830 Returns the L<DBIx::Class::Storage> object for this Schema. Grab this
831 if you want to turn on SQL statement debugging at runtime, or set the
832 quote character. For the default storage, the documentation can be
833 found in L<DBIx::Class::Storage::DBI>.
834
835 =head2 populate
836
837 =over 4
838
839 =item Arguments: L<$source_name|DBIx::Class::ResultSource/source_name>, [ \@column_list, \@row_values+ ] | [ \%col_data+ ]
840
841 =item Return Value: L<\@result_objects|DBIx::Class::Manual::ResultClass> (scalar context) | L<@result_objects|DBIx::Class::Manual::ResultClass> (list context)
842
843 =back
844
845 A convenience shortcut to L<DBIx::Class::ResultSet/populate>. Equivalent to:
846
847  $schema->resultset($source_name)->populate([...]);
848
849 =over 4
850
851 =item NOTE
852
853 The context of this method call has an important effect on what is
854 submitted to storage. In void context data is fed directly to fastpath
855 insertion routines provided by the underlying storage (most often
856 L<DBI/execute_for_fetch>), bypassing the L<new|DBIx::Class::Row/new> and
857 L<insert|DBIx::Class::Row/insert> calls on the
858 L<Result|DBIx::Class::Manual::ResultClass> class, including any
859 augmentation of these methods provided by components. For example if you
860 are using something like L<DBIx::Class::UUIDColumns> to create primary
861 keys for you, you will find that your PKs are empty.  In this case you
862 will have to explicitly force scalar or list context in order to create
863 those values.
864
865 =back
866
867 =cut
868
869 sub populate :DBIC_method_is_indirect_sugar {
870   DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
871
872   my ($self, $name, $data) = @_;
873   my $rs = $self->resultset($name)
874     or $self->throw_exception("'$name' is not a resultset");
875
876   return $rs->populate($data);
877 }
878
879 =head2 connection
880
881 =over 4
882
883 =item Arguments: @args
884
885 =item Return Value: $self
886
887 =back
888
889 Similar to L</connect> except sets the storage object and connection
890 data B<in-place> on C<$self>. You should probably be calling
891 L</connect> to get a properly L<cloned|/clone> Schema object instead.
892
893 If the accessor L</schema_sanity_checker> returns a true value C<$checker>,
894 the following call will take place before return:
895 C<< L<$checker|/schema_sanity_checker>->L<perform_schema_sanity_checks(C<$self>)|DBIx::Class::Schema::SanityChecker/perform_schema_sanity_checks> >>
896
897 =head3 Overloading
898
899 Overload C<connection> to change the behaviour of C<connect>.
900
901 =cut
902
903 my $default_off_stderr_blurb_emitted;
904 sub connection {
905   my ($self, @info) = @_;
906   return $self if !@info && $self->storage;
907
908   my ($storage_class, $args) = ref $self->storage_type
909     ? $self->_normalize_storage_type($self->storage_type)
910     : $self->storage_type
911   ;
912
913   $storage_class =~ s/^::/DBIx::Class::Storage::/;
914
915   dbic_internal_try {
916     $self->ensure_class_loaded ($storage_class);
917   }
918   catch {
919     $self->throw_exception(
920       "Unable to load storage class ${storage_class}: $_"
921     );
922   };
923
924   my $storage = $storage_class->new( $self => $args||{} );
925   $storage->connect_info(\@info);
926   $self->storage($storage);
927
928   if( my $checker = $self->schema_sanity_checker ) {
929     $checker->perform_schema_sanity_checks($self);
930   }
931
932   $self;
933 }
934
935 sub _normalize_storage_type {
936   my ($self, $storage_type) = @_;
937   if(ref $storage_type eq 'ARRAY') {
938     return @$storage_type;
939   } elsif(ref $storage_type eq 'HASH') {
940     return %$storage_type;
941   } else {
942     $self->throw_exception('Unsupported REFTYPE given: '. ref $storage_type);
943   }
944 }
945
946 =head2 compose_namespace
947
948 =over 4
949
950 =item Arguments: $target_namespace, $additional_base_class?
951
952 =item Return Value: $new_schema
953
954 =back
955
956 For each L<DBIx::Class::ResultSource> in the schema, this method creates a
957 class in the target namespace (e.g. $target_namespace::CD,
958 $target_namespace::Artist) that inherits from the corresponding classes
959 attached to the current schema.
960
961 It also attaches a corresponding L<DBIx::Class::ResultSource> object to the
962 new $schema object. If C<$additional_base_class> is given, the new composed
963 classes will inherit from first the corresponding class from the current
964 schema then the base class.
965
966 For example, for a schema with My::Schema::CD and My::Schema::Artist classes,
967
968   $schema->compose_namespace('My::DB', 'Base::Class');
969   print join (', ', @My::DB::CD::ISA) . "\n";
970   print join (', ', @My::DB::Artist::ISA) ."\n";
971
972 will produce the output
973
974   My::Schema::CD, Base::Class
975   My::Schema::Artist, Base::Class
976
977 =cut
978
979 sub compose_namespace {
980   my ($self, $target, $base) = @_;
981
982   my $schema = $self->clone;
983
984   $schema->source_registrations({});
985
986   # the original class-mappings must remain - otherwise
987   # reverse_relationship_info will not work
988   #$schema->class_mappings({});
989
990   {
991     foreach my $source_name ($self->sources) {
992       my $orig_source = $self->source($source_name);
993
994       my $target_class = "${target}::${source_name}";
995       $self->inject_base($target_class, $orig_source->result_class, ($base || ()) );
996
997       $schema->register_source(
998         $source_name,
999         $orig_source->clone(
1000           result_class => $target_class
1001         ),
1002       );
1003     }
1004
1005     # Legacy stuff, not inserting INDIRECT assertions
1006     quote_sub "${target}::${_}" => "shift->schema->$_(\@_)"
1007       for qw(class source resultset);
1008   }
1009
1010   # needed to cover the newly installed stuff via quote_sub above
1011   Class::C3->reinitialize if DBIx::Class::_ENV_::OLD_MRO;
1012
1013   # Give each composed class yet another *schema-less* source copy
1014   # this is used for the freeze/thaw cycle
1015   #
1016   # This is not covered by any tests directly, but is indirectly exercised
1017   # in t/cdbi/sweet/08pager by re-setting the schema on an existing object
1018   # FIXME - there is likely a much cheaper way to take care of this
1019   for my $source_name ($self->sources) {
1020
1021     my $target_class = "${target}::${source_name}";
1022
1023     $target_class->result_source_instance(
1024       $self->source($source_name)->clone(
1025         result_class => $target_class,
1026         schema => ( ref $schema || $schema ),
1027       )
1028     );
1029   }
1030
1031   return $schema;
1032 }
1033
1034 # LEGACY: The intra-call to this was removed in 66d9ef6b and then
1035 # the sub was de-documented way later in 249963d4. No way to be sure
1036 # nothing on darkpan is calling it directly, so keeping as-is
1037 sub setup_connection_class {
1038   my ($class, $target, @info) = @_;
1039   $class->inject_base($target => 'DBIx::Class::DB');
1040   #$target->load_components('DB');
1041   $target->connection(@info);
1042 }
1043
1044 =head2 svp_begin
1045
1046 Creates a new savepoint (does nothing outside a transaction).
1047 Equivalent to calling $schema->storage->svp_begin.  See
1048 L<DBIx::Class::Storage/"svp_begin"> for more information.
1049
1050 =cut
1051
1052 sub svp_begin {
1053   my ($self, $name) = @_;
1054
1055   $self->storage or $self->throw_exception
1056     ('svp_begin called on $schema without storage');
1057
1058   $self->storage->svp_begin($name);
1059 }
1060
1061 =head2 svp_release
1062
1063 Releases a savepoint (does nothing outside a transaction).
1064 Equivalent to calling $schema->storage->svp_release.  See
1065 L<DBIx::Class::Storage/"svp_release"> for more information.
1066
1067 =cut
1068
1069 sub svp_release {
1070   my ($self, $name) = @_;
1071
1072   $self->storage or $self->throw_exception
1073     ('svp_release called on $schema without storage');
1074
1075   $self->storage->svp_release($name);
1076 }
1077
1078 =head2 svp_rollback
1079
1080 Rollback to a savepoint (does nothing outside a transaction).
1081 Equivalent to calling $schema->storage->svp_rollback.  See
1082 L<DBIx::Class::Storage/"svp_rollback"> for more information.
1083
1084 =cut
1085
1086 sub svp_rollback {
1087   my ($self, $name) = @_;
1088
1089   $self->storage or $self->throw_exception
1090     ('svp_rollback called on $schema without storage');
1091
1092   $self->storage->svp_rollback($name);
1093 }
1094
1095 =head2 clone
1096
1097 =over 4
1098
1099 =item Arguments: %attrs?
1100
1101 =item Return Value: $new_schema
1102
1103 =back
1104
1105 Clones the schema and its associated result_source objects and returns the
1106 copy. The resulting copy will have the same attributes as the source schema,
1107 except for those attributes explicitly overridden by the provided C<%attrs>.
1108
1109 =cut
1110
1111 sub clone {
1112   my $self = shift;
1113
1114   my $clone = {
1115       (ref $self ? %$self : ()),
1116       (@_ == 1 && ref $_[0] eq 'HASH' ? %{ $_[0] } : @_),
1117   };
1118   bless $clone, (ref $self || $self);
1119
1120   $clone->$_(undef) for qw/class_mappings source_registrations storage/;
1121
1122   $clone->_copy_state_from($self);
1123
1124   return $clone;
1125 }
1126
1127 # Needed in Schema::Loader - if you refactor, please make a compatibility shim
1128 # -- Caelum
1129 sub _copy_state_from {
1130   my ($self, $from) = @_;
1131
1132   $self->class_mappings({ %{$from->class_mappings} });
1133   $self->source_registrations({ %{$from->source_registrations} });
1134
1135   # we use extra here as we want to leave the class_mappings as they are
1136   # but overwrite the source_registrations entry with the new source
1137   $self->register_extra_source( $_ => $from->source($_) )
1138     for $from->sources;
1139
1140   if ($from->storage) {
1141     $self->storage($from->storage);
1142     $self->storage->set_schema($self);
1143   }
1144 }
1145
1146 =head2 throw_exception
1147
1148 =over 4
1149
1150 =item Arguments: $message
1151
1152 =back
1153
1154 Throws an exception. Obeys the exemption rules of L<DBIx::Class::Carp> to report
1155 errors from outer-user's perspective. See L</exception_action> for details on overriding
1156 this method's behavior.  If L</stacktrace> is turned on, C<throw_exception>'s
1157 default behavior will provide a detailed stack trace.
1158
1159 =cut
1160
1161 sub throw_exception {
1162   my ($self, @args) = @_;
1163
1164   if (
1165     ! DBIx::Class::_Util::in_internal_try()
1166       and
1167     my $act = $self->exception_action
1168   ) {
1169
1170     my $guard_disarmed;
1171
1172     my $guard = scope_guard {
1173       return if $guard_disarmed;
1174       emit_loud_diag( emit_dups => 1, msg => "
1175
1176                     !!! DBIx::Class INTERNAL PANIC !!!
1177
1178 The exception_action() handler installed on '$self'
1179 aborted the stacktrace below via a longjmp (either via Return::Multilevel or
1180 plain goto, or Scope::Upper or something equally nefarious). There currently
1181 is nothing safe DBIx::Class can do, aside from displaying this error. A future
1182 version ( 0.082900, when available ) will reduce the cases in which the
1183 handler is invoked, but this is neither a complete solution, nor can it do
1184 anything for other software that might be affected by a similar problem.
1185
1186                       !!! FIX YOUR ERROR HANDLING !!!
1187
1188 This guard was activated starting",
1189       );
1190     };
1191
1192     dbic_internal_try {
1193       # if it throws - good, we'll assign to @args in the end
1194       # if it doesn't - do different things depending on RV truthiness
1195       if( $act->(@args) ) {
1196         $args[0] = (
1197           "Invocation of the exception_action handler installed on $self did *not*"
1198         .' result in an exception. DBIx::Class is unable to function without a reliable'
1199         .' exception mechanism, ensure your exception_action does not hide exceptions'
1200         ." (original error: $args[0])"
1201         );
1202       }
1203       else {
1204         carp_unique (
1205           "The exception_action handler installed on $self returned false instead"
1206         .' of throwing an exception. This behavior has been deprecated, adjust your'
1207         .' handler to always rethrow the supplied error'
1208         );
1209       }
1210
1211       1;
1212     }
1213     catch {
1214       # We call this to get the necessary warnings emitted and disregard the RV
1215       # as it's definitely an exception if we got as far as this catch{} block
1216       is_exception(
1217         $args[0] = $_
1218       );
1219     };
1220
1221     # Done guarding against https://github.com/PerlDancer/Dancer2/issues/1125
1222     $guard_disarmed = 1;
1223   }
1224
1225   DBIx::Class::Exception->throw( $args[0], $self->stacktrace );
1226 }
1227
1228 =head2 deploy
1229
1230 =over 4
1231
1232 =item Arguments: \%sqlt_args, $dir
1233
1234 =back
1235
1236 Attempts to deploy the schema to the current storage using L<SQL::Translator>.
1237
1238 See L<SQL::Translator/METHODS> for a list of values for C<\%sqlt_args>.
1239 The most common value for this would be C<< { add_drop_table => 1 } >>
1240 to have the SQL produced include a C<DROP TABLE> statement for each table
1241 created. For quoting purposes supply C<quote_identifiers>.
1242
1243 Additionally, the DBIx::Class parser accepts a C<sources> parameter as a hash
1244 ref or an array ref, containing a list of source to deploy. If present, then
1245 only the sources listed will get deployed. Furthermore, you can use the
1246 C<add_fk_index> parser parameter to prevent the parser from creating an index for each
1247 FK.
1248
1249 =cut
1250
1251 sub deploy {
1252   my ($self, $sqltargs, $dir) = @_;
1253   $self->throw_exception("Can't deploy without storage") unless $self->storage;
1254   $self->storage->deploy($self, undef, $sqltargs, $dir);
1255 }
1256
1257 =head2 deployment_statements
1258
1259 =over 4
1260
1261 =item Arguments: See L<DBIx::Class::Storage::DBI/deployment_statements>
1262
1263 =item Return Value: $listofstatements
1264
1265 =back
1266
1267 A convenient shortcut to
1268 C<< $self->storage->deployment_statements($self, @args) >>.
1269 Returns the statements used by L</deploy> and
1270 L<DBIx::Class::Storage/deploy>.
1271
1272 =cut
1273
1274 sub deployment_statements {
1275   my $self = shift;
1276
1277   $self->throw_exception("Can't generate deployment statements without a storage")
1278     if not $self->storage;
1279
1280   $self->storage->deployment_statements($self, @_);
1281 }
1282
1283 =head2 create_ddl_dir
1284
1285 =over 4
1286
1287 =item Arguments: See L<DBIx::Class::Storage::DBI/create_ddl_dir>
1288
1289 =back
1290
1291 A convenient shortcut to
1292 C<< $self->storage->create_ddl_dir($self, @args) >>.
1293
1294 Creates an SQL file based on the Schema, for each of the specified
1295 database types, in the given directory.
1296
1297 =cut
1298
1299 sub create_ddl_dir {
1300   my $self = shift;
1301
1302   $self->throw_exception("Can't create_ddl_dir without storage") unless $self->storage;
1303   $self->storage->create_ddl_dir($self, @_);
1304 }
1305
1306 =head2 ddl_filename
1307
1308 =over 4
1309
1310 =item Arguments: $database-type, $version, $directory, $preversion
1311
1312 =item Return Value: $normalised_filename
1313
1314 =back
1315
1316   my $filename = $table->ddl_filename($type, $version, $dir, $preversion)
1317
1318 This method is called by C<create_ddl_dir> to compose a file name out of
1319 the supplied directory, database type and version number. The default file
1320 name format is: C<$dir$schema-$version-$type.sql>.
1321
1322 You may override this method in your schema if you wish to use a different
1323 format.
1324
1325  WARNING
1326
1327  Prior to DBIx::Class version 0.08100 this method had a different signature:
1328
1329     my $filename = $table->ddl_filename($type, $dir, $version, $preversion)
1330
1331  In recent versions variables $dir and $version were reversed in order to
1332  bring the signature in line with other Schema/Storage methods. If you
1333  really need to maintain backward compatibility, you can do the following
1334  in any overriding methods:
1335
1336     ($dir, $version) = ($version, $dir) if ($DBIx::Class::VERSION < 0.08100);
1337
1338 =cut
1339
1340 sub ddl_filename {
1341   my ($self, $type, $version, $dir, $preversion) = @_;
1342
1343   $version = "$preversion-$version" if $preversion;
1344
1345   my $class = blessed($self) || $self;
1346   $class =~ s/::/-/g;
1347
1348   return "$dir/$class-$version-$type.sql";
1349 }
1350
1351 =head2 thaw
1352
1353 Provided as the recommended way of thawing schema objects. You can call
1354 C<Storable::thaw> directly if you wish, but the thawed objects will not have a
1355 reference to any schema, so are rather useless.
1356
1357 =cut
1358
1359 sub thaw {
1360   my ($self, $obj) = @_;
1361   local $DBIx::Class::ResultSourceHandle::thaw_schema = $self;
1362   return Storable::thaw($obj);
1363 }
1364
1365 =head2 freeze
1366
1367 This doesn't actually do anything beyond calling L<nfreeze|Storable/SYNOPSIS>,
1368 it is just provided here for symmetry.
1369
1370 =cut
1371
1372 sub freeze {
1373   return Storable::nfreeze($_[1]);
1374 }
1375
1376 =head2 dclone
1377
1378 =over 4
1379
1380 =item Arguments: $object
1381
1382 =item Return Value: dcloned $object
1383
1384 =back
1385
1386 Recommended way of dcloning L<DBIx::Class::Row> and L<DBIx::Class::ResultSet>
1387 objects so their references to the schema object
1388 (which itself is B<not> cloned) are properly maintained.
1389
1390 =cut
1391
1392 sub dclone {
1393   my ($self, $obj) = @_;
1394   local $DBIx::Class::ResultSourceHandle::thaw_schema = $self;
1395   return Storable::dclone($obj);
1396 }
1397
1398 =head2 schema_version
1399
1400 Returns the current schema class' $VERSION in a normalised way.
1401
1402 =cut
1403
1404 sub schema_version {
1405   my ($self) = @_;
1406   my $class = ref($self)||$self;
1407
1408   # does -not- use $schema->VERSION
1409   # since that varies in results depending on if version.pm is installed, and if
1410   # so the perl or XS versions. If you want this to change, bug the version.pm
1411   # author to make vpp and vxs behave the same.
1412
1413   my $version;
1414   {
1415     no strict 'refs';
1416     $version = ${"${class}::VERSION"};
1417   }
1418   return $version;
1419 }
1420
1421
1422 =head2 register_class
1423
1424 =over 4
1425
1426 =item Arguments: $source_name, $component_class
1427
1428 =back
1429
1430 This method is called by L</load_namespaces> and L</load_classes> to install the found classes into your Schema. You should be using those instead of this one.
1431
1432 You will only need this method if you have your Result classes in
1433 files which are not named after the packages (or all in the same
1434 file). You may also need it to register classes at runtime.
1435
1436 Registers a class which isa DBIx::Class::ResultSourceProxy. Equivalent to
1437 calling:
1438
1439   $schema->register_source($source_name, $component_class->result_source);
1440
1441 =cut
1442
1443 sub register_class {
1444   my ($self, $source_name, $to_register) = @_;
1445   $self->register_source($source_name => $to_register->result_source);
1446 }
1447
1448 =head2 register_source
1449
1450 =over 4
1451
1452 =item Arguments: $source_name, L<$result_source|DBIx::Class::ResultSource>
1453
1454 =back
1455
1456 This method is called by L</register_class>.
1457
1458 Registers the L<DBIx::Class::ResultSource> in the schema with the given
1459 source name.
1460
1461 =cut
1462
1463 sub register_source { shift->_register_source(@_) }
1464
1465 =head2 unregister_source
1466
1467 =over 4
1468
1469 =item Arguments: $source_name
1470
1471 =back
1472
1473 Removes the L<DBIx::Class::ResultSource> from the schema for the given source name.
1474
1475 =cut
1476
1477 sub unregister_source { shift->_unregister_source(@_) }
1478
1479 =head2 register_extra_source
1480
1481 =over 4
1482
1483 =item Arguments: $source_name, L<$result_source|DBIx::Class::ResultSource>
1484
1485 =back
1486
1487 As L</register_source> but should be used if the result class already
1488 has a source and you want to register an extra one.
1489
1490 =cut
1491
1492 sub register_extra_source { shift->_register_source(@_, { extra => 1 }) }
1493
1494 sub _register_source {
1495   my ($self, $source_name, $supplied_rsrc, $params) = @_;
1496
1497   my $derived_rsrc = $supplied_rsrc->clone({
1498     source_name => $source_name,
1499   });
1500
1501   # Do not move into the clone-hashref above: there are things
1502   # on CPAN that do hook 'sub schema' </facepalm>
1503   # https://metacpan.org/source/LSAUNDERS/DBIx-Class-Preview-1.000003/lib/DBIx/Class/ResultSource/Table/Previewed.pm#L9-38
1504   $derived_rsrc->schema($self);
1505
1506   weaken $derived_rsrc->{schema}
1507     if length( my $schema_class = ref($self) );
1508
1509   my %reg = %{$self->source_registrations};
1510   $reg{$source_name} = $derived_rsrc;
1511   $self->source_registrations(\%reg);
1512
1513   return $derived_rsrc if $params->{extra};
1514
1515   my( $result_class, $result_class_level_rsrc );
1516   if (
1517     $result_class = $derived_rsrc->result_class
1518       and
1519     # There are known cases where $rs_class is *ONLY* an inflator, without
1520     # any hint of a rsrc (e.g. DBIx::Class::KiokuDB::EntryProxy)
1521     $result_class_level_rsrc = dbic_internal_try { $result_class->result_source_instance }
1522   ) {
1523     my %map = %{$self->class_mappings};
1524
1525     carp (
1526       "$result_class already had a registered source which was replaced by "
1527     . 'this call. Perhaps you wanted register_extra_source(), though it is '
1528     . 'more likely you did something wrong.'
1529     ) if (
1530       exists $map{$result_class}
1531         and
1532       $map{$result_class} ne $source_name
1533         and
1534       $result_class_level_rsrc != $supplied_rsrc
1535     );
1536
1537     $map{$result_class} = $source_name;
1538     $self->class_mappings(\%map);
1539
1540
1541     my $schema_class_level_rsrc;
1542     if (
1543       # we are called on a schema instance, not on the class
1544       length $schema_class
1545
1546         and
1547
1548       # the schema class also has a registration with the same name
1549       $schema_class_level_rsrc = dbic_internal_try { $schema_class->source($source_name) }
1550
1551         and
1552
1553       # what we are registering on the schema instance *IS* derived
1554       # from the class-level (top) rsrc...
1555       ( grep { $_ == $derived_rsrc } $result_class_level_rsrc->__derived_instances )
1556
1557         and
1558
1559       # ... while the schema-class-level has stale-markers
1560       keys %{ $schema_class_level_rsrc->{__metadata_divergencies} || {} }
1561     ) {
1562       my $msg =
1563         "The ResultSource instance you just registered on '$self' as "
1564       . "'$source_name' seems to have no relation to $schema_class->"
1565       . "source('$source_name') which in turn is marked stale (likely due "
1566       . "to recent $result_class->... direct class calls). This is almost "
1567       . "always a mistake: perhaps you forgot a cycle of "
1568       . "$schema_class->unregister_source( '$source_name' ) / "
1569       . "$schema_class->register_class( '$source_name' => '$result_class' )"
1570       ;
1571
1572       DBIx::Class::_ENV_::ASSERT_NO_ERRONEOUS_METAINSTANCE_USE
1573         ? emit_loud_diag( msg => $msg, confess => 1 )
1574         : carp_unique($msg)
1575       ;
1576     }
1577   }
1578
1579   $derived_rsrc;
1580 }
1581
1582 my $global_phase_destroy;
1583 sub DESTROY {
1584   ### NO detected_reinvoked_destructor check
1585   ### This code very much relies on being called multuple times
1586
1587   return if $global_phase_destroy ||= in_global_destruction;
1588
1589   my $self = shift;
1590   my $srcs = $self->source_registrations;
1591
1592   for my $source_name (keys %$srcs) {
1593     # find first source that is not about to be GCed (someone other than $self
1594     # holds a reference to it) and reattach to it, weakening our own link
1595     #
1596     # during global destruction (if we have not yet bailed out) this should throw
1597     # which will serve as a signal to not try doing anything else
1598     # however beware - on older perls the exception seems randomly untrappable
1599     # due to some weird race condition during thread joining :(((
1600     if (length ref $srcs->{$source_name} and refcount($srcs->{$source_name}) > 1) {
1601       local $SIG{__DIE__} if $SIG{__DIE__};
1602       local $@ if DBIx::Class::_ENV_::UNSTABLE_DOLLARAT;
1603       eval {
1604         $srcs->{$source_name}->schema($self);
1605         weaken $srcs->{$source_name};
1606         1;
1607       } or do {
1608         $global_phase_destroy = 1;
1609       };
1610
1611       last;
1612     }
1613   }
1614
1615   # Dummy NEXTSTATE ensuring the all temporaries on the stack are garbage
1616   # collected before leaving this scope. Depending on the code above, this
1617   # may very well be just a preventive measure guarding future modifications
1618   undef;
1619 }
1620
1621 sub _unregister_source {
1622     my ($self, $source_name) = @_;
1623     my %reg = %{$self->source_registrations};
1624
1625     my $source = delete $reg{$source_name};
1626     $self->source_registrations(\%reg);
1627     if ($source->result_class) {
1628         my %map = %{$self->class_mappings};
1629         delete $map{$source->result_class};
1630         $self->class_mappings(\%map);
1631     }
1632 }
1633
1634
1635 =head2 compose_connection (DEPRECATED)
1636
1637 =over 4
1638
1639 =item Arguments: $target_namespace, @db_info
1640
1641 =item Return Value: $new_schema
1642
1643 =back
1644
1645 DEPRECATED. You probably wanted compose_namespace.
1646
1647 Actually, you probably just wanted to call connect.
1648
1649 =begin hidden
1650
1651 (hidden due to deprecation)
1652
1653 Calls L<DBIx::Class::Schema/"compose_namespace"> to the target namespace,
1654 calls L<DBIx::Class::Schema/connection> with @db_info on the new schema,
1655 then injects the L<DBix::Class::ResultSetProxy> component and a
1656 resultset_instance classdata entry on all the new classes, in order to support
1657 $target_namespaces::$class->search(...) method calls.
1658
1659 This is primarily useful when you have a specific need for class method access
1660 to a connection. In normal usage it is preferred to call
1661 L<DBIx::Class::Schema/connect> and use the resulting schema object to operate
1662 on L<DBIx::Class::ResultSet> objects with L<DBIx::Class::Schema/resultset> for
1663 more information.
1664
1665 =end hidden
1666
1667 =cut
1668
1669 sub compose_connection {
1670   my ($self, $target, @info) = @_;
1671
1672   carp_once "compose_connection deprecated as of 0.08000"
1673     unless $INC{"DBIx/Class/CDBICompat.pm"};
1674
1675   dbic_internal_try {
1676     require DBIx::Class::ResultSetProxy;
1677   }
1678   catch {
1679     $self->throw_exception
1680       ("No arguments to load_classes and couldn't load DBIx::Class::ResultSetProxy ($_)")
1681   };
1682
1683   if ($self eq $target) {
1684     # Pathological case, largely caused by the docs on early C::M::DBIC::Plain
1685     foreach my $source_name ($self->sources) {
1686       my $source = $self->source($source_name);
1687       my $class = $source->result_class;
1688       $self->inject_base($class, 'DBIx::Class::ResultSetProxy');
1689       $class->mk_classaccessor(resultset_instance => $source->resultset);
1690       $class->mk_classaccessor(class_resolver => $self);
1691     }
1692     $self->connection(@info);
1693     return $self;
1694   }
1695
1696   my $schema = $self->compose_namespace($target, 'DBIx::Class::ResultSetProxy');
1697   quote_sub "${target}::schema", '$s', { '$s' => \$schema };
1698
1699   # needed to cover the newly installed stuff via quote_sub above
1700   Class::C3->reinitialize if DBIx::Class::_ENV_::OLD_MRO;
1701
1702   $schema->connection(@info);
1703   foreach my $source_name ($schema->sources) {
1704     my $source = $schema->source($source_name);
1705     my $class = $source->result_class;
1706     #warn "$source_name $class $source ".$source->storage;
1707
1708     $class->mk_group_accessors( inherited => [ result_source_instance => '_result_source' ] );
1709     # explicit set-call, avoid mro update lag
1710     $class->set_inherited( result_source_instance => $source );
1711
1712     $class->mk_classaccessor(resultset_instance => $source->resultset);
1713     $class->mk_classaccessor(class_resolver => $schema);
1714   }
1715   return $schema;
1716 }
1717
1718 =head1 FURTHER QUESTIONS?
1719
1720 Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
1721
1722 =head1 COPYRIGHT AND LICENSE
1723
1724 This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
1725 by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
1726 redistribute it and/or modify it under the same terms as the
1727 L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.
1728
1729 =cut
1730
1731 1;