DBIx::Connector(3)
π DBIx::Connector(3) π
Okay bestie, this is the manual page for DBIx::Connector β yep, the DBIx::Connector(3) one from User Contributed Perl Documentation β and it's all about fast, safe DBI connection and transaction management. Buckle up. π
πΈ NAME πΈ
DBIx::Connector β Fast, safe DBI connection and transaction management. Periodt.
β¨ SYNOPSIS β¨
use DBIx::Connector;
# Create a connection.
my $conn = DBIx::Connector->new($dsn, $username, $password, {
RaiseError => 1,
AutoCommit => 1,
});
# Get the database handle and do something with it.
my $dbh = $conn->dbh;
$dbh->do('INSERT INTO foo (name) VALUES (?)', undef, 'Fred' );
# Do something with the handle more efficiently.
$conn->run(fixup => sub {
$_->do('INSERT INTO foo (name) VALUES (?)', undef, 'Fred' );
});
π¦ DESCRIPTION π¦
DBIx::Connector gives you a simple interface for fast and safe DBI connection and transaction management. Connecting to a database can be expensive; you don't want your application to re-connect every time you need to run a query. The efficient thing to do is to hang on to a database handle to maintain a connection to the database in order to minimize that overhead. DBIx::Connector lets you do that without having to worry about dropped or corrupted connections.
You might be familiar with Apache::DBI and with the DBI's connect_cached() constructor. DBIx::Connector serves a similar need, but does a much better job. How is it different? I'm glad you asked!
- Fork Safety β Like Apache::DBI, but unlike
connect_cached(),DBIx::Connectorcreates a new database connection if a new process has been"fork"ed. This happens all the time under mod_perl, in POE applications, and elsewhere. Works best with DBI 1.614 and higher. - Thread Safety β Unlike Apache::DBI or
connect_cached(),DBIx::Connectorwill create a new database connection if a new thread has been spawned. As with"fork"ing, spawning a new thread can break database connections. - Works Anywhere β Unlike Apache::DBI,
DBIx::Connectorruns anywhere -- inside of mod_perl or not. Why limit yourself? - Explicit Interface β
DBIx::Connectorhas an explicit interface. There is none of the magical action-at-a-distance crap that Apache::DBI is guilty of, and no global caching. I've personally diagnosed a few issues with Apache::DBI's magic, and killed it off in two different projects in favor ofconnect_cached(), only to be tripped up by other gotchas. No more. - Optimistic Execution β If you use
run()andtxn(), the database handle will be passed without first pinging the server. For the 99% or more of the time when the database is just there, you'll save a ton of overhead without the ping.
DBIx::Connector's other feature is transaction management. Borrowing an interface from DBIx::Class, DBIx::Connector offers an API that efficiently handles the scoping of database transactions so that you needn't worry about managing the transaction yourself. Even better, it offers an API for savepoints if your database supports them. Within a transaction, you can scope savepoints to behave like subtransactions, so that you can save some of your work in a transaction even if part of it fails. See txn() and svp() for the goods. π«Ά
π USAGE π
Unlike Apache::DBI and connect_cached(), DBIx::Connector doesn't cache database handles. Rather, for a given connection, it makes sure that the connection is just there whenever you want it, to the extent possible. The upshot is that it's safe to create a connection and then keep it around for as long as you need it, like so:
my $conn = DBIx::Connector->new(@args);
You can store the connection somewhere in your app where you can easily access it, and for as long as it remains in scope, it will try its hardest to maintain a database connection. Even across "fork"s (especially with DBI 1.614 and higher) and new threads, and even calls to $conn->dbh->disconnect. When you don't need it anymore, let it go out of scope and the database connection will be closed.
The upshot is that your code is responsible for hanging onto a connection for as long as it needs it. There is no magical connection caching like in Apache::DBI and connect_cached().
π Execution Methods π
The real utility of DBIx::Connector comes from the use of the execution methods, run(), txn(), or svp(). Instead of this:
$conn->dbh->do($query);
Try this:
$conn->run(sub { $_->do($query) }); # returns retval from the sub {...}
The difference is that the run() optimistically assumes that an existing database handle is connected and executes the code reference without pinging the database. The vast majority of the time, the connection will of course still be open. You therefore save the overhead of a ping query every time you use run() (or txn()).
Of course, if a block passed to run() dies because the DBI isn't actually connected to the database you'd need to catch that failure and try again. DBIx::Connector provides a way to overcome this issue: connection modes.
π Connection Modes π
When calling run(), txn(), or svp(), each executes within the context of a "connection mode". The supported modes are:
"ping""fixup""no_ping"
Use them via an optional first argument, like so:
$conn->run(ping => sub { $_->do($query) });
Or set up a default mode via the mode() accessor:
$conn->mode('fixup');
$conn->run(sub { $_->do($query) });
The return value of the block will be returned from the method call in scalar or array context as appropriate, and the block can use "wantarray" to determine the context. Returning the value makes them handy for things like constructing a statement handle:
my $sth = $conn->run(fixup => sub {
my $sth = $_->prepare('SELECT isbn, title, rating FROM books');
$sth->execute;
$sth;
});
In "ping" mode, run() will ping the database before running the block. This is similar to what Apache::DBI and the DBI's connect_cached() method do to check the database connection, and is the safest way to do so. If the ping fails, DBIx::Connector will attempt to reconnect to the database before executing the block. However, "ping" mode does impose the overhead of the "ping" every time you use it.
In "fixup" mode, DBIx::Connector executes the block without pinging the database. But in the event the block throws an exception, if DBIx::Connector finds that the database handle is no longer connected, it will reconnect to the database and re-execute the block. Therefore, the code reference should have no side-effects outside of the database, as double-execution in the event of a stale database connection could break something:
my $count;
$conn->run(fixup => sub { $count++ });
say $count; # may be 1 or 2
"fixup" is the most efficient connection mode. If you're confident that the block will have no deleterious side-effects if run twice, this is the best option to choose. If you decide that your block is likely to have too many side-effects to execute more than once, you can simply switch to "ping" mode.
The default is "no_ping", but you likely won't ever use it directly, and isn't recommended in any event.
Simple, huh? Better still, go for the transaction management in txn() and the savepoint management in svp(). You won't be sorry, I promise. π
π Rollback Exceptions π
In the event of a rollback in txn() or svp(), if the rollback itself fails, a DBIx::Connector::TxnRollbackError or DBIx::Connector::SvpRollbackError exception will be thrown, as appropriate. These classes, which inherit from DBIx::Connector::RollbackError, stringify to display both the rollback error and the transaction or savepoint error that led to the rollback, something like this:
Transaction aborted: No such table "foo" at foo.pl line 206.
Transaction rollback failed: Invalid transaction ID at foo.pl line 203.
For finer-grained exception handling, you can access the individual errors via accessors:
"error"β The transaction or savepoint error."rollback_error"β The rollback error.
For example:
use Try::Tiny;
try {
$conn->txn(sub {
# ...
});
} catch {
if (eval { $_->isa('DBIx::Connector::RollbackError') }) {
say STDERR 'Transaction aborted: ', $_->error;
say STDERR 'Rollback failed too: ', $_->rollback_error;
} else {
warn "Caught exception: $_";
}
};
If a svp() rollback fails and its surrounding txn() rollback also fails, the thrown DBIx::Connetor::TxnRollbackError exception object will have the savepoint rollback exception, which will be an DBIx::Connetor::SvpRollbackError exception object in its "error" attribute:
use Try::Tiny;
$conn->txn(sub {
try {
$conn->svp(sub { # ... });
} catch {
if (eval { $_->isa('DBIx::Connector::RollbackError') }) {
if (eval { $_->error->isa('DBIx::Connector::SvpRollbackError') }) {
say STDERR 'Savepoint aborted: ', $_->error->error;
say STDERR 'Its rollback failed too: ', $_->error->rollback_error;
} else {
say STDERR 'Transaction aborted: ', $_->error;
}
say STDERR 'Transaction rollback failed too: ', $_->rollback_error;
} else {
warn "Caught exception: $_";
}
};
});
But most of the time, you should be fine with the stringified form of the exception, which will look something like this:
Transaction aborted: Savepoint aborted: No such table "bar" at foo.pl line 190.
Savepoint rollback failed: Invalid savepoint name at foo.pl line 161.
Transaction rollback failed: Invalid transaction identifier at fool.pl line 184.
This lets you see the original SQL error, plus the errors for the savepoint rollback and transaction rollback failures. π«Ά
π INTERFACE π
And now for the nitty-gritty.
π Constructor π
β¨ new β¨
my $conn = DBIx::Connector->new($dsn, $username, $password, {
RaiseError => 1,
AutoCommit => 1,
});
Constructs and returns a DBIx::Connector object. The supported arguments are exactly the same as those supported by the DBI. Default values for those parameters vary from the DBI as follows:
RaiseErrorβ defaults to true if you don't specify it, and ifHandleErroris also unspecified. Listen: you need either theRaiseErrorattribute, or aHandleErrorattribute that always throws exceptions (like the oneException::Class::DBIhands you), for the exception-handling magic ofrun(),txn(), andsvp()to actually work properly. So yeah β setting it explicitly is highkey recommended if you want real error handling out of those three. Don't skip this one bestie. πAutoInactiveDestroyβ added back in DBI 1.613. Defaults to true if unspecified. This one's a big deal for safe disconnects across forking processes β like, actually important, not just vibes. π
On top of all that, explicitly setting AutoCommit to true is strongly recommended if you're planning to use txn() or svp(). Otherwise you literally won't get the transactional scoping behavior those two methods are famous for. No cap.
If you want to run your own custom logic every single time a new connection to the database gets made, just pass a sub as the connected key to the Callbacks parameter. Peep "Callbacks" in DBI for how to use it and what other callbacks are available. πΈ
Other attributes may get modified by individual drivers, so check the docs for your driver for the deets:
DBIx::Connector::Driver::MSSQLDBIx::Connector::Driver::OracleDBIx::Connector::Driver::PgDBIx::Connector::Driver::SQLiteDBIx::Connector::Driver::mysqlDBIx::Connector::Driver::Firebird
π Class Method π
connect
my $dbh = DBIx::Connector->connect($dsn, $username, $password, \%attr);
This is just syntactic sugar for:
my $dbh = DBIx::Connector->new(@args)->dbh;
Honestly though, there's probably not much point in doing this, because you're generally gonna want to hold onto the DBIx::Connector object itself. Otherwise you'd just use the DBI directly, right? iykyk π€·ββοΈ
β¨ Instance Methods β¨
dbh
my $dbh = $conn->dbh;
Returns the connection's database handle. It'll reuse an existing handle if there is one, if the process hasn't been forked or a new thread spawned, and if the database is pingable. Otherwise it instantiates a fresh handle, caches it, and returns that. Slay.
When you call it from blocks passed to run(), txn(), and svp(), dbh() just assumes the pingability of the database is being handled by those methods and skips the ping(). Otherwise it does all the same validity checks as usual. The upshot? It's totally safe to call dbh() inside those blocks without eating the overhead of multiple pings. In fact it's preferable to do exactly that if you're doing lots of non-database processing in those blocks. π
run
$conn->run(ping => sub { $_->do($query) });
Simply executes the block, locally setting $_ to the database handle and passing it in. Returns whatever the block returned, in scalar or array context as appropriate (and yeah, the block can use wantarray to decide what it wants to do). π
An optional first argument sets the connection mode, overriding whatever's set in the mode() accessor, and it can be one of ping, fixup, or no_ping (that last one's the default). See "Connection Modes" for the full explication, bestie.
For convenience you can nest calls to run() (or txn() or svp()) β just know that the connection mode gets invoked to check the connection (or not) only in the outer-most block method call.
$conn->txn(fixup => sub {
my $dbh = shift;
$dbh->do($_) for @queries;
$conn->run(sub {
$_->do($expensive_query);
$conn->txn(sub {
$_->do($another_expensive_query);
});
});
});
All code executed inside that top-level call to txn() runs in a single transaction. Want subtransactions? Nest svp() calls. π¦
It's preferable to use dbh() to fetch the handle from within the block if your code is doing lots of non-database stuff (shame on you!):
$conn->run(ping => sub {
parse_gigabytes_of_xml(); # Get this out of the transaction!
$conn->dbh->do($query);
});
Why? Because dbh() does a better job making sure the handle is active and fork- and thread-safe β though it will never ping() the database when called from inside a run(), txn(), or svp() block. π
txn
my $sth = $conn->txn(fixup => sub { $_->do($query) });
Starts a transaction, executes the block (locally setting $_ to the database handle and passing it in), then commits the transaction. If the block throws an exception, the transaction gets rolled back and the exception gets re-thrown. Returns whatever the block returned, in scalar or array context as appropriate (and yep, the block can use wantarray). π₯
An optional first argument sets the connection mode, overriding whatever's in the mode() accessor, and may be ping, fixup, or no_ping (default). With fixup mode specifically, that means the transaction block will be re-executed for a new connection if the database handle is no longer connected. And in that case, a second exception from the code block will cause the transaction to be rolled back and the exception re-thrown. Full details live in "Connection Modes".
Just like with run(), calls to txn() can be nested, although the connection mode gets invoked to check the connection (or not) only in the outer-most block method call. And again: use dbh() to grab the handle from inside the block if you're doing lots of non-database processing. π
svp
Executes a code block within the scope of a database savepoint β if your database supports them, that is. Returns whatever the block returned, in scalar or array context as appropriate (and yes, wantarray works here too). β
Think of savepoints as a kind of subtransaction. Which means you can nest your savepoints and recover from failures deeper in the nest without throwing out all the changes higher up. Example time:
$conn->txn(fixup => sub {
my $dbh = shift;
$dbh->do('INSERT INTO table1 VALUES (1)');
eval {
$conn->svp(sub {
shift->do('INSERT INTO table1 VALUES (2)');
die 'OMGWTF?';
});
};
warn "Savepoint failed\n" if $@;
$dbh->do('INSERT INTO table1 VALUES (3)');
});
That transaction inserts the values 1 and 3, but not 2. Bye 2. π
$conn->svp(fixup => sub {
my $dbh = shift;
$dbh->do('INSERT INTO table1 VALUES (4)');
$conn->svp(sub {
shift->do('INSERT INTO table1 VALUES (5)');
});
});
And this one inserts both 4 and 5. Iconic. π
Superficially, svp() resembles run() and txn(), including support for that optional connection mode argument β but plot twist: savepoints can only be used within the scope of a transaction. So svp() will start a transaction for you if it's called without one in progress. It literally just redispatches to txn() with the appropriate connection mode. Which means this call from outside a transaction:
$conn->svp(ping => sub {
$conn->svp( sub { ... } );
});
is equivalent to:
$conn->txn(ping => sub {
$conn->svp( sub { ... } );
})
Savepoints are supported by these RDBMSs:
- PostgreSQL 8.0
- SQLite 3.6.8
- MySQL 5.0.3 (InnoDB)
- Oracle
- Microsoft SQL Server
- Firebird 1.5
For all other RDBMSs, svp() works just like txn(): savepoints get ignored and the outer-most transaction is the only transaction. Honestly it tends to degrade well for non-savepoint-supporting databases, doing the right thing in most cases. π«Ά
mode
my $mode = $conn->mode;
$conn->mode('fixup');
$conn->txn(sub { ... }); # uses fixup mode.
$conn->mode($mode);
Gets and sets the connection mode attribute, which is what run(), txn(), and svp() use when no mode is passed to them. Defaults to no_ping. And heads up: inside a block passed to run(), txn(), or svp(), the mode attribute will be set to that optional first parameter:
$conn->mode('ping');
$conn->txn(fixup => sub {
say $conn->mode; # Outputs "fixup"
});
say $conn->mode; # Outputs "ping"
So you can always reliably tell what mode the code block is executing in. Vibe check passed. β
connected
if ( $conn->connected ) {
$conn->dbh->do($query);
}
Returns true if you're currently connected to the database, false if you're not. You probably won't need to bother with this method tbh β DBIx::Connector uses it internally to figure out whether or not to create a new connection to the database before handing you a handle from dbh(). π
in_txn
if ( $conn->in_txn ) {
say 'Transacting!';
}
Returns true if the connection is in a transaction. Like, inside a txn() block it'd return true. It also works if you use the DBI API to manage transactions (i.e., begin_work() or AutoCommit). π
Essentially it's just sugar for:
$con->run( no_ping => sub { !$_->{AutoCommit} } );
...but without the overhead of the code reference or connection checking. Lowkey efficient. πΈ
disconnect_on_destroy
$conn->disconnect_on_destroy(0);
By default, DBIx::Connector calls $dbh->disconnect when it goes out of scope and gets garbage-collected by the system (that is, in its DESTROY() method). Usually that's exactly what you want β but sometimes it isn't. For example, you might have a module that uses DBIx::Connector internally but then makes the database handle available to callers, even after the DBIx::Connector object goes out of scope. In that case you do not want the handle disconnected when the connector goes poof. So pass a false value to disconnect_on_destroy to prevent the disconnect. Example:
sub database_handle {
my $conn = DBIx::Connector->new(@_);
$conn->run(sub {
# Do stuff here.
});
$conn->disconnect_on_destroy(0);
return $conn->dbh;
}
And of course, if you don't need to do any work with the handle before returning it to your caller, you can just use connect():
sub database_handle {
DBIx::Connector->connect(@_);
}
disconnect
$conn->disconnect;
Disconnects from the database. Unless disconnect_on_destroy() has been passed a false value, DBIx::Connector uses this method internally in its DESTROY method to make sure everything's kept tidy. π§
driver
$conn->driver->begin_work( $conn->dbh );
So like, to make all the database features work in a way that's, y'know, database-neutral (iconic behavior honestly), DBIx::Connector ships a bunch of different database drivers β they're subclasses of DBIx::Connector::Driver β and they've got methods for handling database communications. And yeah, the DBI gives you a standard interface, but for better or for worse, not every driver actually implements it, and some of them straight-up have bugs π. So to dodge all that mess, every bit of database communication goes through these driver objects. No cap. π«Ά
This is genuinely useful when you want more fine-grained control of your transactionality (main character energy for your transactions β¨). Like, say you wanna make your own savepoint inside a transaction β you'd do something like this:
use Try::Tiny;
my $driver = $conn->driver;
$conn->txn(sub {
my $dbh = shift;
try {
$driver->savepoint($dbh, 'mysavepoint');
# do stuff ...
$driver->release('mysavepoint');
} catch {
$driver->rollback_to($dbh, 'mysavepoint');
};
});
Most of the time you should be totally fine getting what you need out of txn() and svp() β they ate, they serve π
β but sometimes you just need that finer control. And in those cases, bestie, use the driver object so your API usage stays universal across all the database back-ends. One vibe, every back-end. π
driver_name
my $driver_name = $conn->driver_name;
Returns the name of the DBI driver that is (or is gonna be) used to connect to the database. Simple as that. π
dsn
my $dsn = $conn->dsn;
Returns the DBI Data Source Name that was originally passed to new() as the first argument. The OG DSN, untouched, exactly how you handed it over. π
β¨ SEE ALSO β¨
DBIx::Connector::DriverDBIDBIx::ClassCatalyst::Model::DBI
π AUTHORS π
This module was written by, drumroll please π₯:
- David E. Wheeler
<david@kineticode.com>
And it's based on documentation, ideas, kibbitzing, and code from these absolute legends:
- Tim Bunce
<http://tim.bunce.name> - Brandon L. Black
<blblack@gmail.com> - Matt S. Trout
<mst@shadowcat.co.uk> - Peter Rabbitson
<ribasushi@cpan.org> - Ash Berlin
<ash@cpan.org> - Rob Kinyon
<rkinyon@cpan.org> - Cory G Watson
<gphat@cpan.org> - Anders Nor Berle
<berle@cpan.org> - John Siracusa
<siracusa@gmail.com> - Alex Pavlovic
<alex.pavlovic@taskforce-1.com> - Many other DBIx::Class contributors
πΈ COPYRIGHT AND LICENSE πΈ
Copyright (c) 2009-2013 David E. Wheeler. Some Rights Reserved.
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. So go off, just keep it Perl-licensed, okay? π§
And that's the whole page, bestie β you made it to the end! π This writeup dropped as part ofperl v5.40.0on2024-10-21. Go forth and connect responsibly. π¦π
π¦ where this page comes from
- epel 10: perl-DBIx-Connector 0.60-1.el10_0 Β· GPL-1.0-or-later OR Artistic-1.0-Perl
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms