diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ed02e6..4f33952 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/README.md b/README.md index 36695d4..8bf1cc3 100644 --- a/README.md +++ b/README.md @@ -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). @@ -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. | @@ -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`. @@ -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. | @@ -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; diff --git a/src/Bindings/Bindings.php b/src/Bindings/Bindings.php index 76fd109..8a12ec7 100644 --- a/src/Bindings/Bindings.php +++ b/src/Bindings/Bindings.php @@ -6,6 +6,7 @@ use Exception; use InvalidArgumentException; use JsonException; +use GeekLab\GLPDO2\Bindings\MySQL\MySQLNumericBindings; use GeekLab\GLPDO2\Dialect; class Bindings @@ -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. * diff --git a/src/Bindings/MySQL/MySQLNumericBindings.php b/src/Bindings/MySQL/MySQLNumericBindings.php index 36c87ab..4c71696 100644 --- a/src/Bindings/MySQL/MySQLNumericBindings.php +++ b/src/Bindings/MySQL/MySQLNumericBindings.php @@ -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. * @@ -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; + } } diff --git a/src/Bindings/UnsignedNumericBindingInterface.php b/src/Bindings/UnsignedNumericBindingInterface.php new file mode 100644 index 0000000..81edbf1 --- /dev/null +++ b/src/Bindings/UnsignedNumericBindingInterface.php @@ -0,0 +1,34 @@ +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 * diff --git a/tests/GLPDO2MySQLTest.php b/tests/GLPDO2MySQLTest.php index a434e66..eb8b954 100644 --- a/tests/GLPDO2MySQLTest.php +++ b/tests/GLPDO2MySQLTest.php @@ -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); + } } diff --git a/tests/GLPDO2PostgreSQLTest.php b/tests/GLPDO2PostgreSQLTest.php index 9da0f17..3eb7d47 100644 --- a/tests/GLPDO2PostgreSQLTest.php +++ b/tests/GLPDO2PostgreSQLTest.php @@ -141,4 +141,24 @@ public function testDollarQuotedFunctionBody(): void $this->assertSame('5', $value); } + + public function testUnsignedValuesAboveBigint(): void + { + // PostgreSQL has no unsigned types; numeric(20) holds the BIGINT UNSIGNED range. + $this->db->queryUpdate( + $this->statement()->sql('CREATE TEMPORARY TABLE "big" ("id" numeric(20) PRIMARY KEY)') + ); + $this->db->queryInsert( + $this->statement()->sql('INSERT INTO "big" VALUES (%%), (%%)') + ->bUInt('18446744073709551615')->bUInt(0) + ); + + $value = $this->db->selectValue( + $this->statement()->sql('SELECT "id" FROM "big" WHERE "id" IN (%%)') + ->bUIntArray(['18446744073709551615', '18446744073709551614']), + 'id' + ); + + $this->assertSame('18446744073709551615', $value); + } } diff --git a/tests/MySQLNumericBindingsTest.php b/tests/MySQLNumericBindingsTest.php index 2bb7659..fba139c 100644 --- a/tests/MySQLNumericBindingsTest.php +++ b/tests/MySQLNumericBindingsTest.php @@ -9,7 +9,7 @@ use PHPUnit\Framework\TestCase; /** - * Unit tests for the integer binding. No database needed. + * Unit tests for the integer bindings. No database needed. */ class MySQLNumericBindingsTest extends TestCase { @@ -62,4 +62,147 @@ public function testBIntRejectsOutOfRange(float | string $value): void (new MySQLNumericBindings())->bInt($value); } + + /** + * @return array + */ + public static function uintProvider(): array + { + return [ + 'zero' => [0, '0'], + 'positive int' => [42, '42'], + 'true' => [true, '1'], + 'false' => [false, '0'], + 'numeric string' => ['123', '123'], + 'leading zeros' => ['007', '7'], + 'all zeros' => ['000', '0'], + 'plus sign and spaces' => [' +5 ', '5'], + 'float truncates' => [1.9, '1'], + 'float string truncates' => ['2.5', '2'], + 'exponent string' => ['1e3', '1000'], + 'negative zero string' => ['-0', '0'], + 'PHP_INT_MAX' => [PHP_INT_MAX, '9223372036854775807'], + 'above PHP_INT_MAX string' => ['9223372036854775808', '9223372036854775808'], + 'UINT64 max string' => ['18446744073709551615', '18446744073709551615'], + ]; + } + + #[DataProvider('uintProvider')] + public function testBUIntBindsUnsignedIntegers(float | bool | int | string $value, string $expected): void + { + $this->assertSame([$expected], (new MySQLNumericBindings())->bUInt($value)); + } + + public function testBUIntBindsNullWhenAllowed(): void + { + $this->assertSame(['NULL'], (new MySQLNumericBindings())->bUInt(null, true)); + } + + /** + * @return array + */ + public static function badUIntProvider(): array + { + return [ + 'null not allowed' => [null], + 'negative int' => [-1], + 'negative string' => ['-5'], + 'negative float' => [-0.5], + 'not numeric' => ['abc'], + 'SQL' => ['1; DROP TABLE users'], + 'hex string' => ['0x10'], + 'above UINT64 max' => ['18446744073709551616'], + 'too many digits' => ['123456789012345678901'], + 'float at 2^63' => [9223372036854775808.0], + 'huge exponent string' => ['1e20'], + 'INF' => [INF], + 'NAN' => [NAN], + ]; + } + + #[DataProvider('badUIntProvider')] + public function testBUIntRejectsInvalidValues(float | string | null $value): void + { + $this->expectException(InvalidArgumentException::class); + + (new MySQLNumericBindings())->bUInt($value); + } + + public function testBUIntArrayValidatesAndRemovesDuplicates(): void + { + $this->assertSame( + ['1, 2, 18446744073709551615'], + (new MySQLNumericBindings())->bUIntArray([1, '2', '01', 2.7, '18446744073709551615']) + ); + } + + /** + * @return array}> + */ + public static function badUIntArrayProvider(): array + { + return [ + 'empty' => [[]], + 'negative' => [[1, -2]], + 'not numeric' => [[1, 'x']], + 'null' => [[1, null]], + 'nested array' => [[1, [2]]], + 'too large' => [['18446744073709551616']], + ]; + } + + /** + * @param array $values + */ + #[DataProvider('badUIntArrayProvider')] + public function testBUIntArrayRejectsInvalidValues(array $values): void + { + $this->expectException(InvalidArgumentException::class); + + (new MySQLNumericBindings())->bUIntArray($values); + } + + public function testStatementPutsUnsignedValuesInTheSql(): void + { + $statement = (new Statement(Bindings\MySQL\MySQLBindingFactory::build())) + ->sql('SELECT * FROM t WHERE id = %% AND n IN (%%) AND m = %%') + ->bUInt('18446744073709551615')->bUIntArray([3, 4])->bUInt(null, true); + + $this->assertSame( + 'SELECT * FROM t WHERE id = 18446744073709551615 AND n IN (3, 4) AND m = NULL', + $statement->getComputed() + ); + } + + public function testCustomNumericBindingsFallBackToMySQLForUnsigned(): void + { + // A NumericBindingInterface written before the unsigned methods existed. + $numeric = new class implements Bindings\NumericBindingInterface { + public function bFloat(float | int | string | null $value = null, int $decimals = 3, bool $null = false): array + { + return ['0']; + } + + public function bInt(float | bool | int | string | null $value = null, bool $null = false): array + { + return [0, PDO::PARAM_INT]; + } + + public function bIntArray(array $data): array + { + return ['0']; + } + }; + + $bindings = new Bindings\Bindings( + new Bindings\MySQL\MySQLDateTimeBindings(), + new Bindings\MySQL\MySQLLogicBindings(), + $numeric, + new Bindings\MySQL\MySQLRawBindings(), + new Bindings\MySQL\MySQLStringBindings() + ); + + $this->assertSame(['5'], $bindings->bUInt(5)); + $this->assertSame(['5, 6'], $bindings->bUIntArray([5, 6])); + } }