1 package DBIx::Class::Schema;
6 use base 'DBIx::Class';
9 use Scalar::Util qw( weaken blessed refaddr );
10 use DBIx::Class::_Util qw(
11 refdesc refcount quote_sub scope_guard
12 is_exception dbic_internal_try dbic_internal_catch
13 fail_on_internal_call emit_loud_diag
15 use Devel::GlobalDestruction;
18 __PACKAGE__->mk_group_accessors( inherited => qw( storage exception_action ) );
19 __PACKAGE__->mk_classaccessor('storage_type' => '::DBI');
20 __PACKAGE__->mk_classaccessor('stacktrace' => $ENV{DBIC_TRACE} || 0);
21 __PACKAGE__->mk_classaccessor('default_resultset_attributes' => {});
23 # These two should have been private from the start but too late now
24 # Undocumented on purpose, hopefully it won't ever be necessary to
26 __PACKAGE__->mk_classaccessor('class_mappings' => {});
27 __PACKAGE__->mk_classaccessor('source_registrations' => {});
29 __PACKAGE__->mk_group_accessors( component_class => 'schema_sanity_checker' );
30 __PACKAGE__->schema_sanity_checker(
31 'DBIx::Class::Schema::SanityChecker'
36 DBIx::Class::Schema - composable schemas
40 package Library::Schema;
41 use base qw/DBIx::Class::Schema/;
43 # load all Result classes in Library/Schema/Result/
44 __PACKAGE__->load_namespaces();
46 package Library::Schema::Result::CD;
47 use base qw/DBIx::Class::Core/;
49 __PACKAGE__->load_components(qw/InflateColumn::DateTime/); # for example
50 __PACKAGE__->table('cd');
52 # Elsewhere in your code:
53 my $schema1 = Library::Schema->connect(
60 my $schema2 = Library::Schema->connect($coderef_returning_dbh);
62 # fetch objects using Library::Schema::Result::DVD
63 my $resultset = $schema1->resultset('DVD')->search( ... );
64 my @dvd_objects = $schema2->resultset('DVD')->search( ... );
68 Creates database classes based on a schema. This is the recommended way to
69 use L<DBIx::Class> and allows you to use more than one concurrent connection
72 NB: If you're used to L<Class::DBI> it's worth reading the L</SYNOPSIS>
73 carefully, as DBIx::Class does things a little differently. Note in
74 particular which module inherits off which.
78 =head2 load_namespaces
82 =item Arguments: %options?
86 package MyApp::Schema;
87 __PACKAGE__->load_namespaces();
89 __PACKAGE__->load_namespaces(
90 result_namespace => 'Res',
91 resultset_namespace => 'RSet',
92 default_resultset_class => '+MyApp::Othernamespace::RSet',
95 With no arguments, this method uses L<Module::Find> to load all of the
96 Result and ResultSet classes under the namespace of the schema from
97 which it is called. For example, C<My::Schema> will by default find
98 and load Result classes named C<My::Schema::Result::*> and ResultSet
99 classes named C<My::Schema::ResultSet::*>.
101 ResultSet classes are associated with Result class of the same name.
102 For example, C<My::Schema::Result::CD> will get the ResultSet class
103 C<My::Schema::ResultSet::CD> if it is present.
105 Both Result and ResultSet namespaces are configurable via the
106 C<result_namespace> and C<resultset_namespace> options.
108 Another option, C<default_resultset_class> specifies a custom default
109 ResultSet class for Result classes with no corresponding ResultSet.
111 All of the namespace and classname options are by default relative to
112 the schema classname. To specify a fully-qualified name, prefix it
113 with a literal C<+>. For example, C<+Other::NameSpace::Result>.
117 You will be warned if ResultSet classes are discovered for which there
118 are no matching Result classes like this:
120 load_namespaces found ResultSet class $classname with no corresponding Result class
122 If a ResultSource instance is found to already have a ResultSet class set
123 using L<resultset_class|DBIx::Class::ResultSource/resultset_class> to some
124 other class, you will be warned like this:
126 We found ResultSet class '$rs_class' for '$result_class', but it seems
127 that you had already set '$result_class' to use '$rs_set' instead
131 # load My::Schema::Result::CD, My::Schema::Result::Artist,
132 # My::Schema::ResultSet::CD, etc...
133 My::Schema->load_namespaces;
135 # Override everything to use ugly names.
136 # In this example, if there is a My::Schema::Res::Foo, but no matching
137 # My::Schema::RSets::Foo, then Foo will have its
138 # resultset_class set to My::Schema::RSetBase
139 My::Schema->load_namespaces(
140 result_namespace => 'Res',
141 resultset_namespace => 'RSets',
142 default_resultset_class => 'RSetBase',
145 # Put things in other namespaces
146 My::Schema->load_namespaces(
147 result_namespace => '+Some::Place::Results',
148 resultset_namespace => '+Another::Place::RSets',
151 To search multiple namespaces for either Result or ResultSet classes,
152 use an arrayref of namespaces for that option. In the case that the
153 same result (or resultset) class exists in multiple namespaces, later
154 entries in the list of namespaces will override earlier ones.
156 My::Schema->load_namespaces(
157 # My::Schema::Results_C::Foo takes precedence over My::Schema::Results_B::Foo :
158 result_namespace => [ 'Results_A', 'Results_B', 'Results_C' ],
159 resultset_namespace => [ '+Some::Place::RSets', 'RSets' ],
164 # Pre-pends our classname to the given relative classname or
165 # class namespace, unless there is a '+' prefix, which will
167 sub _expand_relative_name {
168 my ($class, $name) = @_;
169 $name =~ s/^\+// or $name = "${class}::${name}";
173 # Finds all modules in the supplied namespace, or if omitted in the
174 # namespace of $class. Untaints all findings as they can be assumed
177 require Module::Find;
179 { $_ =~ /(.+)/ } # untaint result
180 Module::Find::findallmod( $_[1] || ref $_[0] || $_[0] )
184 # returns a hash of $shortname => $fullname for every package
185 # found in the given namespaces ($shortname is with the $fullname's
186 # namespace stripped off)
187 sub _map_namespaces {
188 my ($me, $namespaces) = @_;
191 for my $ns (@$namespaces) {
192 $res{ substr($_, length "${ns}::") } = $_
193 for $me->_findallmod($ns);
199 # returns the result_source_instance for the passed class/object,
200 # or dies with an informative message (used by load_namespaces)
201 sub _ns_get_rsrc_instance {
203 my $rs_class = ref ($_[0]) || $_[0];
205 return dbic_internal_try {
206 $rs_class->result_source
207 } dbic_internal_catch {
208 $me->throw_exception (
209 "Attempt to load_namespaces() class $rs_class failed - are you sure this is a real Result Class?: $_"
214 sub load_namespaces {
215 my ($class, %args) = @_;
217 my $result_namespace = delete $args{result_namespace} || 'Result';
218 my $resultset_namespace = delete $args{resultset_namespace} || 'ResultSet';
220 my $default_resultset_class = delete $args{default_resultset_class};
222 $default_resultset_class = $class->_expand_relative_name($default_resultset_class)
223 if $default_resultset_class;
225 $class->throw_exception('load_namespaces: unknown option(s): '
226 . join(q{,}, map { qq{'$_'} } keys %args))
227 if scalar keys %args;
229 for my $arg ($result_namespace, $resultset_namespace) {
230 $arg = [ $arg ] if ( $arg and ! ref $arg );
232 $class->throw_exception('load_namespaces: namespace arguments must be '
233 . 'a simple string or an arrayref')
234 if ref($arg) ne 'ARRAY';
236 $_ = $class->_expand_relative_name($_) for (@$arg);
239 my $results_by_source_name = $class->_map_namespaces($result_namespace);
240 my $resultsets_by_source_name = $class->_map_namespaces($resultset_namespace);
244 # ensure classes are loaded and attached in inheritance order
245 for my $result_class (values %$results_by_source_name) {
246 $class->ensure_class_loaded($result_class);
249 my @source_names_by_subclass_last = sort {
252 scalar @{mro::get_linear_isa( $results_by_source_name->{$a} )}
258 scalar @{mro::get_linear_isa( $results_by_source_name->{$b} )}
261 } keys(%$results_by_source_name);
263 foreach my $source_name (@source_names_by_subclass_last) {
264 my $result_class = $results_by_source_name->{$source_name};
266 my $preset_resultset_class = $class->_ns_get_rsrc_instance ($result_class)->resultset_class;
267 my $found_resultset_class = delete $resultsets_by_source_name->{$source_name};
269 if($preset_resultset_class && $preset_resultset_class ne 'DBIx::Class::ResultSet') {
270 if($found_resultset_class && $found_resultset_class ne $preset_resultset_class) {
271 carp "We found ResultSet class '$found_resultset_class' matching '$results_by_source_name->{$source_name}', but it seems "
272 . "that you had already set the '$results_by_source_name->{$source_name}' resultet to '$preset_resultset_class' instead";
275 # elsif - there may be *no* default_resultset_class, in which case we fallback to
276 # DBIx::Class::Resultset and there is nothing to check
277 elsif($found_resultset_class ||= $default_resultset_class) {
278 $class->ensure_class_loaded($found_resultset_class);
279 if(!$found_resultset_class->isa("DBIx::Class::ResultSet")) {
280 carp "load_namespaces found ResultSet class '$found_resultset_class' that does not subclass DBIx::Class::ResultSet";
283 $class->_ns_get_rsrc_instance ($result_class)->resultset_class($found_resultset_class);
286 my $source_name = $class->_ns_get_rsrc_instance ($result_class)->source_name || $source_name;
288 push(@to_register, [ $source_name, $result_class ]);
292 foreach (sort keys %$resultsets_by_source_name) {
293 carp "load_namespaces found ResultSet class '$resultsets_by_source_name->{$_}' "
294 .'with no corresponding Result class';
297 $class->register_class(@$_) for (@to_register);
306 =item Arguments: @classes?, { $namespace => [ @classes ] }+
310 L</load_classes> is an alternative method to L</load_namespaces>, both of
311 which serve similar purposes, each with different advantages and disadvantages.
312 In the general case you should use L</load_namespaces>, unless you need to
313 be able to specify that only specific classes are loaded at runtime.
315 With no arguments, this method uses L<Module::Find> to find all classes under
316 the schema's namespace. Otherwise, this method loads the classes you specify
317 (using L<use>), and registers them (using L</"register_class">).
319 It is possible to comment out classes with a leading C<#>, but note that perl
320 will think it's a mistake (trying to use a comment in a qw list), so you'll
321 need to add C<no warnings 'qw';> before your load_classes call.
323 If any classes found do not appear to be Result class files, you will
324 get the following warning:
326 Failed to load $comp_class. Can't find source_name method. Is
327 $comp_class really a full DBIC result class? Fix it, move it elsewhere,
328 or make your load_classes call more specific.
332 My::Schema->load_classes(); # loads My::Schema::CD, My::Schema::Artist,
333 # etc. (anything under the My::Schema namespace)
335 # loads My::Schema::CD, My::Schema::Artist, Other::Namespace::Producer but
336 # not Other::Namespace::LinerNotes nor My::Schema::Track
337 My::Schema->load_classes(qw/ CD Artist #Track /, {
338 Other::Namespace => [qw/ Producer #LinerNotes /],
344 my ($class, @params) = @_;
349 foreach my $param (@params) {
350 if (ref $param eq 'ARRAY') {
351 # filter out commented entries
352 my @modules = grep { $_ !~ /^#/ } @$param;
354 push (@{$comps_for{$class}}, @modules);
356 elsif (ref $param eq 'HASH') {
357 # more than one namespace possible
358 for my $comp ( keys %$param ) {
359 # filter out commented entries
360 my @modules = grep { $_ !~ /^#/ } @{$param->{$comp}};
362 push (@{$comps_for{$comp}}, @modules);
366 # filter out commented entries
367 push (@{$comps_for{$class}}, $param) if $param !~ /^#/;
371 my @comp = map { substr $_, length "${class}::" }
372 $class->_findallmod($class);
373 $comps_for{$class} = \@comp;
378 foreach my $prefix (keys %comps_for) {
379 foreach my $comp (@{$comps_for{$prefix}||[]}) {
380 my $comp_class = "${prefix}::${comp}";
381 $class->ensure_class_loaded($comp_class);
383 my $snsub = $comp_class->can('source_name');
385 carp "Failed to load $comp_class. Can't find source_name method. Is $comp_class really a full DBIC result class? Fix it, move it elsewhere, or make your load_classes call more specific.";
388 $comp = $snsub->($comp_class) || $comp;
390 push(@to_register, [ $comp, $comp_class ]);
395 foreach my $to (@to_register) {
396 $class->register_class(@$to);
404 =item Arguments: $storage_type|{$storage_type, \%args}
406 =item Return Value: $storage_type|{$storage_type, \%args}
408 =item Default value: DBIx::Class::Storage::DBI
412 Set the storage class that will be instantiated when L</connect> is called.
413 If the classname starts with C<::>, the prefix C<DBIx::Class::Storage> is
414 assumed by L</connect>.
416 You want to use this to set subclasses of L<DBIx::Class::Storage::DBI>
417 in cases where the appropriate subclass is not autodetected.
419 If your storage type requires instantiation arguments, those are
420 defined as a second argument in the form of a hashref and the entire
421 value needs to be wrapped into an arrayref or a hashref. We support
422 both types of refs here in order to play nice with your
423 Config::[class] or your choice. See
424 L<DBIx::Class::Storage::DBI::Replicated> for an example of this.
426 =head2 default_resultset_attributes
430 =item Arguments: L<\%attrs|DBIx::Class::ResultSet/ATTRIBUTES>
432 =item Return Value: L<\%attrs|DBIx::Class::ResultSet/ATTRIBUTES>
434 =item Default value: None
438 Like L<DBIx::Class::ResultSource/resultset_attributes> stores a collection
439 of resultset attributes, to be used as defaults for B<every> ResultSet
440 instance schema-wide. The same list of CAVEATS and WARNINGS applies, with
441 the extra downside of these defaults being practically inescapable: you will
442 B<not> be able to derive a ResultSet instance with these attributes unset.
447 use base qw/DBIx::Class::Schema/;
448 __PACKAGE__->default_resultset_attributes( { software_limit => 1 } );
450 =head2 schema_sanity_checker
454 =item Arguments: L<perform_schema_sanity_checks()|DBIx::Class::Schema::SanityChecker/perform_schema_sanity_checks> provider
456 =item Return Value: L<perform_schema_sanity_checks()|DBIx::Class::Schema::SanityChecker/perform_schema_sanity_checks> provider
458 =item Default value: L<DBIx::Class::Schema::SanityChecker>
462 On every call to L</connection> if the value of this attribute evaluates to
463 true, DBIC will invoke
464 C<< L<$schema_sanity_checker|/schema_sanity_checker>->L<perform_schema_sanity_checks|DBIx::Class::Schema::SanityChecker/perform_schema_sanity_checks>($schema) >>
465 before returning. The return value of this invocation is ignored.
467 B<YOU ARE STRONGLY URGED> to
468 L<learn more about the reason|DBIx::Class::Schema::SanityChecker/WHY> this
469 feature was introduced. Blindly disabling the checker on existing projects
470 B<may result in data corruption> after upgrade to C<< DBIC >= v0.082900 >>.
475 use base qw/DBIx::Class::Schema/;
476 __PACKAGE__->schema_sanity_checker('My::Schema::SanityChecker');
478 # or to disable all checks:
479 __PACKAGE__->schema_sanity_checker('');
481 Note: setting the value to C<undef> B<will not> have the desired effect,
482 due to an implementation detail of L<Class::Accessor::Grouped> inherited
483 accessors. In order to disable any and all checks you must set this
484 attribute to an empty string as shown in the second example above.
486 =head2 exception_action
490 =item Arguments: $code_reference
492 =item Return Value: $code_reference
494 =item Default value: None
498 When L</throw_exception> is invoked and L</exception_action> is set to a code
499 reference, this reference will be called instead of
500 L<DBIx::Class::Exception/throw>, with the exception message passed as the only
503 Your custom throw code B<must> rethrow the exception, as L</throw_exception> is
504 an integral part of DBIC's internal execution control flow.
509 use base qw/DBIx::Class::Schema/;
510 use My::ExceptionClass;
511 __PACKAGE__->exception_action(sub { My::ExceptionClass->throw(@_) });
512 __PACKAGE__->load_classes;
515 my $schema_obj = My::Schema->connect( .... );
516 $schema_obj->exception_action(sub { My::ExceptionClass->throw(@_) });
522 =item Arguments: boolean
526 Whether L</throw_exception> should include stack trace information.
527 Defaults to false normally, but defaults to true if C<$ENV{DBIC_TRACE}>
530 =head2 sqlt_deploy_hook
534 =item Arguments: $sqlt_schema
538 An optional sub which you can declare in your own Schema class that will get
539 passed the L<SQL::Translator::Schema> object when you deploy the schema via
540 L</create_ddl_dir> or L</deploy>.
542 For an example of what you can do with this, see
543 L<DBIx::Class::Manual::Cookbook/Adding Indexes And Functions To Your SQL>.
545 Note that sqlt_deploy_hook is called by L</deployment_statements>, which in turn
546 is called before L</deploy>. Therefore the hook can be used only to manipulate
547 the L<SQL::Translator::Schema> object before it is turned into SQL fed to the
548 database. If you want to execute post-deploy statements which can not be generated
549 by L<SQL::Translator>, the currently suggested method is to overload L</deploy>
550 and use L<dbh_do|DBIx::Class::Storage::DBI/dbh_do>.
558 =item Arguments: @connectinfo
560 =item Return Value: $new_schema
564 Creates and returns a new Schema object. The connection info set on it
565 is used to create a new instance of the storage backend and set it on
568 See L<DBIx::Class::Storage::DBI/"connect_info"> for DBI-specific
569 syntax on the C<@connectinfo> argument, or L<DBIx::Class::Storage> in
572 Note that C<connect_info> expects an arrayref of arguments, but
573 C<connect> does not. C<connect> wraps its arguments in an arrayref
574 before passing them to C<connect_info>.
578 C<connect> is a convenience method. It is equivalent to calling
579 $schema->clone->connection(@connectinfo). To write your own overloaded
580 version, overload L</connection> instead.
584 sub connect :DBIC_method_is_indirect_sugar {
585 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
586 shift->clone->connection(@_);
593 =item Arguments: L<$source_name|DBIx::Class::ResultSource/source_name>
595 =item Return Value: L<$resultset|DBIx::Class::ResultSet>
599 my $rs = $schema->resultset('DVD');
601 Returns the L<DBIx::Class::ResultSet> object for the registered source
607 my ($self, $source_name) = @_;
608 $self->throw_exception('resultset() expects a source name')
609 unless defined $source_name;
610 return $self->source($source_name)->resultset;
617 =item Return Value: L<@source_names|DBIx::Class::ResultSource/source_name>
621 my @source_names = $schema->sources;
623 Lists names of all the sources registered on this Schema object.
627 sub sources { keys %{shift->source_registrations} }
633 =item Arguments: L<$source_name|DBIx::Class::ResultSource/source_name>
635 =item Return Value: L<$result_source|DBIx::Class::ResultSource>
639 my $source = $schema->source('Book');
641 Returns the L<DBIx::Class::ResultSource> object for the registered
647 my ($self, $source_name) = @_;
649 $self->throw_exception("source() expects a source name")
652 my $source_registrations;
655 ( $source_registrations = $self->source_registrations )->{$source_name}
657 # if we got here, they probably passed a full class name
658 $source_registrations->{ $self->class_mappings->{$source_name} || '' }
660 $self->throw_exception( "Can't find source for ${source_name}" )
664 # We need to prevent alterations of pre-existing $@ due to where this call
665 # sits in the overall stack ( *unless* of course there is an actual error
666 # to report ). set_mro does alter $@ (and yes - it *can* throw an exception)
667 # We do not use local because set_mro *can* throw an actual exception
668 # We do not use a try/catch either, as on one hand it would slow things
669 # down for no reason (we would always rethrow), but also because adding *any*
670 # try/catch block below will segfault various threading tests on older perls
671 # ( which in itself is a FIXME but ENOTIMETODIG )
672 my $old_dollarat = $@;
675 mro::set_mro($_, 'c3') for
678 # some pseudo-sources do not have a result/resultset yet
683 ${"${_}::__INITIAL_MRO_UPON_DBIC_LOAD__"}
691 { length ref $_ ? ref $_ : $_ }
692 ( $rsrc, $rsrc->result_class, $rsrc->resultset_class )
695 # DO NOT REMOVE - see comment above
705 =item Arguments: L<$source_name|DBIx::Class::ResultSource/source_name>
707 =item Return Value: $classname
711 my $class = $schema->class('CD');
713 Retrieves the Result class name for the given source name.
718 return shift->source(shift)->result_class;
725 =item Arguments: C<$coderef>, @coderef_args?
727 =item Return Value: The return value of $coderef
731 Executes C<$coderef> with (optional) arguments C<@coderef_args> atomically,
732 returning its result (if any). Equivalent to calling $schema->storage->txn_do.
733 See L<DBIx::Class::Storage/"txn_do"> for more information.
735 This interface is preferred over using the individual methods L</txn_begin>,
736 L</txn_commit>, and L</txn_rollback> below.
738 WARNING: If you are connected with C<< AutoCommit => 0 >> the transaction is
739 considered nested, and you will still need to call L</txn_commit> to write your
740 changes when appropriate. You will also want to connect with C<< auto_savepoint =>
741 1 >> to get partial rollback to work, if the storage driver for your database
744 Connecting with C<< AutoCommit => 1 >> is recommended.
751 $self->storage or $self->throw_exception
752 ('txn_do called on $schema without storage');
754 $self->storage->txn_do(@_);
757 =head2 txn_scope_guard
759 Runs C<txn_scope_guard> on the schema's storage. See
760 L<DBIx::Class::Storage/txn_scope_guard>.
764 sub txn_scope_guard {
767 $self->storage or $self->throw_exception
768 ('txn_scope_guard called on $schema without storage');
770 $self->storage->txn_scope_guard(@_);
775 Begins a transaction (does nothing if AutoCommit is off). Equivalent to
776 calling $schema->storage->txn_begin. See
777 L<DBIx::Class::Storage/"txn_begin"> for more information.
784 $self->storage or $self->throw_exception
785 ('txn_begin called on $schema without storage');
787 $self->storage->txn_begin;
792 Commits the current transaction. Equivalent to calling
793 $schema->storage->txn_commit. See L<DBIx::Class::Storage/"txn_commit">
794 for more information.
801 $self->storage or $self->throw_exception
802 ('txn_commit called on $schema without storage');
804 $self->storage->txn_commit;
809 Rolls back the current transaction. Equivalent to calling
810 $schema->storage->txn_rollback. See
811 L<DBIx::Class::Storage/"txn_rollback"> for more information.
818 $self->storage or $self->throw_exception
819 ('txn_rollback called on $schema without storage');
821 $self->storage->txn_rollback;
826 my $storage = $schema->storage;
828 Returns the L<DBIx::Class::Storage> object for this Schema. Grab this
829 if you want to turn on SQL statement debugging at runtime, or set the
830 quote character. For the default storage, the documentation can be
831 found in L<DBIx::Class::Storage::DBI>.
837 =item Arguments: L<$source_name|DBIx::Class::ResultSource/source_name>, [ \@column_list, \@row_values+ ] | [ \%col_data+ ]
839 =item Return Value: L<\@result_objects|DBIx::Class::Manual::ResultClass> (scalar context) | L<@result_objects|DBIx::Class::Manual::ResultClass> (list context)
843 A convenience shortcut to L<DBIx::Class::ResultSet/populate>. Equivalent to:
845 $schema->resultset($source_name)->populate([...]);
851 The context of this method call has an important effect on what is
852 submitted to storage. In void context data is fed directly to fastpath
853 insertion routines provided by the underlying storage (most often
854 L<DBI/execute_for_fetch>), bypassing the L<new|DBIx::Class::Row/new> and
855 L<insert|DBIx::Class::Row/insert> calls on the
856 L<Result|DBIx::Class::Manual::ResultClass> class, including any
857 augmentation of these methods provided by components. For example if you
858 are using something like L<DBIx::Class::UUIDColumns> to create primary
859 keys for you, you will find that your PKs are empty. In this case you
860 will have to explicitly force scalar or list context in order to create
867 sub populate :DBIC_method_is_indirect_sugar {
868 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
870 my ($self, $name, $data) = @_;
871 my $rs = $self->resultset($name)
872 or $self->throw_exception("'$name' is not a resultset");
874 return $rs->populate($data);
881 =item Arguments: @args
883 =item Return Value: $self
887 Similar to L</connect> except sets the storage object and connection
888 data B<in-place> on C<$self>. You should probably be calling
889 L</connect> to get a properly L<cloned|/clone> Schema object instead.
891 If the accessor L</schema_sanity_checker> returns a true value C<$checker>,
892 the following call will take place before return:
893 C<< L<$checker|/schema_sanity_checker>->L<perform_schema_sanity_checks(C<$self>)|DBIx::Class::Schema::SanityChecker/perform_schema_sanity_checks> >>
897 Overload C<connection> to change the behaviour of C<connect>.
901 my $default_off_stderr_blurb_emitted;
903 my ($self, @info) = @_;
904 return $self if !@info && $self->storage;
906 my ($storage_class, $args) = ref $self->storage_type
907 ? $self->_normalize_storage_type($self->storage_type)
908 : $self->storage_type
911 $storage_class =~ s/^::/DBIx::Class::Storage::/;
914 $self->ensure_class_loaded ($storage_class);
916 dbic_internal_catch {
917 $self->throw_exception(
918 "Unable to load storage class ${storage_class}: $_"
922 my $storage = $storage_class->new( $self => $args||{} );
923 $storage->connect_info(\@info);
924 $self->storage($storage);
926 if( my $checker = $self->schema_sanity_checker ) {
927 $checker->perform_schema_sanity_checks($self);
933 sub _normalize_storage_type {
934 my ($self, $storage_type) = @_;
935 if(ref $storage_type eq 'ARRAY') {
936 return @$storage_type;
937 } elsif(ref $storage_type eq 'HASH') {
938 return %$storage_type;
940 $self->throw_exception('Unsupported REFTYPE given: '. ref $storage_type);
944 =head2 compose_namespace
948 =item Arguments: $target_namespace, $additional_base_class?
950 =item Return Value: $new_schema
954 For each L<DBIx::Class::ResultSource> in the schema, this method creates a
955 class in the target namespace (e.g. $target_namespace::CD,
956 $target_namespace::Artist) that inherits from the corresponding classes
957 attached to the current schema.
959 It also attaches a corresponding L<DBIx::Class::ResultSource> object to the
960 new $schema object. If C<$additional_base_class> is given, the new composed
961 classes will inherit from first the corresponding class from the current
962 schema then the base class.
964 For example, for a schema with My::Schema::CD and My::Schema::Artist classes,
966 $schema->compose_namespace('My::DB', 'Base::Class');
967 print join (', ', @My::DB::CD::ISA) . "\n";
968 print join (', ', @My::DB::Artist::ISA) ."\n";
970 will produce the output
972 My::Schema::CD, Base::Class
973 My::Schema::Artist, Base::Class
977 sub compose_namespace {
978 my ($self, $target, $base) = @_;
980 my $schema = $self->clone;
982 $schema->source_registrations({});
984 # the original class-mappings must remain - otherwise
985 # reverse_relationship_info will not work
986 #$schema->class_mappings({});
989 foreach my $source_name ($self->sources) {
990 my $orig_source = $self->source($source_name);
992 my $target_class = "${target}::${source_name}";
993 $self->inject_base($target_class, $orig_source->result_class, ($base || ()) );
995 $schema->register_source(
998 result_class => $target_class
1003 # Legacy stuff, not inserting INDIRECT assertions
1004 quote_sub "${target}::${_}" => "shift->schema->$_(\@_)"
1005 for qw(class source resultset);
1008 # needed to cover the newly installed stuff via quote_sub above
1009 Class::C3->reinitialize if DBIx::Class::_ENV_::OLD_MRO;
1011 # Give each composed class yet another *schema-less* source copy
1012 # this is used for the freeze/thaw cycle
1014 # This is not covered by any tests directly, but is indirectly exercised
1015 # in t/cdbi/sweet/08pager by re-setting the schema on an existing object
1016 # FIXME - there is likely a much cheaper way to take care of this
1017 for my $source_name ($self->sources) {
1019 my $target_class = "${target}::${source_name}";
1021 $target_class->result_source_instance(
1022 $self->source($source_name)->clone(
1023 result_class => $target_class,
1024 schema => ( ref $schema || $schema ),
1032 # LEGACY: The intra-call to this was removed in 66d9ef6b and then
1033 # the sub was de-documented way later in 249963d4. No way to be sure
1034 # nothing on darkpan is calling it directly, so keeping as-is
1035 sub setup_connection_class {
1036 my ($class, $target, @info) = @_;
1037 $class->inject_base($target => 'DBIx::Class::DB');
1038 #$target->load_components('DB');
1039 $target->connection(@info);
1044 Creates a new savepoint (does nothing outside a transaction).
1045 Equivalent to calling $schema->storage->svp_begin. See
1046 L<DBIx::Class::Storage/"svp_begin"> for more information.
1051 my ($self, $name) = @_;
1053 $self->storage or $self->throw_exception
1054 ('svp_begin called on $schema without storage');
1056 $self->storage->svp_begin($name);
1061 Releases a savepoint (does nothing outside a transaction).
1062 Equivalent to calling $schema->storage->svp_release. See
1063 L<DBIx::Class::Storage/"svp_release"> for more information.
1068 my ($self, $name) = @_;
1070 $self->storage or $self->throw_exception
1071 ('svp_release called on $schema without storage');
1073 $self->storage->svp_release($name);
1078 Rollback to a savepoint (does nothing outside a transaction).
1079 Equivalent to calling $schema->storage->svp_rollback. See
1080 L<DBIx::Class::Storage/"svp_rollback"> for more information.
1085 my ($self, $name) = @_;
1087 $self->storage or $self->throw_exception
1088 ('svp_rollback called on $schema without storage');
1090 $self->storage->svp_rollback($name);
1097 =item Arguments: %attrs?
1099 =item Return Value: $new_schema
1103 Clones the schema and its associated result_source objects and returns the
1104 copy. The resulting copy will have the same attributes as the source schema,
1105 except for those attributes explicitly overridden by the provided C<%attrs>.
1113 (ref $self ? %$self : ()),
1114 (@_ == 1 && ref $_[0] eq 'HASH' ? %{ $_[0] } : @_),
1116 bless $clone, (ref $self || $self);
1118 $clone->$_(undef) for qw/class_mappings source_registrations storage/;
1120 $clone->_copy_state_from($self);
1125 # Needed in Schema::Loader - if you refactor, please make a compatibility shim
1127 sub _copy_state_from {
1128 my ($self, $from) = @_;
1130 $self->class_mappings({ %{$from->class_mappings} });
1131 $self->source_registrations({ %{$from->source_registrations} });
1133 # we use extra here as we want to leave the class_mappings as they are
1134 # but overwrite the source_registrations entry with the new source
1135 $self->register_extra_source( $_ => $from->source($_) )
1138 if ($from->storage) {
1139 $self->storage($from->storage);
1140 $self->storage->set_schema($self);
1144 =head2 throw_exception
1148 =item Arguments: $message
1152 Throws an exception. Obeys the exemption rules of L<DBIx::Class::Carp> to report
1153 errors from outer-user's perspective. See L</exception_action> for details on overriding
1154 this method's behavior. If L</stacktrace> is turned on, C<throw_exception>'s
1155 default behavior will provide a detailed stack trace.
1159 sub throw_exception {
1160 my ($self, @args) = @_;
1163 ! DBIx::Class::_Util::in_internal_try()
1165 my $act = $self->exception_action
1170 my $guard = scope_guard {
1171 return if $guard_disarmed;
1172 emit_loud_diag( emit_dups => 1, msg => "
1174 !!! DBIx::Class INTERNAL PANIC !!!
1176 The exception_action() handler installed on '$self'
1177 aborted the stacktrace below via a longjmp (either via Return::Multilevel or
1178 plain goto, or Scope::Upper or something equally nefarious). There currently
1179 is nothing safe DBIx::Class can do, aside from displaying this error. A future
1180 version ( 0.082900, when available ) will reduce the cases in which the
1181 handler is invoked, but this is neither a complete solution, nor can it do
1182 anything for other software that might be affected by a similar problem.
1184 !!! FIX YOUR ERROR HANDLING !!!
1186 This guard was activated starting",
1191 # if it throws - good, we'll assign to @args in the end
1192 # if it doesn't - do different things depending on RV truthiness
1193 if( $act->(@args) ) {
1195 "Invocation of the exception_action handler installed on $self did *not*"
1196 .' result in an exception. DBIx::Class is unable to function without a reliable'
1197 .' exception mechanism, ensure your exception_action does not hide exceptions'
1198 ." (original error: $args[0])"
1203 "The exception_action handler installed on $self returned false instead"
1204 .' of throwing an exception. This behavior has been deprecated, adjust your'
1205 .' handler to always rethrow the supplied error'
1211 dbic_internal_catch {
1212 # We call this to get the necessary warnings emitted and disregard the RV
1213 # as it's definitely an exception if we got as far as this catch{} block
1219 # Done guarding against https://github.com/PerlDancer/Dancer2/issues/1125
1220 $guard_disarmed = 1;
1223 DBIx::Class::Exception->throw( $args[0], $self->stacktrace );
1230 =item Arguments: \%sqlt_args, $dir
1234 Attempts to deploy the schema to the current storage using L<SQL::Translator>.
1236 See L<SQL::Translator/METHODS> for a list of values for C<\%sqlt_args>.
1237 The most common value for this would be C<< { add_drop_table => 1 } >>
1238 to have the SQL produced include a C<DROP TABLE> statement for each table
1239 created. For quoting purposes supply C<quote_identifiers>.
1241 Additionally, the DBIx::Class parser accepts a C<sources> parameter as a hash
1242 ref or an array ref, containing a list of source to deploy. If present, then
1243 only the sources listed will get deployed. Furthermore, you can use the
1244 C<add_fk_index> parser parameter to prevent the parser from creating an index for each
1250 my ($self, $sqltargs, $dir) = @_;
1251 $self->throw_exception("Can't deploy without storage") unless $self->storage;
1252 $self->storage->deploy($self, undef, $sqltargs, $dir);
1255 =head2 deployment_statements
1259 =item Arguments: See L<DBIx::Class::Storage::DBI/deployment_statements>
1261 =item Return Value: $listofstatements
1265 A convenient shortcut to
1266 C<< $self->storage->deployment_statements($self, @args) >>.
1267 Returns the statements used by L</deploy> and
1268 L<DBIx::Class::Storage/deploy>.
1272 sub deployment_statements {
1275 $self->throw_exception("Can't generate deployment statements without a storage")
1276 if not $self->storage;
1278 $self->storage->deployment_statements($self, @_);
1281 =head2 create_ddl_dir
1285 =item Arguments: See L<DBIx::Class::Storage::DBI/create_ddl_dir>
1289 A convenient shortcut to
1290 C<< $self->storage->create_ddl_dir($self, @args) >>.
1292 Creates an SQL file based on the Schema, for each of the specified
1293 database types, in the given directory.
1297 sub create_ddl_dir {
1300 $self->throw_exception("Can't create_ddl_dir without storage") unless $self->storage;
1301 $self->storage->create_ddl_dir($self, @_);
1308 =item Arguments: $database-type, $version, $directory, $preversion
1310 =item Return Value: $normalised_filename
1314 my $filename = $table->ddl_filename($type, $version, $dir, $preversion)
1316 This method is called by C<create_ddl_dir> to compose a file name out of
1317 the supplied directory, database type and version number. The default file
1318 name format is: C<$dir$schema-$version-$type.sql>.
1320 You may override this method in your schema if you wish to use a different
1325 Prior to DBIx::Class version 0.08100 this method had a different signature:
1327 my $filename = $table->ddl_filename($type, $dir, $version, $preversion)
1329 In recent versions variables $dir and $version were reversed in order to
1330 bring the signature in line with other Schema/Storage methods. If you
1331 really need to maintain backward compatibility, you can do the following
1332 in any overriding methods:
1334 ($dir, $version) = ($version, $dir) if ($DBIx::Class::VERSION < 0.08100);
1339 my ($self, $type, $version, $dir, $preversion) = @_;
1341 $version = "$preversion-$version" if $preversion;
1343 my $class = blessed($self) || $self;
1346 return "$dir/$class-$version-$type.sql";
1351 Provided as the recommended way of thawing schema objects. You can call
1352 C<Storable::thaw> directly if you wish, but the thawed objects will not have a
1353 reference to any schema, so are rather useless.
1358 my ($self, $obj) = @_;
1359 local $DBIx::Class::ResultSourceHandle::thaw_schema = $self;
1360 return Storable::thaw($obj);
1365 This doesn't actually do anything beyond calling L<nfreeze|Storable/SYNOPSIS>,
1366 it is just provided here for symmetry.
1371 return Storable::nfreeze($_[1]);
1378 =item Arguments: $object
1380 =item Return Value: dcloned $object
1384 Recommended way of dcloning L<DBIx::Class::Row> and L<DBIx::Class::ResultSet>
1385 objects so their references to the schema object
1386 (which itself is B<not> cloned) are properly maintained.
1391 my ($self, $obj) = @_;
1392 local $DBIx::Class::ResultSourceHandle::thaw_schema = $self;
1393 return Storable::dclone($obj);
1396 =head2 schema_version
1398 Returns the current schema class' $VERSION in a normalised way.
1402 sub schema_version {
1404 my $class = ref($self)||$self;
1406 # does -not- use $schema->VERSION
1407 # since that varies in results depending on if version.pm is installed, and if
1408 # so the perl or XS versions. If you want this to change, bug the version.pm
1409 # author to make vpp and vxs behave the same.
1414 $version = ${"${class}::VERSION"};
1420 =head2 register_class
1424 =item Arguments: $source_name, $component_class
1428 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.
1430 You will only need this method if you have your Result classes in
1431 files which are not named after the packages (or all in the same
1432 file). You may also need it to register classes at runtime.
1434 Registers a class which isa DBIx::Class::ResultSourceProxy. Equivalent to
1437 $schema->register_source($source_name, $component_class->result_source);
1441 sub register_class {
1442 my ($self, $source_name, $to_register) = @_;
1443 $self->register_source($source_name => $to_register->result_source);
1446 =head2 register_source
1450 =item Arguments: $source_name, L<$result_source|DBIx::Class::ResultSource>
1454 This method is called by L</register_class>.
1456 Registers the L<DBIx::Class::ResultSource> in the schema with the given
1461 sub register_source { shift->_register_source(@_) }
1463 =head2 unregister_source
1467 =item Arguments: $source_name
1471 Removes the L<DBIx::Class::ResultSource> from the schema for the given source name.
1475 sub unregister_source { shift->_unregister_source(@_) }
1477 =head2 register_extra_source
1481 =item Arguments: $source_name, L<$result_source|DBIx::Class::ResultSource>
1485 As L</register_source> but should be used if the result class already
1486 has a source and you want to register an extra one.
1490 sub register_extra_source { shift->_register_source(@_, { extra => 1 }) }
1492 sub _register_source {
1493 my ($self, $source_name, $supplied_rsrc, $params) = @_;
1495 my $derived_rsrc = $supplied_rsrc->clone({
1496 source_name => $source_name,
1499 # Do not move into the clone-hashref above: there are things
1500 # on CPAN that do hook 'sub schema' </facepalm>
1501 # https://metacpan.org/source/LSAUNDERS/DBIx-Class-Preview-1.000003/lib/DBIx/Class/ResultSource/Table/Previewed.pm#L9-38
1502 $derived_rsrc->schema($self);
1504 weaken $derived_rsrc->{schema}
1505 if length( my $schema_class = ref($self) );
1507 my %reg = %{$self->source_registrations};
1508 $reg{$source_name} = $derived_rsrc;
1509 $self->source_registrations(\%reg);
1511 return $derived_rsrc if $params->{extra};
1513 my( $result_class, $result_class_level_rsrc );
1515 $result_class = $derived_rsrc->result_class
1517 # There are known cases where $rs_class is *ONLY* an inflator, without
1518 # any hint of a rsrc (e.g. DBIx::Class::KiokuDB::EntryProxy)
1519 $result_class_level_rsrc = dbic_internal_try { $result_class->result_source_instance }
1521 my %map = %{$self->class_mappings};
1524 "$result_class already had a registered source which was replaced by "
1525 . 'this call. Perhaps you wanted register_extra_source(), though it is '
1526 . 'more likely you did something wrong.'
1528 exists $map{$result_class}
1530 $map{$result_class} ne $source_name
1532 $result_class_level_rsrc != $supplied_rsrc
1535 $map{$result_class} = $source_name;
1536 $self->class_mappings(\%map);
1539 my $schema_class_level_rsrc;
1541 # we are called on a schema instance, not on the class
1542 length $schema_class
1546 # the schema class also has a registration with the same name
1547 $schema_class_level_rsrc = dbic_internal_try { $schema_class->source($source_name) }
1551 # what we are registering on the schema instance *IS* derived
1552 # from the class-level (top) rsrc...
1553 ( grep { $_ == $derived_rsrc } $result_class_level_rsrc->__derived_instances )
1557 # ... while the schema-class-level has stale-markers
1558 keys %{ $schema_class_level_rsrc->{__metadata_divergencies} || {} }
1561 "The ResultSource instance you just registered on '$self' as "
1562 . "'$source_name' seems to have no relation to $schema_class->"
1563 . "source('$source_name') which in turn is marked stale (likely due "
1564 . "to recent $result_class->... direct class calls). This is almost "
1565 . "always a mistake: perhaps you forgot a cycle of "
1566 . "$schema_class->unregister_source( '$source_name' ) / "
1567 . "$schema_class->register_class( '$source_name' => '$result_class' )"
1570 DBIx::Class::_ENV_::ASSERT_NO_ERRONEOUS_METAINSTANCE_USE
1571 ? emit_loud_diag( msg => $msg, confess => 1 )
1580 my $global_phase_destroy;
1582 ### NO detected_reinvoked_destructor check
1583 ### This code very much relies on being called multuple times
1585 return if $global_phase_destroy ||= in_global_destruction;
1588 my $srcs = $self->source_registrations;
1590 for my $source_name (keys %$srcs) {
1591 # find first source that is not about to be GCed (someone other than $self
1592 # holds a reference to it) and reattach to it, weakening our own link
1594 # during global destruction (if we have not yet bailed out) this should throw
1595 # which will serve as a signal to not try doing anything else
1596 # however beware - on older perls the exception seems randomly untrappable
1597 # due to some weird race condition during thread joining :(((
1598 if (length ref $srcs->{$source_name} and refcount($srcs->{$source_name}) > 1) {
1599 local $SIG{__DIE__} if $SIG{__DIE__};
1600 local $@ if DBIx::Class::_ENV_::UNSTABLE_DOLLARAT;
1602 $srcs->{$source_name}->schema($self);
1603 weaken $srcs->{$source_name};
1606 $global_phase_destroy = 1;
1613 # Dummy NEXTSTATE ensuring the all temporaries on the stack are garbage
1614 # collected before leaving this scope. Depending on the code above, this
1615 # may very well be just a preventive measure guarding future modifications
1619 sub _unregister_source {
1620 my ($self, $source_name) = @_;
1621 my %reg = %{$self->source_registrations};
1623 my $source = delete $reg{$source_name};
1624 $self->source_registrations(\%reg);
1625 if ($source->result_class) {
1626 my %map = %{$self->class_mappings};
1627 delete $map{$source->result_class};
1628 $self->class_mappings(\%map);
1633 =head2 compose_connection (DEPRECATED)
1637 =item Arguments: $target_namespace, @db_info
1639 =item Return Value: $new_schema
1643 DEPRECATED. You probably wanted compose_namespace.
1645 Actually, you probably just wanted to call connect.
1649 (hidden due to deprecation)
1651 Calls L<DBIx::Class::Schema/"compose_namespace"> to the target namespace,
1652 calls L<DBIx::Class::Schema/connection> with @db_info on the new schema,
1653 then injects the L<DBix::Class::ResultSetProxy> component and a
1654 resultset_instance classdata entry on all the new classes, in order to support
1655 $target_namespaces::$class->search(...) method calls.
1657 This is primarily useful when you have a specific need for class method access
1658 to a connection. In normal usage it is preferred to call
1659 L<DBIx::Class::Schema/connect> and use the resulting schema object to operate
1660 on L<DBIx::Class::ResultSet> objects with L<DBIx::Class::Schema/resultset> for
1667 sub compose_connection {
1668 my ($self, $target, @info) = @_;
1670 carp_once "compose_connection deprecated as of 0.08000"
1671 unless $INC{"DBIx/Class/CDBICompat.pm"};
1674 require DBIx::Class::ResultSetProxy;
1676 dbic_internal_catch {
1677 $self->throw_exception
1678 ("No arguments to load_classes and couldn't load DBIx::Class::ResultSetProxy ($_)")
1681 if ($self eq $target) {
1682 # Pathological case, largely caused by the docs on early C::M::DBIC::Plain
1683 foreach my $source_name ($self->sources) {
1684 my $source = $self->source($source_name);
1685 my $class = $source->result_class;
1686 $self->inject_base($class, 'DBIx::Class::ResultSetProxy');
1687 $class->mk_classaccessor(resultset_instance => $source->resultset);
1688 $class->mk_classaccessor(class_resolver => $self);
1690 $self->connection(@info);
1694 my $schema = $self->compose_namespace($target, 'DBIx::Class::ResultSetProxy');
1695 quote_sub "${target}::schema", '$s', { '$s' => \$schema };
1697 # needed to cover the newly installed stuff via quote_sub above
1698 Class::C3->reinitialize if DBIx::Class::_ENV_::OLD_MRO;
1700 $schema->connection(@info);
1701 foreach my $source_name ($schema->sources) {
1702 my $source = $schema->source($source_name);
1703 my $class = $source->result_class;
1704 #warn "$source_name $class $source ".$source->storage;
1706 $class->mk_group_accessors( inherited => [ result_source_instance => '_result_source' ] );
1707 # explicit set-call, avoid mro update lag
1708 $class->set_inherited( result_source_instance => $source );
1710 $class->mk_classaccessor(resultset_instance => $source->resultset);
1711 $class->mk_classaccessor(class_resolver => $schema);
1716 =head1 FURTHER QUESTIONS?
1718 Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
1720 =head1 COPYRIGHT AND LICENSE
1722 This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
1723 by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
1724 redistribute it and/or modify it under the same terms as the
1725 L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.