Matt S Trout > DBIx-Class-0.08100 > DBIx::Class::Storage::DBI

Download:
DBIx-Class-0.08100.tar.gz

Dependencies

Annotate this POD

CPAN RT

New  12
Open  18
Stalled  11
View/Report Bugs
Source   Latest Release: DBIx-Class-0.082810

NAME ^

DBIx::Class::Storage::DBI - DBI storage handler

SYNOPSIS ^

  my $schema = MySchema->connect('dbi:SQLite:my.db');

  $schema->storage->debug(1);
  $schema->dbh_do("DROP TABLE authors");

  $schema->resultset('Book')->search({
     written_on => $schema->storage->datetime_parser(DateTime->now)
  });

DESCRIPTION ^

This class represents the connection to an RDBMS via DBI. See DBIx::Class::Storage for general information. This pod only documents DBI-specific methods and behaviors.

METHODS ^

connect_info

This method is normally called by "connection" in DBIx::Class::Schema, which encapsulates its argument list in an arrayref before passing them here.

The argument list may contain:

Please note that the DBI docs recommend that you always explicitly set AutoCommit to either 0 or 1. DBIx::Class further recommends that it be set to 1, and that you perform transactions via our "txn_do" in DBIx::Class::Schema method. DBIx::Class will set it to 1 if you do not do explicitly set it to zero. This is the default for most DBDs. See "DBIx::Class and AutoCommit" for details.

DBIx::Class specific connection attributes

In addition to the standard DBI connection attributes, DBIx::Class recognizes the following connection options. These options can be mixed in with your other DBI connection attributes, or placed in a seperate hashref (\%extra_attributes) as shown above.

Every time connect_info is invoked, any previous settings for these options will be cleared before setting the new ones, regardless of whether any options are specified in the new connect_info.

on_connect_do

Specifies things to do immediately after connecting or re-connecting to the database. Its value may contain:

an array reference

This contains SQL statements to execute in order. Each element contains a string or a code reference that returns a string.

a code reference

This contains some code to execute. Unlike code references within an array reference, its return value is ignored.

on_disconnect_do

Takes arguments in the same form as "on_connect_do" and executes them immediately before disconnecting from the database.

Note, this only runs if you explicitly call "disconnect" on the storage object.

disable_sth_caching

If set to a true value, this option will disable the caching of statement handles via "prepare_cached" in DBI.

limit_dialect

Sets the limit dialect. This is useful for JDBC-bridge among others where the remote SQL-dialect cannot be determined by the name of the driver alone. See also SQL::Abstract::Limit.

quote_char

Specifies what characters to use to quote table and column names. If you use this you will want to specify "name_sep" as well.

quote_char expects either a single character, in which case is it is placed on either side of the table/column name, or an arrayref of length 2 in which case the table/column name is placed between the elements.

For example under MySQL you should use quote_char => '`', and for SQL Server you should use quote_char => [qw/[ ]/].

name_sep

This only needs to be used in conjunction with quote_char, and is used to specify the charecter that seperates elements (schemas, tables, columns) from each other. In most cases this is simply a ..

The consequences of not supplying this value is that SQL::Abstract will assume DBIx::Class' uses of aliases to be complete column names. The output will look like "me.name" when it should actually be "me"."name".

unsafe

This Storage driver normally installs its own HandleError, sets RaiseError and ShowErrorStatement on, and sets PrintError off on all database handles, including those supplied by a coderef. It does this so that it can have consistent and useful error behavior.

If you set this option to a true value, Storage will not do its usual modifications to the database handle's attributes, and instead relies on the settings in your connect_info DBI options (or the values you set in your connection coderef, in the case that you are connecting via coderef).

Note that your custom settings can cause Storage to malfunction, especially if you set a HandleError handler that suppresses exceptions and/or disable RaiseError.

auto_savepoint

If this option is true, DBIx::Class will use savepoints when nesting transactions, making it possible to recover from failure in the inner transaction without having to abort all outer transactions.

cursor_class

Use this argument to supply a cursor class other than the default DBIx::Class::Storage::DBI::Cursor.

