NAME

DBIx::Class::Schema - composable schemas

SYNOPSIS

package Library::Schema;
use base qw/DBIx::Class::Schema/;

# load all Result classes in Library/Schema/Result/
__PACKAGE__->load_namespaces();

package Library::Schema::Result::CD;
use base qw/DBIx::Class/;
__PACKAGE__->load_components(qw/Core/); # for example
__PACKAGE__->table('cd');

# Elsewhere in your code:
my $schema1 = Library::Schema->connect(
  $dsn,
  $user,
  $password,
  { AutoCommit => 0 },
);

my $schema2 = Library::Schema->connect($coderef_returning_dbh);

# fetch objects using Library::Schema::Result::DVD
my $resultset = $schema1->resultset('DVD')->search( ... );
my @dvd_objects = $schema2->resultset('DVD')->search( ... );

DESCRIPTION

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

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

SETUP METHODS

load_namespaces

Arguments: %options?
 __PACKAGE__->load_namespaces();

 __PACKAGE__->load_namespaces(
  result_namespace => 'Res',
  resultset_namespace => 'RSet',
  default_resultset_class => '+MyDB::Othernamespace::RSet',
);

With no arguments, this method uses Module::Find to load all your Result classes from a sub-namespace Result under your Schema class' namespace. Eg. With a Schema of MyDB::Schema all files in MyDB::Schema::Result are assumed to be Result classes.

It also finds all ResultSet classes in the namespace ResultSet and loads them into the appropriate Result classes using for you. The matching is done by assuming the package name of the ResultSet class is the same as that of the Result class.

You will be warned if ResultSet classes are discovered for which there are no matching Result classes like this:

load_namespaces found ResultSet class $classname with no corresponding Result class

If a Result class is found to already have a ResultSet class set using "resultset_class" to some other class, you will be warned like this:

We found ResultSet class '$rs_class' for '$result', but it seems 
that you had already set '$result' to use '$rs_set' instead

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.

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 +.

Examples:

# load My::Schema::Result::CD, My::Schema::Result::Artist,
#    My::Schema::ResultSet::CD, etc...
My::Schema->load_namespaces;

# 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
My::Schema->load_namespaces(
  result_namespace => 'Res',
  resultset_namespace => 'RSets',
  default_resultset_class => 'RSetBase',
);

# Put things in other namespaces
My::Schema->load_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->load_namespaces(
  # 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' ],
);

load_classes

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

Alternative method to "load_namespaces" which you should look at using if you can.

With no arguments, this method uses Module::Find 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.

If any classes found do not appear to be Result class files, you will get the following warning:

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.

Example:

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 /],
});

storage_type

Arguments: $storage_type|{$storage_type, \%args}
Return value: $storage_type|{$storage_type, \%args}
Default value: DBIx::Class::Storage::DBI

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".

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

If your storage type requires instantiation arguments, those are defined as a second argument in the form of a hashref and the entire value needs to be wrapped into an arrayref or a hashref. We support both types of refs here in order to play nice with your Config::[class] or your choice. See DBIx::Class::Storage::DBI::Replicated for an example of this.

exception_action

Arguments: $code_reference
Return value: $code_reference
Default value: None

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 "throw" in DBIx::Class::Exception.

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.

Example:

package My::Schema;
use base qw/DBIx::Class::Schema/;
use My::ExceptionClass;
__PACKAGE__->exception_action(sub { My::ExceptionClass->throw(@_) });
__PACKAGE__->load_classes;

# 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 });

stacktrace

Arguments: boolean

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

sqlt_deploy_hook

Arguments: $sqlt_schema

An optional sub which you can declare in your own Schema class that will get passed the SQL::Translator::Schema object when you deploy the schema via "create_ddl_dir" or "deploy".

For an example of what you can do with this, see "Adding Indexes And Functions To Your SQL" in DBIx::Class::Manual::Cookbook.

Note that sqlt_deploy_hook is called by "deployment_statements", which in turn is called before "deploy". Therefore the hook can be used only to manipulate the SQL::Translator::Schema object before it is turned into SQL fed to the database. If you want to execute post-deploy statements which can not be generated by SQL::Translator, the currently suggested method is to overload "deploy" and use dbh_do.

METHODS

connect

Arguments: @connectinfo
Return Value: $new_schema

Creates and returns a new Schema object. The connection info set on it is used to create a new instance of the storage backend and set it on the Schema object.

See "connect_info" in DBIx::Class::Storage::DBI for DBI-specific syntax on the @connectinfo argument, or DBIx::Class::Storage in general.

Note that connect_info expects an arrayref of arguments, but connect does not. connect wraps it's arguments in an arrayref before passing them to connect_info.

Overloading

connect is a convenience method. It is equivalent to calling $schema->clone->connection(@connectinfo). To write your own overloaded version, overload "connection" instead.

