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 (Box primitives using (object))
$sth->execute($ctx, [(object)10]);

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

Modules

Class Variables

$DRIVERS_H

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

A cache for driver handles. The keys are driver names (e.g., "SQLite"), and the values are their corresponding driver handle objects (DBI::Dr). This cache is used by "connect" to reuse existing driver instances.

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.

This method performs the following:

  1. Parses the $dsn to identify the driver name (e.g., "SQLite" in "dbi:SQLite:...").

  2. Checks the internal driver cache "$DRIVERS_H". If an instance of the driver already exists, it is reused.

  3. If the driver is not cached, it loads the corresponding driver class (e.g., DBD::SQLite), creates a new instance, and stores it in the "$DRIVERS_H" cache for future use.

  4. Calls the connect method of the driver and returns a database handle (DBI::Db).

$options is an array of key-value pairs. Supported options are defined in option_names.

Exceptions:

  • If $dsn is not defined.

  • If the DSN format is invalid.

  • If the driver class cannot be loaded or an error occurs during connection.

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