DBIx::Class::Schema - composable schemas


DBIx::Class::Schema - composable schemas


  package Library::Schema;
  use base qw/DBIx::Class::Schema/;
  # load Library::Schema::CD, Library::Schema::Book, Library::Schema::DVD
  __PACKAGE__->load_classes(qw/CD Book DVD/);
  package Library::Schema::CD;
  use base qw/DBIx::Class/;
  __PACKAGE__->load_components(qw/PK::Auto Core/); # for example
  # Elsewhere in your code:
  my $schema1 = Library::Schema->connect(
    { AutoCommit => 0 },
  my $schema2 = Library::Schema->connect($coderef_returning_dbh);
  # fetch objects using Library::Schema::DVD
  my $resultset = $schema1->resultset('DVD')->search( ... );
  my @dvd_objects = $schema2->resultset('DVD')->search( ... );


Creates database classes based on a schema. This is the recommended way to use the DBIx::Class manpage and allows you to use more than one concurrent connection with your classes.

NB: If you're used to the Class::DBI manpage it's worth reading the SYNOPSIS carefully, as DBIx::Class does things a little differently. Note in particular which module inherits off which.



Arguments: $moniker, $component_class

Registers a class which isa DBIx::Class::ResultSourceProxy. Equivalent to calling:

  $schema->register_source($moniker, $component_class->result_source_instance);


Arguments: $moniker, $result_source

Registers the the DBIx::Class::ResultSource manpage in the schema with the given moniker.


Arguments: $moniker
Return Value: $classname

Retrieves the result class name for the given moniker. For example:

  my $class = $schema->class('CD');


Arguments: $moniker
Return Value: $result_source
  my $source = $schema->source('Book');

Returns the the DBIx::Class::ResultSource manpage object for the registered moniker.


Return Value: @source_monikers

Returns the source monikers of all source registrations on this schema. For example:

  my @source_monikers = $schema->sources;


  my $storage = $schema->storage;

Returns the the DBIx::Class::Storage manpage object for this Schema.


Arguments: $moniker
Return Value: $result_set
  my $rs = $schema->resultset('DVD');

Returns the the DBIx::Class::ResultSet manpage object for the registered moniker.


Arguments: @classes?, { $namespace => [ @classes ] }+

With no arguments, this method uses the Module::Find manpage to find all classes under the schema's namespace. Otherwise, this method loads the classes you specify (using use), and registers them (using register_class).

It is possible to comment out classes with a leading #, but note that perl will think it's a mistake (trying to use a comment in a qw list), so you'll need to add no warnings 'qw'; before your load_classes call.


  My::Schema->load_classes(); # loads My::Schema::CD, My::Schema::Artist,
                              # etc. (anything under the My::Schema namespace)
  # loads My::Schema::CD, My::Schema::Artist, Other::Namespace::Producer but
  # not Other::Namespace::LinerNotes nor My::Schema::Track
  My::Schema->load_classes(qw/ CD Artist #Track /, {
    Other::Namespace => [qw/ Producer #LinerNotes /],


Arguments: %options?

This is an alternative to load_classes above which assumes an alternative layout for automatic class loading. It assumes that all result classes are underneath a sub-namespace of the schema called Result, any corresponding ResultSet classes are underneath a sub-namespace of the schema called ResultSet.

Both of the sub-namespaces are configurable if you don't like the defaults, via the options result_namespace and resultset_namespace.

If (and only if) you specify the option default_resultset_class, any found Result classes for which we do not find a corresponding ResultSet class will have their resultset_class set to default_resultset_class.

load_namespaces takes care of calling resultset_class for you where neccessary if you didn't do it for yourself.

All of the namespace and classname options to this method are relative to the schema classname by default. To specify a fully-qualified name, prefix it with a literal +.


  # load My::Schema::Result::CD, My::Schema::Result::Artist,
  #    My::Schema::ResultSet::CD, etc...
  # Override everything to use ugly names.
  # In this example, if there is a My::Schema::Res::Foo, but no matching
  #   My::Schema::RSets::Foo, then Foo will have its
  #   resultset_class set to My::Schema::RSetBase
    result_namespace => 'Res',
    resultset_namespace => 'RSets',
    default_resultset_class => 'RSetBase',
  # Put things in other namespaces
    result_namespace => '+Some::Place::Results',
    resultset_namespace => '+Another::Place::RSets',

If you'd like to use multiple namespaces of each type, simply use an arrayref of namespaces for that option. In the case that the same result (or resultset) class exists in multiple namespaces, the latter entries in your list of namespaces will override earlier ones.

    # My::Schema::Results_C::Foo takes precedence over My::Schema::Results_B::Foo :
    result_namespace => [ 'Results_A', 'Results_B', 'Results_C' ],
    resultset_namespace => [ '+Some::Place::RSets', 'RSets' ],

compose_connection (DEPRECATED)

Arguments: $target_namespace, @db_info
Return Value: $new_schema

DEPRECATED. You probably wanted compose_namespace.

Actually, you probably just wanted to call connect.

Calls compose_namespace in the DBIx::Class::Schema manpage to the target namespace, calls connection in the DBIx::Class::Schema manpage with @db_info on the new schema, then injects the the DBix::Class::ResultSetProxy manpage component and a resultset_instance classdata entry on all the new classes, in order to support $target_namespaces::$class->search(...) method calls.

This is primarily useful when you have a specific need for class method access to a connection. In normal usage it is preferred to call connect in the DBIx::Class::Schema manpage and use the resulting schema object to operate on the DBIx::Class::ResultSet manpage objects with resultset in the DBIx::Class::Schema manpage for more information.


Arguments: $target_namespace, $additional_base_class?
Return Value: $new_schema

For each the DBIx::Class::ResultSource manpage in the schema, this method creates a class in the target namespace (e.g. $target_namespace::CD, $target_namespace::Artist) that inherits from the corresponding classes attached to the current schema.

It also attaches a corresponding the DBIx::Class::ResultSource manpage object to the new $schema object. If $additional_base_class is given, the new composed classes will inherit from first the corresponding classe from the current schema then the base class.

For example, for a schema with My::Schema::CD and My::Schema::Artist classes,

  $schema->compose_namespace('My::DB', 'Base::Class');
  print join (', ', @My::DB::CD::ISA) . "\n";
  print join (', ', @My::DB::Artist::ISA) ."\n";

will produce the output

  My::Schema::CD, Base::Class
  My::Schema::Artist, Base::Class


Arguments: $target, @info

Sets up a database connection class to inject between the schema and the subclasses that the schema creates.


Arguments: $storage_type
Return Value: $storage_type

Set the storage class that will be instantiated when connect is called. If the classname starts with ::, the prefix DBIx::Class::Storage is assumed by connect. Defaults to ::DBI, which is the DBIx::Class::Storage::DBI manpage.

You want to use this to hardcoded subclasses of the DBIx::Class::Storage::DBI manpage in cases where the appropriate subclass is not autodetected, such as when dealing with MSSQL via the DBD::Sybase manpage, in which case you'd set it to ::DBI::Sybase::MSSQL.


Arguments: @args
Return Value: $new_schema

Instantiates a new Storage object of type storage_type in the DBIx::Class::Schema manpage and passes the arguments to $storage->connect_info. Sets the connection in-place on the schema.

See connect_info in the DBIx::Class::Storage::DBI manpage for DBI-specific syntax, or the DBIx::Class::Storage manpage in general.


Arguments: @info
Return Value: $new_schema

This is a convenience method. It is equivalent to calling $schema->clone->connection(@info). See connection and clone for more information.


Arguments: $coderef, @coderef_args?
Return Value: The return value of $coderef

Executes $coderef with (optional) arguments @coderef_args atomically, returning its result (if any). Equivalent to calling $schema->storage->txn_do. See txn_do in the DBIx::Class::Storage manpage for more information.

This interface is preferred over using the individual methods txn_begin, txn_commit, and txn_rollback below.


Begins a transaction (does nothing if AutoCommit is off). Equivalent to calling $schema->storage->txn_begin. See txn_begin in the DBIx::Class::Storage::DBI manpage for more information.


Commits the current transaction. Equivalent to calling $schema->storage->txn_commit. See txn_commit in the DBIx::Class::Storage::DBI manpage for more information.


Rolls back the current transaction. Equivalent to calling $schema->storage->txn_rollback. See txn_rollback in the DBIx::Class::Storage::DBI manpage for more information.


Return Value: $new_schema

Clones the schema and its associated result_source objects and returns the copy.


Arguments: $source_name, \@data;

Pass this method a resultsource name, and an arrayref of arrayrefs. The arrayrefs should contain a list of column names, followed by one or many sets of matching data for the given columns.

In void context, insert_bulk in the DBIx::Class::Storage::DBI manpage is used to insert the data, as this is a fast method. However, insert_bulk currently assumes that your datasets all contain the same type of values, using scalar references in a column in one row, and not in another will probably not work.

Otherwise, each set of data is inserted into the database using create in the DBIx::Class::ResultSet manpage, and a arrayref of the resulting row objects is returned.


  $schema->populate('Artist', [
    [ qw/artistid name/ ],
    [ 1, 'Popular Band' ],
    [ 2, 'Indie Band' ],
Since wantarray context is basically the same as looping over $rs->create(...) 
you won't see any performance benefits and in this case the method is more for
convenience. Void context sends the column information directly to storage
using <DBI>s bulk insert method. So the performance will be much better for 
storages that support this method.

Because of this difference in the way void context inserts rows into your database you need to note how this will effect any loaded components that override or augment insert. For example if you are using a component such as the DBIx::Class::UUIDColumns manpage to populate your primary keys you MUST use wantarray context if you want the PKs automatically created.


Arguments: $code_reference

If exception_action is set for this class/object, throw_exception will prefer to call this code reference with the exception as an argument, rather than its normal croak or confess action.

Your subroutine should probably just wrap the error in the exception object/class of your choosing and rethrow. If, against all sage advice, you'd like your exception_action to suppress a particular exception completely, simply have it return true.


   package My::Schema;
   use base qw/DBIx::Class::Schema/;
   use My::ExceptionClass;
   __PACKAGE__->exception_action(sub { My::ExceptionClass->throw(@_) });
   # or:
   my $schema_obj = My::Schema->connect( .... );
   $schema_obj->exception_action(sub { My::ExceptionClass->throw(@_) });
   # suppress all exceptions, like a moron:
   $schema_obj->exception_action(sub { 1 });


Arguments: boolean

Whether throw_exception should include stack trace information. Defaults to false normally, but defaults to true if $ENV{DBIC_TRACE} is true.


Arguments: $message

Throws an exception. Defaults to using the Carp::Clan manpage to report errors from user's perspective. See exception_action for details on overriding this method's behavior. If stacktrace is turned on, throw_exception's default behavior will provide a detailed stack trace.


Arguments: $sqlt_args, $dir

Attempts to deploy the schema to the current storage using the SQL::Translator manpage.

See METHODS in the SQL::Translator manpage for a list of values for $sqlt_args. The most common value for this would be { add_drop_table => 1, } to have the SQL produced include a DROP TABLE statement for each table created.

Additionally, the DBIx::Class parser accepts a sources parameter as a hash ref or an array ref, containing a list of source to deploy. If present, then only the sources listed will get deployed.

create_ddl_dir (EXPERIMENTAL)

Arguments: \@databases, $version, $directory, $preversion, $sqlt_args

Creates an SQL file based on the Schema, for each of the specified database types, in the given directory. Given a previous version number, this will also create a file containing the ALTER TABLE statements to transform the previous schema into the current one. Note that these statements may contain DROP TABLE or DROP COLUMN statements that can potentially destroy data.

The file names are created using the ddl_filename method below, please override this method in your schema if you would like a different file name format. For the ALTER file, the same format is used, replacing $version in the name with ``$preversion-$version''.

If no arguments are passed, then the following default values are used:

databases - ['MySQL', 'SQLite', 'PostgreSQL']
version - $schema->VERSION
directory - './'
preversion - <none>

Note that this feature is currently EXPERIMENTAL and may not work correctly across all databases, or fully handle complex relationships.

WARNING: Please check all SQL files created, before applying them.

ddl_filename (EXPERIMENTAL)

Arguments: $directory, $database-type, $version, $preversion
  my $filename = $table->ddl_filename($type, $dir, $version, $preversion)

This method is called by create_ddl_dir to compose a file name out of the supplied directory, database type and version number. The default file name format is: $dir$schema-$version-$type.sql.

You may override this method in your schema if you wish to use a different format.


Matt S. Trout <mst@shadowcatsystems.co.uk>


You may distribute this code under the same terms as Perl itself.

 DBIx::Class::Schema - composable schemas