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 refdesc refcount quote_sub scope_guard
13 is_exception dbic_internal_try
14 fail_on_internal_call emit_loud_diag
16 use Devel::GlobalDestruction;
19 __PACKAGE__->mk_group_accessors( inherited => qw( storage exception_action ) );
20 __PACKAGE__->mk_classaccessor('storage_type' => '::DBI');
21 __PACKAGE__->mk_classaccessor('stacktrace' => $ENV{DBIC_TRACE} || 0);
22 __PACKAGE__->mk_classaccessor('default_resultset_attributes' => {});
24 # These two should have been private from the start but too late now
25 # Undocumented on purpose, hopefully it won't ever be necessary to
27 __PACKAGE__->mk_classaccessor('class_mappings' => {});
28 __PACKAGE__->mk_classaccessor('source_registrations' => {});
30 __PACKAGE__->mk_group_accessors( component_class => 'schema_sanity_checker' );
31 __PACKAGE__->schema_sanity_checker(
32 'DBIx::Class::Schema::SanityChecker'
37 DBIx::Class::Schema - composable schemas
41 package Library::Schema;
42 use base qw/DBIx::Class::Schema/;
44 # load all Result classes in Library/Schema/Result/
45 __PACKAGE__->load_namespaces();
47 package Library::Schema::Result::CD;
48 use base qw/DBIx::Class::Core/;
50 __PACKAGE__->load_components(qw/InflateColumn::DateTime/); # for example
51 __PACKAGE__->table('cd');
53 # Elsewhere in your code:
54 my $schema1 = Library::Schema->connect(
61 my $schema2 = Library::Schema->connect($coderef_returning_dbh);
63 # fetch objects using Library::Schema::Result::DVD
64 my $resultset = $schema1->resultset('DVD')->search( ... );
65 my @dvd_objects = $schema2->resultset('DVD')->search( ... );
69 Creates database classes based on a schema. This is the recommended way to
70 use L<DBIx::Class> and allows you to use more than one concurrent connection
73 NB: If you're used to L<Class::DBI> it's worth reading the L</SYNOPSIS>
74 carefully, as DBIx::Class does things a little differently. Note in
75 particular which module inherits off which.
79 =head2 load_namespaces
83 =item Arguments: %options?
87 package MyApp::Schema;
88 __PACKAGE__->load_namespaces();
90 __PACKAGE__->load_namespaces(
91 result_namespace => 'Res',
92 resultset_namespace => 'RSet',
93 default_resultset_class => '+MyApp::Othernamespace::RSet',
96 With no arguments, this method uses L<Module::Find> to load all of the
97 Result and ResultSet classes under the namespace of the schema from
98 which it is called. For example, C<My::Schema> will by default find
99 and load Result classes named C<My::Schema::Result::*> and ResultSet
100 classes named C<My::Schema::ResultSet::*>.
102 ResultSet classes are associated with Result class of the same name.
103 For example, C<My::Schema::Result::CD> will get the ResultSet class
104 C<My::Schema::ResultSet::CD> if it is present.
106 Both Result and ResultSet namespaces are configurable via the
107 C<result_namespace> and C<resultset_namespace> options.
109 Another option, C<default_resultset_class> specifies a custom default
110 ResultSet class for Result classes with no corresponding ResultSet.
112 All of the namespace and classname options are by default relative to
113 the schema classname. To specify a fully-qualified name, prefix it
114 with a literal C<+>. For example, C<+Other::NameSpace::Result>.
118 You will be warned if ResultSet classes are discovered for which there
119 are no matching Result classes like this:
121 load_namespaces found ResultSet class $classname with no corresponding Result class
123 If a ResultSource instance is found to already have a ResultSet class set
124 using L<resultset_class|DBIx::Class::ResultSource/resultset_class> to some
125 other class, you will be warned like this:
127 We found ResultSet class '$rs_class' for '$result_class', but it seems
128 that you had already set '$result_class' to use '$rs_set' instead
132 # load My::Schema::Result::CD, My::Schema::Result::Artist,
133 # My::Schema::ResultSet::CD, etc...
134 My::Schema->load_namespaces;
136 # Override everything to use ugly names.
137 # In this example, if there is a My::Schema::Res::Foo, but no matching
138 # My::Schema::RSets::Foo, then Foo will have its
139 # resultset_class set to My::Schema::RSetBase
140 My::Schema->load_namespaces(
141 result_namespace => 'Res',
142 resultset_namespace => 'RSets',
143 default_resultset_class => 'RSetBase',
146 # Put things in other namespaces
147 My::Schema->load_namespaces(
148 result_namespace => '+Some::Place::Results',
149 resultset_namespace => '+Another::Place::RSets',
152 To search multiple namespaces for either Result or ResultSet classes,
153 use an arrayref of namespaces for that option. In the case that the
154 same result (or resultset) class exists in multiple namespaces, later
155 entries in the list of namespaces will override earlier ones.
157 My::Schema->load_namespaces(
158 # My::Schema::Results_C::Foo takes precedence over My::Schema::Results_B::Foo :
159 result_namespace => [ 'Results_A', 'Results_B', 'Results_C' ],
160 resultset_namespace => [ '+Some::Place::RSets', 'RSets' ],
165 # Pre-pends our classname to the given relative classname or
166 # class namespace, unless there is a '+' prefix, which will
168 sub _expand_relative_name {
169 my ($class, $name) = @_;
170 $name =~ s/^\+// or $name = "${class}::${name}";
174 # Finds all modules in the supplied namespace, or if omitted in the
175 # namespace of $class. Untaints all findings as they can be assumed
178 require Module::Find;
180 { $_ =~ /(.+)/ } # untaint result
181 Module::Find::findallmod( $_[1] || ref $_[0] || $_[0] )
185 # returns a hash of $shortname => $fullname for every package
186 # found in the given namespaces ($shortname is with the $fullname's
187 # namespace stripped off)
188 sub _map_namespaces {
189 my ($me, $namespaces) = @_;
192 for my $ns (@$namespaces) {
193 $res{ substr($_, length "${ns}::") } = $_
194 for $me->_findallmod($ns);
200 # returns the result_source_instance for the passed class/object,
201 # or dies with an informative message (used by load_namespaces)
202 sub _ns_get_rsrc_instance {
204 my $rs_class = ref ($_[0]) || $_[0];
206 return dbic_internal_try {
207 $rs_class->result_source
209 $me->throw_exception (
210 "Attempt to load_namespaces() class $rs_class failed - are you sure this is a real Result Class?: $_"
215 sub load_namespaces {
216 my ($class, %args) = @_;
218 my $result_namespace = delete $args{result_namespace} || 'Result';
219 my $resultset_namespace = delete $args{resultset_namespace} || 'ResultSet';
221 my $default_resultset_class = delete $args{default_resultset_class};
223 $default_resultset_class = $class->_expand_relative_name($default_resultset_class)
224 if $default_resultset_class;
226 $class->throw_exception('load_namespaces: unknown option(s): '
227 . join(q{,}, map { qq{'$_'} } keys %args))
228 if scalar keys %args;
230 for my $arg ($result_namespace, $resultset_namespace) {
231 $arg = [ $arg ] if ( $arg and ! ref $arg );
233 $class->throw_exception('load_namespaces: namespace arguments must be '
234 . 'a simple string or an arrayref')
235 if ref($arg) ne 'ARRAY';
237 $_ = $class->_expand_relative_name($_) for (@$arg);
240 my $results_by_source_name = $class->_map_namespaces($result_namespace);
241 my $resultsets_by_source_name = $class->_map_namespaces($resultset_namespace);
245 # ensure classes are loaded and attached in inheritance order
246 for my $result_class (values %$results_by_source_name) {
247 $class->ensure_class_loaded($result_class);
250 my @source_names_by_subclass_last = sort {
253 scalar @{mro::get_linear_isa( $results_by_source_name->{$a} )}
259 scalar @{mro::get_linear_isa( $results_by_source_name->{$b} )}
262 } keys(%$results_by_source_name);
264 foreach my $source_name (@source_names_by_subclass_last) {
265 my $result_class = $results_by_source_name->{$source_name};
267 my $preset_resultset_class = $class->_ns_get_rsrc_instance ($result_class)->resultset_class;
268 my $found_resultset_class = delete $resultsets_by_source_name->{$source_name};
270 if($preset_resultset_class && $preset_resultset_class ne 'DBIx::Class::ResultSet') {
271 if($found_resultset_class && $found_resultset_class ne $preset_resultset_class) {
272 carp "We found ResultSet class '$found_resultset_class' matching '$results_by_source_name->{$source_name}', but it seems "
273 . "that you had already set the '$results_by_source_name->{$source_name}' resultet to '$preset_resultset_class' instead";
276 # elsif - there may be *no* default_resultset_class, in which case we fallback to
277 # DBIx::Class::Resultset and there is nothing to check
278 elsif($found_resultset_class ||= $default_resultset_class) {
279 $class->ensure_class_loaded($found_resultset_class);
280 if(!$found_resultset_class->isa("DBIx::Class::ResultSet")) {
281 carp "load_namespaces found ResultSet class '$found_resultset_class' that does not subclass DBIx::Class::ResultSet";
284 $class->_ns_get_rsrc_instance ($result_class)->resultset_class($found_resultset_class);
287 my $source_name = $class->_ns_get_rsrc_instance ($result_class)->source_name || $source_name;
289 push(@to_register, [ $source_name, $result_class ]);
293 foreach (sort keys %$resultsets_by_source_name) {
294 carp "load_namespaces found ResultSet class '$resultsets_by_source_name->{$_}' "
295 .'with no corresponding Result class';
298 $class->register_class(@$_) for (@to_register);
307 =item Arguments: @classes?, { $namespace => [ @classes ] }+
311 L</load_classes> is an alternative method to L</load_namespaces>, both of
312 which serve similar purposes, each with different advantages and disadvantages.
313 In the general case you should use L</load_namespaces>, unless you need to
314 be able to specify that only specific classes are loaded at runtime.
316 With no arguments, this method uses L<Module::Find> to find all classes under
317 the schema's namespace. Otherwise, this method loads the classes you specify
318 (using L<use>), and registers them (using L</"register_class">).
320 It is possible to comment out classes with a leading C<#>, but note that perl
321 will think it's a mistake (trying to use a comment in a qw list), so you'll
322 need to add C<no warnings 'qw';> before your load_classes call.
324 If any classes found do not appear to be Result class files, you will
325 get the following warning:
327 Failed to load $comp_class. Can't find source_name method. Is
328 $comp_class really a full DBIC result class? Fix it, move it elsewhere,
329 or make your load_classes call more specific.
333 My::Schema->load_classes(); # loads My::Schema::CD, My::Schema::Artist,
334 # etc. (anything under the My::Schema namespace)
336 # loads My::Schema::CD, My::Schema::Artist, Other::Namespace::Producer but
337 # not Other::Namespace::LinerNotes nor My::Schema::Track
338 My::Schema->load_classes(qw/ CD Artist #Track /, {
339 Other::Namespace => [qw/ Producer #LinerNotes /],
345 my ($class, @params) = @_;
350 foreach my $param (@params) {
351 if (ref $param eq 'ARRAY') {
352 # filter out commented entries
353 my @modules = grep { $_ !~ /^#/ } @$param;
355 push (@{$comps_for{$class}}, @modules);
357 elsif (ref $param eq 'HASH') {
358 # more than one namespace possible
359 for my $comp ( keys %$param ) {
360 # filter out commented entries
361 my @modules = grep { $_ !~ /^#/ } @{$param->{$comp}};
363 push (@{$comps_for{$comp}}, @modules);
367 # filter out commented entries
368 push (@{$comps_for{$class}}, $param) if $param !~ /^#/;
372 my @comp = map { substr $_, length "${class}::" }
373 $class->_findallmod($class);
374 $comps_for{$class} = \@comp;
379 foreach my $prefix (keys %comps_for) {
380 foreach my $comp (@{$comps_for{$prefix}||[]}) {
381 my $comp_class = "${prefix}::${comp}";
382 $class->ensure_class_loaded($comp_class);
384 my $snsub = $comp_class->can('source_name');
386 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.";
389 $comp = $snsub->($comp_class) || $comp;
391 push(@to_register, [ $comp, $comp_class ]);
396 foreach my $to (@to_register) {
397 $class->register_class(@$to);
405 =item Arguments: $storage_type|{$storage_type, \%args}
407 =item Return Value: $storage_type|{$storage_type, \%args}
409 =item Default value: DBIx::Class::Storage::DBI
413 Set the storage class that will be instantiated when L</connect> is called.
414 If the classname starts with C<::>, the prefix C<DBIx::Class::Storage> is
415 assumed by L</connect>.
417 You want to use this to set subclasses of L<DBIx::Class::Storage::DBI>
418 in cases where the appropriate subclass is not autodetected.
420 If your storage type requires instantiation arguments, those are
421 defined as a second argument in the form of a hashref and the entire
422 value needs to be wrapped into an arrayref or a hashref. We support
423 both types of refs here in order to play nice with your
424 Config::[class] or your choice. See
425 L<DBIx::Class::Storage::DBI::Replicated> for an example of this.
427 =head2 default_resultset_attributes
431 =item Arguments: L<\%attrs|DBIx::Class::ResultSet/ATTRIBUTES>
433 =item Return Value: L<\%attrs|DBIx::Class::ResultSet/ATTRIBUTES>
435 =item Default value: None
439 Like L<DBIx::Class::ResultSource/resultset_attributes> stores a collection
440 of resultset attributes, to be used as defaults for B<every> ResultSet
441 instance schema-wide. The same list of CAVEATS and WARNINGS applies, with
442 the extra downside of these defaults being practically inescapable: you will
443 B<not> be able to derive a ResultSet instance with these attributes unset.
448 use base qw/DBIx::Class::Schema/;
449 __PACKAGE__->default_resultset_attributes( { software_limit => 1 } );
451 =head2 schema_sanity_checker
455 =item Arguments: L<perform_schema_sanity_checks()|DBIx::Class::Schema::SanityChecker/perform_schema_sanity_checks> provider
457 =item Return Value: L<perform_schema_sanity_checks()|DBIx::Class::Schema::SanityChecker/perform_schema_sanity_checks> provider
459 =item Default value: L<DBIx::Class::Schema::SanityChecker>
463 On every call to L</connection> if the value of this attribute evaluates to
464 true, DBIC will invoke
465 C<< L<$schema_sanity_checker|/schema_sanity_checker>->L<perform_schema_sanity_checks|DBIx::Class::Schema::SanityChecker/perform_schema_sanity_checks>($schema) >>
466 before returning. The return value of this invocation is ignored.
468 B<YOU ARE STRONGLY URGED> to
469 L<learn more about the reason|DBIx::Class::Schema::SanityChecker/WHY> this
470 feature was introduced. Blindly disabling the checker on existing projects
471 B<may result in data corruption> after upgrade to C<< DBIC >= v0.082900 >>.
476 use base qw/DBIx::Class::Schema/;
477 __PACKAGE__->schema_sanity_checker('My::Schema::SanityChecker');
479 # or to disable all checks:
480 __PACKAGE__->schema_sanity_checker('');
482 Note: setting the value to C<undef> B<will not> have the desired effect,
483 due to an implementation detail of L<Class::Accessor::Grouped> inherited
484 accessors. In order to disable any and all checks you must set this
485 attribute to an empty string as shown in the second example above.
487 =head2 exception_action
491 =item Arguments: $code_reference
493 =item Return Value: $code_reference
495 =item Default value: None
499 When L</throw_exception> is invoked and L</exception_action> is set to a code
500 reference, this reference will be called instead of
501 L<DBIx::Class::Exception/throw>, with the exception message passed as the only
504 Your custom throw code B<must> rethrow the exception, as L</throw_exception> is
505 an integral part of DBIC's internal execution control flow.
510 use base qw/DBIx::Class::Schema/;
511 use My::ExceptionClass;
512 __PACKAGE__->exception_action(sub { My::ExceptionClass->throw(@_) });
513 __PACKAGE__->load_classes;
516 my $schema_obj = My::Schema->connect( .... );
517 $schema_obj->exception_action(sub { My::ExceptionClass->throw(@_) });
523 =item Arguments: boolean
527 Whether L</throw_exception> should include stack trace information.
528 Defaults to false normally, but defaults to true if C<$ENV{DBIC_TRACE}>
531 =head2 sqlt_deploy_hook
535 =item Arguments: $sqlt_schema
539 An optional sub which you can declare in your own Schema class that will get
540 passed the L<SQL::Translator::Schema> object when you deploy the schema via
541 L</create_ddl_dir> or L</deploy>.
543 For an example of what you can do with this, see
544 L<DBIx::Class::Manual::Cookbook/Adding Indexes And Functions To Your SQL>.
546 Note that sqlt_deploy_hook is called by L</deployment_statements>, which in turn
547 is called before L</deploy>. Therefore the hook can be used only to manipulate
548 the L<SQL::Translator::Schema> object before it is turned into SQL fed to the
549 database. If you want to execute post-deploy statements which can not be generated
550 by L<SQL::Translator>, the currently suggested method is to overload L</deploy>
551 and use L<dbh_do|DBIx::Class::Storage::DBI/dbh_do>.
559 =item Arguments: @connectinfo
561 =item Return Value: $new_schema
565 Creates and returns a new Schema object. The connection info set on it
566 is used to create a new instance of the storage backend and set it on
569 See L<DBIx::Class::Storage::DBI/"connect_info"> for DBI-specific
570 syntax on the C<@connectinfo> argument, or L<DBIx::Class::Storage> in
573 Note that C<connect_info> expects an arrayref of arguments, but
574 C<connect> does not. C<connect> wraps its arguments in an arrayref
575 before passing them to C<connect_info>.
579 C<connect> is a convenience method. It is equivalent to calling
580 $schema->clone->connection(@connectinfo). To write your own overloaded
581 version, overload L</connection> instead.
585 sub connect :DBIC_method_is_indirect_sugar {
586 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
587 shift->clone->connection(@_);
594 =item Arguments: L<$source_name|DBIx::Class::ResultSource/source_name>
596 =item Return Value: L<$resultset|DBIx::Class::ResultSet>
600 my $rs = $schema->resultset('DVD');
602 Returns the L<DBIx::Class::ResultSet> object for the registered source
608 my ($self, $source_name) = @_;
609 $self->throw_exception('resultset() expects a source name')
610 unless defined $source_name;
611 return $self->source($source_name)->resultset;
618 =item Return Value: L<@source_names|DBIx::Class::ResultSource/source_name>
622 my @source_names = $schema->sources;
624 Lists names of all the sources registered on this Schema object.
628 sub sources { keys %{shift->source_registrations} }
634 =item Arguments: L<$source_name|DBIx::Class::ResultSource/source_name>
636 =item Return Value: L<$result_source|DBIx::Class::ResultSource>
640 my $source = $schema->source('Book');
642 Returns the L<DBIx::Class::ResultSource> object for the registered
648 my ($self, $source_name) = @_;
650 $self->throw_exception("source() expects a source name")
653 my $source_registrations;
656 ( $source_registrations = $self->source_registrations )->{$source_name}
658 # if we got here, they probably passed a full class name
659 $source_registrations->{ $self->class_mappings->{$source_name} || '' }
661 $self->throw_exception( "Can't find source for ${source_name}" )
665 # We need to prevent alterations of pre-existing $@ due to where this call
666 # sits in the overall stack ( *unless* of course there is an actual error
667 # to report ). set_mro does alter $@ (and yes - it *can* throw an exception)
668 # We do not use local because set_mro *can* throw an actual exception
669 # We do not use a try/catch either, as on one hand it would slow things
670 # down for no reason (we would always rethrow), but also because adding *any*
671 # try/catch block below will segfault various threading tests on older perls
672 # ( which in itself is a FIXME but ENOTIMETODIG )
673 my $old_dollarat = $@;
676 mro::set_mro($_, 'c3') for
679 # some pseudo-sources do not have a result/resultset yet
684 ${"${_}::__INITIAL_MRO_UPON_DBIC_LOAD__"}
692 { length ref $_ ? ref $_ : $_ }
693 ( $rsrc, $rsrc->result_class, $rsrc->resultset_class )
696 # DO NOT REMOVE - see comment above
706 =item Arguments: L<$source_name|DBIx::Class::ResultSource/source_name>
708 =item Return Value: $classname
712 my $class = $schema->class('CD');
714 Retrieves the Result class name for the given source name.
719 return shift->source(shift)->result_class;
726 =item Arguments: C<$coderef>, @coderef_args?
728 =item Return Value: The return value of $coderef
732 Executes C<$coderef> with (optional) arguments C<@coderef_args> atomically,
733 returning its result (if any). Equivalent to calling $schema->storage->txn_do.
734 See L<DBIx::Class::Storage/"txn_do"> for more information.
736 This interface is preferred over using the individual methods L</txn_begin>,
737 L</txn_commit>, and L</txn_rollback> below.
739 WARNING: If you are connected with C<< AutoCommit => 0 >> the transaction is
740 considered nested, and you will still need to call L</txn_commit> to write your
741 changes when appropriate. You will also want to connect with C<< auto_savepoint =>
742 1 >> to get partial rollback to work, if the storage driver for your database
745 Connecting with C<< AutoCommit => 1 >> is recommended.
752 $self->storage or $self->throw_exception
753 ('txn_do called on $schema without storage');
755 $self->storage->txn_do(@_);
758 =head2 txn_scope_guard
760 Runs C<txn_scope_guard> on the schema's storage. See
761 L<DBIx::Class::Storage/txn_scope_guard>.
765 sub txn_scope_guard {
768 $self->storage or $self->throw_exception
769 ('txn_scope_guard called on $schema without storage');
771 $self->storage->txn_scope_guard(@_);
776 Begins a transaction (does nothing if AutoCommit is off). Equivalent to
777 calling $schema->storage->txn_begin. See
778 L<DBIx::Class::Storage/"txn_begin"> for more information.
785 $self->storage or $self->throw_exception
786 ('txn_begin called on $schema without storage');
788 $self->storage->txn_begin;
793 Commits the current transaction. Equivalent to calling
794 $schema->storage->txn_commit. See L<DBIx::Class::Storage/"txn_commit">
795 for more information.
802 $self->storage or $self->throw_exception
803 ('txn_commit called on $schema without storage');
805 $self->storage->txn_commit;
810 Rolls back the current transaction. Equivalent to calling
811 $schema->storage->txn_rollback. See
812 L<DBIx::Class::Storage/"txn_rollback"> for more information.
819 $self->storage or $self->throw_exception
820 ('txn_rollback called on $schema without storage');
822 $self->storage->txn_rollback;
827 my $storage = $schema->storage;
829 Returns the L<DBIx::Class::Storage> object for this Schema. Grab this
830 if you want to turn on SQL statement debugging at runtime, or set the
831 quote character. For the default storage, the documentation can be
832 found in L<DBIx::Class::Storage::DBI>.
838 =item Arguments: L<$source_name|DBIx::Class::ResultSource/source_name>, [ \@column_list, \@row_values+ ] | [ \%col_data+ ]
840 =item Return Value: L<\@result_objects|DBIx::Class::Manual::ResultClass> (scalar context) | L<@result_objects|DBIx::Class::Manual::ResultClass> (list context)
844 A convenience shortcut to L<DBIx::Class::ResultSet/populate>. Equivalent to:
846 $schema->resultset($source_name)->populate([...]);
852 The context of this method call has an important effect on what is
853 submitted to storage. In void context data is fed directly to fastpath
854 insertion routines provided by the underlying storage (most often
855 L<DBI/execute_for_fetch>), bypassing the L<new|DBIx::Class::Row/new> and
856 L<insert|DBIx::Class::Row/insert> calls on the
857 L<Result|DBIx::Class::Manual::ResultClass> class, including any
858 augmentation of these methods provided by components. For example if you
859 are using something like L<DBIx::Class::UUIDColumns> to create primary
860 keys for you, you will find that your PKs are empty. In this case you
861 will have to explicitly force scalar or list context in order to create
868 sub populate :DBIC_method_is_indirect_sugar {
869 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
871 my ($self, $name, $data) = @_;
872 my $rs = $self->resultset($name)
873 or $self->throw_exception("'$name' is not a resultset");
875 return $rs->populate($data);
882 =item Arguments: @args
884 =item Return Value: $self
888 Similar to L</connect> except sets the storage object and connection
889 data B<in-place> on C<$self>. You should probably be calling
890 L</connect> to get a properly L<cloned|/clone> Schema object instead.
892 If the accessor L</schema_sanity_checker> returns a true value C<$checker>,
893 the following call will take place before return:
894 C<< L<$checker|/schema_sanity_checker>->L<perform_schema_sanity_checks(C<$self>)|DBIx::Class::Schema::SanityChecker/perform_schema_sanity_checks> >>
898 Overload C<connection> to change the behaviour of C<connect>.
902 my $default_off_stderr_blurb_emitted;
904 my ($self, @info) = @_;
905 return $self if !@info && $self->storage;
907 my ($storage_class, $args) = ref $self->storage_type
908 ? $self->_normalize_storage_type($self->storage_type)
909 : $self->storage_type
912 $storage_class =~ s/^::/DBIx::Class::Storage::/;
915 $self->ensure_class_loaded ($storage_class);
918 $self->throw_exception(
919 "Unable to load storage class ${storage_class}: $_"
923 my $storage = $storage_class->new( $self => $args||{} );
924 $storage->connect_info(\@info);
925 $self->storage($storage);
927 if( my $checker = $self->schema_sanity_checker ) {
928 $checker->perform_schema_sanity_checks($self);
934 sub _normalize_storage_type {
935 my ($self, $storage_type) = @_;
936 if(ref $storage_type eq 'ARRAY') {
937 return @$storage_type;
938 } elsif(ref $storage_type eq 'HASH') {
939 return %$storage_type;
941 $self->throw_exception('Unsupported REFTYPE given: '. ref $storage_type);
945 =head2 compose_namespace
949 =item Arguments: $target_namespace, $additional_base_class?
951 =item Return Value: $new_schema
955 For each L<DBIx::Class::ResultSource> in the schema, this method creates a
956 class in the target namespace (e.g. $target_namespace::CD,
957 $target_namespace::Artist) that inherits from the corresponding classes
958 attached to the current schema.
960 It also attaches a corresponding L<DBIx::Class::ResultSource> object to the
961 new $schema object. If C<$additional_base_class> is given, the new composed
962 classes will inherit from first the corresponding class from the current
963 schema then the base class.
965 For example, for a schema with My::Schema::CD and My::Schema::Artist classes,
967 $schema->compose_namespace('My::DB', 'Base::Class');
968 print join (', ', @My::DB::CD::ISA) . "\n";
969 print join (', ', @My::DB::Artist::ISA) ."\n";
971 will produce the output
973 My::Schema::CD, Base::Class
974 My::Schema::Artist, Base::Class
978 sub compose_namespace {
979 my ($self, $target, $base) = @_;
981 my $schema = $self->clone;
983 $schema->source_registrations({});
985 # the original class-mappings must remain - otherwise
986 # reverse_relationship_info will not work
987 #$schema->class_mappings({});
990 foreach my $source_name ($self->sources) {
991 my $orig_source = $self->source($source_name);
993 my $target_class = "${target}::${source_name}";
994 $self->inject_base($target_class, $orig_source->result_class, ($base || ()) );
996 $schema->register_source(
999 result_class => $target_class
1004 # Legacy stuff, not inserting INDIRECT assertions
1005 quote_sub "${target}::${_}" => "shift->schema->$_(\@_)"
1006 for qw(class source resultset);
1009 # needed to cover the newly installed stuff via quote_sub above
1010 Class::C3->reinitialize if DBIx::Class::_ENV_::OLD_MRO;
1012 # Give each composed class yet another *schema-less* source copy
1013 # this is used for the freeze/thaw cycle
1015 # This is not covered by any tests directly, but is indirectly exercised
1016 # in t/cdbi/sweet/08pager by re-setting the schema on an existing object
1017 # FIXME - there is likely a much cheaper way to take care of this
1018 for my $source_name ($self->sources) {
1020 my $target_class = "${target}::${source_name}";
1022 $target_class->result_source_instance(
1023 $self->source($source_name)->clone(
1024 result_class => $target_class,
1025 schema => ( ref $schema || $schema ),
1033 # LEGACY: The intra-call to this was removed in 66d9ef6b and then
1034 # the sub was de-documented way later in 249963d4. No way to be sure
1035 # nothing on darkpan is calling it directly, so keeping as-is
1036 sub setup_connection_class {
1037 my ($class, $target, @info) = @_;
1038 $class->inject_base($target => 'DBIx::Class::DB');
1039 #$target->load_components('DB');
1040 $target->connection(@info);
1045 Creates a new savepoint (does nothing outside a transaction).
1046 Equivalent to calling $schema->storage->svp_begin. See
1047 L<DBIx::Class::Storage/"svp_begin"> for more information.
1052 my ($self, $name) = @_;
1054 $self->storage or $self->throw_exception
1055 ('svp_begin called on $schema without storage');
1057 $self->storage->svp_begin($name);
1062 Releases a savepoint (does nothing outside a transaction).
1063 Equivalent to calling $schema->storage->svp_release. See
1064 L<DBIx::Class::Storage/"svp_release"> for more information.
1069 my ($self, $name) = @_;
1071 $self->storage or $self->throw_exception
1072 ('svp_release called on $schema without storage');
1074 $self->storage->svp_release($name);
1079 Rollback to a savepoint (does nothing outside a transaction).
1080 Equivalent to calling $schema->storage->svp_rollback. See
1081 L<DBIx::Class::Storage/"svp_rollback"> for more information.
1086 my ($self, $name) = @_;
1088 $self->storage or $self->throw_exception
1089 ('svp_rollback called on $schema without storage');
1091 $self->storage->svp_rollback($name);
1098 =item Arguments: %attrs?
1100 =item Return Value: $new_schema
1104 Clones the schema and its associated result_source objects and returns the
1105 copy. The resulting copy will have the same attributes as the source schema,
1106 except for those attributes explicitly overridden by the provided C<%attrs>.
1114 (ref $self ? %$self : ()),
1115 (@_ == 1 && ref $_[0] eq 'HASH' ? %{ $_[0] } : @_),
1117 bless $clone, (ref $self || $self);
1119 $clone->$_(undef) for qw/class_mappings source_registrations storage/;
1121 $clone->_copy_state_from($self);
1126 # Needed in Schema::Loader - if you refactor, please make a compatibility shim
1128 sub _copy_state_from {
1129 my ($self, $from) = @_;
1131 $self->class_mappings({ %{$from->class_mappings} });
1132 $self->source_registrations({ %{$from->source_registrations} });
1134 # we use extra here as we want to leave the class_mappings as they are
1135 # but overwrite the source_registrations entry with the new source
1136 $self->register_extra_source( $_ => $from->source($_) )
1139 if ($from->storage) {
1140 $self->storage($from->storage);
1141 $self->storage->set_schema($self);
1145 =head2 throw_exception
1149 =item Arguments: $message
1153 Throws an exception. Obeys the exemption rules of L<DBIx::Class::Carp> to report
1154 errors from outer-user's perspective. See L</exception_action> for details on overriding
1155 this method's behavior. If L</stacktrace> is turned on, C<throw_exception>'s
1156 default behavior will provide a detailed stack trace.
1160 sub throw_exception {
1161 my ($self, @args) = @_;
1164 ! DBIx::Class::_Util::in_internal_try()
1166 my $act = $self->exception_action
1171 my $guard = scope_guard {
1172 return if $guard_disarmed;
1173 emit_loud_diag( emit_dups => 1, msg => "
1175 !!! DBIx::Class INTERNAL PANIC !!!
1177 The exception_action() handler installed on '$self'
1178 aborted the stacktrace below via a longjmp (either via Return::Multilevel or
1179 plain goto, or Scope::Upper or something equally nefarious). There currently
1180 is nothing safe DBIx::Class can do, aside from displaying this error. A future
1181 version ( 0.082900, when available ) will reduce the cases in which the
1182 handler is invoked, but this is neither a complete solution, nor can it do
1183 anything for other software that might be affected by a similar problem.
1185 !!! FIX YOUR ERROR HANDLING !!!
1187 This guard was activated starting",
1192 # if it throws - good, we'll assign to @args in the end
1193 # if it doesn't - do different things depending on RV truthiness
1194 if( $act->(@args) ) {
1196 "Invocation of the exception_action handler installed on $self did *not*"
1197 .' result in an exception. DBIx::Class is unable to function without a reliable'
1198 .' exception mechanism, ensure your exception_action does not hide exceptions'
1199 ." (original error: $args[0])"
1204 "The exception_action handler installed on $self returned false instead"
1205 .' of throwing an exception. This behavior has been deprecated, adjust your'
1206 .' handler to always rethrow the supplied error'
1213 # We call this to get the necessary warnings emitted and disregard the RV
1214 # as it's definitely an exception if we got as far as this catch{} block
1220 # Done guarding against https://github.com/PerlDancer/Dancer2/issues/1125
1221 $guard_disarmed = 1;
1224 DBIx::Class::Exception->throw( $args[0], $self->stacktrace );
1231 =item Arguments: \%sqlt_args, $dir
1235 Attempts to deploy the schema to the current storage using L<SQL::Translator>.
1237 See L<SQL::Translator/METHODS> for a list of values for C<\%sqlt_args>.
1238 The most common value for this would be C<< { add_drop_table => 1 } >>
1239 to have the SQL produced include a C<DROP TABLE> statement for each table
1240 created. For quoting purposes supply C<quote_identifiers>.
1242 Additionally, the DBIx::Class parser accepts a C<sources> parameter as a hash
1243 ref or an array ref, containing a list of source to deploy. If present, then
1244 only the sources listed will get deployed. Furthermore, you can use the
1245 C<add_fk_index> parser parameter to prevent the parser from creating an index for each
1251 my ($self, $sqltargs, $dir) = @_;
1252 $self->throw_exception("Can't deploy without storage") unless $self->storage;
1253 $self->storage->deploy($self, undef, $sqltargs, $dir);
1256 =head2 deployment_statements
1260 =item Arguments: See L<DBIx::Class::Storage::DBI/deployment_statements>
1262 =item Return Value: $listofstatements
1266 A convenient shortcut to
1267 C<< $self->storage->deployment_statements($self, @args) >>.
1268 Returns the statements used by L</deploy> and
1269 L<DBIx::Class::Storage/deploy>.
1273 sub deployment_statements {
1276 $self->throw_exception("Can't generate deployment statements without a storage")
1277 if not $self->storage;
1279 $self->storage->deployment_statements($self, @_);
1282 =head2 create_ddl_dir
1286 =item Arguments: See L<DBIx::Class::Storage::DBI/create_ddl_dir>
1290 A convenient shortcut to
1291 C<< $self->storage->create_ddl_dir($self, @args) >>.
1293 Creates an SQL file based on the Schema, for each of the specified
1294 database types, in the given directory.
1298 sub create_ddl_dir {
1301 $self->throw_exception("Can't create_ddl_dir without storage") unless $self->storage;
1302 $self->storage->create_ddl_dir($self, @_);
1309 =item Arguments: $database-type, $version, $directory, $preversion
1311 =item Return Value: $normalised_filename
1315 my $filename = $table->ddl_filename($type, $version, $dir, $preversion)
1317 This method is called by C<create_ddl_dir> to compose a file name out of
1318 the supplied directory, database type and version number. The default file
1319 name format is: C<$dir$schema-$version-$type.sql>.
1321 You may override this method in your schema if you wish to use a different
1326 Prior to DBIx::Class version 0.08100 this method had a different signature:
1328 my $filename = $table->ddl_filename($type, $dir, $version, $preversion)
1330 In recent versions variables $dir and $version were reversed in order to
1331 bring the signature in line with other Schema/Storage methods. If you
1332 really need to maintain backward compatibility, you can do the following
1333 in any overriding methods:
1335 ($dir, $version) = ($version, $dir) if ($DBIx::Class::VERSION < 0.08100);
1340 my ($self, $type, $version, $dir, $preversion) = @_;
1342 $version = "$preversion-$version" if $preversion;
1344 my $class = blessed($self) || $self;
1347 return "$dir/$class-$version-$type.sql";
1352 Provided as the recommended way of thawing schema objects. You can call
1353 C<Storable::thaw> directly if you wish, but the thawed objects will not have a
1354 reference to any schema, so are rather useless.
1359 my ($self, $obj) = @_;
1360 local $DBIx::Class::ResultSourceHandle::thaw_schema = $self;
1361 return Storable::thaw($obj);
1366 This doesn't actually do anything beyond calling L<nfreeze|Storable/SYNOPSIS>,
1367 it is just provided here for symmetry.
1372 return Storable::nfreeze($_[1]);
1379 =item Arguments: $object
1381 =item Return Value: dcloned $object
1385 Recommended way of dcloning L<DBIx::Class::Row> and L<DBIx::Class::ResultSet>
1386 objects so their references to the schema object
1387 (which itself is B<not> cloned) are properly maintained.
1392 my ($self, $obj) = @_;
1393 local $DBIx::Class::ResultSourceHandle::thaw_schema = $self;
1394 return Storable::dclone($obj);
1397 =head2 schema_version
1399 Returns the current schema class' $VERSION in a normalised way.
1403 sub schema_version {
1405 my $class = ref($self)||$self;
1407 # does -not- use $schema->VERSION
1408 # since that varies in results depending on if version.pm is installed, and if
1409 # so the perl or XS versions. If you want this to change, bug the version.pm
1410 # author to make vpp and vxs behave the same.
1415 $version = ${"${class}::VERSION"};
1421 =head2 register_class
1425 =item Arguments: $source_name, $component_class
1429 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 You will only need this method if you have your Result classes in
1432 files which are not named after the packages (or all in the same
1433 file). You may also need it to register classes at runtime.
1435 Registers a class which isa DBIx::Class::ResultSourceProxy. Equivalent to
1438 $schema->register_source($source_name, $component_class->result_source);
1442 sub register_class {
1443 my ($self, $source_name, $to_register) = @_;
1444 $self->register_source($source_name => $to_register->result_source);
1447 =head2 register_source
1451 =item Arguments: $source_name, L<$result_source|DBIx::Class::ResultSource>
1455 This method is called by L</register_class>.
1457 Registers the L<DBIx::Class::ResultSource> in the schema with the given
1462 sub register_source { shift->_register_source(@_) }
1464 =head2 unregister_source
1468 =item Arguments: $source_name
1472 Removes the L<DBIx::Class::ResultSource> from the schema for the given source name.
1476 sub unregister_source { shift->_unregister_source(@_) }
1478 =head2 register_extra_source
1482 =item Arguments: $source_name, L<$result_source|DBIx::Class::ResultSource>
1486 As L</register_source> but should be used if the result class already
1487 has a source and you want to register an extra one.
1491 sub register_extra_source { shift->_register_source(@_, { extra => 1 }) }
1493 sub _register_source {
1494 my ($self, $source_name, $supplied_rsrc, $params) = @_;
1496 my $derived_rsrc = $supplied_rsrc->clone({
1497 source_name => $source_name,
1500 # Do not move into the clone-hashref above: there are things
1501 # on CPAN that do hook 'sub schema' </facepalm>
1502 # https://metacpan.org/source/LSAUNDERS/DBIx-Class-Preview-1.000003/lib/DBIx/Class/ResultSource/Table/Previewed.pm#L9-38
1503 $derived_rsrc->schema($self);
1505 weaken $derived_rsrc->{schema}
1506 if length( my $schema_class = ref($self) );
1508 my %reg = %{$self->source_registrations};
1509 $reg{$source_name} = $derived_rsrc;
1510 $self->source_registrations(\%reg);
1512 return $derived_rsrc if $params->{extra};
1514 my( $result_class, $result_class_level_rsrc );
1516 $result_class = $derived_rsrc->result_class
1518 # There are known cases where $rs_class is *ONLY* an inflator, without
1519 # any hint of a rsrc (e.g. DBIx::Class::KiokuDB::EntryProxy)
1520 $result_class_level_rsrc = dbic_internal_try { $result_class->result_source_instance }
1522 my %map = %{$self->class_mappings};
1525 "$result_class already had a registered source which was replaced by "
1526 . 'this call. Perhaps you wanted register_extra_source(), though it is '
1527 . 'more likely you did something wrong.'
1529 exists $map{$result_class}
1531 $map{$result_class} ne $source_name
1533 $result_class_level_rsrc != $supplied_rsrc
1536 $map{$result_class} = $source_name;
1537 $self->class_mappings(\%map);
1540 my $schema_class_level_rsrc;
1542 # we are called on a schema instance, not on the class
1543 length $schema_class
1547 # the schema class also has a registration with the same name
1548 $schema_class_level_rsrc = dbic_internal_try { $schema_class->source($source_name) }
1552 # what we are registering on the schema instance *IS* derived
1553 # from the class-level (top) rsrc...
1554 ( grep { $_ == $derived_rsrc } $result_class_level_rsrc->__derived_instances )
1558 # ... while the schema-class-level has stale-markers
1559 keys %{ $schema_class_level_rsrc->{__metadata_divergencies} || {} }
1562 "The ResultSource instance you just registered on '$self' as "
1563 . "'$source_name' seems to have no relation to $schema_class->"
1564 . "source('$source_name') which in turn is marked stale (likely due "
1565 . "to recent $result_class->... direct class calls). This is almost "
1566 . "always a mistake: perhaps you forgot a cycle of "
1567 . "$schema_class->unregister_source( '$source_name' ) / "
1568 . "$schema_class->register_class( '$source_name' => '$result_class' )"
1571 DBIx::Class::_ENV_::ASSERT_NO_ERRONEOUS_METAINSTANCE_USE
1572 ? emit_loud_diag( msg => $msg, confess => 1 )
1581 my $global_phase_destroy;
1583 ### NO detected_reinvoked_destructor check
1584 ### This code very much relies on being called multuple times
1586 return if $global_phase_destroy ||= in_global_destruction;
1589 my $srcs = $self->source_registrations;
1591 for my $source_name (keys %$srcs) {
1592 # find first source that is not about to be GCed (someone other than $self
1593 # holds a reference to it) and reattach to it, weakening our own link
1595 # during global destruction (if we have not yet bailed out) this should throw
1596 # which will serve as a signal to not try doing anything else
1597 # however beware - on older perls the exception seems randomly untrappable
1598 # due to some weird race condition during thread joining :(((
1599 if (length ref $srcs->{$source_name} and refcount($srcs->{$source_name}) > 1) {
1600 local $SIG{__DIE__} if $SIG{__DIE__};
1601 local $@ if DBIx::Class::_ENV_::UNSTABLE_DOLLARAT;
1603 $srcs->{$source_name}->schema($self);
1604 weaken $srcs->{$source_name};
1607 $global_phase_destroy = 1;
1614 # Dummy NEXTSTATE ensuring the all temporaries on the stack are garbage
1615 # collected before leaving this scope. Depending on the code above, this
1616 # may very well be just a preventive measure guarding future modifications
1620 sub _unregister_source {
1621 my ($self, $source_name) = @_;
1622 my %reg = %{$self->source_registrations};
1624 my $source = delete $reg{$source_name};
1625 $self->source_registrations(\%reg);
1626 if ($source->result_class) {
1627 my %map = %{$self->class_mappings};
1628 delete $map{$source->result_class};
1629 $self->class_mappings(\%map);
1634 =head2 compose_connection (DEPRECATED)
1638 =item Arguments: $target_namespace, @db_info
1640 =item Return Value: $new_schema
1644 DEPRECATED. You probably wanted compose_namespace.
1646 Actually, you probably just wanted to call connect.
1650 (hidden due to deprecation)
1652 Calls L<DBIx::Class::Schema/"compose_namespace"> to the target namespace,
1653 calls L<DBIx::Class::Schema/connection> with @db_info on the new schema,
1654 then injects the L<DBix::Class::ResultSetProxy> component and a
1655 resultset_instance classdata entry on all the new classes, in order to support
1656 $target_namespaces::$class->search(...) method calls.
1658 This is primarily useful when you have a specific need for class method access
1659 to a connection. In normal usage it is preferred to call
1660 L<DBIx::Class::Schema/connect> and use the resulting schema object to operate
1661 on L<DBIx::Class::ResultSet> objects with L<DBIx::Class::Schema/resultset> for
1668 sub compose_connection {
1669 my ($self, $target, @info) = @_;
1671 carp_once "compose_connection deprecated as of 0.08000"
1672 unless $INC{"DBIx/Class/CDBICompat.pm"};
1675 require DBIx::Class::ResultSetProxy;
1678 $self->throw_exception
1679 ("No arguments to load_classes and couldn't load DBIx::Class::ResultSetProxy ($_)")
1682 if ($self eq $target) {
1683 # Pathological case, largely caused by the docs on early C::M::DBIC::Plain
1684 foreach my $source_name ($self->sources) {
1685 my $source = $self->source($source_name);
1686 my $class = $source->result_class;
1687 $self->inject_base($class, 'DBIx::Class::ResultSetProxy');
1688 $class->mk_classaccessor(resultset_instance => $source->resultset);
1689 $class->mk_classaccessor(class_resolver => $self);
1691 $self->connection(@info);
1695 my $schema = $self->compose_namespace($target, 'DBIx::Class::ResultSetProxy');
1696 quote_sub "${target}::schema", '$s', { '$s' => \$schema };
1698 # needed to cover the newly installed stuff via quote_sub above
1699 Class::C3->reinitialize if DBIx::Class::_ENV_::OLD_MRO;
1701 $schema->connection(@info);
1702 foreach my $source_name ($schema->sources) {
1703 my $source = $schema->source($source_name);
1704 my $class = $source->result_class;
1705 #warn "$source_name $class $source ".$source->storage;
1707 $class->mk_group_accessors( inherited => [ result_source_instance => '_result_source' ] );
1708 # explicit set-call, avoid mro update lag
1709 $class->set_inherited( result_source_instance => $source );
1711 $class->mk_classaccessor(resultset_instance => $source->resultset);
1712 $class->mk_classaccessor(class_resolver => $schema);
1717 =head1 FURTHER QUESTIONS?
1719 Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
1721 =head1 COPYRIGHT AND LICENSE
1723 This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
1724 by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
1725 redistribute it and/or modify it under the same terms as the
1726 L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.