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: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
Unreleased
* 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.
* Added UnsignedNumericBindingInterface (extends NumericBindingInterface), implemented by MySQLNumericBindings. Numeric bindings that don't implement it fall back to the MySQL versions for bUInt() and bUIntArray().
* Added PostgreSQL support: Dialect::PostgreSQL and PostgreSQLBindingFactory. With it, Statement::sql() reads '...' strings without backslash escapes, E'...' strings, $tag$...$tag$ strings, "..." identifiers, "--" comments without a following space and nesting block comments, and "#" isn't a comment. "??" is a literal "?", for the jsonb ?, ?| and ?& operators.
* Bindings takes an optional seventh argument, the Dialect, and has getDialect(). It defaults to MySQL.
* CI runs a PostgreSQL integration test (GLPDO2PostgreSQLTest), skipped locally unless PGHOST is set.
Expand Down
22 changes: 19 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ Build a query one line at a time with `sql()`, and put each value's binding righ
| Placeholder | Filled by | How the value gets to the database |
|---|---|---|
| `?` | `bStr`, `bInt`, `bBool`, `bBoolInt`, `bDate`, `bDateTime`, `bJSON`, `bLike` | Bound as a PDO parameter. The value is never part of the SQL text. |
| `%%` | `bStrArr`, `bIntArray`, `bFloat`, `bIdent`, `bRaw` | Replaced in the SQL text: by a list of bound parameters (`bStrArr`), by validated numbers (`bIntArray`, `bFloat`), by quoted identifiers (`bIdent`), or as is (`bRaw`). |
| `%%` | `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).

Expand Down Expand Up @@ -231,6 +231,7 @@ Every method returns the `Statement`, so calls chain. Methods with a `$null` par
|---|---|---|---|
| `bStr($value, $null = false, $type = PDO::PARAM_STR)` | `?` | string | Pass a different `PDO::PARAM_*` type if needed. |
| `bInt($value, $null = false)` | `?` | integer | Accepts ints, floats and numeric strings. Floats are truncated toward zero. Non-numeric or out-of-range values throw `InvalidArgumentException`. |
| `bUInt($value, $null = false)` | `%%` | unsigned integer | `0` to `18446744073709551615`, for `UNSIGNED` columns. Pass values above `PHP_INT_MAX` as integer strings. Floats are truncated toward zero. Negative, non-numeric and out-of-range values throw `InvalidArgumentException`. See [Unsigned integers](#unsigned-integers). |
| `bFloat($value, $decimals = 3, $null = false)` | `%%` | number with `$decimals` decimal places | Must be numeric. |
| `bBool($value, $null = false)` | `?` | boolean | |
| `bBoolInt($value, $null = false)` | `?` | `0` or `1` | For `TINYINT` flag columns. |
Expand All @@ -240,10 +241,25 @@ Every method returns the `Statement`, so calls chain. Methods with a `$null` par
| `bLike($value, $ends = false, $starts = false)` | `?` | `%value%` | `$starts = true` gives `value%` (starts with). `$ends = true` gives `%value` (ends with). |
| `bStrArr(array $values, $default = '')` | `%%` | `:arr0, :arr1, …` | For `IN (%%)`. Each value is its own bound parameter. If `$values` is empty, `$default` is inserted **as is**. |
| `bIntArray(array $values)` | `%%` | `1, 2, 3` | For `IN (%%)`. Values are cast to integers and duplicates removed. An empty array throws `InvalidArgumentException`. |
| `bUIntArray(array $values)` | `%%` | `1, 2, 3` | For `IN (%%)` on `UNSIGNED` columns. Each value is validated as `bUInt()` does, so a bad value throws rather than being cast. Duplicates are removed. An empty array throws `InvalidArgumentException`. |
| `bIdent($name)` | `%%` | quoted identifier(s) | Table, column or database name, quoted for your database. `'db.users.id'` quotes each part; an array gives a comma-separated list. See [Quoting table and column names](#quoting-table-and-column-names). |
| `bRaw($value)` | `%%` | the value, **as is** | For table names, column names and SQL functions you control. **Never pass user input.** |
| `bind($name, $value, $type = PDO::PARAM_STR)` | `:name` | anything | Binds your own named placeholder. |

### Unsigned integers

`bInt()` binds a PHP integer, which stops at `9223372036854775807` (2⁶³−1), and it accepts negative numbers. For `UNSIGNED` columns, use `bUInt()` and `bUIntArray()` instead. They reject negative values and go up to `BIGINT UNSIGNED`'s maximum, `18446744073709551615` (2⁶⁴−1):

```php
$statement
->sql('SELECT * FROM `events` WHERE `id` = %%')->bUInt('18446744073709551615')
->sql('OR `parent_id` IN (%%)')->bUIntArray([1, 2, '9223372036854775808']);
```

They use `%%` and put the validated digits into the SQL text, rather than binding a parameter. A value above `PHP_INT_MAX` can only be bound as a string, and in an expression or an `IN (...)` list MySQL compares a string with a number as a float, so `18446744073709551615` and `18446744073709551614` would match. Digits in the SQL text are compared exactly. Only digits get through the validation, so this is safe for user input.

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

## 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 @@ -274,7 +290,7 @@ Most bindings send values to MySQL as PDO parameters, so they can't change the q
| Binding | Safe for user input? | Why |
|---|---|---|
| `?` bindings, `bStrArr()` values | ✅ Yes | Sent as bound parameters. |
| `bInt()`, `bFloat()`, `bIntArray()` | ✅ Yes | Validated or cast to numbers before they reach the SQL. |
| `bInt()`, `bUInt()`, `bFloat()`, `bIntArray()`, `bUIntArray()` | ✅ Yes | Validated or cast to numbers before they reach the SQL. |
| `bIdent()` | ⚠️ Can't inject SQL, but still check | Quoted and escaped, so it can't change the query's structure. It can still name any table or column, so check user-chosen names against a list you allow. |
| `bStrArr()`'s `$default` | ❌ No | Inserted as is when the array is empty. |
| `bRaw()` | ❌ No | Inserted as is, by design. |
Expand Down Expand Up @@ -320,7 +336,7 @@ The value bindings are the same as for MySQL. PostgreSQL is stricter about types

## 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:
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:

```php
use GeekLab\GLPDO2\Bindings\Bindings;
Expand Down
42 changes: 42 additions & 0 deletions src/Bindings/Bindings.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Exception;
use InvalidArgumentException;
use JsonException;
use GeekLab\GLPDO2\Bindings\MySQL\MySQLNumericBindings;
use GeekLab\GLPDO2\Dialect;

