Skip to content

Connection API

wind111-lang edited this page Jul 9, 2026 · 1 revision

Connection API

Sumire\Connection is a small wrapper around PDO.

Most application code should use Database, but Connection is useful for schema setup, raw SQL, and integration with existing SQL code.

__construct()

public function __construct(PDO $pdo)

Wraps a PDO instance and configures it with:

  • PDO::ATTR_ERRMODE = PDO::ERRMODE_EXCEPTION
  • PDO::ATTR_DEFAULT_FETCH_MODE = PDO::FETCH_ASSOC
$connection = new Connection(new PDO('sqlite::memory:'));

execute()

public function execute(string $sql, array $params = []): int

Executes a statement and returns the affected row count.

$affected = $connection->execute(
    'UPDATE users SET active = :active WHERE id = :id',
    ['active' => false, 'id' => 1],
);

Parameters are bound with PDO types:

  • null -> PDO::PARAM_NULL
  • bool -> PDO::PARAM_BOOL
  • int -> PDO::PARAM_INT
  • everything else -> PDO::PARAM_STR

fetchOne()

public function fetchOne(string $sql, array $params = []): ?array

Fetches one row as an associative array.

$row = $connection->fetchOne(
    'SELECT * FROM users WHERE id = :id',
    ['id' => 1],
);

Returns null when no row is found.

fetchAll()

public function fetchAll(string $sql, array $params = []): array

Fetches all rows as associative arrays.

$rows = $connection->fetchAll('SELECT * FROM users ORDER BY name ASC');

driverName()

public function driverName(): string

Returns the PDO driver name.

if ($connection->driverName() === 'pgsql') {
    // PostgreSQL-specific behavior
}

lastInsertId()

public function lastInsertId(): string

Returns PDO's last insert ID.

$id = $connection->lastInsertId();

Sumire uses this for generated IDs on SQLite and MySQL.

quoteIdentifier()

public function quoteIdentifier(string $identifier): string

Quotes a table or column identifier for the current driver.

$column = $connection->quoteIdentifier('users.email');

Driver behavior:

Driver Example
MySQL `users`.`email`
SQL Server [users].[email]
Default, including SQLite/PostgreSQL "users"."email"

transaction()

public function transaction(callable $callback): mixed

Runs a callback inside a transaction.

$connection->transaction(function (Connection $connection): void {
    $connection->execute('INSERT INTO logs (message) VALUES (:message)', [
        'message' => 'created',
    ]);
});

If the callback throws, the transaction is rolled back and the original exception is rethrown.

Clone this wiki locally