NAME
DBIO::Storage - Generic Storage Handler
VERSION
version 0.900004
DESCRIPTION
DBIO::Storage is the abstract base class for storage backends. It contains the generic transaction, exception, and cursor plumbing shared by concrete storage implementations.
Most real applications use DBIO::Storage::DBI or a driver-specific subclass such as PostgreSQL, MySQL, or SQLite storage. This module is where the common storage contract is defined.
METHODS
new
Arguments: $schema
Instantiates the Storage object.
set_schema
Used to reset the schema class or object which owns this storage object, such as during "clone" in DBIO::Schema.
set_access_broker
Attach an DBIO::AccessBroker instance to this storage and set the default broker mode (defaults to write). A broker attached before is detached from this storage first ("unset_storage" in DBIO::AccessBroker); other storages stay attached to it.
clear_access_broker
Detach any currently attached broker from this storage. The broker is told ("unset_storage" in DBIO::AccessBroker) and no longer answers for this storage; the other storages it is attached to are not affected.
This is the broker slot only. A storage that keeps more with a broker extends it, and "set_access_broker" where needed: DBIO::Storage::DBI drops the connect info stored from the broker's answer and takes its embedded async backend along ("clear_access_broker" in DBIO::Storage::DBI::AccessBroker), an async storage drops what came with the broker and has its connect info provider refuse from then on ("clear_access_broker" in DBIO::Storage::Async).
current_access_broker_connect_info
Return the current storage-native connect info for the requested mode: the attached broker's answer as it stands now, asked again on every call. Without a broker it returns nothing.
A broker that answers nothing -- undef, an empty hash or array, a false value -- throws, naming the broker class and the shape of the answer, never a value. Every storage opens a new connection only with the broker's current answer: the sync storage's _connect, an async backend's _current_async_connect_info, and a transport reading this method directly all get the refusal from here, instead of falling back to connect info stored from an earlier answer or an earlier connection. A broker that throws is left to throw.
A view over another broker -- one that answers underlying_broker, as DBIO::AccessBroker::HostBound does -- hands an answer of nothing on as it came, so the error names the broker at the bottom that answered nothing, and the view(s) it was asked through.
connected
Returns true if we have an open storage connection, false if it is not (yet) open.
disconnect
Closes any open storage connection unconditionally.
ensure_connected
Initiate a connection to the storage if one isn't already open.
throw_exception
Throws an exception - croaks.
txn_do
Executes $coderef with (optional) arguments @coderef_args atomically, returning its result (if any). If an exception is caught, a rollback is issued and the exception is rethrown. If the rollback fails, (i.e. throws an exception) an exception is thrown that includes a "Rollback failed" message.
For example,
my $author = $schema->resultset('Author')->find(1);
my @titles = qw/Night Day It/;
my $coderef = sub {
# If any one of these fails, the entire transaction fails
$author->create_related('books', {
title => $_
}) foreach (@titles);
return $author->books;
};
my $rs;
try {
$rs = $schema->txn_do($coderef);
} catch {
my $error = shift;
# Transaction failed
die "something terrible has happened!"
if ($error =~ /Rollback failed/); # Rollback failed
deal_with_failed_transaction();
};
In a nested transaction (calling txn_do() from within a txn_do() coderef) only the outermost transaction will issue a "txn_commit", and txn_do() can be called in void, scalar and list context and it will behave as expected.
Please note that all of the code in your coderef, including non-DBIO code, is part of a transaction. This transaction may fail out halfway, or it may get partially double-executed (in the case that our DB connection failed halfway through the transaction, in which case we reconnect and restart the txn). Therefore it is best that any side-effects in your coderef are idempotent (that is, can be re-executed multiple times and get the same result), and that you check up on your side-effects in the case of transaction failure.
Before it reconnects for that restart, a DBI storage disconnects the old handle and warns: the block must not run a second time next to the transaction the old handle still holds open. Statement handles of your own on the old connection are dead from then on.
txn_begin
Starts a transaction.
See the preferred "txn_do" method, which allows for an entire code block to be executed transactionally.
txn_commit
Issues a commit of the current transaction.
It does not perform an actual storage commit unless there's a DBIO transaction currently in effect (i.e. you called "txn_begin").
If the commit of the outermost transaction fails, the transaction is over whatever the server says (a deferred constraint is checked at commit time): the storage resets its transaction state (depth 0, no savepoints, no deferred rollback) exactly as after a failed rollback, so the next statement is not run inside a transaction nobody will commit. It then tries a rollback, so that the server keeps no open transaction; if that fails as well the handle is discarded ("_abandon_after_failed_rollback") and the next statement connects anew. The error of the commit is rethrown, never that of the rollback. This holds for every way to a commit: "commit" in DBIO::Storage::TxnScopeGuard, "txn_do", DBIO::Storage::BlockRunner and a direct call.
txn_rollback
Issues a rollback of the current transaction (or savepoint, if auto_savepoint is enabled, and you are in a nested transaction).
If you are in a nested transaction without auto_savepoint, rollback will put the storage into a "deferred rollback" state and throw a DBIO::Storage::NESTED_ROLLBACK_EXCEPTION exception to help you unwind to the outer-most transaction's scope. Until the "deferred rollback" condition is resolved, the storage engine will throw exceptions on any attempt to begin, commit, or rollback a transaction.
If the rollback of the outermost transaction itself fails, the handle is unusable (the transaction may still be open on the server): the storage resets its transaction state (depth 0, no savepoints, no deferred rollback), a DBI storage disconnects the handle without a further rollback and the next statement connects anew, and the original error is rethrown.
_abandon_after_failed_rollback
Called by "txn_rollback" when the rollback of the outermost transaction itself failed. The handle can no longer be trusted, so the storage forgets the transaction (depth 0, no savepoints, no deferred rollback); a storage that holds a connection (DBIO::Storage::DBI) discards it as well. The original error is rethrown by "txn_rollback" afterwards.
_abandon_after_failed_commit
Called by "txn_commit" when the commit of the outermost transaction failed. The transaction is over: the state is reset first (depth 0, no savepoints, no deferred rollback), then a rollback is tried so the server holds no open transaction, and when that fails too the handle is discarded through "_abandon_after_failed_rollback". Errors of that rollback are swallowed; the error of the commit is rethrown by "txn_commit".
_abandon_handle_before_reconnect
Called by the retry path of DBIO::Storage::BlockRunner right before it reconnects. A no-op here; DBIO::Storage::DBI disconnects the old handle.
_throw_deferred_rollback
_svp_generate_name
register_type
DBIO::PostgreSQL::Storage->register_type('jsonb', {
cake_options => [qw(inflate_json inflate_jsonb)],
components => ['InflateColumn::Serializer'],
col_attrs => { serializer_class => 'JSON' },
});
Registers type metadata for use by DBIO::Cake and other DBIO subsystems. Driver distributions call this in their module body to declare how their specific types should be handled. Subclass registrations inherit from and can override parent class registrations via normal MRO lookup.
type_info
my $info = DBIO::PostgreSQL::Storage->type_info('jsonb');
Returns the type metadata for a given type name, walking up the MRO so subclasses inherit and can override base type definitions. Returns undef if the type is not registered.
all_type_names
my @types = DBIO::PostgreSQL::Storage->all_type_names;
Returns all type names registered for this class and its ancestors (deduplicated, most-derived class wins).
svp_begin
Arguments: $savepoint_name?
Created a new savepoint using the name provided as argument. If no name is provided, one is generated from the number of savepoints currently open: savepoint_0, savepoint_1, ...
svp_release
Arguments: $savepoint_name?
Release the savepoint provided as argument. If none is provided, release the savepoint created most recently. This will implicitly release all savepoints created after the one explicitly released as well.
svp_rollback
Arguments: $savepoint_name?
Rollback to the savepoint provided as argument. If none is provided, rollback to the savepoint created most recently. This will implicitly release all savepoints created after the savepoint we rollback to.
txn_scope_guard
An alternative way of transaction handling based on DBIO::Storage::TxnScopeGuard:
my $txn_guard = $storage->txn_scope_guard;
$result->col1("val1");
$result->update;
$txn_guard->commit;
If an exception occurs, or the guard object otherwise leaves the scope before $txn_guard->commit is called, the transaction will be rolled back by an explicit "txn_rollback" call. In essence this is akin to using a "txn_begin"/"txn_commit" pair, without having to worry about calling "txn_rollback" at the right places. Note that since there is no defined code closure, there will be no retries and other magic upon database disconnection. If you need such functionality see "txn_do".
sql_maker
Returns a sql_maker object - normally an object of class DBIO::SQLMaker.
debug
Causes trace information to be emitted on the "debugobj" object. (or STDERR if "debugobj" has not specifically been set).
The value is the trace level: debug(1) traces the statement, debug(2) adds the bind values (see "DBIO_TRACE"). This is the equivalent to setting DBIO_TRACE in your shell environment.
debugfh
An opportunistic proxy to ->debugobj->debugfh(@_) If the currently set "debugobj" does not have a "debugfh" method, caling this is a no-op.
debugobj
Sets or retrieves the object used for metric collection. Defaults to an instance of DBIO::Storage::Statistics that is compatible with the original method of using a coderef as a callback. See the aforementioned Statistics class for more information.
debugcb
Sets a callback to be executed each time a statement is run; takes a sub reference. Callback is executed as $sub->($op, $info) where $op is SELECT/INSERT/UPDATE/DELETE and $info is what would normally be printed.
See "debugobj" for a better way.
cursor_class
The cursor class for this Storage object.
deploy
Deploy the tables to storage (CREATE TABLE and friends in a SQL-based Storage class). This would normally be called through "deploy" in DBIO::Schema.
connect_info
The arguments of connect_info are always a single array reference, and are Storage-handler specific.
This is normally accessed via "connection" in DBIO::Schema, which encapsulates its argument list in an arrayref before calling connect_info here.
select
Handle a select statement.
insert
Handle an insert statement.
update
Handle an update statement.
delete
Handle a delete statement.
select_single
Performs a select, fetch and return of data - handles a single row only.
select_async
Async variant of "select". Returns a DBIO::Future that resolves with the query result rows as raw arrayrefs -- the same cursor->all shape a real DBIO::Storage::Async backend resolves with (ADR 0053), so the storage-level select_async contract is the same across every async mode. Requires an async connection (connect(..., { async => ... })); on a sync instance it croaks. In the immediate mode it runs synchronously and returns an immediately-resolved Future via "future_class" carrying that same form.
select_single_async
Async variant of "select_single". Resolves with a single raw row arrayref, or undef when there is no row -- the same form a real DBIO::Storage::Async backend resolves with (ADR 0053), rather than the flat column list synchronous "select_single" returns.
insert_async
Async variant of "insert".
update_async
Async variant of "update".
delete_async
Async variant of "delete".
txn_do_async
Async variant of "txn_do". Returns a DBIO::Future that resolves after COMMIT or rejects after ROLLBACK.
The coderef is called with a transaction context as its first argument, followed by any extra txn_do_async arguments: $coderef->($ctx, @args). On a real DBIO::Storage::Async backend $ctx is a DBIO::Storage::Async::TransactionContext pinned to the transaction connection; in the immediate mode it is the storage itself (its *_async methods run in-process inside the transaction), so the portable pattern sub { my ($ctx) = @_; $ctx->insert_async(...) } is substitutable across modes (ADR 0055). A DBIO::Future returned by the coderef is adopted: the transaction resolves with that Future's value(s) on success and rolls back on its failure -- the same across every async mode.
A statement Future the context handed out that failed rolls the transaction back as well, and the transaction fails with that statement's error -- also when nothing awaited it, and also when the coderef caught the failure and returned normally. The same across every async mode (see "txn_do_async" in DBIO::Storage::Async).
$ctx is also what a ResultSet, Row or ResultSetColumn is bound to with with_context, in every async mode ("with_context" in DBIO::ResultSet). In the immediate mode that is this storage: a bound object's *_async run in-process inside the transaction, its failed statements fail the transaction like the context's own, and once the coderef has returned it is refused. The storage's own *_async methods are not guarded that way -- called after the transaction they simply run outside it.
future_class
Returns the class name used to construct Future objects. Defaults to DBIO::Future::Immediate which resolves synchronously. Async storage drivers override this to return their event loop's Future class.
columns_info_for
Returns metadata for the given source's columns. This is *deprecated*, and will be removed before 1.0. You should be specifying the metadata yourself if you need it.
ENVIRONMENT VARIABLES
DBIO_TRACE
If DBIO_TRACE is set then trace information is produced (as when the "debug" method is set).
DBIO_TRACE=1 traces the statement. DBIO_TRACE=2 adds the bind values: each value is run through the redact_bind_value hook ("redact_bind_value" in DBIO::Storage::DBI) and cut to 32 characters, with ... marking the cut; undef is traced as NULL. The level is the leading digits of the value (2=/path/name is level 2); any other true value is level 1. The synchronous storage, DBIO::Replicated and the asynchronous transports follow this one rule, and "debug" holds the level.
If the value is of the form N=/path/name (N the level) then the trace output is written to the file /path/name. The file is opened for append and, when the trace creates it, is readable by its owner alone (mode 0600). The statements of connect actions are traced with the secrets they carry shown as ***[sha256:<8 hex>], a fingerprint of the value.
This environment variable is checked when the storage object is first created (when you call connect on your schema). So, run-time changes to this environment variable will not take effect unless you also re-connect on your schema.
DBIO_TRACE_PROFILE
If DBIO_TRACE_PROFILE is set, DBIO::Storage::Debug::PrettyTrace will be used to format the output from DBIO_TRACE. The value it is set to is the profile that it will be used. If the value is a filename the file is read with Config::Any and the results are used as the configuration for tracing. See "new" in SQL::Abstract::Tree for what that structure should look like.
SEE ALSO
DBIO::Storage::DBI - reference storage implementation using DBI and a subclass of SQL::Abstract ( or similar )
1;
AUTHOR
DBIO & DBIx::Class Authors
COPYRIGHT AND LICENSE
Copyright (C) 2026 DBIO Authors Portions Copyright (C) 2005-2025 DBIx::Class Authors Based on DBIx::Class, heavily modified.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.