Tag: dbi

  • Bringing Non-Blocking I/O to Perl’s DBI: Looking for Community Feedback

    Disclaimer: The opinions stated here are my own, not those of my employer.

    Over my past two posts on bringing native gRPC, Protocol Buffers, and Cloud/GenAI SDKs and modern columnar I/O, vector search, and ML engines to Perl (now tracked across 35 distributions in the PDL Data & ML Ecosystem PR Reviewer’s Guide), a long-standing architectural gap kept resurfacing: once a Perl service is speaking multiplexed HTTP/2 RPCs and streaming Arrow batches in contiguous C memory, how should it talk to relational and cloud databases without blocking the event loop?

    This post introduces an upstream RFC issue (perl5-dbi/dbi#183), a perl.dbi.dev mailing list discussion, a working core implementation in perl5-dbi/dbi#185 (branch feature/non-blocking-core, accompanied by a commit-by-commit PR #185 Reviewer’s Guide), and 8 companion DBD::* pull requests bringing a unified, zero-ABI-breakage non-blocking contract to Perl’s DBI. Nothing in this API surface is set in stone: the primary goal right now is gathering critical review from DBI and DBD::* maintainers, async framework authors, and Perl application developers before finalizing the driver contract.


    1. Twenty Years in the Making: Why Async Perl Databases Fragmented

    When Tim Bunce architected DBI in 1994, vendor C client libraries were overwhelmingly synchronous. As event loops and coroutines grew in popularity, standardizing non-blocking execution inside DBI became one of Perl’s longest-running open design threads:

    • 2004: Tim Bunce’s official August 2004 DBI roadmap listed “Support non-blocking mode for drivers that can enable it in their client API”, and early dbi-dev proposals around $sth->ready and $sth->done explored how to reconcile differing vendor C state machines.
    • 2010: DBI 1.615 shipped DBD::Gofer::Transport::corostream as an experimental Coro/AnyEvent proxy, while noting in the documentation that globally overriding CORE::select was fragile.
    • 2018: Pali opened perl5-dbi/dbi#52 requesting a stable, driver-independent DBI API unifying DBD::Pg and DBD::mysql (alongside parallel statement execution). Tim Bunce replied with an open invitation for someone to synthesize the prior discussions on dbi-dev and drive a concrete implementation forward.

    In the absence of a core contract, individual drivers and frameworks solved the problem incompatibly:

    • DBD::Pg exposed PG_ASYNC, pg_ready, pg_result, and $dbh->{pg_socket} over libpq.
    • DBD::mysql added mysql_async, mysql_async_ready, mysql_async_result, and $dbh->mysql_fd.
    • DBD::MariaDB introduced mariadb_async, mariadb_async_ready, mariadb_async_result, and $dbh->mariadb_sockfd.
    • DBD::ODBC relied on ODBC’s SQL_ATTR_ASYNC_ENABLE and SQL_STILL_EXECUTING polling model without exposing a POSIX socket descriptor at all.

    Higher-level frameworks either had to reach underneath DBI for driver-specific file descriptors (as Mojo::Pg and DBIx::Poggy do), spin up separate worker processes (AnyEvent::DBI, DBIx::Class::Async), or bypass DBI altogether (Database::Async).


    2. Core Design of perl5-dbi/dbi#185: Five Engineering Pillars

    Architecture diagram of non-blocking Perl DBI core support (PR #185) across event-loop adapters, DBIXS.h C/XS driver helpers, relational SQL drivers, and multiplexed HTTP/2 Cloud drivers.
    Figure 1: Non-blocking readiness contract in perl5-dbi/dbi#185 spanning event-loop adapters, ABI-preserving core state, DBIXS.h C/XS helpers, and 8 companion relational and HTTP/2 cloud drivers.

    Pull request perl5-dbi/dbi#185 implements a minimal, opt-in non-blocking core across 8 focused commits (56bd55e through 2ad72af, touching 13 files at +1,412 / -13 lines, with all 228 test files and 12,104 assertions passing; see the local verification commands), alongside a POSIX-pipe reference driver (DBD::MockAsync), DBI::PurePerl and DBD::Gofer parity (2af5246), and a formal driver specification in DBI::DBD (4731bd9). Five constraints guided the design:

    1. Zero Binary ABI Breakage (56bd55e, 5c3d3c0): Five new handle flags (DBIcf_Async, DBIcf_AsyncWantRead, DBIcf_AsyncWantWrite, DBIcf_AsyncMultiplex, and DBIcf_AsyncBufferWrites) pack into unused upper bits (0x01000000 through 0x10000000) of dbih_com_std_t.flags, while two new per-interpreter dbistate_t fields (async_wouldblock_sv and async_notify_watcher) claim 2 of the 3 existing reserved pad2 pointer slots (leaving pad2[1] free). Neither struct sizes nor field offsets change. For OS packagers maintaining libdbi-perl alongside dozens of precompiled XS drivers in Debian trixie/forky or Enterprise Linux, upgrading DBI requires zero binary perl-dbi-abi rebuild transitions.
    2. Strict Synchronous Isolation: All WOULDBLOCK sentinel interception and suppression of RaiseError, PrintError, and HandleError are strictly gated on DBIc_ASYNC(imp_xxh). Existing synchronous applications (even when using legacy drivers that emit err == -1) behave identically to stock DBI.
    3. Event-Loop-Agnostic Readiness (2ad72af): Drivers notify an optional AsyncWatcher object via on_add, on_modify, and on_remove callbacks carrying the socket descriptor and readiness mode ("r", "w", or "rw"), and event loops drive state machines forward via $h->async_read_ready() and $h->async_write_ready(). Optional lazy-loaded DBI::AsyncWatcher adapters cover IO::Async, AnyEvent, EV, and Mojo::IOLoop (or Future::AsyncAwait wrappers) with zero new core CPAN prerequisites.
    4. First-Class C/XS Driver Helpers: DBIXS.h exposes DBIh_ASYNC_SET_WOULDBLOCK, DBIh_ASYNC_NOTIFY_WATCHER, and DBIh_ASYNC_CLEAR_WANT under #ifdef DBIcf_Async, eliminating roughly 50 lines of error-prone Perl-stack and PERL_MAGIC_tied C boilerplate per driver while allowing updated XS drivers to compile cleanly against older DBI releases.
    5. Concurrency, fork(), and Thread Safety (2ff8959, 76aeab9): A parent-aware concurrency guard blocks accidental synchronous calls while AsyncWantRead or AsyncWantWrite is active on a statement handle or its parent $dbh (unless AsyncMultiplex => 1 is advertised by an HTTP/2 or multiplexed transport); storing async state on per-interpreter dbistate_t keeps Perl ithreads clean under Valgrind; and DESTROY skips PID checks so AutoInactiveDestroy continues to work safely across fork().

    3. What It Looks Like in Practice

    From Perl application code, connecting in non-blocking mode, attaching an event-loop watcher, and streaming rows without driver-specific method names looks identical whether the backend is PostgreSQL, MariaDB, MySQL, or Cloud Spanner:

    use strict;
    use warnings;
    use DBI qw(:async);
    use DBI::AsyncWatcher;
    
    my $dbh = DBI->connect('dbi:Pg:dbname=app', $user, $pass, {
        RaiseError => 1,
        Async      => 1,
    });
    $dbh->{AsyncWatcher} = DBI::AsyncWatcher->new('AnyEvent', $dbh);
    
    my $sth = $dbh->prepare('SELECT id, name FROM accounts WHERE active = ?');
    my $rv  = $sth->execute(1);
    
    if (DBI::is_wouldblock($sth->err)) {
        defined(my $rows = $sth->async_read_ready()) or die $sth->errstr;
    }
    
    while (my $row = $sth->fetch_async_row()) {
        last if DBI::is_wouldblock($row);
    }

    Inside a C/XS driver’s dbdimp.c, signaling a non-blocking read yield and registering the underlying socket file descriptor with the caller’s watcher takes just a few lines guarded by #ifdef DBIcf_Async:

    #ifdef DBIcf_Async
    if (DBIc_ASYNC(imp_sth)) {
        DBIc_ASYNC_WANT_READ_on(imp_sth);
        DBIc_ASYNC_WANT_READ_on(imp_dbh);
        DBIh_ASYNC_SET_WOULDBLOCK(sth, imp_sth);
        DBIh_ASYNC_NOTIFY_WATCHER(sth, imp_sth, fd, "on_add", "r");
        return 0;
    }
    #endif

    4. Proving the Contract Across 8 Companion Drivers

    A core specification is only useful if real drivers with very different wire models can implement it cleanly. Early community engagement across dbi-users, perl.dbi.dev, and perl5-dbi/dbi#185 shaped every major trade-off in this prototype:

    • The Single-Event-Loop Principle & Core Isolation (David Nicol): David immediately highlighted the core constraint (“a system should have only one event loop”), arguing for a simple “async-check-and-do” readiness model and lightweight cooperative defer/yield primitives rather than baking heavy futures or promises into DBI core. He also pushed us to explicitly weigh three architectural paths: core C-engine flags, a higher-level named-template facade (handling handle weakening to prevent closure leaks), or a greenfield parallel namespace (DBI_NB:: / DBD_NB::) to leave rock-solid blocking DBI untouched. Weighing that clean-break simplicity against Python 2-to-3-style ecosystem fragmentation led directly to the backward-compatible ndbi proof-of-concept fork.
    • POE Patterns & Review Stewardship (Kurt Starsinic, H. Merijn Brand / Tux, and Daniël van Eeden): With Tux and Daniël van Eeden following the design thread from July 2026 onward, Kurt stepped up to evaluate how POE::Component::EasyDBI and POE event-loop patterns fit the readiness contract, and Tux both encouraged careful multi-reviewer scrutiny (motivating the 8-commit split and Reviewer’s Guide) and suggested Kurt as an arbiter for the PR #185 review.
    • Security Hardening & Driver Adoption (Robert Rothenberg / robrwo and Ed Sabol / esabol): Robert (CPAN Security Group) contributed an incisive review catching unconditional err == -1 suppression, file-static ithreads lifetimes, statement-level capability gates, DESTROY across fork(), and mortal accumulation in fetch_async_*, while Ed asked, “What do we need to do for DBD::Pg? PR welcome!”

    Answering that question led to building and testing 8 companion pull requests spanning traditional C/XS SQL sockets, timer-polled ODBC handles, and HTTP/2 multiplexed gRPC cloud databases:

    DriverPull RequestTransport & Verification Highlights
    DBD::Pg (Debian)bucardo/dbdpg#224libpq (PG_ASYNC, PQsocket, PQflush); verified against live PostgreSQL 17 (14/14 new t/09async_dbi.t + 127/127 existing t/08async.t PASS)
    DBD::mysql (Debian)DBD-mysql#505C client mysql_async, mysql_async_ready, mysql_async_result, and net.fd socket readiness
    DBD::MariaDB (Debian)DBD-MariaDB#257Non-blocking MariaDB wire state machine (mariadb_async_* and sock_fd)
    DBD::ODBCDBD-ODBC#35ODBC SQL_ATTR_ASYNC_ENABLE / SQL_STILL_EXECUTING timer-driven polling without requiring a POSIX socket FD
    DBD::Spannergoogle-auth-library-perl#42Concurrent statement execution over multiplexed HTTP/2 gRPC (AsyncMultiplex => 1) with legacy-DBI fallback
    DBD::BigQuerygoogle-auth-library-perl#43Async JobServiceClient polling plus optional lazy-loaded Storage Read API and PDL::IO::Arrow columnar batch side-loading
    DBD::Bigtablegoogle-auth-library-perl#44GoogleSQL v2 ExecuteQuery streaming over non-blocking HTTP/2 gRPC (AsyncMultiplex => 1)
    DBD::Datastoregoogle-auth-library-perl#45GQL v1 RunQuery over non-blocking HTTP/2 gRPC (AsyncMultiplex => 1)

    Exercising all eight drivers against live databases and event loops immediately surfaced subtleties a synthetic mock could have missed: exempting diagnostic accessors ($sth->err, errstr, state, and set_err) from the active-handle concurrency guard during live PostgreSQL 17 runs; switching DBI::AsyncWatcher from Perl’s FD-aliasing '<&=' mode to dup(2)-backed '<&' so watcher garbage collection never closes a driver’s underlying socket; standardizing async_read_ready() return values (0 while pending, row count or '0E0' on completion, undef strictly on error); supporting non-FD drivers like DBD::ODBC via timer polling; and proving pure-Perl dual-DBI compatibility via defined(&DBI::is_wouldblock) so updated drivers remain installable on older DBI releases.


    5. Open Design Questions: Looking for Community Feedback

    Because a core DBI contract will live for decades once released, getting the ergonomics and edge cases right matters far more than merging quickly. We would especially value maintainer and user feedback on five open design questions:

    1. fetch_async_row() yield convention: Should fetch_async_row() return the DBI_ASYNC_WOULDBLOCK sentinel on a non-blocking yield, or should it return undef (using $sth->{AsyncWantRead} to distinguish a temporary pause from end-of-stream) so a naive while (my $row = $sth->fetch_async_row) loop can never accidentally dereference a truthy sentinel?
    2. Signaling WOULDBLOCK via $h->err vs. handle attributes: Is signaling would-block via $h->err (analogous to POSIX EAGAIN, strictly gated on Async => 1) ergonomic for Perl callers, or is leaving $h->err untouched on yield and inspecting $h->{AsyncWantRead} cleaner?
    3. DBI::AsyncWatcher packaging: Should the lazy-loaded event-loop adapters in DBI::AsyncWatcher ship in DBI core (where they introduce zero hard dependencies), or live in a separate CPAN distribution so adapter release cadence stays decoupled from DBI?
    4. Driver capability opt-in: Is checking for a driver-implemented async_read_ready method the cleanest capability gate for Async => 1, or would DBD::* authors prefer an explicit driver capability flag?
    5. Additional DBD::* prototypes: Which other driver maintainers (for example DBD::Oracle, DBD::SQLite, DBD::Firebird, or DBD::DB2) would like to test or co-author non-blocking prototypes against perl5-dbi/dbi#185?

    If you maintain a DBD::* driver, work on IO::Async, Future::AsyncAwait, AnyEvent, POE, or Mojolicious, or run high-concurrency Perl services in production, please check out the PR #185 Reviewer’s Guide and share your thoughts on perl5-dbi/dbi#185, the RFC issue (#183), or the perl.dbi.dev mailing list thread.