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::Schema::SanityChecker'
38 DBIx::Class::Schema - composable schemas
42 package Library::Schema;
43 use base qw/DBIx::Class::Schema/;
45 # load all Result classes in Library/Schema/Result/
46 __PACKAGE__->load_namespaces();
48 package Library::Schema::Result::CD;
49 use base qw/DBIx::Class::Core/;
51 __PACKAGE__->load_components(qw/InflateColumn::DateTime/); # for example
52 __PACKAGE__->table('cd');
54 # Elsewhere in your code:
55 my $schema1 = Library::Schema->connect(
62 my $schema2 = Library::Schema->connect($coderef_returning_dbh);
64 # fetch objects using Library::Schema::Result::DVD
65 my $resultset = $schema1->resultset('DVD')->search( ... );
66 my @dvd_objects = $schema2->resultset('DVD')->search( ... );
70 Creates database classes based on a schema. This is the recommended way to
71 use L<DBIx::Class> and allows you to use more than one concurrent connection
74 NB: If you're used to L<Class::DBI> it's worth reading the L</SYNOPSIS>
75 carefully, as DBIx::Class does things a little differently. Note in
76 particular which module inherits off which.
80 =head2 load_namespaces
84 =item Arguments: %options?
88 package MyApp::Schema;
89 __PACKAGE__->load_namespaces();
91 __PACKAGE__->load_namespaces(
92 result_namespace => 'Res',
93 resultset_namespace => 'RSet',
94 default_resultset_class => '+MyApp::Othernamespace::RSet',
97 With no arguments, this method uses L<Module::Find> to load all of the
98 Result and ResultSet classes under the namespace of the schema from
99 which it is called. For example, C<My::Schema> will by default find
100 and load Result classes named C<My::Schema::Result::*> and ResultSet
101 classes named C<My::Schema::ResultSet::*>.
103 ResultSet classes are associated with Result class of the same name.
104 For example, C<My::Schema::Result::CD> will get the ResultSet class
105 C<My::Schema::ResultSet::CD> if it is present.
107 Both Result and ResultSet namespaces are configurable via the
108 C<result_namespace> and C<resultset_namespace> options.
110 Another option, C<default_resultset_class> specifies a custom default
111 ResultSet class for Result classes with no corresponding ResultSet.
113 All of the namespace and classname options are by default relative to
114 the schema classname. To specify a fully-qualified name, prefix it
115 with a literal C<+>. For example, C<+Other::NameSpace::Result>.
119 You will be warned if ResultSet classes are discovered for which there
120 are no matching Result classes like this:
122 load_namespaces found ResultSet class $classname with no corresponding Result class
124 If a ResultSource instance is found to already have a ResultSet class set
125 using L<resultset_class|DBIx::Class::ResultSource/resultset_class> to some
126 other class, you will be warned like this:
128 We found ResultSet class '$rs_class' for '$result_class', but it seems
129 that you had already set '$result_class' to use '$rs_set' instead
133 # load My::Schema::Result::CD, My::Schema::Result::Artist,
134 # My::Schema::ResultSet::CD, etc...
135 My::Schema->load_namespaces;
137 # Override everything to use ugly names.
138 # In this example, if there is a My::Schema::Res::Foo, but no matching
139 # My::Schema::RSets::Foo, then Foo will have its
140 # resultset_class set to My::Schema::RSetBase
141 My::Schema->load_namespaces(
142 result_namespace => 'Res',
143 resultset_namespace => 'RSets',
144 default_resultset_class => 'RSetBase',
147 # Put things in other namespaces
148 My::Schema->load_namespaces(
149 result_namespace => '+Some::Place::Results',
150 resultset_namespace => '+Another::Place::RSets',
153 To search multiple namespaces for either Result or ResultSet classes,
154 use an arrayref of namespaces for that option. In the case that the
155 same result (or resultset) class exists in multiple namespaces, later
156 entries in the list of namespaces will override earlier ones.
158 My::Schema->load_namespaces(
159 # My::Schema::Results_C::Foo takes precedence over My::Schema::Results_B::Foo :
160 result_namespace => [ 'Results_A', 'Results_B', 'Results_C' ],
161 resultset_namespace => [ '+Some::Place::RSets', 'RSets' ],
166 # Pre-pends our classname to the given relative classname or
167 # class namespace, unless there is a '+' prefix, which will
169 sub _expand_relative_name {
170 my ($class, $name) = @_;
171 $name =~ s/^\+// or $name = "${class}::${name}";
175 # Finds all modules in the supplied namespace, or if omitted in the
176 # namespace of $class. Untaints all findings as they can be assumed
179 require Module::Find;
181 { $_ =~ /(.+)/ } # untaint result
182 Module::Find::findallmod( $_[1] || ref $_[0] || $_[0] )
186 # returns a hash of $shortname => $fullname for every package
187 # found in the given namespaces ($shortname is with the $fullname's
188 # namespace stripped off)
189 sub _map_namespaces {
190 my ($me, $namespaces) = @_;
193 for my $ns (@$namespaces) {
194 $res{ substr($_, length "${ns}::") } = $_
195 for $me->_findallmod($ns);
201 # returns the result_source_instance for the passed class/object,
202 # or dies with an informative message (used by load_namespaces)
203 sub _ns_get_rsrc_instance {
205 my $rs_class = ref ($_[0]) || $_[0];
207 return dbic_internal_try {
208 $rs_class->result_source
210 $me->throw_exception (
211 "Attempt to load_namespaces() class $rs_class failed - are you sure this is a real Result Class?: $_"
216 sub load_namespaces {
217 my ($class, %args) = @_;
219 my $result_namespace = delete $args{result_namespace} || 'Result';
220 my $resultset_namespace = delete $args{resultset_namespace} || 'ResultSet';
222 my $default_resultset_class = delete $args{default_resultset_class};
224 $default_resultset_class = $class->_expand_relative_name($default_resultset_class)
225 if $default_resultset_class;
227 $class->throw_exception('load_namespaces: unknown option(s): '
228 . join(q{,}, map { qq{'$_'} } keys %args))
229 if scalar keys %args;
231 for my $arg ($result_namespace, $resultset_namespace) {
232 $arg = [ $arg ] if ( $arg and ! ref $arg );
234 $class->throw_exception('load_namespaces: namespace arguments must be '
235 . 'a simple string or an arrayref')
236 if ref($arg) ne 'ARRAY';
238 $_ = $class->_expand_relative_name($_) for (@$arg);
241 my $results_by_source_name = $class->_map_namespaces($result_namespace);
242 my $resultsets_by_source_name = $class->_map_namespaces($resultset_namespace);
246 # ensure classes are loaded and attached in inheritance order
247 for my $result_class (values %$results_by_source_name) {
248 $class->ensure_class_loaded($result_class);
251 my @source_names_by_subclass_last = sort {
254 scalar @{mro::get_linear_isa( $results_by_source_name->{$a} )}
260 scalar @{mro::get_linear_isa( $results_by_source_name->{$b} )}
263 } keys(%$results_by_source_name);
265 foreach my $source_name (@source_names_by_subclass_last) {
266 my $result_class = $results_by_source_name->{$source_name};
268 my $preset_resultset_class = $class->_ns_get_rsrc_instance ($result_class)->resultset_class;
269 my $found_resultset_class = delete $resultsets_by_source_name->{$source_name};
271 if($preset_resultset_class && $preset_resultset_class ne 'DBIx::Class::ResultSet') {
272 if($found_resultset_class && $found_resultset_class ne $preset_resultset_class) {
273 carp "We found ResultSet class '$found_resultset_class' matching '$results_by_source_name->{$source_name}', but it seems "
274 . "that you had already set the '$results_by_source_name->{$source_name}' resultet to '$preset_resultset_class' instead";
277 # elsif - there may be *no* default_resultset_class, in which case we fallback to
278 # DBIx::Class::Resultset and there is nothing to check
279 elsif($found_resultset_class ||= $default_resultset_class) {
280 $class->ensure_class_loaded($found_resultset_class);
281 if(!$found_resultset_class->isa("DBIx::Class::ResultSet")) {
282 carp "load_namespaces found ResultSet class '$found_resultset_class' that does not subclass DBIx::Class::ResultSet";
285 $class->_ns_get_rsrc_instance ($result_class)->resultset_class($found_resultset_class);
288 my $source_name = $class->_ns_get_rsrc_instance ($result_class)->source_name || $source_name;
290 push(@to_register, [ $source_name, $result_class ]);
294 foreach (sort keys %$resultsets_by_source_name) {
295 carp "load_namespaces found ResultSet class '$resultsets_by_source_name->{$_}' "
296 .'with no corresponding Result class';
299 $class->register_class(@$_) for (@to_register);
308 =item Arguments: @classes?, { $namespace => [ @classes ] }+
312 L</load_classes> is an alternative method to L</load_namespaces>, both of
313 which serve similar purposes, each with different advantages and disadvantages.
314 In the general case you should use L</load_namespaces>, unless you need to
315 be able to specify that only specific classes are loaded at runtime.
317 With no arguments, this method uses L<Module::Find> to find all classes under
318 the schema's namespace. Otherwise, this method loads the classes you specify
319 (using L<use>), and registers them (using L</"register_class">).
321 It is possible to comment out classes with a leading C<#>, but note that perl
322 will think it's a mistake (trying to use a comment in a qw list), so you'll
323 need to add C<no warnings 'qw';> before your load_classes call.
325 If any classes found do not appear to be Result class files, you will
326 get the following warning:
328 Failed to load $comp_class. Can't find source_name method. Is
329 $comp_class really a full DBIC result class? Fix it, move it elsewhere,
330 or make your load_classes call more specific.
334 My::Schema->load_classes(); # loads My::Schema::CD, My::Schema::Artist,
335 # etc. (anything under the My::Schema namespace)
337 # loads My::Schema::CD, My::Schema::Artist, Other::Namespace::Producer but
338 # not Other::Namespace::LinerNotes nor My::Schema::Track
339 My::Schema->load_classes(qw/ CD Artist #Track /, {
340 Other::Namespace => [qw/ Producer #LinerNotes /],
346 my ($class, @params) = @_;
351 foreach my $param (@params) {
352 if (ref $param eq 'ARRAY') {
353 # filter out commented entries
354 my @modules = grep { $_ !~ /^#/ } @$param;
356 push (@{$comps_for{$class}}, @modules);
358 elsif (ref $param eq 'HASH') {
359 # more than one namespace possible
360 for my $comp ( keys %$param ) {
361 # filter out commented entries
362 my @modules = grep { $_ !~ /^#/ } @{$param->{$comp}};
364 push (@{$comps_for{$comp}}, @modules);
368 # filter out commented entries
369 push (@{$comps_for{$class}}, $param) if $param !~ /^#/;
373 my @comp = map { substr $_, length "${class}::" }
374 $class->_findallmod($class);
375 $comps_for{$class} = \@comp;
380 foreach my $prefix (keys %comps_for) {
381 foreach my $comp (@{$comps_for{$prefix}||[]}) {
382 my $comp_class = "${prefix}::${comp}";
383 $class->ensure_class_loaded($comp_class);
385 my $snsub = $comp_class->can('source_name');
387 carp "Failed to load $comp_class. Can't find source_name method. Is $comp_class really a full DBIC result class? Fix it, move it elsewhere, or make your load_classes call more specific.";
390 $comp = $snsub->($comp_class) || $comp;
392 push(@to_register, [ $comp, $comp_class ]);
397 foreach my $to (@to_register) {
398 $class->register_class(@$to);
406 =item Arguments: $storage_type|{$storage_type, \%args}
408 =item Return Value: $storage_type|{$storage_type, \%args}
410 =item Default value: DBIx::Class::Storage::DBI
414 Set the storage class that will be instantiated when L</connect> is called.
415 If the classname starts with C<::>, the prefix C<DBIx::Class::Storage> is
416 assumed by L</connect>.
418 You want to use this to set subclasses of L<DBIx::Class::Storage::DBI>
419 in cases where the appropriate subclass is not autodetected.
421 If your storage type requires instantiation arguments, those are
422 defined as a second argument in the form of a hashref and the entire
423 value needs to be wrapped into an arrayref or a hashref. We support
424 both types of refs here in order to play nice with your
425 Config::[class] or your choice. See
426 L<DBIx::Class::Storage::DBI::Replicated> for an example of this.
428 =head2 default_resultset_attributes
432 =item Arguments: L<\%attrs|DBIx::Class::ResultSet/ATTRIBUTES>
434 =item Return Value: L<\%attrs|DBIx::Class::ResultSet/ATTRIBUTES>
436 =item Default value: None
440 Like L<DBIx::Class::ResultSource/resultset_attributes> stores a collection
441 of resultset attributes, to be used as defaults for B<every> ResultSet
442 instance schema-wide. The same list of CAVEATS and WARNINGS applies, with
443 the extra downside of these defaults being practically inescapable: you will
444 B<not> be able to derive a ResultSet instance with these attributes unset.
449 use base qw/DBIx::Class::Schema/;
450 __PACKAGE__->default_resultset_attributes( { software_limit => 1 } );
452 =head2 schema_sanity_checker
456 =item Arguments: L<perform_schema_sanity_checks()|DBIx::Class::Schema::SanityChecker/perform_schema_sanity_checks> provider
458 =item Return Value: L<perform_schema_sanity_checks()|DBIx::Class::Schema::SanityChecker/perform_schema_sanity_checks> provider
460 =item Default value: L<DBIx::Class::Schema::SanityChecker>
464 On every call to L</connection> if the value of this attribute evaluates to
465 true, DBIC will invoke
466 C<< L<$schema_sanity_checker|/schema_sanity_checker>->L<perform_schema_sanity_checks|DBIx::Class::Schema::SanityChecker/perform_schema_sanity_checks>($schema) >>
467 before returning. The return value of this invocation is ignored.
469 B<YOU ARE STRONGLY URGED> to
470 L<learn more about the reason|DBIx::Class::Schema::SanityChecker/WHY> this
471 feature was introduced. Blindly disabling the checker on existing projects
472 B<may result in data corruption> after upgrade to C<< DBIC >= v0.082900 >>.
477 use base qw/DBIx::Class::Schema/;
478 __PACKAGE__->schema_sanity_checker('My::Schema::SanityChecker');
480 # or to disable all checks:
481 __PACKAGE__->schema_sanity_checker('');
483 Note: setting the value to C<undef> B<will not> have the desired effect,
484 due to an implementation detail of L<Class::Accessor::Grouped> inherited
485 accessors. In order to disable any and all checks you must set this
486 attribute to an empty string as shown in the second example above.
488 =head2 exception_action
492 =item Arguments: $code_reference
494 =item Return Value: $code_reference
496 =item Default value: None
500 When L</throw_exception> is invoked and L</exception_action> is set to a code
501 reference, this reference will be called instead of
502 L<DBIx::Class::Exception/throw>, with the exception message passed as the only
505 Your custom throw code B<must> rethrow the exception, as L</throw_exception> is
506 an integral part of DBIC's internal execution control flow.
511 use base qw/DBIx::Class::Schema/;
512 use My::ExceptionClass;
513 __PACKAGE__->exception_action(sub { My::ExceptionClass->throw(@_) });
514 __PACKAGE__->load_classes;
517 my $schema_obj = My::Schema->connect( .... );
518 $schema_obj->exception_action(sub { My::ExceptionClass->throw(@_) });
524 =item Arguments: boolean
528 Whether L</throw_exception> should include stack trace information.
529 Defaults to false normally, but defaults to true if C<$ENV{DBIC_TRACE}>
532 =head2 sqlt_deploy_hook
536 =item Arguments: $sqlt_schema
540 An optional sub which you can declare in your own Schema class that will get
541 passed the L<SQL::Translator::Schema> object when you deploy the schema via
542 L</create_ddl_dir> or L</deploy>.
544 For an example of what you can do with this, see
545 L<DBIx::Class::Manual::Cookbook/Adding Indexes And Functions To Your SQL>.
547 Note that sqlt_deploy_hook is called by L</deployment_statements>, which in turn
548 is called before L</deploy>. Therefore the hook can be used only to manipulate
549 the L<SQL::Translator::Schema> object before it is turned into SQL fed to the
550 database. If you want to execute post-deploy statements which can not be generated
551 by L<SQL::Translator>, the currently suggested method is to overload L</deploy>
552 and use L<dbh_do|DBIx::Class::Storage::DBI/dbh_do>.
560 =item Arguments: @connectinfo
562 =item Return Value: $new_schema
566 Creates and returns a new Schema object. The connection info set on it
567 is used to create a new instance of the storage backend and set it on
570 See L<DBIx::Class::Storage::DBI/"connect_info"> for DBI-specific
571 syntax on the C<@connectinfo> argument, or L<DBIx::Class::Storage> in
574 Note that C<connect_info> expects an arrayref of arguments, but
575 C<connect> does not. C<connect> wraps its arguments in an arrayref
576 before passing them to C<connect_info>.
580 C<connect> is a convenience method. It is equivalent to calling
581 $schema->clone->connection(@connectinfo). To write your own overloaded
582 version, overload L</connection> instead.
586 sub connect :DBIC_method_is_indirect_sugar {
587 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
588 shift->clone->connection(@_);
595 =item Arguments: L<$source_name|DBIx::Class::ResultSource/source_name>
597 =item Return Value: L<$resultset|DBIx::Class::ResultSet>
601 my $rs = $schema->resultset('DVD');
603 Returns the L<DBIx::Class::ResultSet> object for the registered source
609 my ($self, $source_name) = @_;
610 $self->throw_exception('resultset() expects a source name')
611 unless defined $source_name;
612 return $self->source($source_name)->resultset;
619 =item Return Value: L<@source_names|DBIx::Class::ResultSource/source_name>
623 my @source_names = $schema->sources;
625 Lists names of all the sources registered on this Schema object.
629 sub sources { keys %{shift->source_registrations} }
635 =item Arguments: L<$source_name|DBIx::Class::ResultSource/source_name>
637 =item Return Value: L<$result_source|DBIx::Class::ResultSource>
641 my $source = $schema->source('Book');
643 Returns the L<DBIx::Class::ResultSource> object for the registered
649 my ($self, $source_name) = @_;
651 $self->throw_exception("source() expects a source name")
654 my $source_registrations;
657 ( $source_registrations = $self->source_registrations )->{$source_name}
659 # if we got here, they probably passed a full class name
660 $source_registrations->{ $self->class_mappings->{$source_name} || '' }
662 $self->throw_exception( "Can't find source for ${source_name}" )
666 # We need to prevent alterations of pre-existing $@ due to where this call
667 # sits in the overall stack ( *unless* of course there is an actual error
668 # to report ). set_mro does alter $@ (and yes - it *can* throw an exception)
669 # We do not use local because set_mro *can* throw an actual exception
670 # We do not use a try/catch either, as on one hand it would slow things
671 # down for no reason (we would always rethrow), but also because adding *any*
672 # try/catch block below will segfault various threading tests on older perls
673 # ( which in itself is a FIXME but ENOTIMETODIG )
674 my $old_dollarat = $@;
677 mro::set_mro($_, 'c3') for
680 # some pseudo-sources do not have a result/resultset yet
685 ${"${_}::__INITIAL_MRO_UPON_DBIC_LOAD__"}
693 { length ref $_ ? ref $_ : $_ }
694 ( $rsrc, $rsrc->result_class, $rsrc->resultset_class )
697 # DO NOT REMOVE - see comment above
707 =item Arguments: L<$source_name|DBIx::Class::ResultSource/source_name>
709 =item Return Value: $classname
713 my $class = $schema->class('CD');
715 Retrieves the Result class name for the given source name.
720 return shift->source(shift)->result_class;
727 =item Arguments: C<$coderef>, @coderef_args?
729 =item Return Value: The return value of $coderef
733 Executes C<$coderef> with (optional) arguments C<@coderef_args> atomically,
734 returning its result (if any). Equivalent to calling $schema->storage->txn_do.
735 See L<DBIx::Class::Storage/"txn_do"> for more information.
737 This interface is preferred over using the individual methods L</txn_begin>,
738 L</txn_commit>, and L</txn_rollback> below.
740 WARNING: If you are connected with C<< AutoCommit => 0 >> the transaction is
741 considered nested, and you will still need to call L</txn_commit> to write your
742 changes when appropriate. You will also want to connect with C<< auto_savepoint =>
743 1 >> to get partial rollback to work, if the storage driver for your database
746 Connecting with C<< AutoCommit => 1 >> is recommended.
753 $self->storage or $self->throw_exception
754 ('txn_do called on $schema without storage');
756 $self->storage->txn_do(@_);
759 =head2 txn_scope_guard
761 Runs C<txn_scope_guard> on the schema's storage. See
762 L<DBIx::Class::Storage/txn_scope_guard>.
766 sub txn_scope_guard {
769 $self->storage or $self->throw_exception
770 ('txn_scope_guard called on $schema without storage');
772 $self->storage->txn_scope_guard(@_);
777 Begins a transaction (does nothing if AutoCommit is off). Equivalent to
778 calling $schema->storage->txn_begin. See
779 L<DBIx::Class::Storage/"txn_begin"> for more information.
786 $self->storage or $self->throw_exception
787 ('txn_begin called on $schema without storage');
789 $self->storage->txn_begin;
794 Commits the current transaction. Equivalent to calling
795 $schema->storage->txn_commit. See L<DBIx::Class::Storage/"txn_commit">
796 for more information.
803 $self->storage or $self->throw_exception
804 ('txn_commit called on $schema without storage');
806 $self->storage->txn_commit;
811 Rolls back the current transaction. Equivalent to calling
812 $schema->storage->txn_rollback. See
813 L<DBIx::Class::Storage/"txn_rollback"> for more information.
820 $self->storage or $self->throw_exception
821 ('txn_rollback called on $schema without storage');
823 $self->storage->txn_rollback;
828 my $storage = $schema->storage;
830 Returns the L<DBIx::Class::Storage> object for this Schema. Grab this
831 if you want to turn on SQL statement debugging at runtime, or set the
832 quote character. For the default storage, the documentation can be
833 found in L<DBIx::Class::Storage::DBI>.
839 =item Arguments: L<$source_name|DBIx::Class::ResultSource/source_name>, [ \@column_list, \@row_values+ ] | [ \%col_data+ ]
841 =item Return Value: L<\@result_objects|DBIx::Class::Manual::ResultClass> (scalar context) | L<@result_objects|DBIx::Class::Manual::ResultClass> (list context)
845 A convenience shortcut to L<DBIx::Class::ResultSet/populate>. Equivalent to:
847 $schema->resultset($source_name)->populate([...]);
853 The context of this method call has an important effect on what is
854 submitted to storage. In void context data is fed directly to fastpath
855 insertion routines provided by the underlying storage (most often
856 L<DBI/execute_for_fetch>), bypassing the L<new|DBIx::Class::Row/new> and
857 L<insert|DBIx::Class::Row/insert> calls on the
858 L<Result|DBIx::Class::Manual::ResultClass> class, including any
859 augmentation of these methods provided by components. For example if you
860 are using something like L<DBIx::Class::UUIDColumns> to create primary
861 keys for you, you will find that your PKs are empty. In this case you
862 will have to explicitly force scalar or list context in order to create
869 sub populate :DBIC_method_is_indirect_sugar {
870 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
872 my ($self, $name, $data) = @_;
873 my $rs = $self->resultset($name)
874 or $self->throw_exception("'$name' is not a resultset");
876 return $rs->populate($data);
883 =item Arguments: @args
885 =item Return Value: $self
889 Similar to L</connect> except sets the storage object and connection
890 data B<in-place> on C<$self>. You should probably be calling
891 L</connect> to get a properly L<cloned|/clone> Schema object instead.
893 If the accessor L</schema_sanity_checker> returns a true value C<$checker>,
894 the following call will take place before return:
895 C<< L<$checker|/schema_sanity_checker>->L<perform_schema_sanity_checks(C<$self>)|DBIx::Class::Schema::SanityChecker/perform_schema_sanity_checks> >>
899 Overload C<connection> to change the behaviour of C<connect>.
903 my $default_off_stderr_blurb_emitted;
905 my ($self, @info) = @_;
906 return $self if !@info && $self->storage;
908 my ($storage_class, $args) = ref $self->storage_type
909 ? $self->_normalize_storage_type($self->storage_type)
910 : $self->storage_type
913 $storage_class =~ s/^::/DBIx::Class::Storage::/;
916 $self->ensure_class_loaded ($storage_class);
919 $self->throw_exception(
920 "Unable to load storage class ${storage_class}: $_"
924 my $storage = $storage_class->new( $self => $args||{} );
925 $storage->connect_info(\@info);
926 $self->storage($storage);
928 if( my $checker = $self->schema_sanity_checker ) {
929 $checker->perform_schema_sanity_checks($self);
935 sub _normalize_storage_type {
936 my ($self, $storage_type) = @_;
937 if(ref $storage_type eq 'ARRAY') {
938 return @$storage_type;
939 } elsif(ref $storage_type eq 'HASH') {
940 return %$storage_type;
942 $self->throw_exception('Unsupported REFTYPE given: '. ref $storage_type);
946 =head2 compose_namespace
950 =item Arguments: $target_namespace, $additional_base_class?
952 =item Return Value: $new_schema
956 For each L<DBIx::Class::ResultSource> in the schema, this method creates a
957 class in the target namespace (e.g. $target_namespace::CD,
958 $target_namespace::Artist) that inherits from the corresponding classes
959 attached to the current schema.
961 It also attaches a corresponding L<DBIx::Class::ResultSource> object to the
962 new $schema object. If C<$additional_base_class> is given, the new composed
963 classes will inherit from first the corresponding class from the current
964 schema then the base class.
966 For example, for a schema with My::Schema::CD and My::Schema::Artist classes,
968 $schema->compose_namespace('My::DB', 'Base::Class');
969 print join (', ', @My::DB::CD::ISA) . "\n";
970 print join (', ', @My::DB::Artist::ISA) ."\n";
972 will produce the output
974 My::Schema::CD, Base::Class
975 My::Schema::Artist, Base::Class
979 sub compose_namespace {
980 my ($self, $target, $base) = @_;
982 my $schema = $self->clone;
984 $schema->source_registrations({});
986 # the original class-mappings must remain - otherwise
987 # reverse_relationship_info will not work
988 #$schema->class_mappings({});
991 foreach my $source_name ($self->sources) {
992 my $orig_source = $self->source($source_name);
994 my $target_class = "${target}::${source_name}";
995 $self->inject_base($target_class, $orig_source->result_class, ($base || ()) );
997 $schema->register_source(
1000 result_class => $target_class
1005 # Legacy stuff, not inserting INDIRECT assertions
1006 quote_sub "${target}::${_}" => "shift->schema->$_(\@_)"
1007 for qw(class source resultset);
1010 # needed to cover the newly installed stuff via quote_sub above
1011 Class::C3->reinitialize if DBIx::Class::_ENV_::OLD_MRO;
1013 # Give each composed class yet another *schema-less* source copy
1014 # this is used for the freeze/thaw cycle
1016 # This is not covered by any tests directly, but is indirectly exercised
1017 # in t/cdbi/sweet/08pager by re-setting the schema on an existing object
1018 # FIXME - there is likely a much cheaper way to take care of this
1019 for my $source_name ($self->sources) {
1021 my $target_class = "${target}::${source_name}";
1023 $target_class->result_source_instance(
1024 $self->source($source_name)->clone(
1025 result_class => $target_class,
1026 schema => ( ref $schema || $schema ),
1034 # LEGACY: The intra-call to this was removed in 66d9ef6b and then
1035 # the sub was de-documented way later in 249963d4. No way to be sure
1036 # nothing on darkpan is calling it directly, so keeping as-is
1037 sub setup_connection_class {
1038 my ($class, $target, @info) = @_;
1039 $class->inject_base($target => 'DBIx::Class::DB');
1040 #$target->load_components('DB');
1041 $target->connection(@info);
1046 Creates a new savepoint (does nothing outside a transaction).
1047 Equivalent to calling $schema->storage->svp_begin. See
1048 L<DBIx::Class::Storage/"svp_begin"> for more information.
1053 my ($self, $name) = @_;
1055 $self->storage or $self->throw_exception
1056 ('svp_begin called on $schema without storage');
1058 $self->storage->svp_begin($name);
1063 Releases a savepoint (does nothing outside a transaction).
1064 Equivalent to calling $schema->storage->svp_release. See
1065 L<DBIx::Class::Storage/"svp_release"> for more information.
1070 my ($self, $name) = @_;
1072 $self->storage or $self->throw_exception
1073 ('svp_release called on $schema without storage');
1075 $self->storage->svp_release($name);
1080 Rollback to a savepoint (does nothing outside a transaction).
1081 Equivalent to calling $schema->storage->svp_rollback. See
1082 L<DBIx::Class::Storage/"svp_rollback"> for more information.
1087 my ($self, $name) = @_;
1089 $self->storage or $self->throw_exception
1090 ('svp_rollback called on $schema without storage');
1092 $self->storage->svp_rollback($name);
1099 =item Arguments: %attrs?
1101 =item Return Value: $new_schema
1105 Clones the schema and its associated result_source objects and returns the
1106 copy. The resulting copy will have the same attributes as the source schema,
1107 except for those attributes explicitly overridden by the provided C<%attrs>.
1115 (ref $self ? %$self : ()),
1116 (@_ == 1 && ref $_[0] eq 'HASH' ? %{ $_[0] } : @_),
1118 bless $clone, (ref $self || $self);
1120 $clone->$_(undef) for qw/class_mappings source_registrations storage/;
1122 $clone->_copy_state_from($self);
1127 # Needed in Schema::Loader - if you refactor, please make a compatibility shim
1129 sub _copy_state_from {
1130 my ($self, $from) = @_;
1132 $self->class_mappings({ %{$from->class_mappings} });
1133 $self->source_registrations({ %{$from->source_registrations} });
1135 # we use extra here as we want to leave the class_mappings as they are
1136 # but overwrite the source_registrations entry with the new source
1137 $self->register_extra_source( $_ => $from->source($_) )
1140 if ($from->storage) {
1141 $self->storage($from->storage);
1142 $self->storage->set_schema($self);
1146 =head2 throw_exception
1150 =item Arguments: $message
1154 Throws an exception. Obeys the exemption rules of L<DBIx::Class::Carp> to report
1155 errors from outer-user's perspective. See L</exception_action> for details on overriding
1156 this method's behavior. If L</stacktrace> is turned on, C<throw_exception>'s
1157 default behavior will provide a detailed stack trace.
1161 sub throw_exception {
1162 my ($self, @args) = @_;
1165 ! DBIx::Class::_Util::in_internal_try()
1167 my $act = $self->exception_action
1172 my $guard = scope_guard {
1173 return if $guard_disarmed;
1174 emit_loud_diag( emit_dups => 1, msg => "
1176 !!! DBIx::Class INTERNAL PANIC !!!
1178 The exception_action() handler installed on '$self'
1179 aborted the stacktrace below via a longjmp (either via Return::Multilevel or
1180 plain goto, or Scope::Upper or something equally nefarious). There currently
1181 is nothing safe DBIx::Class can do, aside from displaying this error. A future
1182 version ( 0.082900, when available ) will reduce the cases in which the
1183 handler is invoked, but this is neither a complete solution, nor can it do
1184 anything for other software that might be affected by a similar problem.
1186 !!! FIX YOUR ERROR HANDLING !!!
1188 This guard was activated starting",
1193 # if it throws - good, we'll assign to @args in the end
1194 # if it doesn't - do different things depending on RV truthiness
1195 if( $act->(@args) ) {
1197 "Invocation of the exception_action handler installed on $self did *not*"
1198 .' result in an exception. DBIx::Class is unable to function without a reliable'
1199 .' exception mechanism, ensure your exception_action does not hide exceptions'
1200 ." (original error: $args[0])"
1205 "The exception_action handler installed on $self returned false instead"
1206 .' of throwing an exception. This behavior has been deprecated, adjust your'
1207 .' handler to always rethrow the supplied error'
1214 # We call this to get the necessary warnings emitted and disregard the RV
1215 # as it's definitely an exception if we got as far as this catch{} block
1221 # Done guarding against https://github.com/PerlDancer/Dancer2/issues/1125
1222 $guard_disarmed = 1;
1225 DBIx::Class::Exception->throw( $args[0], $self->stacktrace );
1232 =item Arguments: \%sqlt_args, $dir
1236 Attempts to deploy the schema to the current storage using L<SQL::Translator>.
1238 See L<SQL::Translator/METHODS> for a list of values for C<\%sqlt_args>.
1239 The most common value for this would be C<< { add_drop_table => 1 } >>
1240 to have the SQL produced include a C<DROP TABLE> statement for each table
1241 created. For quoting purposes supply C<quote_identifiers>.
1243 Additionally, the DBIx::Class parser accepts a C<sources> parameter as a hash
1244 ref or an array ref, containing a list of source to deploy. If present, then
1245 only the sources listed will get deployed. Furthermore, you can use the
1246 C<add_fk_index> parser parameter to prevent the parser from creating an index for each
1252 my ($self, $sqltargs, $dir) = @_;
1253 $self->throw_exception("Can't deploy without storage") unless $self->storage;
1254 $self->storage->deploy($self, undef, $sqltargs, $dir);
1257 =head2 deployment_statements
1261 =item Arguments: See L<DBIx::Class::Storage::DBI/deployment_statements>
1263 =item Return Value: $listofstatements
1267 A convenient shortcut to
1268 C<< $self->storage->deployment_statements($self, @args) >>.
1269 Returns the statements used by L</deploy> and
1270 L<DBIx::Class::Storage/deploy>.
1274 sub deployment_statements {
1277 $self->throw_exception("Can't generate deployment statements without a storage")
1278 if not $self->storage;
1280 $self->storage->deployment_statements($self, @_);
1283 =head2 create_ddl_dir
1287 =item Arguments: See L<DBIx::Class::Storage::DBI/create_ddl_dir>
1291 A convenient shortcut to
1292 C<< $self->storage->create_ddl_dir($self, @args) >>.
1294 Creates an SQL file based on the Schema, for each of the specified
1295 database types, in the given directory.
1299 sub create_ddl_dir {
1302 $self->throw_exception("Can't create_ddl_dir without storage") unless $self->storage;
1303 $self->storage->create_ddl_dir($self, @_);
1310 =item Arguments: $database-type, $version, $directory, $preversion
1312 =item Return Value: $normalised_filename
1316 my $filename = $table->ddl_filename($type, $version, $dir, $preversion)
1318 This method is called by C<create_ddl_dir> to compose a file name out of
1319 the supplied directory, database type and version number. The default file
1320 name format is: C<$dir$schema-$version-$type.sql>.
1322 You may override this method in your schema if you wish to use a different
1327 Prior to DBIx::Class version 0.08100 this method had a different signature:
1329 my $filename = $table->ddl_filename($type, $dir, $version, $preversion)
1331 In recent versions variables $dir and $version were reversed in order to
1332 bring the signature in line with other Schema/Storage methods. If you
1333 really need to maintain backward compatibility, you can do the following
1334 in any overriding methods:
1336 ($dir, $version) = ($version, $dir) if ($DBIx::Class::VERSION < 0.08100);
1341 my ($self, $type, $version, $dir, $preversion) = @_;
1343 $version = "$preversion-$version" if $preversion;
1345 my $class = blessed($self) || $self;
1348 return "$dir/$class-$version-$type.sql";
1353 Provided as the recommended way of thawing schema objects. You can call
1354 C<Storable::thaw> directly if you wish, but the thawed objects will not have a
1355 reference to any schema, so are rather useless.
1360 my ($self, $obj) = @_;
1361 local $DBIx::Class::ResultSourceHandle::thaw_schema = $self;
1362 return Storable::thaw($obj);
1367 This doesn't actually do anything beyond calling L<nfreeze|Storable/SYNOPSIS>,
1368 it is just provided here for symmetry.
1373 return Storable::nfreeze($_[1]);
1380 =item Arguments: $object
1382 =item Return Value: dcloned $object
1386 Recommended way of dcloning L<DBIx::Class::Row> and L<DBIx::Class::ResultSet>
1387 objects so their references to the schema object
1388 (which itself is B<not> cloned) are properly maintained.
1393 my ($self, $obj) = @_;
1394 local $DBIx::Class::ResultSourceHandle::thaw_schema = $self;
1395 return Storable::dclone($obj);
1398 =head2 schema_version
1400 Returns the current schema class' $VERSION in a normalised way.
1404 sub schema_version {
1406 my $class = ref($self)||$self;
1408 # does -not- use $schema->VERSION
1409 # since that varies in results depending on if version.pm is installed, and if
1410 # so the perl or XS versions. If you want this to change, bug the version.pm
1411 # author to make vpp and vxs behave the same.
1416 $version = ${"${class}::VERSION"};
1422 =head2 register_class
1426 =item Arguments: $source_name, $component_class
1430 This method is called by L</load_namespaces> and L</load_classes> to install the found classes into your Schema. You should be using those instead of this one.
1432 You will only need this method if you have your Result classes in
1433 files which are not named after the packages (or all in the same
1434 file). You may also need it to register classes at runtime.
1436 Registers a class which isa DBIx::Class::ResultSourceProxy. Equivalent to
1439 $schema->register_source($source_name, $component_class->result_source);
1443 sub register_class {
1444 my ($self, $source_name, $to_register) = @_;
1445 $self->register_source($source_name => $to_register->result_source);
1448 =head2 register_source
1452 =item Arguments: $source_name, L<$result_source|DBIx::Class::ResultSource>
1456 This method is called by L</register_class>.
1458 Registers the L<DBIx::Class::ResultSource> in the schema with the given
1463 sub register_source { shift->_register_source(@_) }
1465 =head2 unregister_source
1469 =item Arguments: $source_name
1473 Removes the L<DBIx::Class::ResultSource> from the schema for the given source name.
1477 sub unregister_source { shift->_unregister_source(@_) }
1479 =head2 register_extra_source
1483 =item Arguments: $source_name, L<$result_source|DBIx::Class::ResultSource>
1487 As L</register_source> but should be used if the result class already
1488 has a source and you want to register an extra one.
1492 sub register_extra_source { shift->_register_source(@_, { extra => 1 }) }
1494 sub _register_source {
1495 my ($self, $source_name, $supplied_rsrc, $params) = @_;
1497 my $derived_rsrc = $supplied_rsrc->clone({
1498 source_name => $source_name,
1501 # Do not move into the clone-hashref above: there are things
1502 # on CPAN that do hook 'sub schema' </facepalm>
1503 # https://metacpan.org/source/LSAUNDERS/DBIx-Class-Preview-1.000003/lib/DBIx/Class/ResultSource/Table/Previewed.pm#L9-38
1504 $derived_rsrc->schema($self);
1506 weaken $derived_rsrc->{schema}
1507 if length( my $schema_class = ref($self) );
1509 my %reg = %{$self->source_registrations};
1510 $reg{$source_name} = $derived_rsrc;
1511 $self->source_registrations(\%reg);
1513 return $derived_rsrc if $params->{extra};
1515 my( $result_class, $result_class_level_rsrc );
1517 $result_class = $derived_rsrc->result_class
1519 # There are known cases where $rs_class is *ONLY* an inflator, without
1520 # any hint of a rsrc (e.g. DBIx::Class::KiokuDB::EntryProxy)
1521 $result_class_level_rsrc = dbic_internal_try { $result_class->result_source_instance }
1523 my %map = %{$self->class_mappings};
1526 "$result_class already had a registered source which was replaced by "
1527 . 'this call. Perhaps you wanted register_extra_source(), though it is '
1528 . 'more likely you did something wrong.'
1530 exists $map{$result_class}
1532 $map{$result_class} ne $source_name
1534 $result_class_level_rsrc != $supplied_rsrc
1537 $map{$result_class} = $source_name;
1538 $self->class_mappings(\%map);
1541 my $schema_class_level_rsrc;
1543 # we are called on a schema instance, not on the class
1544 length $schema_class
1548 # the schema class also has a registration with the same name
1549 $schema_class_level_rsrc = dbic_internal_try { $schema_class->source($source_name) }
1553 # what we are registering on the schema instance *IS* derived
1554 # from the class-level (top) rsrc...
1555 ( grep { $_ == $derived_rsrc } $result_class_level_rsrc->__derived_instances )
1559 # ... while the schema-class-level has stale-markers
1560 keys %{ $schema_class_level_rsrc->{__metadata_divergencies} || {} }
1563 "The ResultSource instance you just registered on '$self' as "
1564 . "'$source_name' seems to have no relation to $schema_class->"
1565 . "source('$source_name') which in turn is marked stale (likely due "
1566 . "to recent $result_class->... direct class calls). This is almost "
1567 . "always a mistake: perhaps you forgot a cycle of "
1568 . "$schema_class->unregister_source( '$source_name' ) / "
1569 . "$schema_class->register_class( '$source_name' => '$result_class' )"
1572 DBIx::Class::_ENV_::ASSERT_NO_ERRONEOUS_METAINSTANCE_USE
1573 ? emit_loud_diag( msg => $msg, confess => 1 )
1582 my $global_phase_destroy;
1584 ### NO detected_reinvoked_destructor check
1585 ### This code very much relies on being called multuple times
1587 return if $global_phase_destroy ||= in_global_destruction;
1590 my $srcs = $self->source_registrations;
1592 for my $source_name (keys %$srcs) {
1593 # find first source that is not about to be GCed (someone other than $self
1594 # holds a reference to it) and reattach to it, weakening our own link
1596 # during global destruction (if we have not yet bailed out) this should throw
1597 # which will serve as a signal to not try doing anything else
1598 # however beware - on older perls the exception seems randomly untrappable
1599 # due to some weird race condition during thread joining :(((
1600 if (length ref $srcs->{$source_name} and refcount($srcs->{$source_name}) > 1) {
1601 local $SIG{__DIE__} if $SIG{__DIE__};
1602 local $@ if DBIx::Class::_ENV_::UNSTABLE_DOLLARAT;
1604 $srcs->{$source_name}->schema($self);
1605 weaken $srcs->{$source_name};
1608 $global_phase_destroy = 1;
1615 # Dummy NEXTSTATE ensuring the all temporaries on the stack are garbage
1616 # collected before leaving this scope. Depending on the code above, this
1617 # may very well be just a preventive measure guarding future modifications
1621 sub _unregister_source {
1622 my ($self, $source_name) = @_;
1623 my %reg = %{$self->source_registrations};
1625 my $source = delete $reg{$source_name};
1626 $self->source_registrations(\%reg);
1627 if ($source->result_class) {
1628 my %map = %{$self->class_mappings};
1629 delete $map{$source->result_class};
1630 $self->class_mappings(\%map);
1635 =head2 compose_connection (DEPRECATED)
1639 =item Arguments: $target_namespace, @db_info
1641 =item Return Value: $new_schema
1645 DEPRECATED. You probably wanted compose_namespace.
1647 Actually, you probably just wanted to call connect.
1651 (hidden due to deprecation)
1653 Calls L<DBIx::Class::Schema/"compose_namespace"> to the target namespace,
1654 calls L<DBIx::Class::Schema/connection> with @db_info on the new schema,
1655 then injects the L<DBix::Class::ResultSetProxy> component and a
1656 resultset_instance classdata entry on all the new classes, in order to support
1657 $target_namespaces::$class->search(...) method calls.
1659 This is primarily useful when you have a specific need for class method access
1660 to a connection. In normal usage it is preferred to call
1661 L<DBIx::Class::Schema/connect> and use the resulting schema object to operate
1662 on L<DBIx::Class::ResultSet> objects with L<DBIx::Class::Schema/resultset> for
1669 sub compose_connection {
1670 my ($self, $target, @info) = @_;
1672 carp_once "compose_connection deprecated as of 0.08000"
1673 unless $INC{"DBIx/Class/CDBICompat.pm"};
1676 require DBIx::Class::ResultSetProxy;
1679 $self->throw_exception
1680 ("No arguments to load_classes and couldn't load DBIx::Class::ResultSetProxy ($_)")
1683 if ($self eq $target) {
1684 # Pathological case, largely caused by the docs on early C::M::DBIC::Plain
1685 foreach my $source_name ($self->sources) {
1686 my $source = $self->source($source_name);
1687 my $class = $source->result_class;
1688 $self->inject_base($class, 'DBIx::Class::ResultSetProxy');
1689 $class->mk_classaccessor(resultset_instance => $source->resultset);
1690 $class->mk_classaccessor(class_resolver => $self);
1692 $self->connection(@info);
1696 my $schema = $self->compose_namespace($target, 'DBIx::Class::ResultSetProxy');
1697 quote_sub "${target}::schema", '$s', { '$s' => \$schema };
1699 # needed to cover the newly installed stuff via quote_sub above
1700 Class::C3->reinitialize if DBIx::Class::_ENV_::OLD_MRO;
1702 $schema->connection(@info);
1703 foreach my $source_name ($schema->sources) {
1704 my $source = $schema->source($source_name);
1705 my $class = $source->result_class;
1706 #warn "$source_name $class $source ".$source->storage;
1708 $class->mk_group_accessors( inherited => [ result_source_instance => '_result_source' ] );
1709 # explicit set-call, avoid mro update lag
1710 $class->set_inherited( result_source_instance => $source );
1712 $class->mk_classaccessor(resultset_instance => $source->resultset);
1713 $class->mk_classaccessor(class_resolver => $schema);
1718 =head1 FURTHER QUESTIONS?
1720 Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
1722 =head1 COPYRIGHT AND LICENSE
1724 This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
1725 by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
1726 redistribute it and/or modify it under the same terms as the
1727 L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.