Pular para o conteúdo principal

Database Driver Interface

The DbDriverInterface is the core interface for all database drivers in AnyDataset-DB. It defines the standard methods that all database drivers must implement, providing a consistent API for interacting with different database systems.

Important

As of version 6.0, some high-level query methods in DbDriverInterface are deprecated in favor of using DatabaseExecutor. See the deprecation section below and the DatabaseExecutor documentation for the recommended approach.

Interface Definition

All drivers in the AnyDataset-DB library implement this interface, which extends DbTransactionInterface:

interface DbDriverInterface extends DbTransactionInterface
{
// Methods to implement
}

Available Methods

Connection Management

MethodDescription
schema()Static method that returns the supported schema(s) for the driver (e.g., 'mysql', 'pgsql')
isConnected(bool $softCheck = false, bool $throwError = false): boolChecks if the connection is active
reconnect(bool $force = false): boolRe-establishes a connection to the database
disconnect(): voidCloses the connection to the database
getDbConnection(): mixedReturns the low-level database connection object
getUri(): UriReturns the connection URI

Low-Level Query Execution

MethodDescription
prepareStatement(string $sql, ?array $params = null, ?array &$cacheInfo = []): mixedPrepares an SQL statement for execution
executeCursor(mixed $statement): voidExecutes a prepared statement
processMultiRowset(mixed $statement): voidProcesses multiple result sets
getDriverIterator(mixed $statement, int $preFetch = 0, ?string $entityClass = null, ?PropertyHandlerInterface $entityTransformer = null): GenericDbIterator|GenericIteratorCreates a driver-specific iterator from a statement

High-Level Query Execution (Deprecated)

Deprecated

Deprecated in version 6.0, will be removed in version 7.0. Use DatabaseExecutor instead for these operations.

MethodDescriptionReplacement
getIterator(string|SqlStatement $sql, ?array $params = null, int $preFetch = 0): GenericDbIterator|GenericIteratorExecutes a SELECT query and returns an iteratorDatabaseExecutor::using($driver)->getIterator()
getScalar(mixed $sql, ?array $array = null): mixedReturns a single value from the first column of the first rowDatabaseExecutor::using($driver)->getScalar()
execute(mixed $sql, ?array $array = null): boolExecutes a non-query SQL statementDatabaseExecutor::using($driver)->execute()
executeAndGetId(string|SqlStatement $sql, ?array $array = null): mixedExecutes a query and returns the last inserted IDDatabaseExecutor::using($driver)->executeAndGetId()
getAllFields(string $tablename): arrayGets all field names from a tableDatabaseExecutor::using($driver)->getAllFields()

Database Metadata and Helpers

MethodDescription
getSqlDialect(): SqlDialectInterfaceReturns a helper object with database-specific functions
getSqlDialectClass(): stringReturns the class name of the SQL dialect implementation

Advanced Settings

MethodDescription
isSupportMultiRowset(): boolChecks if the driver supports multiple result sets
setSupportMultiRowset(bool $multipleRowSet): voidSets whether the driver should support multiple result sets

Logging

MethodDescription
enableLogger(LoggerInterface $logger): voidSets a PSR-3 compliant logger for the driver
log(string $message, array $context = []): voidLogs a message using the configured logger

Transaction Methods (from DbTransactionInterface)

The interface extends DbTransactionInterface, so it also includes these transaction methods:

MethodDescription
beginTransaction(IsolationLevelEnum $isolationLevel = null): voidStarts a new transaction
commitTransaction(): voidCommits the current transaction
rollbackTransaction(): voidRolls back the current transaction
hasActiveTransaction(): boolChecks if there is an active transaction
activeIsolationLevel(): ?IsolationLevelEnumReturns the isolation level of the current transaction

Usage Example

<?php
use ByJG\AnyDataset\Db\Factory;
use ByJG\AnyDataset\Db\DatabaseExecutor;
use ByJG\AnyDataset\Db\SqlStatement;
use ByJG\AnyDataset\Db\IsolationLevelEnum;