Some real-life examples of arguments to "connect_info" and "connect" in DBIx::Class::Schema

  # Simple SQLite connection
  ->connect_info([ 'dbi:SQLite:./foo.db' ]);

  # Connect via subref
  ->connect_info([ sub { DBI->connect(...) } ]);

  # A bit more complicated
  ->connect_info(
    [
      'dbi:Pg:dbname=foo',
      'postgres',
      'my_pg_password',
      { AutoCommit => 1 },
      { quote_char => q{"}, name_sep => q{.} },
    ]
  );

  # Equivalent to the previous example
  ->connect_info(
    [
      'dbi:Pg:dbname=foo',
      'postgres',
      'my_pg_password',
      { AutoCommit => 1, quote_char => q{"}, name_sep => q{.} },
    ]
  );

  # Same, but with hashref as argument
  # See parse_connect_info for explanation
  ->connect_info(
    [{
      dsn         => 'dbi:Pg:dbname=foo',
      user        => 'postgres',
      password    => 'my_pg_password',
      AutoCommit  => 1,
      quote_char  => q{"},
      name_sep    => q{.},
    }]
  );

  # Subref + DBIx::Class-specific connection options
  ->connect_info(
    [
      sub { DBI->connect(...) },
      {
          quote_char => q{`},
          name_sep => q{@},
          on_connect_do => ['SET search_path TO myschema,otherschema,public'],
          disable_sth_caching => 1,
      },
    ]
  );

on_connect_do

This method is deprecated in favour of setting via "connect_info".

dbh_do

Arguments: ($subref | $method_name), @extra_coderef_args?

Execute the given $subref or $method_name using the new exception-based connection management.

The first two arguments will be the storage object that dbh_do was called on and a database handle to use. Any additional arguments will be passed verbatim to the called subref as arguments 2 and onwards.

Using this (instead of $self->_dbh or $self->dbh) ensures correct exception handling and reconnection (or failover in future subclasses).

Your subref should have no side-effects outside of the database, as there is the potential for your subref to be partially double-executed if the database connection was stale/dysfunctional.

Example:

  my @stuff = $schema->storage->dbh_do(
    sub {
      my ($storage, $dbh, @cols) = @_;
      my $cols = join(q{, }, @cols);
      $dbh->selectrow_array("SELECT $cols FROM foo");
    },
    @column_list
  );

disconnect

Our disconnect method also performs a rollback first if the database is not in AutoCommit mode.

with_deferred_fk_checks

Arguments: $coderef
Return Value: The return value of $coderef

Storage specific method to run the code ref with FK checks deferred or in MySQL's case disabled entirely.

dbh

Returns the dbh - a data base handle of class DBI.

select

Arguments: $ident, $select, $condition, $attrs

Handle a SQL select statement.

sth

Arguments: $sql

Returns a DBI sth (statement handle) for the supplied SQL.

last_insert_id

Return the row id of the last insert.

sqlt_type

Returns the database driver name.

bind_attribute_by_data_type

Given a datatype from column info, returns a database specific bind attribute for $dbh->bind_param($val,$attribute) or nothing if we will let the database planner just handle it.

Generally only needed for special case column types, like bytea in postgres.

create_ddl_dir

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

Creates a SQL file based on the Schema, for each of the specified database types, in the given directory.

By default, \%sqlt_args will have

 { add_drop_table => 1, ignore_constraint_names => 1, ignore_index_names => 1 }

merged with the hash passed in. To disable any of those features, pass in a hashref like the following

 { ignore_constraint_names => 0, # ... other options }

deployment_statements

Arguments: $schema, $type, $version, $directory, $sqlt_args

Returns the statements used by "deploy" and "deploy" in DBIx::Class::Schema. The database driver name is given by $type, though the value from "sqlt_type" is used if it is not specified.

$directory is used to return statements from files in a previously created "create_ddl_dir" directory and is optional. The filenames are constructed from "ddl_filename" in DBIx::Class::Schema, the schema name and the $version.

If no $directory is specified then the statements are constructed on the fly using SQL::Translator and $version is ignored.

See "METHODS" in SQL::Translator for a list of values for $sqlt_args.

datetime_parser

Returns the datetime parser class

datetime_parser_type

Defines (returns) the datetime parser class - currently hardwired to DateTime::Format::MySQL

build_datetime_parser

See "datetime_parser"

is_replicating

A boolean that reports if a particular DBIx::Class::Storage::DBI is set to replicate from a master database. Default is undef, which is the result returned by databases that don't support replication.

lag_behind_master

Returns a number that represents a certain amount of lag behind a master db when a given storage is replicating. The number is database dependent, but starts at zero and increases with the amount of lag. Default in undef

USAGE NOTES ^

DBIx::Class and AutoCommit

DBIx::Class can do some wonderful magic with handling exceptions, disconnections, and transactions when you use AutoCommit => 1 combined with txn_do for transaction support.

If you set AutoCommit => 0 in your connect info, then you are always in an assumed transaction between commits, and you're telling us you'd like to manage that manually. A lot of the magic protections offered by this module will go away. We can't protect you from exceptions due to database disconnects because we don't know anything about how to restart your transactions. You're on your own for handling all sorts of exceptional cases if you choose the AutoCommit => 0 path, just as you would be with raw DBI.

SQL METHODS ^

The module defines a set of methods within the DBIC::SQL::Abstract namespace. These build on SQL::Abstract::Limit to provide the SQL query functions.

The following methods are extended:-

delete
insert
select
update
limit_dialect

See "connect_info" for details.

quote_char

See "connect_info" for details.

name_sep

See "connect_info" for details.

AUTHORS ^

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

Andy Grundman <andy@hybridized.org>

LICENSE ^

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

syntax highlighting: