PHP Luminova: PDO Database Driver
Luminova’s PDO driver for database connections, query execution, transactions, and native PDO access.
The PdoDriver class is Luminova's PDO based database driver. It implements DatabaseDriverInterface and gives you one API for prepared statements, value binding, result fetching, transactions, savepoints, and database level locks.
You normally don't create it yourself. The Connection class builds it when the connection setting is pdo.
Getting Started
Get the driver from a connection instance:
use Luminova\Database\Connection;
$db = Connection::getInstance()->database();Or create a standalone driver from a configuration object:
use App\Config\Database;
use Luminova\Database\Connection;
$db = Connection::with(Database::fromArray([
'connection' => 'pdo',
'pdo_driver' => 'mysql',
'host' => 'localhost',
'port' => 3306,
'database' => 'my_db',
'username' => 'root',
'password' => 'password',
]));Configuration keys used by this driver:
| Key | Default | Description |
|---|---|---|
pdo_driver | mysql | PDO driver name. Supported: mysql, pgsql, sqlite, sqlsrv, dblib, cubrid, oci. Any other value throws a DatabaseException. |
host | localhost | Database server host. |
port | 3306 | Database server port. |
database | '' | Database name. |
username | root | Database username. Ignored for SQLite. |
password | '' | Database password. Ignored for SQLite. |
charset | utf8mb4 | Connection charset. utf8 and utf-8 are converted to utf8mb4. |
sqlite_path | null | Path to the SQLite file. Required when pdo_driver is sqlite. |
emulate_prepares | true | Sets PDO::ATTR_EMULATE_PREPARES. |
persistent | false | Sets PDO::ATTR_PERSISTENT. Always enabled when running in the CLI. |
socket | false | MySQL only. Connect through a Unix socket instead of TCP. |
socket_path | '' | MySQL only. Unix socket path. |
buffered_query | false | MySQL only. Sets PDO::MYSQL_ATTR_USE_BUFFERED_QUERY. |
timeout | 0 | MySQL only. Sets PDO::ATTR_TIMEOUT in seconds when greater than zero. |
commands | [] | MySQL only. List of SET statements to run when the connection opens. |
Additional Notes
Error mode and fetch mode:The driver always connects with
PDO::ERRMODE_EXCEPTIONandPDO::FETCH_OBJas the default fetch mode.Unix socket (MySQL):A socket connection is used when running in the CLI, when
socketistrue, or when running inside thenovakitcontainer. The driver readssocket_path, then falls back topdo_mysql.default_socketfromphp.ini. ADatabaseExceptionis thrown when neither is set.Init commands (MySQL):Only
SETstatements are allowed incommands, any other statement throws aDatabaseException. If none of them is aSET NAMESstatement,SET NAMES <charset>is added automatically.SSL (MySQL):Server certificate verification is turned on in production.
Missing connection:Methods that need a live connection throw a
DatabaseExceptionwhen called beforeconnect()or afterclose().Differences from MySQLi:Row counts, binding lifetime, and savepoint handling differ between the two drivers. See Driver differences in the MySQLi driver docs.
Basic Usage
Select rows with a prepared statement:
use Luminova\Database\Connection;
$db = Connection::getInstance()->database();
$db->prepare('SELECT * FROM users WHERE status = :status')
->bind(':status', 'active')
->execute();
$users = $db->fetchAll();Insert a row and read its ID:
$db->prepare('INSERT INTO users (name, email) VALUES (:name, :email)')
->execute([':name' => 'John Doe', ':email' => '[email protected]']);
$id = $db->getLastInsertId();Read rows one at a time:
$db->query('SELECT id, name FROM users');
while ($row = $db->fetchNext()) {
echo $row->name;
}Run a transaction:
use Throwable;
try {
$db->beginTransaction();
$db->prepare('UPDATE accounts SET balance = balance - :amount WHERE id = :id')
->execute([':amount' => 100, ':id' => 1]);
$db->prepare('UPDATE accounts SET balance = balance + :amount WHERE id = :id')
->execute([':amount' => 100, ':id' => 2]);
$db->commit();
} catch (Throwable $e) {
$db->rollback();
throw $e;
}Class Definition
- Class namespace:
Luminova\Database\Driver\PdoDriver - This class is
finaland extendsLuminova\Database\Driver\Helpers\AbstractDatabaseDriver - This class implements: Luminova\Interface\DatabaseDriverInterface
Constants
Inherited from AbstractDatabaseDriver and accessed through the driver class, for example PdoDriver::TRANSACTION_READ_ONLY.
| Constant | Value | Used with |
|---|---|---|
TRANSACTION_MODE_NONE | 0 | Skips changing the transaction mode. |
TRANSACTION_WITH_CONSISTENT_SNAPSHOT | 1 | beginTransaction() flag. |
TRANSACTION_READ_WRITE | 2 | beginTransaction() flag. |
TRANSACTION_READ_UNCOMMITTED | 3 | setTransactionIsolation() level. |
TRANSACTION_READ_ONLY | 4 | beginTransaction() flag. |
TRANSACTION_READ_COMMITTED | 5 | setTransactionIsolation() level. |
TRANSACTION_REPEATABLE_READ | 6 | setTransactionIsolation() level. |
TRANSACTION_SERIALIZABLE | 7 | setTransactionIsolation() level. |
Only
TRANSACTION_WITH_CONSISTENT_SNAPSHOT,TRANSACTION_READ_WRITEandTRANSACTION_READ_ONLYare bit flags. Don't pass isolation level constants tobeginTransaction(), their values overlap with the flag bits.
Methods
constructor
Creates the driver from a configuration object. The PDO driver name is read from pdo_driver and lowercased. It does not connect, call connect() to open the connection.
public function __construct(AbstractConfig $config)Parameters:
| Parameter | Type | Description |
|---|---|---|
$config | AbstractConfig | Database connection configuration. |
getInstance
Returns a shared driver instance, creating it with $config on the first call. The $config argument is ignored on later calls.
public static function getInstance(AbstractConfig $config) : DatabaseDriverInterfaceParameters:
| Parameter | Type | Description |
|---|---|---|
$config | AbstractConfig | The configuration object used to initialize the database instance on first creation. |
The shared instance is stored on
AbstractDatabaseDriver, soPdoDriverand MysqliDriver share one slot. Whichever driver is created first is returned by later calls on either class.
connect
Opens the PDO connection. If the connection already exists, it returns true without reconnecting.
public function connect(): boolReturn:
bool - Return true when connected.
Throws:
- Luminova\Exceptions\DatabaseException - If the PDO driver is unsupported, the SQLite path is missing, an init command is invalid, a socket path is required but missing, or the connection fails. Other errors are wrapped in a
DatabaseException.
isConnected
Checks the driver's connection state. It does not ping the server.
public function isConnected(): boolReturn:
bool - Returns true if connected, false otherwise.
close
Frees the active statement, releases the PDO object, and decrements the open connection count.
public function close(): voidgetDriver
Gets the PDO driver name reported by PDO::ATTR_DRIVER_NAME, for example mysql.
public function getDriver(): ?stringReturn:
string|null - Return the driver name, or null when not connected.
getVersion
Gets the database server version string for the active PDO driver.
public function getVersion(): ?stringReturn:
string|null - Return the version string, or null if it cannot be determined.
getConfig
Gets one configuration value, or all values when $property is null. Property names are trimmed and case insensitive.
public function getConfig(?string $property): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$property | ?string | Configuration property name, case-insensitive. Pass null to retrieve all configuration settings. |
Return:
mixed - Return the value, null for an empty or unknown key, or the full configuration array when $property is null.
getConn
Gets the driver connection wrapper, which gives access to the native PDO object.
public function getConn(): DriverConnectionInterfaceReturn:
DriverConnectionInterface - Returns the driver connection wrapper.
getOpenConnections
Gets the number of open driver connections. The counter is static, so it is shared by all driver instances.
public static function getOpenConnections(): intReturn:
int - Returns the number of open connection.
exists
Checks whether a table exists in the current database. It runs its own prepared statement, so it replaces the current statement.
public function exists(string $table): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$table | string | The table name to check. |
Return:
bool - Returns true if the table exists, otherwise false.
Example:
if ($db->exists('users')) {
// The table is there
}prepare
Prepares an SQL statement and resets the previous query state. Use named placeholders such as :id.
public function prepare(string $query): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$query | string | The SQL query string to prepare. |
Return:
self - Returns the instance of database driver interface.
Throws:
- Luminova\Exceptions\DatabaseException - If there is no active connection.
bind
Binds a value to a named placeholder using PDOStatement::bindValue().
public function bind(string $param, mixed $value, ?int $type = null): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$param | string | Named placeholder, for example :id. |
$value | mixed | The value to bind. |
$type | ?int | A PARAM_* constant or a native PDO::PARAM_* value. null resolves the type from the value with getType(). |
Return:
self - Return the driver instance.
Throws:
- Luminova\Exceptions\DatabaseException - If there is no prepared statement.
PARAM_FLOATis bound as a string, because PDO has no float type.
value
Alias of bind().
public function value(string $param, mixed $value, ?int $type = null): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$param | string | The placeholder named parameter (e.g., ':columnName'). |
$value | mixed | The value to bind. |
$type | ?int | (Optional) The data type for the value (default: null). - PARAM_*, PARAM_* - For MySQLi and PDO driver. - PDO::PARAM_* - For PDO driver only supports custom type. - NULL - Resolve by value internally. |
Return:
self - Returns the instance of database driver interface.
param
Binds a variable by reference using PDOStatement::bindParam(). The variable is read when execute() runs, so changes made before then are used.
public function param(string $param, mixed &$value, ?int $type = null): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$param | string | The placeholder named parameter (e.g., ':columnName'). |
$value | mixed | The variable to bind by reference. |
$type | ?int | (Optional) The data type for the value (default: null). - PARAM_*, PARAM_* - For MySQLi and PDO driver. - PDO::PARAM_* - For PDO driver only supports custom type. - NULL - Resolve by value internally. |
Return:
self - Returns the instance of database driver interface.
Example:
$status = 'active';
$db->prepare('UPDATE users SET status = :status WHERE id = :id')
->param(':status', $status)
->bind(':id', 100);
$status = 'inactive';
$db->execute();getType
Resolves the PDO parameter type for a value.
public static function getType(mixed $value): intParameters:
| Parameter | Type | Description |
|---|---|---|
$value | mixed | The value to evaluate. |
Return:
int - Returns the driver parameter type code.
| Value | Result |
|---|---|
null | PDO::PARAM_NULL |
bool | PDO::PARAM_BOOL |
int | PDO::PARAM_INT |
| resource | PDO::PARAM_LOB |
| string with any byte outside tab, line breaks and printable ASCII | PDO::PARAM_LOB |
| everything else | PDO::PARAM_STR |
The string check is byte based, so multibyte UTF-8 text is resolved as
PDO::PARAM_LOB. Pass an explicit$typetobind()if you needPARAM_STR.
execute
Executes the prepared statement. When $params is given, PDO uses it as the full set of input parameters.
public function execute(?array $params = null): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$params | ?array<array-key,mixed> | Values for the placeholders, keyed by name (:id) or in positional order. |
Return:
bool - Return true on success.
Throws:
- Luminova\Exceptions\DatabaseException - If there is no prepared statement or the execution fails. On failure the statement is freed.
query
Runs an SQL query immediately, without placeholders, and keeps the result for fetching.
public function query(string $query): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$query | string | The SQL query string to execute. |
Return:
self - Returns the instance of database driver interface.
Example:
$users = $db->query('SELECT * FROM users')->fetchAll();exec
Runs an SQL statement without placeholders and returns the affected row count.
public function exec(string $query): intParameters:
| Parameter | Type | Description |
|---|---|---|
$query | string | The SQL query string to execute. |
Return:
int - Return 0 when the statement fails, otherwise the affected rows with a minimum of 1. DDL statements that report no row count return 1.
Example:
$affected = $db->exec("UPDATE users SET status = 'active' WHERE last_login > NOW() - INTERVAL 30 DAY");ok
Checks whether the last query was executed successfully.
public function ok(): boolReturn:
bool - Returns true on success, false on failure.
Example:
$db->prepare('SELECT * FROM users WHERE id = :id')->bind(':id', 100);
$db->execute();
if ($db->ok()) {
$user = $db->fetchNext();
}getResult
Retrieves a result in the shape given by $returnMode.
public function getResult(int $returnMode = RETURN_ALL, int $fetchAS = FETCH_OBJ): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$returnMode | int | The mode of the result to return (e.g., RETURN_*). Available Modes: - RETURN_NEXT: Fetch the next row (same as $db->fetchNext(...)). - RETURN_2D_NUM: Fetch a 2D numeric array (same as $db->getInt()). - RETURN_INT: Fetch a single integer value (same as $db->getCount()). - RETURN_ID: Fetch the last insert ID (same as $db->getLastInsertId()). - RETURN_COUNT: Fetch the count of affected rows (same as $db->rowCount()). - RETURN_COLUMN: Fetch specific columns (same as $db->getColumns()). - RETURN_ALL: Fetch all rows (same as $db->fetchAll(...)). - RETURN_STMT: Return the statement object itself (same as $db->getStatement()). - RETURN_RESULT: Return the query result in MySQLi or statement in PDO. (default RETURN_ALL). |
$fetchAS | int | The result fetch mode (e.g, FETCH_*). Used only with RETURN_NEXT and RETURN_ALL modes. |
Return:
mixed - Returns the result based on the specified mode and return type.
| Return mode | Same as |
|---|---|
RETURN_NEXT | fetchNext($fetchAS) |
RETURN_ALL | fetchAll($fetchAS) |
RETURN_2D_NUM | getInt() |
RETURN_INT | getCount() |
RETURN_ID | getLastInsertId() |
RETURN_COUNT | rowCount() |
RETURN_COLUMN | getColumns() |
RETURN_STMT | getStatement() |
RETURN_RESULT | The PDOStatement, or null when there is none. |
| Any other value | fetch($returnMode, $fetchAS) |
$fetchAS is only used with RETURN_NEXT, RETURN_ALL, and the fallback to fetch().
fetch
Fetches rows from the active statement.
public function fetch(int $returnMode = RETURN_ALL, int $fetchAS = FETCH_OBJ): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$returnMode | int | RETURN_ALL fetches all rows. RETURN_NEXT and RETURN_STREAM fetch one row per call (default RETURN_ALL). |
$fetchAS | int | One of FETCH_ASSOC, FETCH_BOTH, FETCH_OBJ, FETCH_COLUMN, FETCH_KEY_PAIR, FETCH_NUM, FETCH_CLASS. An unknown value falls back to FETCH_OBJ. |
Return:
mixed - Return an array of rows for RETURN_ALL (empty when there are none), or a single row, or false when no more rows are left.
Throws:
- Luminova\Exceptions\DatabaseException - If there is no statement.
With
FETCH_CLASSrows are returned asstdClass. To hydrate your own class, usefetchObject()orfetchAllObject().
Example:
$db->query('SELECT id, name FROM users');
$names = $db->fetch(RETURN_ALL, FETCH_KEY_PAIR);fetchNext
Fetches the next row.
public function fetchNext(int $mode = FETCH_OBJ): array|object|boolParameters:
| Parameter | Type | Description |
|---|---|---|
$mode | int | The result fetch mode (e.g, FETCH_* default: FETCH_OBJ). |
Return:
array<array-key,mixed>|object|bool - Return the row, or false when no more rows are available.
getNext
Alias of fetchNext().
public function getNext(int $mode = FETCH_OBJ): array|object|boolParameters:
| Parameter | Type | Description |
|---|---|---|
$mode | int | The result fetch mode (e.g, FETCH_* default: FETCH_OBJ). |
Return:
array<array-key,mixed>|object|bool - Returns the next row as an object or array, or false if no more rows are available.
fetchAll
Fetches all remaining rows.
public function fetchAll(int $mode = FETCH_OBJ): array|object|boolParameters:
| Parameter | Type | Description |
|---|---|---|
$mode | int | The result fetch mode (e.g, FETCH_* default: FETCH_OBJ). |
Return:
array<array-key,mixed>|object|bool - Return the rows, or false when the result is empty.
getAll
Alias of fetchAll().
public function getAll(int $mode = FETCH_OBJ): array|object|boolParameters:
| Parameter | Type | Description |
|---|---|---|
$mode | int | The result fetch mode (e.g, FETCH_* default: FETCH_OBJ). |
Return:
array<array-key,mixed>|object|bool - Returns an array of result objects or arrays, an empty array if no rows are found or false.
fetchObject
Fetches the next row as an instance of a class. Without $class, a stdClass is returned.
public function fetchObject(?string $class = null, mixed ...$arguments): ?objectParameters:
| Parameter | Type | Description |
|---|---|---|
$class | ?string | Class to instantiate. Defaults to stdClass. |
$arguments | mixed | Constructor arguments passed when creating the class instance. |
Return:
object|null - Return the instance, or null when there is no row.
Example:
$db->prepare('SELECT * FROM users WHERE id = :id');
$db->execute([':id' => 1]);
$user = $db->fetchObject(App\Models\User::class);fetchAllObject
Fetches all remaining rows as instances of a class. Without $class, stdClass objects are returned.
public function fetchAllObject(?string $class = null, mixed ...$arguments): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$class | ?string | Fully qualified class name to instantiate. Defaults to stdClass. (default null). |
$arguments | mixed | Constructor arguments passed when creating class instances. |
Return:
array<array-key,mixed> - Return a list of instances, empty when there are no rows.
getColumns
Fetches all rows using a column oriented fetch mode.
public function getColumns(int $mode = FETCH_COLUMN): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$mode | int | The fetch mode (default: FETCH_COLUMN). |
Return:
array<array-key,mixed> - Return the values of the first column by default, or an empty array.
getInt
Fetches all rows as numeric arrays.
public function getInt(): arrayReturn:
array<array-key,mixed> - Returns a 2D array of integers, or an empty array if no results are found.
getCount
Reads the first value of the first row as an integer, which suits queries like SELECT COUNT(*).
public function getCount(): intReturn:
int - Return the value, or 0 when there are no results.
getLastInsertId
Gets the ID generated by the last INSERT. Pass a sequence name for databases that use sequences, such as PostgreSQL.
public function getLastInsertId(?string $name = null): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$name | ?string | Optional sequence name. Ignored by drivers that do not support named sequences. |
Return:
mixed - Return the ID, or null when there is none or the driver is not connected.
rowCount
Gets the number of rows affected or returned by the active statement, as reported by PDOStatement::rowCount().
public function rowCount(): intReturn:
int - Returns the number of affected rows.
columnCount
Gets the number of columns in the active result set.
public function columnCount(): intReturn:
int - Returns the number of result columns.
getStatement
Gets the active PDOStatement.
public function getStatement(): ?PDOStatementReturn:
PDOStatement|null - The last prepared statement, or null if unavailable.
isStatement
Checks whether there is an active PDOStatement.
public function isStatement(): boolReturn:
bool - Returns true if is a prepared statement, false otherwise.
isResult
Checks whether the last operation was run through query() or exec() and nothing has been bound since.
public function isResult(): boolReturn:
bool - Returns true if query result, false otherwise.
hasActiveCursor
Checks whether the active statement has columns, meaning it can return rows. This method exists on PdoDriver only.
public function hasActiveCursor(): boolReturn:
bool - Returns true when an active statement has result columns.
free
Closes the statement cursor and clears the active statement.
public function free(): voidbeginTransaction
Starts a transaction, optionally with flags and a savepoint name.
public function beginTransaction(int $flags = self::TRANSACTION_MODE_NONE, ?string $name = null): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$flags | int | Combine TRANSACTION_WITH_CONSISTENT_SNAPSHOT, TRANSACTION_READ_WRITE and TRANSACTION_READ_ONLY with \|. They are sent as START TRANSACTION ... (default self::TRANSACTION_MODE_NONE). |
$name | ?string | Creates a savepoint with this name after the transaction starts. Required when a transaction is already active. |
Return:
bool - Return true when the transaction (and savepoint) started.
Throws:
- Luminova\Exceptions\DatabaseException - If a transaction is active and
$nameis null, the savepoint name is invalid or already used, or the transaction fails to start.
Example:
$db->beginTransaction(
PdoDriver::TRANSACTION_WITH_CONSISTENT_SNAPSHOT | PdoDriver::TRANSACTION_READ_ONLY
);tryBeginTransaction
Same as beginTransaction(), but returns false instead of throwing.
public function tryBeginTransaction(
int $flags = self::TRANSACTION_MODE_NONE,
?string $name = null
): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$flags | int | Transaction flags. Defaults to self::TRANSACTION_MODE_NONE. (default self::TRANSACTION_MODE_NONE). |
$name | ?string | Optional savepoint name when supported. (default null). |
Return:
bool - Returns true on success, or false if the transaction cannot start.
beginNestedTransaction
Starts a transaction when none is active, otherwise creates a savepoint with a generated name.
public function beginNestedTransaction(
int $flags = self::TRANSACTION_MODE_NONE,
bool $closeCursor = false
): string|bool|nullParameters:
| Parameter | Type | Description |
|---|---|---|
$flags | int | Transaction flags, used only when a new transaction starts (default self::TRANSACTION_MODE_NONE). |
$closeCursor | bool | Free the active statement before starting (default false). |
Return:
string|bool|null - Return null when a new transaction started, the savepoint name for a nested transaction, or false on failure.
Example:
$name = $db->beginNestedTransaction();
if ($name === false) {
return;
}
try {
// Run queries...
if ($name !== null) {
$db->release($name);
} else {
$db->commit();
}
} catch (Throwable $e) {
$db->rollback();
throw $e;
}tryBeginNestedTransaction
Same as beginNestedTransaction(), but returns false instead of throwing.
public function tryBeginNestedTransaction(
int $flags = self::TRANSACTION_MODE_NONE,
bool $closeCursor = false
): string|bool|nullParameters:
| Parameter | Type | Description |
|---|---|---|
$flags | int | Transaction flags. Defaults to self::TRANSACTION_MODE_NONE. (default self::TRANSACTION_MODE_NONE). |
$closeCursor | bool | Whether to free the active statement cursor before starting. (default false). |
Return:
string|bool|null - Returns: - string: The savepoint name when a nested transaction is created. - null: A new transaction was started successfully. - false: Failed to start a transaction or create a savepoint.
savepoint
Creates a savepoint inside the active transaction.
public function savepoint(string $name): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string | The name for a savepoint. |
Return:
bool - Returns true on success or false on failure.
Names are cleaned before use: characters other than letters, digits and underscores are removed, purely numeric names get a tnx_ prefix, and the result is cut to 64 characters. The same cleaning is applied in commit(), rollback() and release(), so you can pass the original name to them.
Throws:
- Luminova\Exceptions\DatabaseException - If there is no active transaction, the name is empty after cleaning, or the savepoint already exists.
commit
Commits the active transaction, or releases a savepoint when $name is given. Returns true when no transaction is active.
public function commit(int $flags = 0, ?string $name = null): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$flags | int | Optional flags for custom handling. (default 0). |
$name | ?string | Optional name for a savepoint. |
Return:
bool - Returns true if the transaction was successfully committed.
$flagsis not used by the PDO driver.
Throws:
- Luminova\Exceptions\DatabaseException - If the savepoint does not exist or the commit fails.
rollback
Rolls back the active transaction, or rolls back to a savepoint when $name is given. Returns true when no transaction is active.
public function rollback(int $flags = 0, ?string $name = null): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$flags | int | Optional flags for custom handling (MySQLi only). (default 0). |
$name | ?string | Optional name of the savepoint to roll back to. If provided, rolls back to the savepoint in PDO. |
Return:
bool - Returns true if the rollback was successful, otherwise false.
$flagsis not used by the PDO driver.
Throws:
- Luminova\Exceptions\DatabaseException - If the savepoint does not exist or the rollback fails.
release
Releases a savepoint without ending the transaction. Returns false when no transaction is active.
public function release(string $name): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string | The savepoint name to release. |
Return:
bool - Returns true on success or false on failure.
inTransaction
Checks whether a transaction is active, using the native PDO::inTransaction().
public function inTransaction(): boolReturn:
bool - Returns true if there is an active transaction, otherwise false.
setTransactionIsolation
Sets the isolation level with SET TRANSACTION ISOLATION LEVEL. Call it before a transaction starts.
public function setTransactionIsolation(int $level = self::TRANSACTION_READ_COMMITTED): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$level | int | TRANSACTION_READ_UNCOMMITTED, TRANSACTION_READ_COMMITTED, TRANSACTION_REPEATABLE_READ or TRANSACTION_SERIALIZABLE. TRANSACTION_MODE_NONE does nothing and returns true. |
Return:
bool - Returns true on success, or false otherwise.
Throws:
- Luminova\Exceptions\DatabaseException - If the level is invalid, a transaction is already active, or the database rejects the statement.
TRANSACTION_READ_WRITEandTRANSACTION_READ_ONLYare not isolation levels. Pass them as flags tobeginTransaction()instead.
lock
Acquires a named database lock and waits up to $timeout seconds.
public function lock(string|int $identifier, int $timeout = 300): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$identifier | string|int | Lock identifier. |
$timeout | int | Maximum time in seconds to wait for acquiring the lock. |
Return:
bool - Return true if the lock was acquired.
The lock mechanism depends on the database: MySQL named locks, PostgreSQL advisory locks (non numeric identifiers are hashed), and for SQLite a lease table named dbms_locks, created on first use. $timeout does not apply to PostgreSQL.
Example:
if ($db->lock('daily-report', 30)) {
try {
// Do the work
} finally {
$db->unlock('daily-report');
}
}tryLock
Attempts to acquire a lock without waiting.
public function tryLock(string|int $identifier): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$identifier | string|int | Lock identifier. |
Return:
bool - Returns true if the lock was acquired, false if it is already held or acquisition failed.
This method currently returns
falsewhatever the outcome. The result is stored internally, so callisLocked()to find out whether the lock was acquired.
unlock
Releases a named lock.
public function unlock(string|int $identifier): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$identifier | string|int | Lock identifier. |
Return:
bool - Returns true if the lock was released successfully, false otherwise.
isLocked
Checks whether a lock is held. A lock acquired or released through this driver instance is answered from memory, otherwise the database is queried.
public function isLocked(string|int $identifier): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$identifier | string|int | Lock identifier. |
Return:
bool - Returns true if the lock is currently held, false if it is available.
error
Gets the last error message from the active statement, or from the connection when there is no statement.
public function error(): stringReturn:
string - Return the message, an empty string if none, or Connection not established when not connected.
errors
Gets statement and connection error details.
public function errors(): arrayReturn:
array<string,array<string,mixed>> - Returns statement and connection error details.
| Key | Type | Description |
|---|---|---|
statement.errno | string|int | SQLSTATE code, or -1 when there is no statement. |
statement.error | string|null | Driver error message, or null. |
statement.num_rows | int|null | Row count of the statement, or null when there is no statement. |
connection.errno | string|int | SQLSTATE code, or -1 when not connected. |
connection.error | string|null | Driver error message, or Connection not established. |
info
Gets the parsed PDO::ATTR_CONNECTION_STATUS value as key and value pairs.
public function info(): arrayReturn:
array<array-key,mixed> - Return ['status' => 'disconnected'] when not connected, ['status' => 'idle'] when the driver reports nothing, otherwise the parsed pairs (empty if the status text has no key: value parts).
setDebug
Enables or disables debug mode.
public function setDebug(bool $debug): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$debug | bool | Enable or disable debug mode. |
Return:
self - Returns the instance of database driver interface.
dumpDebug
Dumps the active statement's parameters with PDOStatement::debugDumpParams() when debug mode is on.
public function dumpDebug(): boolReturn:
bool - Return false when debug mode is off or there is no statement.
profiling
Starts or stops query timing. Timing is recorded only when profiling is enabled by the debug.show.performance.profiling environment setting. The driver calls it for you around each query, so you rarely need it directly.
public function profiling(
bool $start = true,
bool $finishedTransaction = false,
?string $fn = null
): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$start | bool | Whether to start profiling; false stops profiling. (default true). |
$finishedTransaction | bool | Whether profiling is being stopped after a transaction has been committed or rolled back. (default false). |
$fn | ?string | (default null). |
While a transaction is active, timing is held back until the transaction is committed or rolled back. Results are stored under Runtime::QUERY_PROFILING:
use Luminova\Runtime;
$profiling = Runtime::get(Runtime::QUERY_PROFILING);getQueryTime
Gets the total query execution time in seconds.
public function getQueryTime(): float|intReturn:
float|int - Returns the total query execution time in seconds.
getLastQueryTime
Gets the last query execution time in seconds.
public function getLastQueryTime(): float|intReturn:
float|int - Returns the last query execution time in seconds.
Both timing methods return
0unless profiling is enabled.
enableNamedPlaceholder
Enable or disable named placeholder handling.
public function enableNamedPlaceholder(bool $enabled = true): staticParameters:
| Parameter | Type | Description |
|---|---|---|
$enabled | bool | Whether to enable named placeholders (default true). |
Return:
static - Returns the current driver.
isNamedPlaceholderEnabled
Check whether the driver supports named placeholders.
public function isNamedPlaceholderEnabled(): boolReturn:
bool - Returns true when named placeholders are supported.