-
-
Notifications
You must be signed in to change notification settings - Fork 0
Connection API
wind111-lang edited this page Jul 9, 2026
·
1 revision
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.
public function __construct(PDO $pdo)Wraps a PDO instance and configures it with:
PDO::ATTR_ERRMODE = PDO::ERRMODE_EXCEPTIONPDO::ATTR_DEFAULT_FETCH_MODE = PDO::FETCH_ASSOC
$connection = new Connection(new PDO('sqlite::memory:'));public function execute(string $sql, array $params = []): intExecutes 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
public function fetchOne(string $sql, array $params = []): ?arrayFetches one row as an associative array.
$row = $connection->fetchOne(
'SELECT * FROM users WHERE id = :id',
['id' => 1],
);Returns null when no row is found.
public function fetchAll(string $sql, array $params = []): arrayFetches all rows as associative arrays.
$rows = $connection->fetchAll('SELECT * FROM users ORDER BY name ASC');public function driverName(): stringReturns the PDO driver name.
if ($connection->driverName() === 'pgsql') {
// PostgreSQL-specific behavior
}public function lastInsertId(): stringReturns PDO's last insert ID.
$id = $connection->lastInsertId();Sumire uses this for generated IDs on SQLite and MySQL.
public function quoteIdentifier(string $identifier): stringQuotes 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" |
public function transaction(callable $callback): mixedRuns 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.