Name

SPVM::DBI - Database Independent Interface

Description

DBI class in SPVM provides a database-independent interface for database connections. It acts as a factory to create a database handle (DBI::Db) by loading the appropriate driver (DBI::Dr).

Caution

SPVM::DBI is under early development. This is an alpha release.

This module is not yet tested and is in a highly experimental stage. The interface and implementation are subject to change without notice. Use this module at your own risk. It is not recommended for production use.

Usage

use DBI;
use DBD::SQLite;
use Go::Context;

my $ctx = Go::Context->new;
my $dsn = "dbi:SQLite:dbname=:memory:";

# 1. Connect to a database
my $dbh = DBI->connect($ctx, $dsn, "user", "password");

# 2. Prepare a statement
my $sql = "SELECT id, name FROM users WHERE id > ?";
my $sth = $dbh->prepare($ctx, $sql);

# 3. Execute with bind values
$sth->execute($ctx, [(object)10]);

# 4. Fetch rows in a while loop (Simple usage)
while (my $row = $sth->fetch($ctx)) {
  my $id   = $row->[0]->(int);
  my $name = $row->[1]->(string);
  
  # Process the data...
}

# 5. Fast fetch with buffer reuse (Zero-allocation)
# Prepare the "vessels" (objects) in advance to avoid allocations inside the loop.
# Use new_string_len to allocate a string buffer without redundant initialization.
my $columns = [(object)Int->new(0), new_string_len 100]; 
my $ret_row = new object[2];

while (my $row = $sth->fetch($ctx, $columns, $ret_row)) {
  # The driver updates the existing objects in $columns.
  # $row is the same as $ret_row.
  my $id   = $row->[0]->(int);
  my $name = $row->[1]->(string);
  
}

Modules

Class Variables

$DRIVERS_H

our $DRIVERS_H : cache Hash of DBI::Dr;

A cache for driver handles.

Class Methods

connect

static method connect : DBI::Db ($ctx : Go::Context, $dsn : string, $user : string = undef, $password : string = undef, $options : object[] = undef)

Establishes a connection to the database specified by the $dsn.

For more information about the available options that can be passed in $options (such as timeouts and TCP settings), please see the DBI::Dr#connect method.

This method performs the following steps:

1. DSN Parsing

Validates the $dsn and parses it to extract the driver name (e.g., extracting "SQLite" from "dbi:SQLite:dbname=:memory:").

2. Driver Resolution

Checks the internal cache "$DRIVERS_H". If the driver (e.g., DBD::SQLite) is already loaded, it reuses the existing driver instance.

3. Dynamic Driver Creation

If the driver is not in the cache, creates a new instance of the driver class calling new method. The new instance is then stored in the cache.

4. Handover to Driver

Calls the connect method of the resolved driver handle (DBI::Dr) to obtain a database handle (DBI::Db).

See Also

DBI::Db, DBI::Dr, Go::Context

Repository

https://github.com/yuki-kimoto/SPVM-DBI

Author

Yuki Kimoto kimoto.yuki@gmail.com

Copyright & License

Copyright (c) 2026 Yuki Kimoto

MIT License