resultset

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

Returns the DBIx::Class::ResultSet object for the registered source name.

sources

Return Value: @source_names
my @source_names = $schema->sources;

Lists names of all the sources registered on this Schema object.

source

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

Returns the DBIx::Class::ResultSource object for the registered source name.

class

Arguments: $source_name
Return Value: $classname
my $class = $schema->class('CD');

Retrieves the Result class name for the given source name.

txn_do

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 DBIx::Class::Storage for more information.

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

WARNING: If you are connected with AutoCommit = 0> the transaction is considered nested, and you will still need to call "txn_commit" to write your changes when appropriate. You will also want to connect with auto_savepoint = 1> to get partial rollback to work, if the storage driver for your database supports it.

Connecting with AutoCommit = 1> is recommended.

txn_scope_guard

Runs txn_scope_guard on the schema's storage. See "txn_scope_guard" in DBIx::Class::Storage.

txn_begin

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

txn_commit

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

txn_rollback

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

storage

my $storage = $schema->storage;

Returns the DBIx::Class::Storage object for this Schema. Grab this if you want to turn on SQL statement debugging at runtime, or set the quote character. For the default storage, the documentation can be found in DBIx::Class::Storage::DBI.

populate

Arguments: $source_name, \@data;
Return value: \@$objects | nothing

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 DBIx::Class::Storage::DBI 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 DBIx::Class::ResultSet, and a arrayref of the resulting row objects is returned.

i.e.,

$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 DBIx::Class::UUIDColumns to populate your primary keys you MUST use wantarray context if you want the PKs automatically created.

connection

Arguments: @args
Return Value: $new_schema

Similar to "connect" except sets the storage object and connection data in-place on the Schema class. You should probably be calling "connect" to get a proper Schema object instead.

Overloading

Overload connection to change the behaviour of connect.

compose_namespace

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

For each DBIx::Class::ResultSource 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 DBIx::Class::ResultSource 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

svp_begin

Creates a new savepoint (does nothing outside a transaction). Equivalent to calling $schema->storage->svp_begin. See "svp_begin" in DBIx::Class::Storage::DBI for more information.

svp_release

Releases a savepoint (does nothing outside a transaction). Equivalent to calling $schema->storage->svp_release. See "svp_release" in DBIx::Class::Storage::DBI for more information.

svp_rollback

Rollback to a savepoint (does nothing outside a transaction). Equivalent to calling $schema->storage->svp_rollback. See "svp_rollback" in DBIx::Class::Storage::DBI for more information.

clone

Return Value: $new_schema

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

throw_exception

Arguments: $message

Throws an exception. Defaults to using Carp::Clan 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.

deploy

Arguments: $sqlt_args, $dir

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

See "METHODS" in SQL::Translator 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. For quoting purposes use producer_options value with quote_table_names and quote_field_names.

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. Furthermore, you can use the add_fk_index parser parameter to prevent the parser from creating an index for each FK.

deployment_statements

Arguments: $rdbms_type, $sqlt_args, $dir
Return value: $listofstatements

A convenient shortcut to storage->deployment_statements(). Returns the SQL statements used by "deploy" and "deploy" in DBIx::Class::Schema::Storage. $rdbms_type provides the (optional) SQLT (not DBI) database driver name for which the SQL statements are produced. If not supplied, the type is determined by interrogating the current connection. The other two arguments are identical to those of "deploy".

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".

See "deploy" in DBIx::Class::Schema for details of $sqlt_args.

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

databases - ['MySQL', 'SQLite', 'PostgreSQL']
version - $schema->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

Arguments: $database-type, $version, $directory, $preversion
Return value: $normalised_filename
my $filename = $table->ddl_filename($type, $version, $dir, $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.

thaw

Provided as the recommended way of thawing schema objects. You can call Storable::thaw directly if you wish, but the thawed objects will not have a reference to any schema, so are rather useless

freeze

This doesn't actualy do anything more than call "freeze" in Storable, it is just provided here for symetry.

dclone

Recommeneded way of dcloning objects. This is needed to properly maintain references to the schema object (which itself is not cloned.)

schema_version

Returns the current schema class' $VERSION in a normalised way.

register_class

Arguments: $moniker, $component_class

This method is called by "load_namespaces" and "load_classes" to install the found classes into your Schema. You should be using those instead of this one.

You will only need this method if you have your Result classes in files which are not named after the packages (or all in the same file). You may also need it to register classes at runtime.

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

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

register_source

Arguments: $moniker, $result_source

This method is called by "register_class".

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

register_extra_source

Arguments: $moniker, $result_source

As "register_source" but should be used if the result class already has a source and you want to register an extra one.

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.

AUTHORS

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

LICENSE

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