NAME

DBIx::Class::Async::Schema - Non-blocking, worker-pool based Proxy for DBIx::Class::Schema

VERSION

Version 0.56

SYNOPSIS

use IO::Async::Loop;
use DBIx::Class::Async::Schema;

my $loop = IO::Async::Loop->new;

# Connect returns a proxy object immediately
my $schema = DBIx::Class::Async::Schema->connect(
    "dbi:SQLite:dbname=myapp.db", undef, undef, {},
    {
        schema_class   => 'MyApp::Schema',
        workers        => 4,
        enable_metrics => 1,
        loop           => $loop,
    }
);

# Use the 'await' helper for one-off scripts
my $count = $schema->await( $schema->resultset('User')->count_future );

# Or use standard Future chaining for web/event apps
$schema->resultset('User')->find_future(1)->then(sub {
    my $user = shift;
    print "Found async user: " . $user->name;
})->retain;

DESCRIPTION

DBIx::Class::Async::Schema acts as a non-blocking bridge to your standard DBIx::Class schemas. Instead of executing queries in the main event loop (which would block your UI or web server), this module offloads queries to a managed pool of background worker processes.

METHODS

connect

my $schema = DBIx::Class::Async::Schema->connect($dsn, $user, $pass, $dbi_attrs, \%async_attrs);

Initialises the worker pool and returns a proxy schema instance.

  • schema_class (Required): The name of your existing DBIC Schema class.

  • workers: Number of background processes (Default: 2).

  • loop: An IO::Async::Loop instance. If not provided, one will be created.

  • enable_retry: Automatically retry deadlocks/transient errors.

resultset

my $rs = $schema->resultset('Source');

Returns a DBIx::Class::Async::ResultSet object. This RS behaves like standard DBIC but provides *_future variants (e.g., all_future, count_future).

METADATA & REFLECTION

source( $source_name )

Returns the DBIx::Class::ResultSource for the given name.

Unlike standard DBIC, this uses a persistent metadata provider (a cached internal schema) to ensure that ResultSource objects remain stable across async calls without re-connecting to the database unnecessarily.

sources()

Returns a list of all source names available in the schema. This creates a temporary, light-weight connection to extract the current schema structure and then immediately disconnects to save resources.

class( $source_name )

Returns the Result Class string (e.g., MyApp::Schema::Result::User) for the given source. Useful for dynamic inspections.

schema_class()

Returns the name of the base DBIx::Class schema class being proxied.

schema_version()

Returns the version number defined in your DBIC Schema class, if available.

TRANSACTION MANAGEMENT

txn_begin / txn_commit / txn_rollback

These methods return Future objects. Because workers are persistent, calling txn_begin pins your current logic to a specific worker until commit or rollback is called.

Note: Use these carefully in an async loop to avoid "Worker Starvation" where all workers are waiting on long-running manual transactions.

txn_batch( @operations | \@operations )

The high-performance alternative to manual transactions. It sends a "bundle" of operations to a worker to be executed in a single atomic block.

$schema->txn_batch(
    { type      => 'create',
      resultset => 'User',
      data      => { name => 'Alice' }
    },
    { type      => 'update',
      resultset => 'Stats',
      data      => { count => 1 },
      where     => { id    => 5 }
    }
);

LIFECYCLE & STATE

clone( workers => $count )

Creates a fresh instance of the Async Schema. This is useful if you need a separate pool of workers for "heavy" reporting queries vs. "light" web queries.

disconnect()

Gracefully shuts down all background worker processes and flushes the metadata caches. Use this during app shutdown to prevent zombie processes.

storage()

Returns the DBIx::Class::Async::Storage::DBI wrapper. This is provided for compatibility with components that expect to inspect the DBIC storage layer.

UTILITIES

populate( $source_name, \@data )

Performs a high-speed bulk insert. This delegates to the ResultSet's populate logic and is significantly faster than calling create in a loop.

search_with_prefetch( $source_name, \%cond, \@prefetch, \%attrs )

A specialised shortcut for complex joins. It forces collapse => 1 to ensure that the data structure returned from the worker process is properly "folded" into objects, preventing Cartesian product issues over IPC.

FUTURE HANDLING & UNWRAPPING

This package provides methods to handle Future objects, including recursive unwrapping for complex async operations and methods for parallel execution.

await

my $data = $schema->await($future);
my @data_list = $schema->await($future);