class Bindings
Expand Down Expand Up @@ -151,6 +152,47 @@ public function bIntArray(array $data): array
return $this->numeric->bIntArray($data);
}

/**
* Bind an unsigned integer (0 to 18446744073709551615), with NULL option. Uses %%
*
* @param float | bool | int | string | null $value
* @param bool $null
*
* @return array{string}
* @throws InvalidArgumentException
*/
public function bUInt(float | bool | int | string | null $value = null, bool $null = false): array
{
return $this->unsigned()->bUInt($value, $null);
}

/**
* Convert an array of unsigned integers to comma separated values. Uses %%
* Great for IN() statements.
*
* @param array{} | array{mixed} $data
*
* @return array{string}
* @throws InvalidArgumentException
*/
public function bUIntArray(array $data): array
{
return $this->unsigned()->bUIntArray($data);
}

/**
* The numeric bindings, if they handle unsigned integers. Otherwise the MySQL ones, which work
* for any database since they only validate the value.
*
* @return UnsignedNumericBindingInterface
*/
private function unsigned(): UnsignedNumericBindingInterface
{
return $this->numeric instanceof UnsignedNumericBindingInterface
? $this->numeric
: new MySQLNumericBindings();
}

/**
* Quote an identifier (database, table, column), or a list of them, for the SQL text.
*
Expand Down
119 changes: 117 additions & 2 deletions src/Bindings/MySQL/MySQLNumericBindings.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@

use PDO;
use InvalidArgumentException;
use GeekLab\GLPDO2\Bindings\NumericBindingInterface;
use GeekLab\GLPDO2\Bindings\UnsignedNumericBindingInterface;

class MySQLNumericBindings implements NumericBindingInterface
class MySQLNumericBindings implements UnsignedNumericBindingInterface
{
/** @const string UINT64_MAX The largest BIGINT UNSIGNED value, 2^64 - 1. */
private const UINT64_MAX = '18446744073709551615';

