mindplay/sql
Database framework and query builder.
This library implements (yet another) database abstraction and (yet another) query builder.
It supports:
- Query-builders for
INSERT, UPDATE, DELETE and SELECT queries, with a chainable API.
- Schema abstraction with bi-directional conversions between PHP data-types/objects and relational data.
- An abstraction over
PDO adding support for array values with PDO-style :name placeholders.
- Streaming iteration of query results enabling you to process results in arbitrary-size batches.
- On-the-fly mapping of functions against individual records, or batches of records.
- NOT an object/relational-mapper.
An important non-goal of this project is the ability to switch from one database technology to another -
while we do support both MySQL and PostgreSQL, and while a lot of the implementations are shared, no attempt
is made at hiding or abstracting the differences between each technology. On the contrary, we try to make it
plain and obvious that there are differences, both in terms of capabilities and best patterns for each DBMS.
We favor simplicity over ease of use - this library minimally abstracts PDO and stays reasonably close to SQL
and the relational model, rather than attempting to hide it.
Project Status
Per SimVersion, the 0.x release series is feature-incomplete, not "unstable",
and will not transition to 1.x until it is feature-complete.
The project has been widely used on many internal projects in our organization - it is "stable", but is still
subject to changes, and will remain so for the foreseeable future.
The public API has been largely stable for many releases - at this point, most breaking changes are changes to
the internal protected portion of the API; typically, a major 0.x+1 release has very little impact on client code.
Contributions
Current target is php 8.1 or later.
Code adheres to PSR-2 and PSR-4.
You need a working Docker installation to run the tests.
Using VS Code
The project includes a DevContainer and a launch.json for testing and debugging
with VS Code - just open the project in VS Code, hit F5 to run the tests, and you should be good to go. ✨
Using Docker
To launch Docker and run the test-suite, e.g. in PHP 8.3:
Once the Docker environment is running, you can run the tests more quickly on the existing Docker environment:
Once running, if you prefer, you can also just shell into the PHP container and run the tests from there, for example:
docker compose exec php bash
composer update
composer test
exit
Overview
The concepts used in this library can be roughly divided into two main areas: the framework and the model.
The framework (the mindplay\sql\framework namespace) consists of database Connection, Statement and
Prepared Statement abstractions, and an implementation of these for PDO.
In addition, the framework includes an iterable Result model which includes support for a Mapper abstraction
and implementations providing support for custom operations on individual records, as well as processing of
large result sets in batches.
The model (the mindplay\sql\model namespace) includes a Driver abstraction, Query Builders for INSERT, SELECT,
UPDATE, DELETE and custom SQL queries, a Schema model and a Type abstraction, which includes a Mapper
implementation for Type conversions.
Usage
Every project needs a Schema class and one Table class for every table in that schema.
This boostrapping process may seem a little verbose, but with IDE support, you will write these simple
classes in no-time - these classes in turn will provide support for static analysis tools and IDEs,
e.g. with auto-completion for table/column names, making your database work simple and safe.
It's worth it.
Creating Table Models
Define your table model by extending the Table class.
Your table classes act as factories for Column objects.
Add one method per column, each returning a Column object - the Table class provides several different
protected factory-methods to help with the creation of Column instances.
The method-name should match the column name, so you can use __FUNCTION__ to avoid repetition.
The Table class implements __get() so you can skip the parens when referencing columns.
You should add a @property-read annotation for each column for optimal static analysis.
The table model pattern looks like this:
/**
* @property-read Column $id
* @property-read Column $first_name
* @property-read Column $last_name
*/
class UserTable extends Table
{
public function id($alias)
{
return $this->autoColumn(__FUNCTION__, IntType::class, $alias);
}
public function first_name($alias)
{
return $this->requiredColumn(__FUNCTION__, StringType::class, $alias);
}
public function last_name($alias)
{
return $this->requiredColumn(__FUNCTION__, StringType::class, $alias);
}
}
The following protected factory-methods are available to help create Column instances:
-
requiredColumn() for non-optional columns: the INSERT query-builder will throw an exception
if you don't explicitly specify a value for these.
-
optionalColumn() for columns that have a default value and/or allow NULLs.
-
autoColumn() for columns that the database itself will populate, e.g. auto-incrementing or
columns that are otherwise initialized by the database itself.
Refer to the Table API for arguments.
Note that "required" and "optional" do not necessarily correlate 1:1 with IS NULL in your schema.
For example, a column could be "required" but still allow SQL NULL values - in this case, "required"
means you must explicitly supply a null-value e.g. to the INSERT query-builder, which may be safer and
more explicit for some use-cases.
Column Types
Every Column references a Type by it's class-name. (e.g. DateType::class, etc.)
Type implementations are responsible for converting between SQL values and PHP values, in both directions.
Type implementations are auto-wired in the DI container internally - you don't need to explicitly
register a custom Type implementation.
Built-in types are available for the scalar PHP types (string, int, float, bool and null) as well
as a few other SQL types.
For available types and documentation, look in the mindplay\sql\model\types namespace.
Creating Schema Models
Define your schema model by extending the Schema class.
Your schema class acts as a factory for Table objects.
Add one method per Table type, each returning a Table object - the Schema class provides a
protected factory-method createTable() to help with the creation of Table instances.
The method-name should match the table-name, so you can use __FUNCTION__ to avoid repetition.
The Schema class implements __get() so you can skip the parens when referencing tables.
You should add a @property-read annotation for each table for optimal static analysis.
The schema model pattern looks like this:
/**
* @property-read UserTable $user
* @property-read AddressTable $address
*/
class UserSchema extends Schema
{
/**
* @param string $alias
*
* @return UserTable
*/
public function user($alias)
{
return $this->createTable(UserTable::class, __FUNCTION__, $alias);
}
/**
* @param string $alias
*
* @return AddressTable
*/
public function address($alias)
{
return $this->createTable(AddressTable::class, __FUNCTION__, $alias);
}
}
Bootstrapping a Project
If you use a dependency injection container, you should perform this bootstrapping once and register
these objects as services in your container.
First, select a Database implementation - for example:
$db = new MySQLDatabase();
Next, create (and register in your DI container) your Schema model:
/** @var UserSchema $schema */
$schema = $db->getSchema(UserSchema::class);
Finally, create (and register) a matching Connection implementation - for example:
$connection = $db->createConnection(new PDO("mysql:dbname=foo;host=127.0.0.1", "root", "root"));
Don't quibble about the fact that you need three different dependencies - it may seem complicated
or verbose, but it's actually very simple; each of these three components have a very distinct
purpose and scope:
-
The Database model acts as a factory for Schema-types and various query-types (insert, select, etc.)
-
Your Schema-type acts as a factory-class for your domain-specific Table-types.
-
The Connection object provides a thin wrapper over PDO, which doesn't have an interface of it's own.
Note that the Database model and Schema-types have no dependency on the Connection object - the
database model and query-builders operate entirely in the abstract with no dependency on any physical
database connection, which is great, as it enables you to write (and unit-test) complex query-builders
independently of any database connection.
Building Queries
Creating a query begins with the Database model and your Schema-type.
Here is a basic example of building a SELECT query with a SelectQuery builder, which is created
by the select() factory-method:
$user = $schema->user;
$query = $db->select($user)
->where("{$user->first_name} LIKE :name")
->bind("name", "%rasmus%")
->order("{$user->last_name} DESC, {$user->first_name} DESC")
->page(1, 20); // page 1, 20 records per page, e.g.: OFFSET 0 LIMIT 20
Note the use of __toString() magic, which is supported by Table-types and Column objects: these
properties/methods return quoted names - for example, {$user->last_name} expands to "user"."last_name"
if you're using a PostgresConnection.
Factory-methods are available for the following query-builders:
select(Table $from) creates a SelectQuery builder for SELECT queries
insert(Table $into) creates an InsertQuery builder for INSERT queries
update(Table $table) creates an UpdateQuery builder for UPDATE queries
delete(Table $table) creates DeleteQuery builder for DELETE queries
sql(string $sql) creates a SQLQuery builder for custom SQL queries
All of the query-builders support parameter binding via bind() and apply().
Query-builders for SELECT, UPDATE and DELETE queries support conditions via the where() method.
In addition, some query-builders support a few features specific to those types of queries.
Binding Parameters
All types of query-builders extend the Query builder, which implements parameter binding - the one
feature that is common to all query-types, including the "raw" SQLQuery type.
⚠ To avoid SQL injection, all values should be bound to placeholders - we can't prevent you from
inserting literal values directly into queries, but don't: you should always use parameter binding.
You can bind individual placeholders (such as :name) to values using the bind()