Suspends the current process, running the underlying IO::Async::Loop until the provided Future is ready.

This method implements recursive unwrapping of nested Futures. If the top-level Future resolves to another Future (e.g., a txn_do call), this method will continue to resolve them until the final data payload is reached.

Throws an exception immediately if the Future chain fails.

Returns the final "leaf" value(s) to the caller. The return value respects the context of the caller (list or scalar).

run_parallel

my $combined_future = $schema->run_parallel(
    sub { $_[0]->resultset('User')->find_future(1) },
    sub { $_[0]->resultset('Log')->count_future() },
);

Takes a list of coderefs, executes them concurrently passing the schema object as the first argument, and returns a single Future. This returned Future resolves to a list of all results when all tasks have completed.

Note: The coderefs passed to this method must return a Future object. Typically, you would use async methods like find_future or search_future within these coderefs.

await_all

my ($user, $log_count) = $schema->await_all($combined_future);
# OR
my ($user, $log_count) = $schema->await_all($f1, $f2);

Takes a single combined Future (like one returned by "run_parallel") or a list of individual Future objects.

It uses "await" to synchronously wait for all provided Futures to resolve, and returns the final data results in the same order as the inputs.

Throws an exception if any of the Futures fail.

CUSTOM INFLATION & SERIALISATION

Because this module uses a Worker-Pool architecture, data must travel across process boundaries. Standard Perl objects (like DateTime or JSON blobs) cannot simply be "shared" as live memory.

DBIx::Class::Async::Schema automatically detects your DBIC inflate_column definitions and mirrors them in the Worker processes.

How it works

1. Deflation (Main to Worker)

When you pass an object to create or update, the bridge deflates it into a storable format before sending it to the worker.

2. Inflation (Worker to Main)

When results come back, the bridge automatically re-applies your inflate coderefs to turn raw strings back into rich objects.

JSON Support

The new design includes built-in support for serializer_class => 'JSON'. If detected in your ResultSource metadata, it will automatically handle the decode/encode cycle using JSON in a non-blocking manner.

Manual Registration

If you have complex objects that aren't handled by standard DBIC inflation, you can register them manually:

$schema->inflate_column('User', 'preferences', {
    inflate => sub { my $val = shift; decode_json($val) },
    deflate => sub { my $obj = shift; encode_json($obj) },
});

PERFORMANCE TIPS

Worker Count

Adjust the workers parameter based on your database connection limits. Typically 2-4 workers per CPU core works well. Each worker maintains its own persistent DB connection.

Prefetching

Use search_with_prefetch to fetch related data in one trip across the process boundary. This significantly reduces the overhead of IPC (Inter-Process Communication).

ERROR HANDLING

All methods return Future objects. Errors from workers (SQL errors, timeouts, connection drops) are propagated as Future failures. Use ->catch or try/catch with await.

STATISTICS & METRICS

If enable_metrics is enabled, you can query the internal state:

  • total_queries(): Total operations processed.

  • cache_hits(): Operations resolved via the internal cache.

  • error_count(): Total failed operations.

EXTENSIBILITY & AUTOLOAD

If you call a method on this object that is not defined in the Async package, it will attempt to proxy the call to the Native DBIC Schema.

This allows you to use custom methods defined in your MyApp::Schema class seamlessly. However, be aware that calls made via AUTOLOAD are executed in the Parent Process context and may be blocking unless they specifically return a Future.

AUTHOR

Mohammad Sajid Anwar, <mohammad.anwar at yahoo.com>

REPOSITORY

https://github.com/manwar/DBIx-Class-Async

BUGS

Please report any bugs or feature requests through the web interface at https://github.com/manwar/DBIx-Class-Async/issues. I will be notified and then you'll automatically be notified of progress on your bug as I make changes.

SUPPORT

You can find documentation for this module with the perldoc command.

perldoc DBIx::Class::Async::Schema

You can also look for information at:

LICENSE AND COPYRIGHT

Copyright (C) 2026 Mohammad Sajid Anwar.

This program is free software; you can redistribute it and / or modify it under the terms of the the Artistic License (2.0). You may obtain a copy of the full license at: http://www.perlfoundation.org/artistic_license_2_0 Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License.By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. If your Modified Version has been derived from a Modified Version made by someone other than you,you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement,then this Artistic License to you shall terminate on the date that such litigation is filed. Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.