NAME

DBIx::Fast::Connector - DBIx::Fast connection manager fork safe

SYNOPSIS

# Normally built for you by DBIx::Fast->new; direct use:
my $conn = DBIx::Fast::Connector->new(
    dsn   => 'dbi:MariaDB:dbname=app;host=localhost',
    user  => 'app',
    pass  => $password,
    attrs => { RaiseError => 1, AutoCommit => 1 },
);

my $dbh = $conn->dbh;      # live, fork-safe handle (reconnects if needed)
$conn->disconnect;

DESCRIPTION

Minimal connection manager that provides automatic reconnection and fork safety.

FORK SAFETY

A process that forks (preforking servers such as Hypnotoad, job queues such as Minion, Parallel::ForkManager) hands the child a copy of every open connection. The child must neither use nor close the parent's connection: dbh detects the fork and opens a fresh connection in the child, and the inherited one is neutralized.

DBD::MariaDB (1.24, the current CPAN release) ignores InactiveDestroy and AutoInactiveDestroy in the child: at exit, DBI's disconnect_all closes every connection the driver knows, including the inherited one, and the server drops the parent's connection (upstream DBD-MariaDB PR #175 / issue #210). DBIx::Fast works around it: the child points its copy of the socket at /dev/null before the driver can close it, so the driver releases its resources normally and the parent's connection survives. This happens

  • immediately at fork time, when the optional POSIX::AtFork is installed;

  • otherwise when the child calls dbh, drops the connector, or reaches END.

Other drivers honour InactiveDestroy, which is all they get.

With POSIX::AtFork installed, fork detection is also cheaper: dbh compares a fork generation counter instead of reading $$, which is a getpid() system call on each read (about 10% of a simple val against SQLite).

METHODS

new

my $conn = DBIx::Fast::Connector->new(
    dsn        => $dsn,
    user       => $user,
    pass       => $pass,
    attrs      => \%attrs,
    on_connect => sub ($dbh) { ... },   # optional
);

Creates a new connector (named parameters). The DBI connection is established lazily on the first call to dbh. on_connect is a coderef invoked with the fresh handle on every (re)connect.

dbh

my $dbh = $conn->dbh;

Returns the DBI database handle. Automatically reconnects if the handle is stale or if the process has forked since the last connection. Dies with "connection lost mid-transaction" if a handle is found dead while a transaction was open (AutoCommit off), rather than silently reconnecting an autocommit session.

disconnect

Disconnects and clears the cached handle.

mode

Accepts a mode argument (ignored). Exists for compatibility.

SEE ALSO

DBIx::Fast, DBI, DBIx::Connector, POSIX::AtFork

AUTHOR

SeHarrys

LICENSE

This is free software under the Artistic License 2.0.