// Get a database driver instance
$dbDriver = Factory::getDbInstance('mysql://user:password@host/database');

// Create a DatabaseExecutor (recommended)
$executor = DatabaseExecutor::using($dbDriver);

// Connection management (still done through driver)
if (!$dbDriver->isConnected()) {
$dbDriver->reconnect();
}

// Basic query execution (using executor)
$iterator = $executor->getIterator("SELECT * FROM users WHERE active = :active", [':active' => true]);
foreach ($iterator as $row) {
echo $row->get('name') . "\n";
}

// Using SqlStatement
$sqlStatement = new SqlStatement(
"SELECT * FROM users WHERE active = :active AND role = :role",
[':active' => true]
);
$iterator = $executor->getIterator($sqlStatement, [':role' => 'admin']);

// Transaction example (can use either executor or driver)
$executor->beginTransaction(IsolationLevelEnum::SERIALIZABLE);
try {
$executor->execute("INSERT INTO users (name, email) VALUES (:name, :email)", [
':name' => 'John Doe',
':email' => '[email protected]'
]);

$lastId = $executor->executeAndGetId(
"INSERT INTO user_roles (user_id, role) VALUES (:user_id, :role)",
[':user_id' => $lastId, ':role' => 'admin']
);

$executor->commitTransaction();
} catch (Exception $ex) {
$executor->rollbackTransaction();
throw $ex;
}

// Clean up (still done through driver)
$dbDriver->disconnect();

Legacy Approach (Deprecated)

<?php
use ByJG\AnyDataset\Db\Factory;

// Get a database driver instance
$dbDriver = Factory::getDbInstance('mysql://user:password@host/database');

// ⚠️ Deprecated: Direct query methods on driver will be removed in version 7.0
$iterator = $dbDriver->getIterator("SELECT * FROM users WHERE active = :active", [':active' => true]);
foreach ($iterator as $row) {
echo $row->get('name') . "\n";
}

Creating Custom Drivers

To create a custom database driver, you must implement the DbDriverInterface interface. The easiest way is to extend the DbPdoDriver abstract class, which provides many of the required implementations.

<?php
namespace MyApp\Database;

use ByJG\AnyDataset\Db\DbPdoDriver;
use Override;

class MyCustomDriver extends DbPdoDriver
{
#[Override]
public static function schema()
{
return "mycustom";
}

// Override other methods as needed
}

// Register your driver
\ByJG\AnyDataset\Db\Factory::registerDbDriver(MyCustomDriver::class);

// Now you can use it
$db = \ByJG\AnyDataset\Db\Factory::getDbInstance("mycustom://user:pass@host/db");

Deprecated Methods

As of version 6.0, the following methods are deprecated and will be removed in version 7.0:

  • getIterator() - Use DatabaseExecutor::using($driver)->getIterator() instead
  • getScalar() - Use DatabaseExecutor::using($driver)->getScalar() instead
  • execute() - Use DatabaseExecutor::using($driver)->execute() instead
  • executeAndGetId() - Use DatabaseExecutor::using($driver)->executeAndGetId() instead
  • getAllFields() - Use DatabaseExecutor::using($driver)->getAllFields() instead

For a complete migration guide, see Deprecated Features.

Available Implementations

AnyDataset-DB provides several implementations of the DbDriverInterface:

ClassSchemaDescription
PdoMysqlmysqlMySQL and MariaDB driver
PdoPgsqlpgsqlPostgreSQL driver
PdoSqlitesqliteSQLite driver
PdoDblibdblibSQL Server driver (using FreeTDS)
PdoSqlsrvsqlsrvSQL Server driver (using Microsoft driver)
PdoOciociOracle driver (using PDO OCI)
DbOci8Driveroci8Oracle driver (using OCI8 extension)
PdoOdbcodbcODBC driver
PdoPdopdoGeneric PDO driver
DatabaseRouterN/ASpecial driver for routing queries to different databases

See Also