Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ jobs:
- uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: pdo_mysql, pdo_pgsql
extensions: pdo_mysql, pdo_pgsql, pdo_sqlite
coverage: none

- uses: ramsey/composer-install@v4
Expand Down
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
Unreleased
* Added SQLite 3 support: Dialect::SQLite and SQLiteBindingFactory. With it, Statement::sql() reads '...' strings without backslash escapes, "...", `...` and [...] identifiers, "--" comments without a following space and non-nesting block comments, and "#" isn't a comment.
* Added SQLiteNumericBindings: bUInt() and bUIntArray() stop at 9223372036854775807, SQLite's integer maximum, since SQLite reads larger numbers as floats and can't tell them apart.
* MySQLNumericBindings' unsigned maximum is now the protected UINT_MAX constant, so subclasses can lower it.
* CI installs pdo_sqlite; GLPDO2SQLiteTest runs against an in-memory database.
* Added Statement::bIdent() to quote table, column and database names for the database in use, with a '%%' placeholder. 'db.users.id' quotes each part, 'users.*' keeps the star, and an array gives a column list.
* Added IdentifierBindingInterface, with QuotedIdentifierBindings (any quote characters), MySQLIdentifierBindings (backticks) and PostgreSQLIdentifierBindings (double quotes). Bindings takes it as an optional sixth argument and defaults to MySQL, so existing code doesn't change.
* Added Statement::bUInt() and bUIntArray() for unsigned integers, 0 to 18446744073709551615 (BIGINT UNSIGNED). They reject negative values, accept values above PHP_INT_MAX as integer strings, and use '%%' so the value is compared exactly. A string parameter would be compared as a float in MySQL expressions and IN() lists.
Expand Down
41 changes: 37 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ $users = $db->selectRows(
- [Query methods](#query-methods)
- [Security](#security)
- [PostgreSQL](#postgresql)
- [SQLite](#sqlite)
- [Custom bindings](#custom-bindings)
- [Limitations](#limitations)
- [Development](#development)
Expand Down Expand Up @@ -70,7 +71,7 @@ With GLPDO2:
composer require geeklab/glpdo2
```

Requires PHP 8.3 or newer, with the `pdo_mysql` extension for MySQL and MariaDB or `pdo_pgsql` for PostgreSQL. PHP 8.4 or newer is recommended for PostgreSQL; see [PostgreSQL](#postgresql).
Requires PHP 8.3 or newer, with the `pdo_mysql` extension for MySQL and MariaDB, `pdo_pgsql` for PostgreSQL, or `pdo_sqlite` for SQLite 3. PHP 8.4 or newer is recommended for PostgreSQL; see [PostgreSQL](#postgresql).

## Quick start

Expand Down Expand Up @@ -184,11 +185,11 @@ Build a query one line at a time with `sql()`, and put each value's binding righ
| `?` | `bStr`, `bInt`, `bBool`, `bBoolInt`, `bDate`, `bDateTime`, `bJSON`, `bLike` | Bound as a PDO parameter. The value is never part of the SQL text. |
| `%%` | `bStrArr`, `bIntArray`, `bUInt`, `bUIntArray`, `bFloat`, `bIdent`, `bRaw` | Replaced in the SQL text: by a list of bound parameters (`bStrArr`), by validated numbers (`bIntArray`, `bUInt`, `bUIntArray`, `bFloat`), by quoted identifiers (`bIdent`), or as is (`bRaw`). |

Placeholders are filled in order: the first `?` gets the first `?`-type binding, and the first `%%` gets the first `%%`-type binding. Inside quoted strings and comments, `?` and `%%` are plain text, so `WHERE note = 'Why?'` works. Inside quoted identifiers (backticks for MySQL, double quotes for PostgreSQL), `%%` is still a placeholder, so `` `%%` `` with `bRaw()` can fill in a table name. What counts as a string or comment depends on the database; see [PostgreSQL](#postgresql).
Placeholders are filled in order: the first `?` gets the first `?`-type binding, and the first `%%` gets the first `%%`-type binding. Inside quoted strings and comments, `?` and `%%` are plain text, so `WHERE note = 'Why?'` works. Inside quoted identifiers (backticks for MySQL, double quotes for PostgreSQL, any of `"..."`, `` `...` `` and `[...]` for SQLite), `%%` is still a placeholder, so `` `%%` `` with `bRaw()` can fill in a table name. What counts as a string or comment depends on the database; see [PostgreSQL](#postgresql) and [SQLite](#sqlite).

### Quoting table and column names

The examples here quote names with MySQL backticks. To leave quoting to the library, put `%%` where the name goes and bind it with `bIdent()`. The bindings decide how to quote it: backticks for MySQL, double quotes for PostgreSQL.
The examples here quote names with MySQL backticks. To leave quoting to the library, put `%%` where the name goes and bind it with `bIdent()`. The bindings decide how to quote it: backticks for MySQL, double quotes for PostgreSQL and SQLite.

```php
$statement
Expand Down Expand Up @@ -260,6 +261,8 @@ They use `%%` and put the validated digits into the SQL text, rather than bindin

PostgreSQL has no unsigned types. There, `bUInt()` checks that a value isn't negative, and values above 2⁶³−1 need a `numeric` column.

SQLite integers are signed 64-bit, and SQLite reads any larger number as a float, so 2⁶⁴−1 and 2⁶⁴−2 would be stored as the same value. With the SQLite bindings, `bUInt()` and `bUIntArray()` therefore stop at `9223372036854775807` and throw above it. Store larger values as text with `bStr()`.

## Query methods

All of these are on `GLPDO2` and take a `Statement`. Errors come through as `PDOException`, as long as the connection uses `PDO::ERRMODE_EXCEPTION`.
Expand Down Expand Up @@ -334,6 +337,36 @@ PDO scans the SQL again before sending it, and its scanner doesn't follow all of

The value bindings are the same as for MySQL. PostgreSQL is stricter about types, so add a cast where it can't infer one, such as `?::date`, `?::jsonb` or `?::int` in a select list. `bBoolInt()` binds `0` or `1`, which a PostgreSQL `boolean` column won't accept; use `bBool()` there.

## SQLite

Build the bindings with `SQLiteBindingFactory`. Everything else works as it does for MySQL:

```php
use GeekLab\GLPDO2\Bindings\SQLite\SQLiteBindingFactory;

$pdo = new PDO('sqlite:/path/to/app.db', null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$db = new GLPDO2($pdo);
$statement = new Statement(SQLiteBindingFactory::build());

$rows = $db->selectRows(
$statement
->sql('SELECT %% FROM %%')->bIdent(['id', 'name'])->bIdent('users')
->sql('WHERE "settings" ->> ? = ?')->bStr('$.theme')->bStr('dark')
);
```

With it, `sql()` reads the text by SQLite's rules:

| | SQLite |
|---|---|
| Strings | `'...'`. A backslash is a plain character; `''` is a quote. |
| Quoted identifiers | `"..."`, `` `...` `` and `[...]` |
| Comments | `--` (no whitespace needed after it) and `/* */` (doesn't nest) |

`#` and `$` have no special meaning, and `??` is two placeholders, since SQLite has no `?` operator.

SQLite handles PDO placeholders itself, so none of the PDO limits described under [PostgreSQL](#postgresql) apply. SQLite has no boolean type: `bBool()` stores `1` or `0`. Dates from `bDate()` and `bDateTime()` are stored as text, which SQLite's date functions read. For unsigned integers above 2⁶³−1, see [Unsigned integers](#unsigned-integers).

## Custom bindings

The bindings are grouped into six interfaces in `GeekLab\GLPDO2\Bindings`: date/time, logic, numeric, raw, string and identifier. `MySQLBindingFactory::build()` creates the MySQL set. To change how a type is bound, implement the matching interface (or extend the MySQL class) and pass your own set in. `bUInt()` and `bUIntArray()` are in `UnsignedNumericBindingInterface`, which extends the numeric interface. If your numeric bindings only implement `NumericBindingInterface`, those two use the MySQL versions:
Expand Down Expand Up @@ -373,7 +406,7 @@ $bindings = new Bindings(

## Limitations

- **MySQL, MariaDB and PostgreSQL.** Other databases may work for simple queries, but aren't tested. See [PostgreSQL](#postgresql) for limits that come from PDO.
- **MySQL, MariaDB, PostgreSQL and SQLite 3.** Other databases may work for simple queries, but aren't tested. See [PostgreSQL](#postgresql) for limits that come from PDO.
- **Invalid dates don't throw.** `bDate()` and `bDateTime()` bind `1970-01-01` (`1970-01-01 00:00:00`) for a value that isn't in the expected format, and only accept years 1900–2099. Validate dates first if that matters.
- **`bLike()` doesn't escape wildcards.** A `%` or `_` in the value acts as a wildcard.
- **`getComputed()` is approximate.** It shows string values in quotes without escaping them.
Expand Down
8 changes: 5 additions & 3 deletions src/Bindings/MySQL/MySQLNumericBindings.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@

class MySQLNumericBindings implements UnsignedNumericBindingInterface
{
/** @const string UINT64_MAX The largest BIGINT UNSIGNED value, 2^64 - 1. */
private const UINT64_MAX = '18446744073709551615';
/** @const string UINT_MAX The largest value bUInt() accepts: BIGINT UNSIGNED's maximum, 2^64 - 1. */
protected const UINT_MAX = '18446744073709551615';

/**
* Bind a float.
Expand Down Expand Up @@ -189,7 +189,9 @@ private function toUInt(float | bool | int | string $value): string
if (is_string($value) && preg_match('/^\s*\+?0*(\d+)\s*$/', $value, $match) === 1) {
$digits = $match[1];

if (strlen($digits) > 20 || (strlen($digits) === 20 && strcmp($digits, self::UINT64_MAX) > 0)) {
$max = static::UINT_MAX;

if (strlen($digits) > strlen($max) || (strlen($digits) === strlen($max) && strcmp($digits, $max) > 0)) {
throw new InvalidArgumentException(
'Can not bind ' . var_export($value, true) . ' in unsigned integer spot: out of range.'
);
Expand Down
31 changes: 31 additions & 0 deletions src/Bindings/SQLite/SQLiteBindingFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace GeekLab\GLPDO2\Bindings\SQLite;

use GeekLab\GLPDO2\Bindings\Bindings;
use GeekLab\GLPDO2\Bindings\MySQL\MySQLDateTimeBindings;
use GeekLab\GLPDO2\Bindings\MySQL\MySQLLogicBindings;
use GeekLab\GLPDO2\Bindings\MySQL\MySQLRawBindings;
use GeekLab\GLPDO2\Bindings\MySQL\MySQLStringBindings;
use GeekLab\GLPDO2\Dialect;

class SQLiteBindingFactory
{
/**
* The value bindings are plain PDO types that SQLite accepts as well, so the MySQL classes are reused,
* except that bUInt() stops at SQLite's integer maximum.
* What differs is identifier quoting and how Statement::sql() reads the SQL text.
*/
public static function build(): Bindings
{
return new Bindings(
new MySQLDateTimeBindings(),
new MySQLLogicBindings(),
new SQLiteNumericBindings(),
new MySQLRawBindings(),
new MySQLStringBindings(),
new SQLiteIdentifierBindings(),
Dialect::SQLite
);
}
}
16 changes: 16 additions & 0 deletions src/Bindings/SQLite/SQLiteIdentifierBindings.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

namespace GeekLab\GLPDO2\Bindings\SQLite;

use GeekLab\GLPDO2\Bindings\QuotedIdentifierBindings;

/**
* Quotes identifiers with double quotes, the SQL standard form SQLite prefers: "main"."users"."id"
*/
class SQLiteIdentifierBindings extends QuotedIdentifierBindings
{
public function __construct()
{
parent::__construct('"');
}
}
16 changes: 16 additions & 0 deletions src/Bindings/SQLite/SQLiteNumericBindings.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

namespace GeekLab\GLPDO2\Bindings\SQLite;

use GeekLab\GLPDO2\Bindings\MySQL\MySQLNumericBindings;

/**
* SQLite integers are signed 64-bit. SQLite reads a larger number as a float, so 2^64 - 1 and 2^64 - 2
* would be stored as the same value. bUInt() and bUIntArray() throw above 2^63 - 1 instead.
* Store larger values as text, with bStr().
*/
class SQLiteNumericBindings extends MySQLNumericBindings
{
/** @const string UINT_MAX SQLite's largest integer, 2^63 - 1. */
protected const UINT_MAX = '9223372036854775807';
}
8 changes: 8 additions & 0 deletions src/Dialect.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use GeekLab\GLPDO2\Bindings\IdentifierBindingInterface;
use GeekLab\GLPDO2\Bindings\MySQL\MySQLIdentifierBindings;
use GeekLab\GLPDO2\Bindings\PostgreSQL\PostgreSQLIdentifierBindings;
use GeekLab\GLPDO2\Bindings\SQLite\SQLiteIdentifierBindings;

/**
* The SQL dialect a statement is written in.
Expand All @@ -24,6 +25,12 @@ enum Dialect
*/
case PostgreSQL;

/**
* SQLite 3: '...' strings without backslash escapes, "...", `...` and [...] identifiers,
* "--" and non-nesting block comments.
*/
case SQLite;

/**
* The identifier quoting this dialect uses.
*
Expand All @@ -34,6 +41,7 @@ public function identifierBindings(): IdentifierBindingInterface
return match ($this) {
self::MySQL => new MySQLIdentifierBindings(),
self::PostgreSQL => new PostgreSQLIdentifierBindings(),
self::SQLite => new SQLiteIdentifierBindings(),
};
}
}
Loading