Skip to content

SQL Driver

The SQL Driver plugin provides a unified interface for database operations across different SQL backends, with support for specifications (query criteria).

Four adapters are available:

  • InMemoryDriver stores data in memory for fast testing without database setup.
  • SqliteDriver executes operations against SQLite databases.
  • MysqlDriver executes operations against MySQL databases.
  • PostgresqlDriver executes operations against PostgreSQL databases.

Why Use It

Repository implementations need a consistent way to perform CRUD operations across different databases. The SQL Driver abstracts database-specific syntax (upserts, quoting) while supporting the Specification pattern for complex queries.

Usage

The driver is typically used within repository implementations:

// Find by ID
$row = $this->driver->findById('books', $bookId);

// Save (insert or update)
$this->driver->save('books', [
    'id' => $book->getId()->getValue(),
    'title' => $book->getTitle()->getValue(),
    'status' => $book->getStatus()->value,
]);

// Find with specification
$spec = new BookByStatusSpecification(BookStatus::Available);
$rows = $this->driver->findBy('books', $spec, ['title' => 'ASC']);

// Delete
$this->driver->deleteById('books', $bookId);

Specifications implement toSql() for database queries and toInMemoryFilter() for in-memory filtering.

Testing

The InMemoryDriver enables fast, isolated tests without database setup:

$driver = new InMemoryDriver();
$driver->save('books', ['id' => '123', 'title' => 'Clean Code']);
$book = $driver->findById('books', $id);
$driver->reset('books');  // Clear table for next test

See Also