1 package DBIx::Class::Schema;
6 use Carp::Clan qw/^DBIx::Class/;
7 use Scalar::Util qw/weaken/;
9 use base qw/DBIx::Class/;
11 __PACKAGE__->mk_classdata('class_mappings' => {});
12 __PACKAGE__->mk_classdata('source_registrations' => {});
13 __PACKAGE__->mk_classdata('storage_type' => '::DBI');
14 __PACKAGE__->mk_classdata('storage');
18 DBIx::Class::Schema - composable schemas
22 package Library::Schema;
23 use base qw/DBIx::Class::Schema/;
25 # load Library::Schema::CD, Library::Schema::Book, Library::Schema::DVD
26 __PACKAGE__->load_classes(qw/CD Book DVD/);
28 package Library::Schema::CD;
29 use base qw/DBIx::Class/;
30 __PACKAGE__->load_components(qw/PK::Auto Core/); # for example
31 __PACKAGE__->table('cd');
33 # Elsewhere in your code:
34 my $schema1 = Library::Schema->connect(
41 my $schema2 = Library::Schema->connect($coderef_returning_dbh);
43 # fetch objects using Library::Schema::DVD
44 my $resultset = $schema1->resultset('DVD')->search( ... );
45 my @dvd_objects = $schema2->resultset('DVD')->search( ... );
49 Creates database classes based on a schema. This is the recommended way to
50 use L<DBIx::Class> and allows you to use more than one concurrent connection
53 NB: If you're used to L<Class::DBI> it's worth reading the L</SYNOPSIS>
54 carefully, as DBIx::Class does things a little differently. Note in
55 particular which module inherits off which.
63 =item Arguments: $moniker, $component_class
67 Registers a class which isa DBIx::Class::ResultSourceProxy. Equivalent to
70 $schema->register_source($moniker, $component_class->result_source_instance);
75 my ($self, $moniker, $to_register) = @_;
76 $self->register_source($moniker => $to_register->result_source_instance);
79 =head2 register_source
83 =item Arguments: $moniker, $result_source
87 Registers the L<DBIx::Class::ResultSource> in the schema with the given
93 my ($self, $moniker, $source) = @_;
94 my %reg = %{$self->source_registrations};
95 $reg{$moniker} = $source;
96 $self->source_registrations(\%reg);
97 $source->schema($self);
98 weaken($source->{schema}) if ref($self);
99 if ($source->result_class) {
100 my %map = %{$self->class_mappings};
101 $map{$source->result_class} = $moniker;
102 $self->class_mappings(\%map);
110 =item Arguments: $moniker
112 =item Return Value: $classname
116 Retrieves the result class name for the given moniker. For example:
118 my $class = $schema->class('CD');
123 my ($self, $moniker) = @_;
124 return $self->source($moniker)->result_class;
131 =item Arguments: $moniker
133 =item Return Value: $result_source
137 my $source = $schema->source('Book');
139 Returns the L<DBIx::Class::ResultSource> object for the registered moniker.
144 my ($self, $moniker) = @_;
145 my $sreg = $self->source_registrations;
146 return $sreg->{$moniker} if exists $sreg->{$moniker};
148 # if we got here, they probably passed a full class name
149 my $mapped = $self->class_mappings->{$moniker};
150 $self->throw_exception("Can't find source for ${moniker}")
151 unless $mapped && exists $sreg->{$mapped};
152 return $sreg->{$mapped};
159 =item Return Value: @source_monikers
163 Returns the source monikers of all source registrations on this schema.
166 my @source_monikers = $schema->sources;
170 sub sources { return keys %{shift->source_registrations}; }
174 my $storage = $schema->storage;
176 Returns the L<DBIx::Class::Storage> object for this Schema.
182 =item Arguments: $moniker
184 =item Return Value: $result_set
188 my $rs = $schema->resultset('DVD');
190 Returns the L<DBIx::Class::ResultSet> object for the registered moniker.
195 my ($self, $moniker) = @_;
196 return $self->source($moniker)->resultset;
203 =item Arguments: @classes?, { $namespace => [ @classes ] }+
207 With no arguments, this method uses L<Module::Find> to find all classes under
208 the schema's namespace. Otherwise, this method loads the classes you specify
209 (using L<use>), and registers them (using L</"register_class">).
211 It is possible to comment out classes with a leading C<#>, but note that perl
212 will think it's a mistake (trying to use a comment in a qw list), so you'll
213 need to add C<no warnings 'qw';> before your load_classes call.
217 My::Schema->load_classes(); # loads My::Schema::CD, My::Schema::Artist,
218 # etc. (anything under the My::Schema namespace)
220 # loads My::Schema::CD, My::Schema::Artist, Other::Namespace::Producer but
221 # not Other::Namespace::LinerNotes nor My::Schema::Track
222 My::Schema->load_classes(qw/ CD Artist #Track /, {
223 Other::Namespace => [qw/ Producer #LinerNotes /],
229 my ($class, @params) = @_;
234 foreach my $param (@params) {
235 if (ref $param eq 'ARRAY') {
236 # filter out commented entries
237 my @modules = grep { $_ !~ /^#/ } @$param;
239 push (@{$comps_for{$class}}, @modules);
241 elsif (ref $param eq 'HASH') {
242 # more than one namespace possible
243 for my $comp ( keys %$param ) {
244 # filter out commented entries
245 my @modules = grep { $_ !~ /^#/ } @{$param->{$comp}};
247 push (@{$comps_for{$comp}}, @modules);
251 # filter out commented entries
252 push (@{$comps_for{$class}}, $param) if $param !~ /^#/;
256 eval "require Module::Find;";
257 $class->throw_exception(
258 "No arguments to load_classes and couldn't load Module::Find ($@)"
260 my @comp = map { substr $_, length "${class}::" }
261 Module::Find::findallmod($class);
262 $comps_for{$class} = \@comp;
267 no warnings qw/redefine/;
268 local *Class::C3::reinitialize = sub { };
269 foreach my $prefix (keys %comps_for) {
270 foreach my $comp (@{$comps_for{$prefix}||[]}) {
271 my $comp_class = "${prefix}::${comp}";
272 { # try to untaint module name. mods where this fails
273 # are left alone so we don't have to change the old behavior
274 no locale; # localized \w doesn't untaint expression
275 if ( $comp_class =~ m/^( (?:\w+::)* \w+ )$/x ) {
279 $class->ensure_class_loaded($comp_class);
280 $comp_class->source_name($comp) unless $comp_class->source_name;
282 push(@to_register, [ $comp_class->source_name, $comp_class ]);
286 Class::C3->reinitialize;
288 foreach my $to (@to_register) {
289 $class->register_class(@$to);
290 # if $class->can('result_source_instance');
294 =head2 compose_connection
298 =item Arguments: $target_namespace, @db_info
300 =item Return Value: $new_schema
304 Calls L<DBIx::Class::Schema/"compose_namespace"> to the target namespace,
305 calls L<DBIx::Class::Schema/connection> with @db_info on the new schema,
306 then injects the L<DBix::Class::ResultSetProxy> component and a
307 resultset_instance classdata entry on all the new classes, in order to support
308 $target_namespaces::$class->search(...) method calls.
310 This is primarily useful when you have a specific need for class method access
311 to a connection. In normal usage it is preferred to call
312 L<DBIx::Class::Schema/connect> and use the resulting schema object to operate
313 on L<DBIx::Class::ResultSet> objects with L<DBIx::Class::Schema/resultset> for
318 sub compose_connection {
319 my ($self, $target, @info) = @_;
320 my $base = 'DBIx::Class::ResultSetProxy';
321 eval "require ${base};";
322 $self->throw_exception
323 ("No arguments to load_classes and couldn't load ${base} ($@)")
326 if ($self eq $target) {
327 # Pathological case, largely caused by the docs on early C::M::DBIC::Plain
328 foreach my $moniker ($self->sources) {
329 my $source = $self->source($moniker);
330 my $class = $source->result_class;
331 $self->inject_base($class, $base);
332 $class->mk_classdata(resultset_instance => $source->resultset);
333 $class->mk_classdata(class_resolver => $self);
335 $self->connection(@info);
339 my $schema = $self->compose_namespace($target, $base);
342 *{"${target}::schema"} = sub { $schema };
345 $schema->connection(@info);
346 foreach my $moniker ($schema->sources) {
347 my $source = $schema->source($moniker);
348 my $class = $source->result_class;
349 #warn "$moniker $class $source ".$source->storage;
350 $class->mk_classdata(result_source_instance => $source);
351 $class->mk_classdata(resultset_instance => $source->resultset);
352 $class->mk_classdata(class_resolver => $schema);
357 =head2 compose_namespace
361 =item Arguments: $target_namespace, $additional_base_class?
363 =item Return Value: $new_schema
367 For each L<DBIx::Class::ResultSource> in the schema, this method creates a
368 class in the target namespace (e.g. $target_namespace::CD,
369 $target_namespace::Artist) that inherits from the corresponding classes
370 attached to the current schema.
372 It also attaches a corresponding L<DBIx::Class::ResultSource> object to the
373 new $schema object. If C<$additional_base_class> is given, the new composed
374 classes will inherit from first the corresponding classe from the current
375 schema then the base class.
377 For example, for a schema with My::Schema::CD and My::Schema::Artist classes,
379 $schema->compose_namespace('My::DB', 'Base::Class');
380 print join (', ', @My::DB::CD::ISA) . "\n";
381 print join (', ', @My::DB::Artist::ISA) ."\n";
383 will produce the output
385 My::Schema::CD, Base::Class
386 My::Schema::Artist, Base::Class
390 sub compose_namespace {
391 my ($self, $target, $base) = @_;
392 my $schema = $self->clone;
394 no warnings qw/redefine/;
395 local *Class::C3::reinitialize = sub { };
396 foreach my $moniker ($schema->sources) {
397 my $source = $schema->source($moniker);
398 my $target_class = "${target}::${moniker}";
400 $target_class => $source->result_class, ($base ? $base : ())
402 $source->result_class($target_class);
403 $target_class->result_source_instance($source)
404 if $target_class->can('result_source_instance');
407 Class::C3->reinitialize();
410 foreach my $meth (qw/class source resultset/) {
411 *{"${target}::${meth}"} =
412 sub { shift->schema->$meth(@_) };
418 =head2 setup_connection_class
422 =item Arguments: $target, @info
426 Sets up a database connection class to inject between the schema and the
427 subclasses that the schema creates.
431 sub setup_connection_class {
432 my ($class, $target, @info) = @_;
433 $class->inject_base($target => 'DBIx::Class::DB');
434 #$target->load_components('DB');
435 $target->connection(@info);
442 =item Arguments: $storage_type
444 =item Return Value: $storage_type
448 Set the storage class that will be instantiated when L</connect> is called.
449 If the classname starts with C<::>, the prefix C<DBIx::Class::Storage> is
450 assumed by L</connect>. Defaults to C<::DBI>,
451 which is L<DBIx::Class::Storage::DBI>.
453 You want to use this to hardcoded subclasses of L<DBIx::Class::Storage::DBI>
454 in cases where the appropriate subclass is not autodetected, such as when
455 dealing with MSSQL via L<DBD::Sybase>, in which case you'd set it to
456 C<::DBI::Sybase::MSSQL>.
462 =item Arguments: @args
464 =item Return Value: $new_schema
468 Instantiates a new Storage object of type
469 L<DBIx::Class::Schema/"storage_type"> and passes the arguments to
470 $storage->connect_info. Sets the connection in-place on the schema. See
471 L<DBIx::Class::Storage::DBI/"connect_info"> for more information.
476 my ($self, @info) = @_;
477 return $self if !@info && $self->storage;
478 my $storage_class = $self->storage_type;
479 $storage_class = 'DBIx::Class::Storage'.$storage_class
480 if $storage_class =~ m/^::/;
481 eval "require ${storage_class};";
482 $self->throw_exception(
483 "No arguments to load_classes and couldn't load ${storage_class} ($@)"
485 my $storage = $storage_class->new;
486 $storage->connect_info(\@info);
487 $self->storage($storage);
495 =item Arguments: @info
497 =item Return Value: $new_schema
501 This is a convenience method. It is equivalent to calling
502 $schema->clone->connection(@info). See L</connection> and L</clone> for more
507 sub connect { shift->clone->connection(@_) }
511 Begins a transaction (does nothing if AutoCommit is off). Equivalent to
512 calling $schema->storage->txn_begin. See
513 L<DBIx::Class::Storage::DBI/"txn_begin"> for more information.
517 sub txn_begin { shift->storage->txn_begin }
521 Commits the current transaction. Equivalent to calling
522 $schema->storage->txn_commit. See L<DBIx::Class::Storage::DBI/"txn_commit">
523 for more information.
527 sub txn_commit { shift->storage->txn_commit }
531 Rolls back the current transaction. Equivalent to calling
532 $schema->storage->txn_rollback. See
533 L<DBIx::Class::Storage::DBI/"txn_rollback"> for more information.
537 sub txn_rollback { shift->storage->txn_rollback }
543 =item Arguments: C<$coderef>, @coderef_args?
545 =item Return Value: The return value of $coderef
549 Executes C<$coderef> with (optional) arguments C<@coderef_args> atomically,
550 returning its result (if any). If an exception is caught, a rollback is issued
551 and the exception is rethrown. If the rollback fails, (i.e. throws an
552 exception) an exception is thrown that includes a "Rollback failed" message.
556 my $author_rs = $schema->resultset('Author')->find(1);
557 my @titles = qw/Night Day It/;
560 # If any one of these fails, the entire transaction fails
561 $author_rs->create_related('books', {
563 }) foreach (@titles);
565 return $author->books;
570 $rs = $schema->txn_do($coderef);
573 if ($@) { # Transaction failed
574 die "something terrible has happened!" #
575 if ($@ =~ /Rollback failed/); # Rollback failed
577 deal_with_failed_transaction();
580 In a nested transaction (calling txn_do() from within a txn_do() coderef) only
581 the outermost transaction will issue a L<DBIx::Class::Schema/"txn_commit"> on
582 the Schema's storage, and txn_do() can be called in void, scalar and list
583 context and it will behave as expected.
588 my ($self, $coderef, @args) = @_;
590 $self->storage or $self->throw_exception
591 ('txn_do called on $schema without storage');
592 ref $coderef eq 'CODE' or $self->throw_exception
593 ('$coderef must be a CODE reference');
595 my (@return_values, $return_value);
597 $self->txn_begin; # If this throws an exception, no rollback is needed
599 my $wantarray = wantarray; # Need to save this since the context
600 # inside the eval{} block is independent
601 # of the context that called txn_do()
604 # Need to differentiate between scalar/list context to allow for
605 # returning a list in scalar context to get the size of the list
608 @return_values = $coderef->(@args);
609 } elsif (defined $wantarray) {
611 $return_value = $coderef->(@args);
627 my $rollback_error = $@;
628 my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
629 $self->throw_exception($error) # propagate nested rollback
630 if $rollback_error =~ /$exception_class/;
632 $self->throw_exception(
633 "Transaction aborted: $error. Rollback failed: ${rollback_error}"
636 $self->throw_exception($error); # txn failed but rollback succeeded
640 return $wantarray ? @return_values : $return_value;
647 =item Return Value: $new_schema
651 Clones the schema and its associated result_source objects and returns the
658 my $clone = { (ref $self ? %$self : ()) };
659 bless $clone, (ref $self || $self);
661 foreach my $moniker ($self->sources) {
662 my $source = $self->source($moniker);
663 my $new = $source->new($source);
664 $clone->register_source($moniker => $new);
673 =item Arguments: $source_name, \@data;
677 Pass this method a resultsource name, and an arrayref of
678 arrayrefs. The arrayrefs should contain a list of column names,
679 followed by one or many sets of matching data for the given columns.
681 Each set of data is inserted into the database using
682 L<DBIx::Class::ResultSet/create>, and a arrayref of the resulting row
687 $schema->populate('Artist', [
688 [ qw/artistid name/ ],
689 [ 1, 'Popular Band' ],
697 my ($self, $name, $data) = @_;
698 my $rs = $self->resultset($name);
699 my @names = @{shift(@$data)};
701 foreach my $item (@$data) {
703 @create{@names} = @$item;
704 push(@created, $rs->create(\%create));
709 =head2 throw_exception
713 =item Arguments: $message
717 Throws an exception. Defaults to using L<Carp::Clan> to report errors from
722 sub throw_exception {
727 =head2 deploy (EXPERIMENTAL)
731 =item Arguments: $sqlt_args, $dir
735 Attempts to deploy the schema to the current storage using L<SQL::Translator>.
737 Note that this feature is currently EXPERIMENTAL and may not work correctly
738 across all databases, or fully handle complex relationships.
740 See L<SQL::Translator/METHODS> for a list of values for C<$sqlt_args>. The most
741 common value for this would be C<< { add_drop_table => 1, } >> to have the SQL
742 produced include a DROP TABLE statement for each table created.
747 my ($self, $sqltargs, $dir) = @_;
748 $self->throw_exception("Can't deploy without storage") unless $self->storage;
749 $self->storage->deploy($self, undef, $sqltargs, $dir);
752 =head2 create_ddl_dir (EXPERIMENTAL)
756 =item Arguments: \@databases, $version, $directory, $sqlt_args
760 Creates an SQL file based on the Schema, for each of the specified
761 database types, in the given directory.
763 Note that this feature is currently EXPERIMENTAL and may not work correctly
764 across all databases, or fully handle complex relationships.
771 $self->throw_exception("Can't create_ddl_dir without storage") unless $self->storage;
772 $self->storage->create_ddl_dir($self, @_);
775 =head2 ddl_filename (EXPERIMENTAL)
777 my $filename = $table->ddl_filename($type, $dir, $version)
779 Creates a filename for a SQL file based on the table class name. Not
780 intended for direct end user use.
785 my ($self, $type, $dir, $version) = @_;
787 my $filename = ref($self);
788 $filename =~ s/::/-/g;
789 $filename = "$dir$filename-$version-$type.sql";
798 Matt S. Trout <mst@shadowcatsystems.co.uk>
802 You may distribute this code under the same terms as Perl itself.