1 package DBIx::Class::Schema;
6 use base 'DBIx::Class';
11 use Scalar::Util qw/weaken blessed/;
12 use DBIx::Class::_Util qw(
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' => {});
33 DBIx::Class::Schema - composable schemas
37 package Library::Schema;
38 use base qw/DBIx::Class::Schema/;
40 # load all Result classes in Library/Schema/Result/
41 __PACKAGE__->load_namespaces();
43 package Library::Schema::Result::CD;
44 use base qw/DBIx::Class::Core/;
46 __PACKAGE__->load_components(qw/InflateColumn::DateTime/); # for example
47 __PACKAGE__->table('cd');
49 # Elsewhere in your code:
50 my $schema1 = Library::Schema->connect(
57 my $schema2 = Library::Schema->connect($coderef_returning_dbh);
59 # fetch objects using Library::Schema::Result::DVD
60 my $resultset = $schema1->resultset('DVD')->search( ... );
61 my @dvd_objects = $schema2->resultset('DVD')->search( ... );
65 Creates database classes based on a schema. This is the recommended way to
66 use L<DBIx::Class> and allows you to use more than one concurrent connection
69 NB: If you're used to L<Class::DBI> it's worth reading the L</SYNOPSIS>
70 carefully, as DBIx::Class does things a little differently. Note in
71 particular which module inherits off which.
75 =head2 load_namespaces
79 =item Arguments: %options?
83 package MyApp::Schema;
84 __PACKAGE__->load_namespaces();
86 __PACKAGE__->load_namespaces(
87 result_namespace => 'Res',
88 resultset_namespace => 'RSet',
89 default_resultset_class => '+MyApp::Othernamespace::RSet',
92 With no arguments, this method uses L<Module::Find> to load all of the
93 Result and ResultSet classes under the namespace of the schema from
94 which it is called. For example, C<My::Schema> will by default find
95 and load Result classes named C<My::Schema::Result::*> and ResultSet
96 classes named C<My::Schema::ResultSet::*>.
98 ResultSet classes are associated with Result class of the same name.
99 For example, C<My::Schema::Result::CD> will get the ResultSet class
100 C<My::Schema::ResultSet::CD> if it is present.
102 Both Result and ResultSet namespaces are configurable via the
103 C<result_namespace> and C<resultset_namespace> options.
105 Another option, C<default_resultset_class> specifies a custom default
106 ResultSet class for Result classes with no corresponding ResultSet.
108 All of the namespace and classname options are by default relative to
109 the schema classname. To specify a fully-qualified name, prefix it
110 with a literal C<+>. For example, C<+Other::NameSpace::Result>.
114 You will be warned if ResultSet classes are discovered for which there
115 are no matching Result classes like this:
117 load_namespaces found ResultSet class $classname with no corresponding Result class
119 If a ResultSource instance is found to already have a ResultSet class set
120 using L<resultset_class|DBIx::Class::ResultSource/resultset_class> to some
121 other class, you will be warned like this:
123 We found ResultSet class '$rs_class' for '$result_class', but it seems
124 that you had already set '$result_class' to use '$rs_set' instead
128 # load My::Schema::Result::CD, My::Schema::Result::Artist,
129 # My::Schema::ResultSet::CD, etc...
130 My::Schema->load_namespaces;
132 # Override everything to use ugly names.
133 # In this example, if there is a My::Schema::Res::Foo, but no matching
134 # My::Schema::RSets::Foo, then Foo will have its
135 # resultset_class set to My::Schema::RSetBase
136 My::Schema->load_namespaces(
137 result_namespace => 'Res',
138 resultset_namespace => 'RSets',
139 default_resultset_class => 'RSetBase',
142 # Put things in other namespaces
143 My::Schema->load_namespaces(
144 result_namespace => '+Some::Place::Results',
145 resultset_namespace => '+Another::Place::RSets',
148 To search multiple namespaces for either Result or ResultSet classes,
149 use an arrayref of namespaces for that option. In the case that the
150 same result (or resultset) class exists in multiple namespaces, later
151 entries in the list of namespaces will override earlier ones.
153 My::Schema->load_namespaces(
154 # My::Schema::Results_C::Foo takes precedence over My::Schema::Results_B::Foo :
155 result_namespace => [ 'Results_A', 'Results_B', 'Results_C' ],
156 resultset_namespace => [ '+Some::Place::RSets', 'RSets' ],
161 # Pre-pends our classname to the given relative classname or
162 # class namespace, unless there is a '+' prefix, which will
164 sub _expand_relative_name {
165 my ($class, $name) = @_;
166 $name =~ s/^\+// or $name = "${class}::${name}";
170 # Finds all modules in the supplied namespace, or if omitted in the
171 # namespace of $class. Untaints all findings as they can be assumed
174 require Module::Find;
176 { $_ =~ /(.+)/ } # untaint result
177 Module::Find::findallmod( $_[1] || ref $_[0] || $_[0] )
181 # returns a hash of $shortname => $fullname for every package
182 # found in the given namespaces ($shortname is with the $fullname's
183 # namespace stripped off)
184 sub _map_namespaces {
185 my ($me, $namespaces) = @_;
188 for my $ns (@$namespaces) {
189 $res{ substr($_, length "${ns}::") } = $_
190 for $me->_findallmod($ns);
196 # returns the result_source_instance for the passed class/object,
197 # or dies with an informative message (used by load_namespaces)
198 sub _ns_get_rsrc_instance {
200 my $rs_class = ref ($_[0]) || $_[0];
202 return dbic_internal_try {
203 $rs_class->result_source_instance
205 $me->throw_exception (
206 "Attempt to load_namespaces() class $rs_class failed - are you sure this is a real Result Class?: $_"
211 sub load_namespaces {
212 my ($class, %args) = @_;
214 my $result_namespace = delete $args{result_namespace} || 'Result';
215 my $resultset_namespace = delete $args{resultset_namespace} || 'ResultSet';
217 my $default_resultset_class = delete $args{default_resultset_class};
219 $default_resultset_class = $class->_expand_relative_name($default_resultset_class)
220 if $default_resultset_class;
222 $class->throw_exception('load_namespaces: unknown option(s): '
223 . join(q{,}, map { qq{'$_'} } keys %args))
224 if scalar keys %args;
226 for my $arg ($result_namespace, $resultset_namespace) {
227 $arg = [ $arg ] if ( $arg and ! ref $arg );
229 $class->throw_exception('load_namespaces: namespace arguments must be '
230 . 'a simple string or an arrayref')
231 if ref($arg) ne 'ARRAY';
233 $_ = $class->_expand_relative_name($_) for (@$arg);
236 my $results_by_source_name = $class->_map_namespaces($result_namespace);
237 my $resultsets_by_source_name = $class->_map_namespaces($resultset_namespace);
241 no warnings qw/redefine/;
242 local *Class::C3::reinitialize = sub { } if DBIx::Class::_ENV_::OLD_MRO;
243 use warnings qw/redefine/;
245 # ensure classes are loaded and attached in inheritance order
246 for my $result_class (values %$results_by_source_name) {
247 $class->ensure_class_loaded($result_class);
250 my @source_names_by_subclass_last = sort {
253 scalar @{mro::get_linear_isa( $results_by_source_name->{$a} )}
259 scalar @{mro::get_linear_isa( $results_by_source_name->{$b} )}
262 } keys(%$results_by_source_name);
264 foreach my $source_name (@source_names_by_subclass_last) {
265 my $result_class = $results_by_source_name->{$source_name};
267 my $preset_resultset_class = $class->_ns_get_rsrc_instance ($result_class)->resultset_class;
268 my $found_resultset_class = delete $resultsets_by_source_name->{$source_name};
270 if($preset_resultset_class && $preset_resultset_class ne 'DBIx::Class::ResultSet') {
271 if($found_resultset_class && $found_resultset_class ne $preset_resultset_class) {
272 carp "We found ResultSet class '$found_resultset_class' matching '$results_by_source_name->{$source_name}', but it seems "
273 . "that you had already set the '$results_by_source_name->{$source_name}' resultet to '$preset_resultset_class' instead";
276 # elsif - there may be *no* default_resultset_class, in which case we fallback to
277 # DBIx::Class::Resultset and there is nothing to check
278 elsif($found_resultset_class ||= $default_resultset_class) {
279 $class->ensure_class_loaded($found_resultset_class);
280 if(!$found_resultset_class->isa("DBIx::Class::ResultSet")) {
281 carp "load_namespaces found ResultSet class '$found_resultset_class' that does not subclass DBIx::Class::ResultSet";
284 $class->_ns_get_rsrc_instance ($result_class)->resultset_class($found_resultset_class);
287 my $source_name = $class->_ns_get_rsrc_instance ($result_class)->source_name || $source_name;
289 push(@to_register, [ $source_name, $result_class ]);
293 foreach (sort keys %$resultsets_by_source_name) {
294 carp "load_namespaces found ResultSet class '$resultsets_by_source_name->{$_}' "
295 .'with no corresponding Result class';
298 Class::C3->reinitialize if DBIx::Class::_ENV_::OLD_MRO;
300 $class->register_class(@$_) for (@to_register);
309 =item Arguments: @classes?, { $namespace => [ @classes ] }+
313 L</load_classes> is an alternative method to L</load_namespaces>, both of
314 which serve similar purposes, each with different advantages and disadvantages.
315 In the general case you should use L</load_namespaces>, unless you need to
316 be able to specify that only specific classes are loaded at runtime.
318 With no arguments, this method uses L<Module::Find> to find all classes under
319 the schema's namespace. Otherwise, this method loads the classes you specify
320 (using L<use>), and registers them (using L</"register_class">).
322 It is possible to comment out classes with a leading C<#>, but note that perl
323 will think it's a mistake (trying to use a comment in a qw list), so you'll
324 need to add C<no warnings 'qw';> before your load_classes call.
326 If any classes found do not appear to be Result class files, you will
327 get the following warning:
329 Failed to load $comp_class. Can't find source_name method. Is
330 $comp_class really a full DBIC result class? Fix it, move it elsewhere,
331 or make your load_classes call more specific.
335 My::Schema->load_classes(); # loads My::Schema::CD, My::Schema::Artist,
336 # etc. (anything under the My::Schema namespace)
338 # loads My::Schema::CD, My::Schema::Artist, Other::Namespace::Producer but
339 # not Other::Namespace::LinerNotes nor My::Schema::Track
340 My::Schema->load_classes(qw/ CD Artist #Track /, {
341 Other::Namespace => [qw/ Producer #LinerNotes /],
347 my ($class, @params) = @_;
352 foreach my $param (@params) {
353 if (ref $param eq 'ARRAY') {
354 # filter out commented entries
355 my @modules = grep { $_ !~ /^#/ } @$param;
357 push (@{$comps_for{$class}}, @modules);
359 elsif (ref $param eq 'HASH') {
360 # more than one namespace possible
361 for my $comp ( keys %$param ) {
362 # filter out commented entries
363 my @modules = grep { $_ !~ /^#/ } @{$param->{$comp}};
365 push (@{$comps_for{$comp}}, @modules);
369 # filter out commented entries
370 push (@{$comps_for{$class}}, $param) if $param !~ /^#/;
374 my @comp = map { substr $_, length "${class}::" }
375 $class->_findallmod($class);
376 $comps_for{$class} = \@comp;
381 no warnings qw/redefine/;
382 local *Class::C3::reinitialize = sub { } if DBIx::Class::_ENV_::OLD_MRO;
383 use warnings qw/redefine/;
385 foreach my $prefix (keys %comps_for) {
386 foreach my $comp (@{$comps_for{$prefix}||[]}) {
387 my $comp_class = "${prefix}::${comp}";
388 $class->ensure_class_loaded($comp_class);
390 my $snsub = $comp_class->can('source_name');
392 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.";
395 $comp = $snsub->($comp_class) || $comp;
397 push(@to_register, [ $comp, $comp_class ]);
401 Class::C3->reinitialize if DBIx::Class::_ENV_::OLD_MRO;
403 foreach my $to (@to_register) {
404 $class->register_class(@$to);
412 =item Arguments: $storage_type|{$storage_type, \%args}
414 =item Return Value: $storage_type|{$storage_type, \%args}
416 =item Default value: DBIx::Class::Storage::DBI
420 Set the storage class that will be instantiated when L</connect> is called.
421 If the classname starts with C<::>, the prefix C<DBIx::Class::Storage> is
422 assumed by L</connect>.
424 You want to use this to set subclasses of L<DBIx::Class::Storage::DBI>
425 in cases where the appropriate subclass is not autodetected.
427 If your storage type requires instantiation arguments, those are
428 defined as a second argument in the form of a hashref and the entire
429 value needs to be wrapped into an arrayref or a hashref. We support
430 both types of refs here in order to play nice with your
431 Config::[class] or your choice. See
432 L<DBIx::Class::Storage::DBI::Replicated> for an example of this.
434 =head2 default_resultset_attributes
438 =item Arguments: L<\%attrs|DBIx::Class::ResultSet/ATTRIBUTES>
440 =item Return Value: L<\%attrs|DBIx::Class::ResultSet/ATTRIBUTES>
442 =item Default value: None
446 Like L<DBIx::Class::ResultSource/resultset_attributes> stores a collection
447 of resultset attributes, to be used as defaults for B<every> ResultSet
448 instance schema-wide. The same list of CAVEATS and WARNINGS applies, with
449 the extra downside of these defaults being practically inescapable: you will
450 B<not> be able to derive a ResultSet instance with these attributes unset.
455 use base qw/DBIx::Class::Schema/;
456 __PACKAGE__->default_resultset_attributes( { software_limit => 1 } );
458 =head2 exception_action
462 =item Arguments: $code_reference
464 =item Return Value: $code_reference
466 =item Default value: None
470 When L</throw_exception> is invoked and L</exception_action> is set to a code
471 reference, this reference will be called instead of
472 L<DBIx::Class::Exception/throw>, with the exception message passed as the only
475 Your custom throw code B<must> rethrow the exception, as L</throw_exception> is
476 an integral part of DBIC's internal execution control flow.
481 use base qw/DBIx::Class::Schema/;
482 use My::ExceptionClass;
483 __PACKAGE__->exception_action(sub { My::ExceptionClass->throw(@_) });
484 __PACKAGE__->load_classes;
487 my $schema_obj = My::Schema->connect( .... );
488 $schema_obj->exception_action(sub { My::ExceptionClass->throw(@_) });
494 =item Arguments: boolean
498 Whether L</throw_exception> should include stack trace information.
499 Defaults to false normally, but defaults to true if C<$ENV{DBIC_TRACE}>
502 =head2 sqlt_deploy_hook
506 =item Arguments: $sqlt_schema
510 An optional sub which you can declare in your own Schema class that will get
511 passed the L<SQL::Translator::Schema> object when you deploy the schema via
512 L</create_ddl_dir> or L</deploy>.
514 For an example of what you can do with this, see
515 L<DBIx::Class::Manual::Cookbook/Adding Indexes And Functions To Your SQL>.
517 Note that sqlt_deploy_hook is called by L</deployment_statements>, which in turn
518 is called before L</deploy>. Therefore the hook can be used only to manipulate
519 the L<SQL::Translator::Schema> object before it is turned into SQL fed to the
520 database. If you want to execute post-deploy statements which can not be generated
521 by L<SQL::Translator>, the currently suggested method is to overload L</deploy>
522 and use L<dbh_do|DBIx::Class::Storage::DBI/dbh_do>.
530 =item Arguments: @connectinfo
532 =item Return Value: $new_schema
536 Creates and returns a new Schema object. The connection info set on it
537 is used to create a new instance of the storage backend and set it on
540 See L<DBIx::Class::Storage::DBI/"connect_info"> for DBI-specific
541 syntax on the C<@connectinfo> argument, or L<DBIx::Class::Storage> in
544 Note that C<connect_info> expects an arrayref of arguments, but
545 C<connect> does not. C<connect> wraps its arguments in an arrayref
546 before passing them to C<connect_info>.
550 C<connect> is a convenience method. It is equivalent to calling
551 $schema->clone->connection(@connectinfo). To write your own overloaded
552 version, overload L</connection> instead.
557 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
558 shift->clone->connection(@_);
565 =item Arguments: L<$source_name|DBIx::Class::ResultSource/source_name>
567 =item Return Value: L<$resultset|DBIx::Class::ResultSet>
571 my $rs = $schema->resultset('DVD');
573 Returns the L<DBIx::Class::ResultSet> object for the registered source
579 my ($self, $source_name) = @_;
580 $self->throw_exception('resultset() expects a source name')
581 unless defined $source_name;
582 return $self->source($source_name)->resultset;
589 =item Return Value: L<@source_names|DBIx::Class::ResultSource/source_name>
593 my @source_names = $schema->sources;
595 Lists names of all the sources registered on this Schema object.
599 sub sources { keys %{shift->source_registrations} }
605 =item Arguments: L<$source_name|DBIx::Class::ResultSource/source_name>
607 =item Return Value: L<$result_source|DBIx::Class::ResultSource>
611 my $source = $schema->source('Book');
613 Returns the L<DBIx::Class::ResultSource> object for the registered
621 $self->throw_exception("source() expects a source name")
624 my $source_name = shift;
626 my $sreg = $self->source_registrations;
627 return $sreg->{$source_name} if exists $sreg->{$source_name};
629 # if we got here, they probably passed a full class name
630 my $mapped = $self->class_mappings->{$source_name};
631 $self->throw_exception("Can't find source for ${source_name}")
632 unless $mapped && exists $sreg->{$mapped};
633 return $sreg->{$mapped};
640 =item Arguments: L<$source_name|DBIx::Class::ResultSource/source_name>
642 =item Return Value: $classname
646 my $class = $schema->class('CD');
648 Retrieves the Result class name for the given source name.
653 return shift->source(shift)->result_class;
660 =item Arguments: C<$coderef>, @coderef_args?
662 =item Return Value: The return value of $coderef
666 Executes C<$coderef> with (optional) arguments C<@coderef_args> atomically,
667 returning its result (if any). Equivalent to calling $schema->storage->txn_do.
668 See L<DBIx::Class::Storage/"txn_do"> for more information.
670 This interface is preferred over using the individual methods L</txn_begin>,
671 L</txn_commit>, and L</txn_rollback> below.
673 WARNING: If you are connected with C<< AutoCommit => 0 >> the transaction is
674 considered nested, and you will still need to call L</txn_commit> to write your
675 changes when appropriate. You will also want to connect with C<< auto_savepoint =>
676 1 >> to get partial rollback to work, if the storage driver for your database
679 Connecting with C<< AutoCommit => 1 >> is recommended.
686 $self->storage or $self->throw_exception
687 ('txn_do called on $schema without storage');
689 $self->storage->txn_do(@_);
692 =head2 txn_scope_guard
694 Runs C<txn_scope_guard> on the schema's storage. See
695 L<DBIx::Class::Storage/txn_scope_guard>.
699 sub txn_scope_guard {
702 $self->storage or $self->throw_exception
703 ('txn_scope_guard called on $schema without storage');
705 $self->storage->txn_scope_guard(@_);
710 Begins a transaction (does nothing if AutoCommit is off). Equivalent to
711 calling $schema->storage->txn_begin. See
712 L<DBIx::Class::Storage/"txn_begin"> for more information.
719 $self->storage or $self->throw_exception
720 ('txn_begin called on $schema without storage');
722 $self->storage->txn_begin;
727 Commits the current transaction. Equivalent to calling
728 $schema->storage->txn_commit. See L<DBIx::Class::Storage/"txn_commit">
729 for more information.
736 $self->storage or $self->throw_exception
737 ('txn_commit called on $schema without storage');
739 $self->storage->txn_commit;
744 Rolls back the current transaction. Equivalent to calling
745 $schema->storage->txn_rollback. See
746 L<DBIx::Class::Storage/"txn_rollback"> for more information.
753 $self->storage or $self->throw_exception
754 ('txn_rollback called on $schema without storage');
756 $self->storage->txn_rollback;
761 my $storage = $schema->storage;
763 Returns the L<DBIx::Class::Storage> object for this Schema. Grab this
764 if you want to turn on SQL statement debugging at runtime, or set the
765 quote character. For the default storage, the documentation can be
766 found in L<DBIx::Class::Storage::DBI>.
772 =item Arguments: L<$source_name|DBIx::Class::ResultSource/source_name>, [ \@column_list, \@row_values+ ] | [ \%col_data+ ]
774 =item Return Value: L<\@result_objects|DBIx::Class::Manual::ResultClass> (scalar context) | L<@result_objects|DBIx::Class::Manual::ResultClass> (list context)
778 A convenience shortcut to L<DBIx::Class::ResultSet/populate>. Equivalent to:
780 $schema->resultset($source_name)->populate([...]);
786 The context of this method call has an important effect on what is
787 submitted to storage. In void context data is fed directly to fastpath
788 insertion routines provided by the underlying storage (most often
789 L<DBI/execute_for_fetch>), bypassing the L<new|DBIx::Class::Row/new> and
790 L<insert|DBIx::Class::Row/insert> calls on the
791 L<Result|DBIx::Class::Manual::ResultClass> class, including any
792 augmentation of these methods provided by components. For example if you
793 are using something like L<DBIx::Class::UUIDColumns> to create primary
794 keys for you, you will find that your PKs are empty. In this case you
795 will have to explicitly force scalar or list context in order to create
803 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
805 my ($self, $name, $data) = @_;
806 my $rs = $self->resultset($name)
807 or $self->throw_exception("'$name' is not a resultset");
809 return $rs->populate($data);
816 =item Arguments: @args
818 =item Return Value: $self
822 Similar to L</connect> except sets the storage object and connection
823 data B<in-place> on C<$self>. You should probably be calling
824 L</connect> to get a properly L<cloned|/clone> Schema object instead.
828 Overload C<connection> to change the behaviour of C<connect>.
833 my ($self, @info) = @_;
834 return $self if !@info && $self->storage;
836 my ($storage_class, $args) = ref $self->storage_type
837 ? $self->_normalize_storage_type($self->storage_type)
838 : $self->storage_type
841 $storage_class =~ s/^::/DBIx::Class::Storage::/;
844 $self->ensure_class_loaded ($storage_class);
847 $self->throw_exception(
848 "Unable to load storage class ${storage_class}: $_"
852 my $storage = $storage_class->new( $self => $args||{} );
853 $storage->connect_info(\@info);
854 $self->storage($storage);
858 sub _normalize_storage_type {
859 my ($self, $storage_type) = @_;
860 if(ref $storage_type eq 'ARRAY') {
861 return @$storage_type;
862 } elsif(ref $storage_type eq 'HASH') {
863 return %$storage_type;
865 $self->throw_exception('Unsupported REFTYPE given: '. ref $storage_type);
869 =head2 compose_namespace
873 =item Arguments: $target_namespace, $additional_base_class?
875 =item Return Value: $new_schema
879 For each L<DBIx::Class::ResultSource> in the schema, this method creates a
880 class in the target namespace (e.g. $target_namespace::CD,
881 $target_namespace::Artist) that inherits from the corresponding classes
882 attached to the current schema.
884 It also attaches a corresponding L<DBIx::Class::ResultSource> object to the
885 new $schema object. If C<$additional_base_class> is given, the new composed
886 classes will inherit from first the corresponding class from the current
887 schema then the base class.
889 For example, for a schema with My::Schema::CD and My::Schema::Artist classes,
891 $schema->compose_namespace('My::DB', 'Base::Class');
892 print join (', ', @My::DB::CD::ISA) . "\n";
893 print join (', ', @My::DB::Artist::ISA) ."\n";
895 will produce the output
897 My::Schema::CD, Base::Class
898 My::Schema::Artist, Base::Class
902 sub compose_namespace {
903 my ($self, $target, $base) = @_;
905 my $schema = $self->clone;
907 $schema->source_registrations({});
909 # the original class-mappings must remain - otherwise
910 # reverse_relationship_info will not work
911 #$schema->class_mappings({});
914 no warnings qw/redefine/;
915 local *Class::C3::reinitialize = sub { } if DBIx::Class::_ENV_::OLD_MRO;
916 use warnings qw/redefine/;
918 foreach my $source_name ($self->sources) {
919 my $orig_source = $self->source($source_name);
921 my $target_class = "${target}::${source_name}";
922 $self->inject_base($target_class, $orig_source->result_class, ($base || ()) );
924 # register_source examines result_class, and then returns us a clone
925 my $new_source = $schema->register_source($source_name, bless
926 { %$orig_source, result_class => $target_class },
930 if ($target_class->can('result_source_instance')) {
931 # give the class a schema-less source copy
932 $target_class->result_source_instance( bless
933 { %$new_source, schema => ref $new_source->{schema} || $new_source->{schema} },
939 # Legacy stuff, not inserting INDIRECT assertions
940 quote_sub "${target}::${_}" => "shift->schema->$_(\@_)"
941 for qw(class source resultset);
944 Class::C3->reinitialize() if DBIx::Class::_ENV_::OLD_MRO;
949 # LEGACY: The intra-call to this was removed in 66d9ef6b and then
950 # the sub was de-documented way later in 249963d4. No way to be sure
951 # nothing on darkpan is calling it directly, so keeping as-is
952 sub setup_connection_class {
953 my ($class, $target, @info) = @_;
954 $class->inject_base($target => 'DBIx::Class::DB');
955 #$target->load_components('DB');
956 $target->connection(@info);
961 Creates a new savepoint (does nothing outside a transaction).
962 Equivalent to calling $schema->storage->svp_begin. See
963 L<DBIx::Class::Storage/"svp_begin"> for more information.
968 my ($self, $name) = @_;
970 $self->storage or $self->throw_exception
971 ('svp_begin called on $schema without storage');
973 $self->storage->svp_begin($name);
978 Releases a savepoint (does nothing outside a transaction).
979 Equivalent to calling $schema->storage->svp_release. See
980 L<DBIx::Class::Storage/"svp_release"> for more information.
985 my ($self, $name) = @_;
987 $self->storage or $self->throw_exception
988 ('svp_release called on $schema without storage');
990 $self->storage->svp_release($name);
995 Rollback to a savepoint (does nothing outside a transaction).
996 Equivalent to calling $schema->storage->svp_rollback. See
997 L<DBIx::Class::Storage/"svp_rollback"> for more information.
1002 my ($self, $name) = @_;
1004 $self->storage or $self->throw_exception
1005 ('svp_rollback called on $schema without storage');
1007 $self->storage->svp_rollback($name);
1014 =item Arguments: %attrs?
1016 =item Return Value: $new_schema
1020 Clones the schema and its associated result_source objects and returns the
1021 copy. The resulting copy will have the same attributes as the source schema,
1022 except for those attributes explicitly overridden by the provided C<%attrs>.
1030 (ref $self ? %$self : ()),
1031 (@_ == 1 && ref $_[0] eq 'HASH' ? %{ $_[0] } : @_),
1033 bless $clone, (ref $self || $self);
1035 $clone->$_(undef) for qw/class_mappings source_registrations storage/;
1037 $clone->_copy_state_from($self);
1042 # Needed in Schema::Loader - if you refactor, please make a compatibility shim
1044 sub _copy_state_from {
1045 my ($self, $from) = @_;
1047 $self->class_mappings({ %{$from->class_mappings} });
1048 $self->source_registrations({ %{$from->source_registrations} });
1050 foreach my $source_name ($from->sources) {
1051 my $source = $from->source($source_name);
1052 my $new = $source->new($source);
1053 # we use extra here as we want to leave the class_mappings as they are
1054 # but overwrite the source_registrations entry with the new source
1055 $self->register_extra_source($source_name => $new);
1058 if ($from->storage) {
1059 $self->storage($from->storage);
1060 $self->storage->set_schema($self);
1064 =head2 throw_exception
1068 =item Arguments: $message
1072 Throws an exception. Obeys the exemption rules of L<DBIx::Class::Carp> to report
1073 errors from outer-user's perspective. See L</exception_action> for details on overriding
1074 this method's behavior. If L</stacktrace> is turned on, C<throw_exception>'s
1075 default behavior will provide a detailed stack trace.
1079 sub throw_exception {
1080 my ($self, @args) = @_;
1083 ! DBIx::Class::_Util::in_internal_try()
1085 my $act = $self->exception_action
1090 my $guard = scope_guard {
1091 return if $guard_disarmed;
1092 emit_loud_diag( emit_dups => 1, msg => "
1094 !!! DBIx::Class INTERNAL PANIC !!!
1096 The exception_action() handler installed on '$self'
1097 aborted the stacktrace below via a longjmp (either via Return::Multilevel or
1098 plain goto, or Scope::Upper or something equally nefarious). There currently
1099 is nothing safe DBIx::Class can do, aside from displaying this error. A future
1100 version ( 0.082900, when available ) will reduce the cases in which the
1101 handler is invoked, but this is neither a complete solution, nor can it do
1102 anything for other software that might be affected by a similar problem.
1104 !!! FIX YOUR ERROR HANDLING !!!
1106 This guard was activated starting",
1111 # if it throws - good, we'll assign to @args in the end
1112 # if it doesn't - do different things depending on RV truthiness
1113 if( $act->(@args) ) {
1115 "Invocation of the exception_action handler installed on $self did *not*"
1116 .' result in an exception. DBIx::Class is unable to function without a reliable'
1117 .' exception mechanism, ensure your exception_action does not hide exceptions'
1118 ." (original error: $args[0])"
1123 "The exception_action handler installed on $self returned false instead"
1124 .' of throwing an exception. This behavior has been deprecated, adjust your'
1125 .' handler to always rethrow the supplied error'
1132 # We call this to get the necessary warnings emitted and disregard the RV
1133 # as it's definitely an exception if we got as far as this catch{} block
1139 # Done guarding against https://github.com/PerlDancer/Dancer2/issues/1125
1140 $guard_disarmed = 1;
1143 DBIx::Class::Exception->throw( $args[0], $self->stacktrace );
1150 =item Arguments: \%sqlt_args, $dir
1154 Attempts to deploy the schema to the current storage using L<SQL::Translator>.
1156 See L<SQL::Translator/METHODS> for a list of values for C<\%sqlt_args>.
1157 The most common value for this would be C<< { add_drop_table => 1 } >>
1158 to have the SQL produced include a C<DROP TABLE> statement for each table
1159 created. For quoting purposes supply C<quote_identifiers>.
1161 Additionally, the DBIx::Class parser accepts a C<sources> parameter as a hash
1162 ref or an array ref, containing a list of source to deploy. If present, then
1163 only the sources listed will get deployed. Furthermore, you can use the
1164 C<add_fk_index> parser parameter to prevent the parser from creating an index for each
1170 my ($self, $sqltargs, $dir) = @_;
1171 $self->throw_exception("Can't deploy without storage") unless $self->storage;
1172 $self->storage->deploy($self, undef, $sqltargs, $dir);
1175 =head2 deployment_statements
1179 =item Arguments: See L<DBIx::Class::Storage::DBI/deployment_statements>
1181 =item Return Value: $listofstatements
1185 A convenient shortcut to
1186 C<< $self->storage->deployment_statements($self, @args) >>.
1187 Returns the statements used by L</deploy> and
1188 L<DBIx::Class::Storage/deploy>.
1192 sub deployment_statements {
1195 $self->throw_exception("Can't generate deployment statements without a storage")
1196 if not $self->storage;
1198 $self->storage->deployment_statements($self, @_);
1201 =head2 create_ddl_dir
1205 =item Arguments: See L<DBIx::Class::Storage::DBI/create_ddl_dir>
1209 A convenient shortcut to
1210 C<< $self->storage->create_ddl_dir($self, @args) >>.
1212 Creates an SQL file based on the Schema, for each of the specified
1213 database types, in the given directory.
1217 sub create_ddl_dir {
1220 $self->throw_exception("Can't create_ddl_dir without storage") unless $self->storage;
1221 $self->storage->create_ddl_dir($self, @_);
1228 =item Arguments: $database-type, $version, $directory, $preversion
1230 =item Return Value: $normalised_filename
1234 my $filename = $table->ddl_filename($type, $version, $dir, $preversion)
1236 This method is called by C<create_ddl_dir> to compose a file name out of
1237 the supplied directory, database type and version number. The default file
1238 name format is: C<$dir$schema-$version-$type.sql>.
1240 You may override this method in your schema if you wish to use a different
1245 Prior to DBIx::Class version 0.08100 this method had a different signature:
1247 my $filename = $table->ddl_filename($type, $dir, $version, $preversion)
1249 In recent versions variables $dir and $version were reversed in order to
1250 bring the signature in line with other Schema/Storage methods. If you
1251 really need to maintain backward compatibility, you can do the following
1252 in any overriding methods:
1254 ($dir, $version) = ($version, $dir) if ($DBIx::Class::VERSION < 0.08100);
1259 my ($self, $type, $version, $dir, $preversion) = @_;
1261 $version = "$preversion-$version" if $preversion;
1263 my $class = blessed($self) || $self;
1266 return "$dir/$class-$version-$type.sql";
1271 Provided as the recommended way of thawing schema objects. You can call
1272 C<Storable::thaw> directly if you wish, but the thawed objects will not have a
1273 reference to any schema, so are rather useless.
1278 my ($self, $obj) = @_;
1279 local $DBIx::Class::ResultSourceHandle::thaw_schema = $self;
1280 return Storable::thaw($obj);
1285 This doesn't actually do anything beyond calling L<nfreeze|Storable/SYNOPSIS>,
1286 it is just provided here for symmetry.
1291 return Storable::nfreeze($_[1]);
1298 =item Arguments: $object
1300 =item Return Value: dcloned $object
1304 Recommended way of dcloning L<DBIx::Class::Row> and L<DBIx::Class::ResultSet>
1305 objects so their references to the schema object
1306 (which itself is B<not> cloned) are properly maintained.
1311 my ($self, $obj) = @_;
1312 local $DBIx::Class::ResultSourceHandle::thaw_schema = $self;
1313 return Storable::dclone($obj);
1316 =head2 schema_version
1318 Returns the current schema class' $VERSION in a normalised way.
1322 sub schema_version {
1324 my $class = ref($self)||$self;
1326 # does -not- use $schema->VERSION
1327 # since that varies in results depending on if version.pm is installed, and if
1328 # so the perl or XS versions. If you want this to change, bug the version.pm
1329 # author to make vpp and vxs behave the same.
1334 $version = ${"${class}::VERSION"};
1340 =head2 register_class
1344 =item Arguments: $source_name, $component_class
1348 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.
1350 You will only need this method if you have your Result classes in
1351 files which are not named after the packages (or all in the same
1352 file). You may also need it to register classes at runtime.
1354 Registers a class which isa DBIx::Class::ResultSourceProxy. Equivalent to
1357 $schema->register_source($source_name, $component_class->result_source_instance);
1361 sub register_class {
1362 my ($self, $source_name, $to_register) = @_;
1363 $self->register_source($source_name => $to_register->result_source_instance);
1366 =head2 register_source
1370 =item Arguments: $source_name, L<$result_source|DBIx::Class::ResultSource>
1374 This method is called by L</register_class>.
1376 Registers the L<DBIx::Class::ResultSource> in the schema with the given
1381 sub register_source { shift->_register_source(@_) }
1383 =head2 unregister_source
1387 =item Arguments: $source_name
1391 Removes the L<DBIx::Class::ResultSource> from the schema for the given source name.
1395 sub unregister_source { shift->_unregister_source(@_) }
1397 =head2 register_extra_source
1401 =item Arguments: $source_name, L<$result_source|DBIx::Class::ResultSource>
1405 As L</register_source> but should be used if the result class already
1406 has a source and you want to register an extra one.
1410 sub register_extra_source { shift->_register_source(@_, { extra => 1 }) }
1412 sub _register_source {
1413 my ($self, $source_name, $source, $params) = @_;
1415 $source = $source->new({ %$source, source_name => $source_name });
1417 $source->schema($self);
1418 weaken $source->{schema} if ref($self);
1420 my %reg = %{$self->source_registrations};
1421 $reg{$source_name} = $source;
1422 $self->source_registrations(\%reg);
1424 return $source if $params->{extra};
1426 my $rs_class = $source->result_class;
1427 if ($rs_class and my $rsrc = dbic_internal_try { $rs_class->result_source_instance } ) {
1428 my %map = %{$self->class_mappings};
1430 exists $map{$rs_class}
1432 $map{$rs_class} ne $source_name
1434 $rsrc ne $_[2] # orig_source
1437 "$rs_class already had a registered source which was replaced by this call. "
1438 . 'Perhaps you wanted register_extra_source(), though it is more likely you did '
1439 . 'something wrong.'
1443 $map{$rs_class} = $source_name;
1444 $self->class_mappings(\%map);
1450 my $global_phase_destroy;
1452 ### NO detected_reinvoked_destructor check
1453 ### This code very much relies on being called multuple times
1455 return if $global_phase_destroy ||= in_global_destruction;
1458 my $srcs = $self->source_registrations;
1460 for my $source_name (keys %$srcs) {
1461 # find first source that is not about to be GCed (someone other than $self
1462 # holds a reference to it) and reattach to it, weakening our own link
1464 # during global destruction (if we have not yet bailed out) this should throw
1465 # which will serve as a signal to not try doing anything else
1466 # however beware - on older perls the exception seems randomly untrappable
1467 # due to some weird race condition during thread joining :(((
1468 if (length ref $srcs->{$source_name} and refcount($srcs->{$source_name}) > 1) {
1469 local $SIG{__DIE__} if $SIG{__DIE__};
1470 local $@ if DBIx::Class::_ENV_::UNSTABLE_DOLLARAT;
1472 $srcs->{$source_name}->schema($self);
1473 weaken $srcs->{$source_name};
1476 $global_phase_destroy = 1;
1483 # Dummy NEXTSTATE ensuring the all temporaries on the stack are garbage
1484 # collected before leaving this scope. Depending on the code above, this
1485 # may very well be just a preventive measure guarding future modifications
1489 sub _unregister_source {
1490 my ($self, $source_name) = @_;
1491 my %reg = %{$self->source_registrations};
1493 my $source = delete $reg{$source_name};
1494 $self->source_registrations(\%reg);
1495 if ($source->result_class) {
1496 my %map = %{$self->class_mappings};
1497 delete $map{$source->result_class};
1498 $self->class_mappings(\%map);
1503 =head2 compose_connection (DEPRECATED)
1507 =item Arguments: $target_namespace, @db_info
1509 =item Return Value: $new_schema
1513 DEPRECATED. You probably wanted compose_namespace.
1515 Actually, you probably just wanted to call connect.
1519 (hidden due to deprecation)
1521 Calls L<DBIx::Class::Schema/"compose_namespace"> to the target namespace,
1522 calls L<DBIx::Class::Schema/connection> with @db_info on the new schema,
1523 then injects the L<DBix::Class::ResultSetProxy> component and a
1524 resultset_instance classdata entry on all the new classes, in order to support
1525 $target_namespaces::$class->search(...) method calls.
1527 This is primarily useful when you have a specific need for class method access
1528 to a connection. In normal usage it is preferred to call
1529 L<DBIx::Class::Schema/connect> and use the resulting schema object to operate
1530 on L<DBIx::Class::ResultSet> objects with L<DBIx::Class::Schema/resultset> for
1537 sub compose_connection {
1538 my ($self, $target, @info) = @_;
1540 carp_once "compose_connection deprecated as of 0.08000"
1541 unless $INC{"DBIx/Class/CDBICompat.pm"};
1544 require DBIx::Class::ResultSetProxy;
1547 $self->throw_exception
1548 ("No arguments to load_classes and couldn't load DBIx::Class::ResultSetProxy ($_)")
1551 if ($self eq $target) {
1552 # Pathological case, largely caused by the docs on early C::M::DBIC::Plain
1553 foreach my $source_name ($self->sources) {
1554 my $source = $self->source($source_name);
1555 my $class = $source->result_class;
1556 $self->inject_base($class, 'DBIx::Class::ResultSetProxy');
1557 $class->mk_classaccessor(resultset_instance => $source->resultset);
1558 $class->mk_classaccessor(class_resolver => $self);
1560 $self->connection(@info);
1564 my $schema = $self->compose_namespace($target, 'DBIx::Class::ResultSetProxy');
1565 quote_sub "${target}::schema", '$s', { '$s' => \$schema };
1567 $schema->connection(@info);
1568 foreach my $source_name ($schema->sources) {
1569 my $source = $schema->source($source_name);
1570 my $class = $source->result_class;
1571 #warn "$source_name $class $source ".$source->storage;
1572 $class->mk_classaccessor(result_source_instance => $source);
1573 $class->mk_classaccessor(resultset_instance => $source->resultset);
1574 $class->mk_classaccessor(class_resolver => $schema);
1579 =head1 FURTHER QUESTIONS?
1581 Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
1583 =head1 COPYRIGHT AND LICENSE
1585 This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
1586 by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
1587 redistribute it and/or modify it under the same terms as the
1588 L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.