1 package DBIx::Class::Schema;
6 use base 'DBIx::Class';
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
17 use Devel::GlobalDestruction;
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' => {});
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
28 __PACKAGE__->mk_classaccessor('class_mappings' => {});
29 __PACKAGE__->mk_classaccessor('source_registrations' => {});
31 __PACKAGE__->mk_group_accessors( component_class => 'schema_sanity_checker' );
32 __PACKAGE__->schema_sanity_checker(
33 DBIx::Class::_ENV_::OLD_MRO ? false :
34 'DBIx::Class::Schema::SanityChecker'
39 DBIx::Class::Schema - composable schemas
43 package Library::Schema;
44 use base qw/DBIx::Class::Schema/;
46 # load all Result classes in Library/Schema/Result/
47 __PACKAGE__->load_namespaces();
49 package Library::Schema::Result::CD;
50 use base qw/DBIx::Class::Core/;
52 __PACKAGE__->load_components(qw/InflateColumn::DateTime/); # for example
53 __PACKAGE__->table('cd');
55 # Elsewhere in your code:
56 my $schema1 = Library::Schema->connect(
63 my $schema2 = Library::Schema->connect($coderef_returning_dbh);
65 # fetch objects using Library::Schema::Result::DVD
66 my $resultset = $schema1->resultset('DVD')->search( ... );
67 my @dvd_objects = $schema2->resultset('DVD')->search( ... );
71 Creates database classes based on a schema. This is the recommended way to
72 use L<DBIx::Class> and allows you to use more than one concurrent connection
75 NB: If you're used to L<Class::DBI> it's worth reading the L</SYNOPSIS>
76 carefully, as DBIx::Class does things a little differently. Note in
77 particular which module inherits off which.
81 =head2 load_namespaces
85 =item Arguments: %options?
89 package MyApp::Schema;
90 __PACKAGE__->load_namespaces();
92 __PACKAGE__->load_namespaces(
93 result_namespace => 'Res',
94 resultset_namespace => 'RSet',
95 default_resultset_class => '+MyApp::Othernamespace::RSet',
98 With no arguments, this method uses L<Module::Find> to load all of the
99 Result and ResultSet classes under the namespace of the schema from
100 which it is called. For example, C<My::Schema> will by default find
101 and load Result classes named C<My::Schema::Result::*> and ResultSet
102 classes named C<My::Schema::ResultSet::*>.
104 ResultSet classes are associated with Result class of the same name.
105 For example, C<My::Schema::Result::CD> will get the ResultSet class
106 C<My::Schema::ResultSet::CD> if it is present.
108 Both Result and ResultSet namespaces are configurable via the
109 C<result_namespace> and C<resultset_namespace> options.
111 Another option, C<default_resultset_class> specifies a custom default
112 ResultSet class for Result classes with no corresponding ResultSet.
114 All of the namespace and classname options are by default relative to
115 the schema classname. To specify a fully-qualified name, prefix it
116 with a literal C<+>. For example, C<+Other::NameSpace::Result>.
120 You will be warned if ResultSet classes are discovered for which there
121 are no matching Result classes like this:
123 load_namespaces found ResultSet class $classname with no corresponding Result class
125 If a ResultSource instance is found to already have a ResultSet class set
126 using L<resultset_class|DBIx::Class::ResultSource/resultset_class> to some
127 other class, you will be warned like this:
129 We found ResultSet class '$rs_class' for '$result_class', but it seems
130 that you had already set '$result_class' to use '$rs_set' instead
134 # load My::Schema::Result::CD, My::Schema::Result::Artist,
135 # My::Schema::ResultSet::CD, etc...
136 My::Schema->load_namespaces;
138 # Override everything to use ugly names.
139 # In this example, if there is a My::Schema::Res::Foo, but no matching
140 # My::Schema::RSets::Foo, then Foo will have its
141 # resultset_class set to My::Schema::RSetBase
142 My::Schema->load_namespaces(
143 result_namespace => 'Res',
144 resultset_namespace => 'RSets',
145 default_resultset_class => 'RSetBase',
148 # Put things in other namespaces
149 My::Schema->load_namespaces(
150 result_namespace => '+Some::Place::Results',
151 resultset_namespace => '+Another::Place::RSets',
154 To search multiple namespaces for either Result or ResultSet classes,
155 use an arrayref of namespaces for that option. In the case that the
156 same result (or resultset) class exists in multiple namespaces, later
157 entries in the list of namespaces will override earlier ones.
159 My::Schema->load_namespaces(
160 # My::Schema::Results_C::Foo takes precedence over My::Schema::Results_B::Foo :
161 result_namespace => [ 'Results_A', 'Results_B', 'Results_C' ],
162 resultset_namespace => [ '+Some::Place::RSets', 'RSets' ],
167 # Pre-pends our classname to the given relative classname or
168 # class namespace, unless there is a '+' prefix, which will
170 sub _expand_relative_name {
171 my ($class, $name) = @_;
172 $name =~ s/^\+// or $name = "${class}::${name}";
176 # Finds all modules in the supplied namespace, or if omitted in the
177 # namespace of $class. Untaints all findings as they can be assumed
180 require Module::Find;
182 { $_ =~ /(.+)/ } # untaint result
183 Module::Find::findallmod( $_[1] || ref $_[0] || $_[0] )
187 # returns a hash of $shortname => $fullname for every package
188 # found in the given namespaces ($shortname is with the $fullname's
189 # namespace stripped off)
190 sub _map_namespaces {
191 my ($me, $namespaces) = @_;
194 for my $ns (@$namespaces) {
195 $res{ substr($_, length "${ns}::") } = $_
196 for $me->_findallmod($ns);
202 # returns the result_source_instance for the passed class/object,
203 # or dies with an informative message (used by load_namespaces)
204 sub _ns_get_rsrc_instance {
206 my $rs_class = ref ($_[0]) || $_[0];
208 return dbic_internal_try {
209 $rs_class->result_source
211 $me->throw_exception (
212 "Attempt to load_namespaces() class $rs_class failed - are you sure this is a real Result Class?: $_"
217 sub load_namespaces {
218 my ($class, %args) = @_;
220 my $result_namespace = delete $args{result_namespace} || 'Result';
221 my $resultset_namespace = delete $args{resultset_namespace} || 'ResultSet';
223 my $default_resultset_class = delete $args{default_resultset_class};
225 $default_resultset_class = $class->_expand_relative_name($default_resultset_class)
226 if $default_resultset_class;
228 $class->throw_exception('load_namespaces: unknown option(s): '
229 . join(q{,}, map { qq{'$_'} } keys %args))
230 if scalar keys %args;
232 for my $arg ($result_namespace, $resultset_namespace) {
233 $arg = [ $arg ] if ( $arg and ! ref $arg );
235 $class->throw_exception('load_namespaces: namespace arguments must be '
236 . 'a simple string or an arrayref')
237 if ref($arg) ne 'ARRAY';
239 $_ = $class->_expand_relative_name($_) for (@$arg);
242 my $results_by_source_name = $class->_map_namespaces($result_namespace);
243 my $resultsets_by_source_name = $class->_map_namespaces($resultset_namespace);
247 # ensure classes are loaded and attached in inheritance order
248 for my $result_class (values %$results_by_source_name) {
249 $class->ensure_class_loaded($result_class);
252 my @source_names_by_subclass_last = sort {
255 scalar @{mro::get_linear_isa( $results_by_source_name->{$a} )}
261 scalar @{mro::get_linear_isa( $results_by_source_name->{$b} )}
264 } keys(%$results_by_source_name);
266 foreach my $source_name (@source_names_by_subclass_last) {
267 my $result_class = $results_by_source_name->{$source_name};
269 my $preset_resultset_class = $class->_ns_get_rsrc_instance ($result_class)->resultset_class;
270 my $found_resultset_class = delete $resultsets_by_source_name->{$source_name};
272 if($preset_resultset_class && $preset_resultset_class ne 'DBIx::Class::ResultSet') {
273 if($found_resultset_class && $found_resultset_class ne $preset_resultset_class) {
274 carp "We found ResultSet class '$found_resultset_class' matching '$results_by_source_name->{$source_name}', but it seems "
275 . "that you had already set the '$results_by_source_name->{$source_name}' resultet to '$preset_resultset_class' instead";
278 # elsif - there may be *no* default_resultset_class, in which case we fallback to
279 # DBIx::Class::Resultset and there is nothing to check
280 elsif($found_resultset_class ||= $default_resultset_class) {
281 $class->ensure_class_loaded($found_resultset_class);
282 if(!$found_resultset_class->isa("DBIx::Class::ResultSet")) {
283 carp "load_namespaces found ResultSet class '$found_resultset_class' that does not subclass DBIx::Class::ResultSet";
286 $class->_ns_get_rsrc_instance ($result_class)->resultset_class($found_resultset_class);
289 my $source_name = $class->_ns_get_rsrc_instance ($result_class)->source_name || $source_name;
291 push(@to_register, [ $source_name, $result_class ]);
295 foreach (sort keys %$resultsets_by_source_name) {
296 carp "load_namespaces found ResultSet class '$resultsets_by_source_name->{$_}' "
297 .'with no corresponding Result class';
300 $class->register_class(@$_) for (@to_register);
309 =item Arguments: @classes?, { $namespace => [ @classes ] }+
313 L</load_classes> is an alternative method to L</load_namespaces>, both of
314 which serve similar purposes, each with different advantages and disadvantages.
315 In the general case you should use L</load_namespaces>, unless you need to
316 be able to specify that only specific classes are loaded at runtime.
318 With no arguments, this method uses L<Module::Find> to find all classes under
319 the schema's namespace. Otherwise, this method loads the classes you specify
320 (using L<use>), and registers them (using L</"register_class">).
322 It is possible to comment out classes with a leading C<#>, but note that perl
323 will think it's a mistake (trying to use a comment in a qw list), so you'll
324 need to add C<no warnings 'qw';> before your load_classes call.
326 If any classes found do not appear to be Result class files, you will
327 get the following warning:
329 Failed to load $comp_class. Can't find source_name method. Is
330 $comp_class really a full DBIC result class? Fix it, move it elsewhere,
331 or make your load_classes call more specific.
335 My::Schema->load_classes(); # loads My::Schema::CD, My::Schema::Artist,
336 # etc. (anything under the My::Schema namespace)
338 # loads My::Schema::CD, My::Schema::Artist, Other::Namespace::Producer but
339 # not Other::Namespace::LinerNotes nor My::Schema::Track
340 My::Schema->load_classes(qw/ CD Artist #Track /, {
341 Other::Namespace => [qw/ Producer #LinerNotes /],
347 my ($class, @params) = @_;
352 foreach my $param (@params) {
353 if (ref $param eq 'ARRAY') {
354 # filter out commented entries
355 my @modules = grep { $_ !~ /^#/ } @$param;
357 push (@{$comps_for{$class}}, @modules);
359 elsif (ref $param eq 'HASH') {
360 # more than one namespace possible
361 for my $comp ( keys %$param ) {
362 # filter out commented entries
363 my @modules = grep { $_ !~ /^#/ } @{$param->{$comp}};
365 push (@{$comps_for{$comp}}, @modules);
369 # filter out commented entries
370 push (@{$comps_for{$class}}, $param) if $param !~ /^#/;
374 my @comp = map { substr $_, length "${class}::" }
375 $class->_findallmod($class);
376 $comps_for{$class} = \@comp;
381 foreach my $prefix (keys %comps_for) {
382 foreach my $comp (@{$comps_for{$prefix}||[]}) {
383 my $comp_class = "${prefix}::${comp}";
384 $class->ensure_class_loaded($comp_class);
386 my $snsub = $comp_class->can('source_name');
388 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.";
391 $comp = $snsub->($comp_class) || $comp;
393 push(@to_register, [ $comp, $comp_class ]);
398 foreach my $to (@to_register) {
399 $class->register_class(@$to);
407 =item Arguments: $storage_type|{$storage_type, \%args}
409 =item Return Value: $storage_type|{$storage_type, \%args}
411 =item Default value: DBIx::Class::Storage::DBI
415 Set the storage class that will be instantiated when L</connect> is called.
416 If the classname starts with C<::>, the prefix C<DBIx::Class::Storage> is
417 assumed by L</connect>.
419 You want to use this to set subclasses of L<DBIx::Class::Storage::DBI>
420 in cases where the appropriate subclass is not autodetected.
422 If your storage type requires instantiation arguments, those are
423 defined as a second argument in the form of a hashref and the entire
424 value needs to be wrapped into an arrayref or a hashref. We support
425 both types of refs here in order to play nice with your
426 Config::[class] or your choice. See
427 L<DBIx::Class::Storage::DBI::Replicated> for an example of this.
429 =head2 default_resultset_attributes
433 =item Arguments: L<\%attrs|DBIx::Class::ResultSet/ATTRIBUTES>
435 =item Return Value: L<\%attrs|DBIx::Class::ResultSet/ATTRIBUTES>
437 =item Default value: None
441 Like L<DBIx::Class::ResultSource/resultset_attributes> stores a collection
442 of resultset attributes, to be used as defaults for B<every> ResultSet
443 instance schema-wide. The same list of CAVEATS and WARNINGS applies, with
444 the extra downside of these defaults being practically inescapable: you will
445 B<not> be able to derive a ResultSet instance with these attributes unset.
450 use base qw/DBIx::Class::Schema/;
451 __PACKAGE__->default_resultset_attributes( { software_limit => 1 } );
453 =head2 schema_sanity_checker
457 =item Arguments: L<perform_schema_sanity_checks()|DBIx::Class::Schema::SanityChecker/perform_schema_sanity_checks> provider
459 =item Return Value: L<perform_schema_sanity_checks()|DBIx::Class::Schema::SanityChecker/perform_schema_sanity_checks> provider
461 =item Default value: L<DBIx::Class::Schema::SanityChecker>
465 On every call to L</connection> if the value of this attribute evaluates to
466 true, DBIC will invoke
467 C<< L<$schema_sanity_checker|/schema_sanity_checker>->L<perform_schema_sanity_checks|DBIx::Class::Schema::SanityChecker/perform_schema_sanity_checks>($schema) >>
468 before returning. The return value of this invocation is ignored.
470 B<YOU ARE STRONGLY URGED> to
471 L<learn more about the reason|DBIx::Class::Schema::SanityChecker/WHY> this
472 feature was introduced. Blindly disabling the checker on existing projects
473 B<may result in data corruption> after upgrade to C<< DBIC >= v0.082900 >>.
478 use base qw/DBIx::Class::Schema/;
479 __PACKAGE__->schema_sanity_checker('My::Schema::SanityChecker');
481 # or to disable all checks:
482 __PACKAGE__->schema_sanity_checker('');
484 Note: setting the value to C<undef> B<will not> have the desired effect,
485 due to an implementation detail of L<Class::Accessor::Grouped> inherited
486 accessors. In order to disable any and all checks you must set this
487 attribute to an empty string as shown in the second example above.
489 =head2 exception_action
493 =item Arguments: $code_reference
495 =item Return Value: $code_reference
497 =item Default value: None
501 When L</throw_exception> is invoked and L</exception_action> is set to a code
502 reference, this reference will be called instead of
503 L<DBIx::Class::Exception/throw>, with the exception message passed as the only
506 Your custom throw code B<must> rethrow the exception, as L</throw_exception> is
507 an integral part of DBIC's internal execution control flow.
512 use base qw/DBIx::Class::Schema/;
513 use My::ExceptionClass;
514 __PACKAGE__->exception_action(sub { My::ExceptionClass->throw(@_) });
515 __PACKAGE__->load_classes;
518 my $schema_obj = My::Schema->connect( .... );
519 $schema_obj->exception_action(sub { My::ExceptionClass->throw(@_) });
525 =item Arguments: boolean
529 Whether L</throw_exception> should include stack trace information.
530 Defaults to false normally, but defaults to true if C<$ENV{DBIC_TRACE}>
533 =head2 sqlt_deploy_hook
537 =item Arguments: $sqlt_schema
541 An optional sub which you can declare in your own Schema class that will get
542 passed the L<SQL::Translator::Schema> object when you deploy the schema via
543 L</create_ddl_dir> or L</deploy>.
545 For an example of what you can do with this, see
546 L<DBIx::Class::Manual::Cookbook/Adding Indexes And Functions To Your SQL>.
548 Note that sqlt_deploy_hook is called by L</deployment_statements>, which in turn
549 is called before L</deploy>. Therefore the hook can be used only to manipulate
550 the L<SQL::Translator::Schema> object before it is turned into SQL fed to the
551 database. If you want to execute post-deploy statements which can not be generated
552 by L<SQL::Translator>, the currently suggested method is to overload L</deploy>
553 and use L<dbh_do|DBIx::Class::Storage::DBI/dbh_do>.
561 =item Arguments: @connectinfo
563 =item Return Value: $new_schema
567 Creates and returns a new Schema object. The connection info set on it
568 is used to create a new instance of the storage backend and set it on
571 See L<DBIx::Class::Storage::DBI/"connect_info"> for DBI-specific
572 syntax on the C<@connectinfo> argument, or L<DBIx::Class::Storage> in
575 Note that C<connect_info> expects an arrayref of arguments, but
576 C<connect> does not. C<connect> wraps its arguments in an arrayref
577 before passing them to C<connect_info>.
581 C<connect> is a convenience method. It is equivalent to calling
582 $schema->clone->connection(@connectinfo). To write your own overloaded
583 version, overload L</connection> instead.
587 sub connect :DBIC_method_is_indirect_sugar {
588 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
589 shift->clone->connection(@_);
596 =item Arguments: L<$source_name|DBIx::Class::ResultSource/source_name>
598 =item Return Value: L<$resultset|DBIx::Class::ResultSet>
602 my $rs = $schema->resultset('DVD');
604 Returns the L<DBIx::Class::ResultSet> object for the registered source
610 my ($self, $source_name) = @_;
611 $self->throw_exception('resultset() expects a source name')
612 unless defined $source_name;
613 return $self->source($source_name)->resultset;
620 =item Return Value: L<@source_names|DBIx::Class::ResultSource/source_name>
624 my @source_names = $schema->sources;
626 Lists names of all the sources registered on this Schema object.
630 sub sources { keys %{shift->source_registrations} }
636 =item Arguments: L<$source_name|DBIx::Class::ResultSource/source_name>
638 =item Return Value: L<$result_source|DBIx::Class::ResultSource>
642 my $source = $schema->source('Book');
644 Returns the L<DBIx::Class::ResultSource> object for the registered
650 my ($self, $source_name) = @_;
652 $self->throw_exception("source() expects a source name")
655 my $source_registrations;
658 ( $source_registrations = $self->source_registrations )->{$source_name}
660 # if we got here, they probably passed a full class name
661 $source_registrations->{ $self->class_mappings->{$source_name} || '' }
663 $self->throw_exception( "Can't find source for ${source_name}" )
667 # We need to prevent alterations of pre-existing $@ due to where this call
668 # sits in the overall stack ( *unless* of course there is an actual error
669 # to report ). set_mro does alter $@ (and yes - it *can* throw an exception)
670 # We do not use local because set_mro *can* throw an actual exception
671 # We do not use a try/catch either, as on one hand it would slow things
672 # down for no reason (we would always rethrow), but also because adding *any*
673 # try/catch block below will segfault various threading tests on older perls
674 # ( which in itself is a FIXME but ENOTIMETODIG )
675 my $old_dollarat = $@;
678 mro::set_mro($_, 'c3') for
681 # some pseudo-sources do not have a result/resultset yet
686 ${"${_}::__INITIAL_MRO_UPON_DBIC_LOAD__"}
694 { length ref $_ ? ref $_ : $_ }
695 ( $rsrc, $rsrc->result_class, $rsrc->resultset_class )
698 # DO NOT REMOVE - see comment above
708 =item Arguments: L<$source_name|DBIx::Class::ResultSource/source_name>
710 =item Return Value: $classname
714 my $class = $schema->class('CD');
716 Retrieves the Result class name for the given source name.
721 return shift->source(shift)->result_class;
728 =item Arguments: C<$coderef>, @coderef_args?
730 =item Return Value: The return value of $coderef
734 Executes C<$coderef> with (optional) arguments C<@coderef_args> atomically,
735 returning its result (if any). Equivalent to calling $schema->storage->txn_do.
736 See L<DBIx::Class::Storage/"txn_do"> for more information.
738 This interface is preferred over using the individual methods L</txn_begin>,
739 L</txn_commit>, and L</txn_rollback> below.
741 WARNING: If you are connected with C<< AutoCommit => 0 >> the transaction is
742 considered nested, and you will still need to call L</txn_commit> to write your
743 changes when appropriate. You will also want to connect with C<< auto_savepoint =>
744 1 >> to get partial rollback to work, if the storage driver for your database
747 Connecting with C<< AutoCommit => 1 >> is recommended.
754 $self->storage or $self->throw_exception
755 ('txn_do called on $schema without storage');
757 $self->storage->txn_do(@_);
760 =head2 txn_scope_guard
762 Runs C<txn_scope_guard> on the schema's storage. See
763 L<DBIx::Class::Storage/txn_scope_guard>.
767 sub txn_scope_guard {
770 $self->storage or $self->throw_exception
771 ('txn_scope_guard called on $schema without storage');
773 $self->storage->txn_scope_guard(@_);
778 Begins a transaction (does nothing if AutoCommit is off). Equivalent to
779 calling $schema->storage->txn_begin. See
780 L<DBIx::Class::Storage/"txn_begin"> for more information.
787 $self->storage or $self->throw_exception
788 ('txn_begin called on $schema without storage');
790 $self->storage->txn_begin;
795 Commits the current transaction. Equivalent to calling
796 $schema->storage->txn_commit. See L<DBIx::Class::Storage/"txn_commit">
797 for more information.
804 $self->storage or $self->throw_exception
805 ('txn_commit called on $schema without storage');
807 $self->storage->txn_commit;
812 Rolls back the current transaction. Equivalent to calling
813 $schema->storage->txn_rollback. See
814 L<DBIx::Class::Storage/"txn_rollback"> for more information.
821 $self->storage or $self->throw_exception
822 ('txn_rollback called on $schema without storage');
824 $self->storage->txn_rollback;
829 my $storage = $schema->storage;
831 Returns the L<DBIx::Class::Storage> object for this Schema. Grab this
832 if you want to turn on SQL statement debugging at runtime, or set the
833 quote character. For the default storage, the documentation can be
834 found in L<DBIx::Class::Storage::DBI>.
840 =item Arguments: L<$source_name|DBIx::Class::ResultSource/source_name>, [ \@column_list, \@row_values+ ] | [ \%col_data+ ]
842 =item Return Value: L<\@result_objects|DBIx::Class::Manual::ResultClass> (scalar context) | L<@result_objects|DBIx::Class::Manual::ResultClass> (list context)
846 A convenience shortcut to L<DBIx::Class::ResultSet/populate>. Equivalent to:
848 $schema->resultset($source_name)->populate([...]);
854 The context of this method call has an important effect on what is
855 submitted to storage. In void context data is fed directly to fastpath
856 insertion routines provided by the underlying storage (most often
857 L<DBI/execute_for_fetch>), bypassing the L<new|DBIx::Class::Row/new> and
858 L<insert|DBIx::Class::Row/insert> calls on the
859 L<Result|DBIx::Class::Manual::ResultClass> class, including any
860 augmentation of these methods provided by components. For example if you
861 are using something like L<DBIx::Class::UUIDColumns> to create primary
862 keys for you, you will find that your PKs are empty. In this case you
863 will have to explicitly force scalar or list context in order to create
870 sub populate :DBIC_method_is_indirect_sugar {
871 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
873 my ($self, $name, $data) = @_;
874 my $rs = $self->resultset($name)
875 or $self->throw_exception("'$name' is not a resultset");
877 return $rs->populate($data);
884 =item Arguments: @args
886 =item Return Value: $self
890 Similar to L</connect> except sets the storage object and connection
891 data B<in-place> on C<$self>. You should probably be calling
892 L</connect> to get a properly L<cloned|/clone> Schema object instead.
894 If the accessor L</schema_sanity_checker> returns a true value C<$checker>,
895 the following call will take place before return:
896 C<< L<$checker|/schema_sanity_checker>->L<perform_schema_sanity_checks(C<$self>)|DBIx::Class::Schema::SanityChecker/perform_schema_sanity_checks> >>
900 Overload C<connection> to change the behaviour of C<connect>.
904 my $default_off_stderr_blurb_emitted;
906 my ($self, @info) = @_;
907 return $self if !@info && $self->storage;
909 my ($storage_class, $args) = ref $self->storage_type
910 ? $self->_normalize_storage_type($self->storage_type)
911 : $self->storage_type
914 $storage_class =~ s/^::/DBIx::Class::Storage::/;
917 $self->ensure_class_loaded ($storage_class);
920 $self->throw_exception(
921 "Unable to load storage class ${storage_class}: $_"
925 my $storage = $storage_class->new( $self => $args||{} );
926 $storage->connect_info(\@info);
927 $self->storage($storage);
931 ### Begin 5.8 "you have not selected a checker" warning
933 # We can not blanket-enable this on 5.8 - it is just too expensive for
934 # day to day execution. We also can't just go silent - there are genuine
935 # regressions ( due to core changes) for which this is the only line of
936 # defense. So instead we whine on STDERR that folks need to do something
938 # Beyond suboptimal, but given the constraints the best we can do :(
940 # This should stay around for at least 3~4 years
942 DBIx::Class::_ENV_::OLD_MRO
944 ! $default_off_stderr_blurb_emitted
946 length ref $self->schema_sanity_checker
948 length ref __PACKAGE__->schema_sanity_checker
951 refaddr( $self->schema_sanity_checker )
953 refaddr( __PACKAGE__->schema_sanity_checker )
958 "Sanity checks for schema %s are disabled on this perl $]: "
959 . '*THIS IS POTENTIALLY VERY DANGEROUS*. You are strongly urged to '
960 . "read http://is.gd/dbic_sancheck_5_008 before proceeding\n",
961 ( defined( blessed $self ) ? refdesc $self : "'$self'" )
964 $default_off_stderr_blurb_emitted = 1;
966 ### End 5.8 "you have not selected a checker" warning
970 if( my $checker = $self->schema_sanity_checker ) {
971 $checker->perform_schema_sanity_checks($self);
977 sub _normalize_storage_type {
978 my ($self, $storage_type) = @_;
979 if(ref $storage_type eq 'ARRAY') {
980 return @$storage_type;
981 } elsif(ref $storage_type eq 'HASH') {
982 return %$storage_type;
984 $self->throw_exception('Unsupported REFTYPE given: '. ref $storage_type);
988 =head2 compose_namespace
992 =item Arguments: $target_namespace, $additional_base_class?
994 =item Return Value: $new_schema
998 For each L<DBIx::Class::ResultSource> in the schema, this method creates a
999 class in the target namespace (e.g. $target_namespace::CD,
1000 $target_namespace::Artist) that inherits from the corresponding classes
1001 attached to the current schema.
1003 It also attaches a corresponding L<DBIx::Class::ResultSource> object to the
1004 new $schema object. If C<$additional_base_class> is given, the new composed
1005 classes will inherit from first the corresponding class from the current
1006 schema then the base class.
1008 For example, for a schema with My::Schema::CD and My::Schema::Artist classes,
1010 $schema->compose_namespace('My::DB', 'Base::Class');
1011 print join (', ', @My::DB::CD::ISA) . "\n";
1012 print join (', ', @My::DB::Artist::ISA) ."\n";
1014 will produce the output
1016 My::Schema::CD, Base::Class
1017 My::Schema::Artist, Base::Class
1021 sub compose_namespace {
1022 my ($self, $target, $base) = @_;
1024 my $schema = $self->clone;
1026 $schema->source_registrations({});
1028 # the original class-mappings must remain - otherwise
1029 # reverse_relationship_info will not work
1030 #$schema->class_mappings({});
1033 foreach my $source_name ($self->sources) {
1034 my $orig_source = $self->source($source_name);
1036 my $target_class = "${target}::${source_name}";
1037 $self->inject_base($target_class, $orig_source->result_class, ($base || ()) );
1039 $schema->register_source(
1041 $orig_source->clone(
1042 result_class => $target_class
1047 # Legacy stuff, not inserting INDIRECT assertions
1048 quote_sub "${target}::${_}" => "shift->schema->$_(\@_)"
1049 for qw(class source resultset);
1052 # needed to cover the newly installed stuff via quote_sub above
1053 Class::C3->reinitialize if DBIx::Class::_ENV_::OLD_MRO;
1055 # Give each composed class yet another *schema-less* source copy
1056 # this is used for the freeze/thaw cycle
1058 # This is not covered by any tests directly, but is indirectly exercised
1059 # in t/cdbi/sweet/08pager by re-setting the schema on an existing object
1060 # FIXME - there is likely a much cheaper way to take care of this
1061 for my $source_name ($self->sources) {
1063 my $target_class = "${target}::${source_name}";
1065 $target_class->result_source_instance(
1066 $self->source($source_name)->clone(
1067 result_class => $target_class,
1068 schema => ( ref $schema || $schema ),
1076 # LEGACY: The intra-call to this was removed in 66d9ef6b and then
1077 # the sub was de-documented way later in 249963d4. No way to be sure
1078 # nothing on darkpan is calling it directly, so keeping as-is
1079 sub setup_connection_class {
1080 my ($class, $target, @info) = @_;
1081 $class->inject_base($target => 'DBIx::Class::DB');
1082 #$target->load_components('DB');
1083 $target->connection(@info);
1088 Creates a new savepoint (does nothing outside a transaction).
1089 Equivalent to calling $schema->storage->svp_begin. See
1090 L<DBIx::Class::Storage/"svp_begin"> for more information.
1095 my ($self, $name) = @_;
1097 $self->storage or $self->throw_exception
1098 ('svp_begin called on $schema without storage');
1100 $self->storage->svp_begin($name);
1105 Releases a savepoint (does nothing outside a transaction).
1106 Equivalent to calling $schema->storage->svp_release. See
1107 L<DBIx::Class::Storage/"svp_release"> for more information.
1112 my ($self, $name) = @_;
1114 $self->storage or $self->throw_exception
1115 ('svp_release called on $schema without storage');
1117 $self->storage->svp_release($name);
1122 Rollback to a savepoint (does nothing outside a transaction).
1123 Equivalent to calling $schema->storage->svp_rollback. See
1124 L<DBIx::Class::Storage/"svp_rollback"> for more information.
1129 my ($self, $name) = @_;
1131 $self->storage or $self->throw_exception
1132 ('svp_rollback called on $schema without storage');
1134 $self->storage->svp_rollback($name);
1141 =item Arguments: %attrs?
1143 =item Return Value: $new_schema
1147 Clones the schema and its associated result_source objects and returns the
1148 copy. The resulting copy will have the same attributes as the source schema,
1149 except for those attributes explicitly overridden by the provided C<%attrs>.
1157 (ref $self ? %$self : ()),
1158 (@_ == 1 && ref $_[0] eq 'HASH' ? %{ $_[0] } : @_),
1160 bless $clone, (ref $self || $self);
1162 $clone->$_(undef) for qw/class_mappings source_registrations storage/;
1164 $clone->_copy_state_from($self);
1169 # Needed in Schema::Loader - if you refactor, please make a compatibility shim
1171 sub _copy_state_from {
1172 my ($self, $from) = @_;
1174 $self->class_mappings({ %{$from->class_mappings} });
1175 $self->source_registrations({ %{$from->source_registrations} });
1177 # we use extra here as we want to leave the class_mappings as they are
1178 # but overwrite the source_registrations entry with the new source
1179 $self->register_extra_source( $_ => $from->source($_) )
1182 if ($from->storage) {
1183 $self->storage($from->storage);
1184 $self->storage->set_schema($self);
1188 =head2 throw_exception
1192 =item Arguments: $message
1196 Throws an exception. Obeys the exemption rules of L<DBIx::Class::Carp> to report
1197 errors from outer-user's perspective. See L</exception_action> for details on overriding
1198 this method's behavior. If L</stacktrace> is turned on, C<throw_exception>'s
1199 default behavior will provide a detailed stack trace.
1203 sub throw_exception {
1204 my ($self, @args) = @_;
1207 ! DBIx::Class::_Util::in_internal_try()
1209 my $act = $self->exception_action
1214 my $guard = scope_guard {
1215 return if $guard_disarmed;
1216 emit_loud_diag( emit_dups => 1, msg => "
1218 !!! DBIx::Class INTERNAL PANIC !!!
1220 The exception_action() handler installed on '$self'
1221 aborted the stacktrace below via a longjmp (either via Return::Multilevel or
1222 plain goto, or Scope::Upper or something equally nefarious). There currently
1223 is nothing safe DBIx::Class can do, aside from displaying this error. A future
1224 version ( 0.082900, when available ) will reduce the cases in which the
1225 handler is invoked, but this is neither a complete solution, nor can it do
1226 anything for other software that might be affected by a similar problem.
1228 !!! FIX YOUR ERROR HANDLING !!!
1230 This guard was activated starting",
1235 # if it throws - good, we'll assign to @args in the end
1236 # if it doesn't - do different things depending on RV truthiness
1237 if( $act->(@args) ) {
1239 "Invocation of the exception_action handler installed on $self did *not*"
1240 .' result in an exception. DBIx::Class is unable to function without a reliable'
1241 .' exception mechanism, ensure your exception_action does not hide exceptions'
1242 ." (original error: $args[0])"
1247 "The exception_action handler installed on $self returned false instead"
1248 .' of throwing an exception. This behavior has been deprecated, adjust your'
1249 .' handler to always rethrow the supplied error'
1256 # We call this to get the necessary warnings emitted and disregard the RV
1257 # as it's definitely an exception if we got as far as this catch{} block
1263 # Done guarding against https://github.com/PerlDancer/Dancer2/issues/1125
1264 $guard_disarmed = 1;
1267 DBIx::Class::Exception->throw( $args[0], $self->stacktrace );
1274 =item Arguments: \%sqlt_args, $dir
1278 Attempts to deploy the schema to the current storage using L<SQL::Translator>.
1280 See L<SQL::Translator/METHODS> for a list of values for C<\%sqlt_args>.
1281 The most common value for this would be C<< { add_drop_table => 1 } >>
1282 to have the SQL produced include a C<DROP TABLE> statement for each table
1283 created. For quoting purposes supply C<quote_identifiers>.
1285 Additionally, the DBIx::Class parser accepts a C<sources> parameter as a hash
1286 ref or an array ref, containing a list of source to deploy. If present, then
1287 only the sources listed will get deployed. Furthermore, you can use the
1288 C<add_fk_index> parser parameter to prevent the parser from creating an index for each
1294 my ($self, $sqltargs, $dir) = @_;
1295 $self->throw_exception("Can't deploy without storage") unless $self->storage;
1296 $self->storage->deploy($self, undef, $sqltargs, $dir);
1299 =head2 deployment_statements
1303 =item Arguments: See L<DBIx::Class::Storage::DBI/deployment_statements>
1305 =item Return Value: $listofstatements
1309 A convenient shortcut to
1310 C<< $self->storage->deployment_statements($self, @args) >>.
1311 Returns the statements used by L</deploy> and
1312 L<DBIx::Class::Storage/deploy>.
1316 sub deployment_statements {
1319 $self->throw_exception("Can't generate deployment statements without a storage")
1320 if not $self->storage;
1322 $self->storage->deployment_statements($self, @_);
1325 =head2 create_ddl_dir
1329 =item Arguments: See L<DBIx::Class::Storage::DBI/create_ddl_dir>
1333 A convenient shortcut to
1334 C<< $self->storage->create_ddl_dir($self, @args) >>.
1336 Creates an SQL file based on the Schema, for each of the specified
1337 database types, in the given directory.
1341 sub create_ddl_dir {
1344 $self->throw_exception("Can't create_ddl_dir without storage") unless $self->storage;
1345 $self->storage->create_ddl_dir($self, @_);
1352 =item Arguments: $database-type, $version, $directory, $preversion
1354 =item Return Value: $normalised_filename
1358 my $filename = $table->ddl_filename($type, $version, $dir, $preversion)
1360 This method is called by C<create_ddl_dir> to compose a file name out of
1361 the supplied directory, database type and version number. The default file
1362 name format is: C<$dir$schema-$version-$type.sql>.
1364 You may override this method in your schema if you wish to use a different
1369 Prior to DBIx::Class version 0.08100 this method had a different signature:
1371 my $filename = $table->ddl_filename($type, $dir, $version, $preversion)
1373 In recent versions variables $dir and $version were reversed in order to
1374 bring the signature in line with other Schema/Storage methods. If you
1375 really need to maintain backward compatibility, you can do the following
1376 in any overriding methods:
1378 ($dir, $version) = ($version, $dir) if ($DBIx::Class::VERSION < 0.08100);
1383 my ($self, $type, $version, $dir, $preversion) = @_;
1385 $version = "$preversion-$version" if $preversion;
1387 my $class = blessed($self) || $self;
1390 return "$dir/$class-$version-$type.sql";
1395 Provided as the recommended way of thawing schema objects. You can call
1396 C<Storable::thaw> directly if you wish, but the thawed objects will not have a
1397 reference to any schema, so are rather useless.
1402 my ($self, $obj) = @_;
1403 local $DBIx::Class::ResultSourceHandle::thaw_schema = $self;
1404 return Storable::thaw($obj);
1409 This doesn't actually do anything beyond calling L<nfreeze|Storable/SYNOPSIS>,
1410 it is just provided here for symmetry.
1415 return Storable::nfreeze($_[1]);
1422 =item Arguments: $object
1424 =item Return Value: dcloned $object
1428 Recommended way of dcloning L<DBIx::Class::Row> and L<DBIx::Class::ResultSet>
1429 objects so their references to the schema object
1430 (which itself is B<not> cloned) are properly maintained.
1435 my ($self, $obj) = @_;
1436 local $DBIx::Class::ResultSourceHandle::thaw_schema = $self;
1437 return Storable::dclone($obj);
1440 =head2 schema_version
1442 Returns the current schema class' $VERSION in a normalised way.
1446 sub schema_version {
1448 my $class = ref($self)||$self;
1450 # does -not- use $schema->VERSION
1451 # since that varies in results depending on if version.pm is installed, and if
1452 # so the perl or XS versions. If you want this to change, bug the version.pm
1453 # author to make vpp and vxs behave the same.
1458 $version = ${"${class}::VERSION"};
1464 =head2 register_class
1468 =item Arguments: $source_name, $component_class
1472 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.
1474 You will only need this method if you have your Result classes in
1475 files which are not named after the packages (or all in the same
1476 file). You may also need it to register classes at runtime.
1478 Registers a class which isa DBIx::Class::ResultSourceProxy. Equivalent to
1481 $schema->register_source($source_name, $component_class->result_source);
1485 sub register_class {
1486 my ($self, $source_name, $to_register) = @_;
1487 $self->register_source($source_name => $to_register->result_source);
1490 =head2 register_source
1494 =item Arguments: $source_name, L<$result_source|DBIx::Class::ResultSource>
1498 This method is called by L</register_class>.
1500 Registers the L<DBIx::Class::ResultSource> in the schema with the given
1505 sub register_source { shift->_register_source(@_) }
1507 =head2 unregister_source
1511 =item Arguments: $source_name
1515 Removes the L<DBIx::Class::ResultSource> from the schema for the given source name.
1519 sub unregister_source { shift->_unregister_source(@_) }
1521 =head2 register_extra_source
1525 =item Arguments: $source_name, L<$result_source|DBIx::Class::ResultSource>
1529 As L</register_source> but should be used if the result class already
1530 has a source and you want to register an extra one.
1534 sub register_extra_source { shift->_register_source(@_, { extra => 1 }) }
1536 sub _register_source {
1537 my ($self, $source_name, $supplied_rsrc, $params) = @_;
1539 my $derived_rsrc = $supplied_rsrc->clone({
1540 source_name => $source_name,
1543 # Do not move into the clone-hashref above: there are things
1544 # on CPAN that do hook 'sub schema' </facepalm>
1545 # https://metacpan.org/source/LSAUNDERS/DBIx-Class-Preview-1.000003/lib/DBIx/Class/ResultSource/Table/Previewed.pm#L9-38
1546 $derived_rsrc->schema($self);
1548 weaken $derived_rsrc->{schema}
1549 if length( my $schema_class = ref($self) );
1551 my %reg = %{$self->source_registrations};
1552 $reg{$source_name} = $derived_rsrc;
1553 $self->source_registrations(\%reg);
1555 return $derived_rsrc if $params->{extra};
1557 my( $result_class, $result_class_level_rsrc );
1559 $result_class = $derived_rsrc->result_class
1561 # There are known cases where $rs_class is *ONLY* an inflator, without
1562 # any hint of a rsrc (e.g. DBIx::Class::KiokuDB::EntryProxy)
1563 $result_class_level_rsrc = dbic_internal_try { $result_class->result_source_instance }
1565 my %map = %{$self->class_mappings};
1568 "$result_class already had a registered source which was replaced by "
1569 . 'this call. Perhaps you wanted register_extra_source(), though it is '
1570 . 'more likely you did something wrong.'
1572 exists $map{$result_class}
1574 $map{$result_class} ne $source_name
1576 $result_class_level_rsrc != $supplied_rsrc
1579 $map{$result_class} = $source_name;
1580 $self->class_mappings(\%map);
1583 my $schema_class_level_rsrc;
1585 # we are called on a schema instance, not on the class
1586 length $schema_class
1590 # the schema class also has a registration with the same name
1591 $schema_class_level_rsrc = dbic_internal_try { $schema_class->source($source_name) }
1595 # what we are registering on the schema instance *IS* derived
1596 # from the class-level (top) rsrc...
1597 ( grep { $_ == $derived_rsrc } $result_class_level_rsrc->__derived_instances )
1601 # ... while the schema-class-level has stale-markers
1602 keys %{ $schema_class_level_rsrc->{__metadata_divergencies} || {} }
1605 "The ResultSource instance you just registered on '$self' as "
1606 . "'$source_name' seems to have no relation to $schema_class->"
1607 . "source('$source_name') which in turn is marked stale (likely due "
1608 . "to recent $result_class->... direct class calls). This is almost "
1609 . "always a mistake: perhaps you forgot a cycle of "
1610 . "$schema_class->unregister_source( '$source_name' ) / "
1611 . "$schema_class->register_class( '$source_name' => '$result_class' )"
1614 DBIx::Class::_ENV_::ASSERT_NO_ERRONEOUS_METAINSTANCE_USE
1615 ? emit_loud_diag( msg => $msg, confess => 1 )
1624 my $global_phase_destroy;
1626 ### NO detected_reinvoked_destructor check
1627 ### This code very much relies on being called multuple times
1629 return if $global_phase_destroy ||= in_global_destruction;
1632 my $srcs = $self->source_registrations;
1634 for my $source_name (keys %$srcs) {
1635 # find first source that is not about to be GCed (someone other than $self
1636 # holds a reference to it) and reattach to it, weakening our own link
1638 # during global destruction (if we have not yet bailed out) this should throw
1639 # which will serve as a signal to not try doing anything else
1640 # however beware - on older perls the exception seems randomly untrappable
1641 # due to some weird race condition during thread joining :(((
1642 if (length ref $srcs->{$source_name} and refcount($srcs->{$source_name}) > 1) {
1643 local $SIG{__DIE__} if $SIG{__DIE__};
1644 local $@ if DBIx::Class::_ENV_::UNSTABLE_DOLLARAT;
1646 $srcs->{$source_name}->schema($self);
1647 weaken $srcs->{$source_name};
1650 $global_phase_destroy = 1;
1657 # Dummy NEXTSTATE ensuring the all temporaries on the stack are garbage
1658 # collected before leaving this scope. Depending on the code above, this
1659 # may very well be just a preventive measure guarding future modifications
1663 sub _unregister_source {
1664 my ($self, $source_name) = @_;
1665 my %reg = %{$self->source_registrations};
1667 my $source = delete $reg{$source_name};
1668 $self->source_registrations(\%reg);
1669 if ($source->result_class) {
1670 my %map = %{$self->class_mappings};
1671 delete $map{$source->result_class};
1672 $self->class_mappings(\%map);
1677 =head2 compose_connection (DEPRECATED)
1681 =item Arguments: $target_namespace, @db_info
1683 =item Return Value: $new_schema
1687 DEPRECATED. You probably wanted compose_namespace.
1689 Actually, you probably just wanted to call connect.
1693 (hidden due to deprecation)
1695 Calls L<DBIx::Class::Schema/"compose_namespace"> to the target namespace,
1696 calls L<DBIx::Class::Schema/connection> with @db_info on the new schema,
1697 then injects the L<DBix::Class::ResultSetProxy> component and a
1698 resultset_instance classdata entry on all the new classes, in order to support
1699 $target_namespaces::$class->search(...) method calls.
1701 This is primarily useful when you have a specific need for class method access
1702 to a connection. In normal usage it is preferred to call
1703 L<DBIx::Class::Schema/connect> and use the resulting schema object to operate
1704 on L<DBIx::Class::ResultSet> objects with L<DBIx::Class::Schema/resultset> for
1711 sub compose_connection {
1712 my ($self, $target, @info) = @_;
1714 carp_once "compose_connection deprecated as of 0.08000"
1715 unless $INC{"DBIx/Class/CDBICompat.pm"};
1718 require DBIx::Class::ResultSetProxy;
1721 $self->throw_exception
1722 ("No arguments to load_classes and couldn't load DBIx::Class::ResultSetProxy ($_)")
1725 if ($self eq $target) {
1726 # Pathological case, largely caused by the docs on early C::M::DBIC::Plain
1727 foreach my $source_name ($self->sources) {
1728 my $source = $self->source($source_name);
1729 my $class = $source->result_class;
1730 $self->inject_base($class, 'DBIx::Class::ResultSetProxy');
1731 $class->mk_classaccessor(resultset_instance => $source->resultset);
1732 $class->mk_classaccessor(class_resolver => $self);
1734 $self->connection(@info);
1738 my $schema = $self->compose_namespace($target, 'DBIx::Class::ResultSetProxy');
1739 quote_sub "${target}::schema", '$s', { '$s' => \$schema };
1741 # needed to cover the newly installed stuff via quote_sub above
1742 Class::C3->reinitialize if DBIx::Class::_ENV_::OLD_MRO;
1744 $schema->connection(@info);
1745 foreach my $source_name ($schema->sources) {
1746 my $source = $schema->source($source_name);
1747 my $class = $source->result_class;
1748 #warn "$source_name $class $source ".$source->storage;
1750 $class->mk_group_accessors( inherited => [ result_source_instance => '_result_source' ] );
1751 # explicit set-call, avoid mro update lag
1752 $class->set_inherited( result_source_instance => $source );
1754 $class->mk_classaccessor(resultset_instance => $source->resultset);
1755 $class->mk_classaccessor(class_resolver => $schema);
1760 =head1 FURTHER QUESTIONS?
1762 Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
1764 =head1 COPYRIGHT AND LICENSE
1766 This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
1767 by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
1768 redistribute it and/or modify it under the same terms as the
1769 L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.