/**
* Bind a float.
*
Expand Down Expand Up @@ -111,4 +114,116 @@ public function bIntArray(array $data): array
// Turn into a comma delimited string.
return [implode(', ', $numbers)];
}

/**
* Bind an unsigned integer (0 to 18446744073709551615), with NULL option. Uses %%
* The value goes into the SQL as digits, not as a bound parameter: MySQL compares a string parameter
* with a number as a float, which can't tell large values apart. The digits are validated, so this is
* safe for user input.
*
* @param float | bool | int | string | null $value
* @param bool $null
*
* @return array{string}
* @throws InvalidArgumentException
*/
public function bUInt(float | bool | int | string | null $value = null, bool $null = false): array
{
// Use NULL?
if ($value === null) {
if ($null) {
return ['NULL'];
}

throw new InvalidArgumentException('Can not bind NULL in unsigned integer spot.');
}

return [$this->toUInt($value)];
}

/**
* Convert an array of unsigned integers to comma separated values. Uses %%
* Great for IN() statements. Every value is validated as bUInt() does, and duplicates are removed.
*
* @param array{} | array{mixed} $data
*
* @return array{string}
* @throws InvalidArgumentException
*/
public function bUIntArray(array $data): array
{
if (empty($data)) {
throw new InvalidArgumentException('Can not bind an empty array.');
}

$numbers = [];

foreach ($data as $value) {
if (!is_scalar($value)) {
throw new InvalidArgumentException('Can not bind a non-scalar value in an unsigned integer array.');
}

$numbers[$this->toUInt($value)] = true;
}

return [implode(', ', array_keys($numbers))];
}

/**
* Validate an unsigned integer and return it as a string of digits.
* Floats are truncated toward zero, as bInt() does. Values above PHP_INT_MAX must be integer strings,
* since a float can't hold them exactly.
*
* @param float | bool | int | string $value
*
* @return string
* @throws InvalidArgumentException
*/
private function toUInt(float | bool | int | string $value): string
{
if (is_bool($value)) {
return $value ? '1' : '0';
}

// Integer strings are checked digit by digit, so values above PHP_INT_MAX stay exact.
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)) {
throw new InvalidArgumentException(
'Can not bind ' . var_export($value, true) . ' in unsigned integer spot: out of range.'
);
}

return $digits;
}

if (!is_numeric($value)) {
throw new InvalidArgumentException(
'Can not bind ' . var_export($value, true) . ' in unsigned integer spot.'
);
}

$number = +$value;

if ($number < 0) {
throw new InvalidArgumentException(
'Can not bind ' . var_export($value, true) . ' in unsigned integer spot: negative.'
);
}

if (is_float($number)) {
// (float)PHP_INT_MAX rounds up to 2^63, hence >=. Larger values need an integer string.
if (!is_finite($number) || $number >= PHP_INT_MAX) {
throw new InvalidArgumentException(
'Can not bind ' . var_export($value, true) . ' in unsigned integer spot: out of range '
. 'for a float. Pass values above ' . PHP_INT_MAX . ' as an integer string.'
);
}

$number = (int)$number;
}

return (string)$number;
}
}
34 changes: 34 additions & 0 deletions src/Bindings/UnsignedNumericBindingInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

namespace GeekLab\GLPDO2\Bindings;

use InvalidArgumentException;

/**
* Unsigned integer bindings, kept apart from NumericBindingInterface so existing implementations of it don't break.
* Bindings falls back to MySQLNumericBindings for these when the numeric bindings don't implement this.
*/
interface UnsignedNumericBindingInterface extends NumericBindingInterface
{
/**
* Bind an unsigned integer (0 to 18446744073709551615), with NULL option. Uses %%
*
* @param float | bool | int | string | null $value
* @param bool $null
*
* @return array{string}
* @throws InvalidArgumentException
*/
public function bUInt(float | bool | int | string | null $value = null, bool $null = false): array;

/**
* Convert an array of unsigned integers to comma separated values. Uses %%
* Great for IN() statements.
*
* @param array{} | array{mixed} $data
*
* @return array{string}
* @throws InvalidArgumentException
*/
public function bUIntArray(array $data): array;
}
36 changes: 36 additions & 0 deletions src/Statement.php
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,42 @@ public function bIdent(string | array $name): self
return $this;
}

/**
* Bind an unsigned integer (0 to 18446744073709551615), with NULL option. Uses %%
* Values above PHP_INT_MAX can be given as integer strings. Floats are truncated toward zero.
* Negative values, non-numeric strings and values above the maximum throw InvalidArgumentException.
*
* @param float | bool | int | string | null $value
* @param bool $null
*
* @return Statement
* @throws InvalidArgumentException
*/
public function bUInt(float | bool | int | string | null $value = null, bool $null = false): self
{
$binding = $this->bindings->bUInt($value, $null);
$this->rawBind($this->getNextName('raw'), $binding[0]);

return $this;
}

/**
* Convert an array of unsigned integers to comma separated values. Uses %%
* Great for IN() statements. Every value is validated as bUInt() does, and duplicates are removed.
*
* @param array{} | array{mixed} $data
*
* @return Statement
* @throws InvalidArgumentException
*/
public function bUIntArray(array $data): self
{
$binding = $this->bindings->bUIntArray($data);
$this->rawBind($this->getNextName('raw'), $binding[0]);

return $this;
}

/**
* Bind an object or JSON string to a string
*
Expand Down
45 changes: 45 additions & 0 deletions tests/GLPDO2MySQLTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1662,4 +1662,49 @@ public function testBadTransaction(): void
$this->db->beginTransaction();
$this->db->queryInsert($Statement);
}

/**
* Values above PHP_INT_MAX go in exactly, and comparisons tell neighbours apart,
* even in expressions where MySQL would compare a string parameter as a float.
*
* @return void
* @throws Exception
*/
public function testUnsignedBigint(): void
{
$Statement = new GLPDO2\Statement(GLPDO2\Bindings\MySQL\MySQLBindingFactory::build());

$this->db->queryUpdate($Statement->sql('DROP TABLE IF EXISTS `test_unsigned`'));
$this->db->queryUpdate(
$Statement->reset()->sql('CREATE TABLE `test_unsigned` (`id` BIGINT UNSIGNED PRIMARY KEY)')
);
$this->db->queryInsert(
$Statement->reset()
->sql('INSERT INTO `test_unsigned` VALUES (%%), (%%)')
->bUInt('18446744073709551614')->bUInt(PHP_INT_MAX)
);

$max = $this->db->selectValue(
$Statement->reset()->sql('SELECT MAX(`id`) AS m FROM `test_unsigned`'),
'm'
);
$this->assertSame('18446744073709551614', $max);

$count = $this->db->selectValue(
$Statement->reset()
->sql('SELECT COUNT(*) AS c FROM `test_unsigned`')
->sql('WHERE `id` + 0 = %% OR `id` IN (%%)')
->bUInt('18446744073709551615')->bUIntArray(['18446744073709551613', '1']),
'c'
);
$this->assertSame('0', $count);

$count = $this->db->selectValue(
$Statement->reset()
->sql('SELECT COUNT(*) AS c FROM `test_unsigned` WHERE `id` IN (%%)')
->bUIntArray(['18446744073709551614', PHP_INT_MAX]),
'c'
);
$this->assertSame('2', $count);
}
}
Loading