diff --git a/README.md b/README.md index d74bba2..8f89f1a 100644 --- a/README.md +++ b/README.md @@ -1,151 +1,311 @@ +# GLPDO2 + [![CI](https://github.com/ellisgl/GeekLab-GLPDO2/actions/workflows/ci.yml/badge.svg)](https://github.com/ellisgl/GeekLab-GLPDO2/actions/workflows/ci.yml) [![Packagist Version](https://img.shields.io/packagist/v/geeklab/glpdo2)](https://packagist.org/packages/geeklab/glpdo2) [![PHP Version](https://img.shields.io/packagist/dependency-v/geeklab/glpdo2/php)](https://packagist.org/packages/geeklab/glpdo2) [![PHPStan](https://img.shields.io/badge/PHPStan-level%208-brightgreen)](https://phpstan.org/) -[![License: BSD-3-Clause](https://img.shields.io/badge/License-BSD--3--Clause-blue.svg)](https://opensource.org/licenses/BSD-3-Clause) +[![License: BSD-3-Clause](https://img.shields.io/badge/License-BSD--3--Clause-blue.svg)](LICENSE.BSD) + +**A small PDO wrapper that keeps every value next to its placeholder, and binds it with the right type.** + +You still write plain SQL. GLPDO2 removes the bookkeeping around it: matching placeholders to values, picking `PDO::PARAM_*` types, validating input, building `IN (...)` lists, and seeing the final query when something goes wrong. + +```php +$users = $db->selectRows( + $statement + ->sql('SELECT `id`, `name`') + ->sql('FROM `users`') + ->sql('WHERE `active` = ?')->bBool(true) + ->sql('AND `role` IN (%%)')->bStrArr(['admin', 'editor']) + ->sql('AND `created` >= ?')->bDate('2026-01-01') + ->sql('ORDER BY `name`') + ->sql('LIMIT ?')->bInt(10) +); +``` -GeekLab\GLPDO2 -============ +## Contents + +- [Why GLPDO2](#why-glpdo2) +- [Installation](#installation) +- [Quick start](#quick-start) +- [How statements work](#how-statements-work) +- [Binding methods](#binding-methods) +- [Query methods](#query-methods) +- [Security](#security) +- [Custom bindings](#custom-bindings) +- [Limitations](#limitations) +- [Development](#development) + +## Why GLPDO2 + +The same query with plain PDO: + +```php +$sql = 'SELECT `id`, `name` FROM `users` + WHERE `active` = :active AND `role` IN (:role0, :role1) + AND `created` >= :created ORDER BY `name` LIMIT :limit'; + +$stmt = $pdo->prepare($sql); +$stmt->bindValue(':active', true, PDO::PARAM_BOOL); +$stmt->bindValue(':role0', 'admin'); +$stmt->bindValue(':role1', 'editor'); +$stmt->bindValue(':created', '2026-01-01'); +$stmt->bindValue(':limit', 10, PDO::PARAM_INT); // forget PARAM_INT and LIMIT breaks +$stmt->execute(); +$users = $stmt->fetchAll(PDO::FETCH_ASSOC); +``` -Easy to use PDO Wrapper for PHP >= 8.1 +With GLPDO2: -### Latest -2026-11-25 (4.0.12) -* `?` and `%%` inside quoted strings and comments are no longer treated as placeholders, so SQL like `WHERE note = 'Why?'` works. -* Two `%%` placeholders in one `sql()` call now each get their own value. -* A `-- comment` in one `sql()` call no longer comments out the calls after it. +- **Values sit next to their placeholders.** Adding or removing a condition is a one-line change, with no list of names to keep in sync. +- **Each binding knows its type.** `bInt()` binds an integer and rejects `'abc'`. `bBool()` binds a boolean. `bDate()` checks for `YYYY-MM-DD`. +- **`IN (...)` lists are one call.** `bStrArr()` binds each value as its own parameter, and `bIntArray()` builds a list of integers. +- **You can see the final SQL.** `getComputed()` returns the query with the values filled in, for logging and debugging. +- **It's still PDO.** Bring your own connection, keep your own SQL, and drop down to PDO whenever you want. -### Features -* Bind value by the correct type. E.g. Don't bind as a string where an integer bind should be. -* Bindings are injected, so you can create your own! -* Help prevent injections. -* PSR1/2/4 Compliant. +## Installation -### Installation +```bash composer require geeklab/glpdo2 +``` + +Requires PHP 8.1 or newer with the `pdo_mysql` extension. The bindings are written for MySQL and MariaDB. -### Todo -* More tests, since we can test at many levels and implementations. -* Better schema for testing. -* Better docs. -* More of a real wold example. -* Reduce the complexity? +## Quick start + +The examples use this table: + +```sql +CREATE TABLE `users` ( + `id` INT AUTO_INCREMENT PRIMARY KEY, + `name` VARCHAR(100) NOT NULL, + `role` VARCHAR(20) NOT NULL, + `active` BOOLEAN NOT NULL DEFAULT TRUE, + `settings` JSON NULL, + `created` DATE NOT NULL +); +``` -### Basic Usage (Quick-N-Dirty) +### Connect ```php - PDO::ERRMODE_EXCEPTION, +]); -$dbConn = new PDO('mysql:host=localhost;dbname=playground', 'root', '', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]); -$db = new \GeekLab\GLPDO2\GLPDO2($dbConn); -$Statement = new \GeekLab\GLPDO2\Statement(GLPDO2\Bindings\MySQL\MySQLBindingFactory::build()); -$start = 0; -$limit = 5; +$db = new GLPDO2($pdo); +$bindings = MySQLBindingFactory::build(); +``` -$Statement->sql('SELECT *') - ->sql('FROM (') - ->sql(' SELECT *') - ->sql(' FROM `mock_data`') - ->sql(' LIMIT ?, ?')->bInt($start)->bInt($limit) - ->sql(' ) SUBQ') - ->sql('ORDER BY `id` DESC;'); +Create a `Statement` for each query, or reuse one with `reset()`. -// Show computedSQL statement -print_r($Statement->getComputed()); +### Insert -$res = $db->selectRows($Statement); +```php +$id = $db->queryInsert( + (new Statement($bindings)) + ->sql('INSERT INTO `users` (`name`, `role`, `settings`, `created`)') + ->sql('VALUES (?, ?, ?, ?)') + ->bStr('Ada') + ->bStr('admin') + ->bJSON('{"theme": "dark"}') + ->bDate('2026-03-14') +); +// $id is the new row's ID, as a string: "1" +``` -print_r($res); +### Select + +```php +// Many rows +$admins = $db->selectRows( + (new Statement($bindings)) + ->sql('SELECT `id`, `name` FROM `users`') + ->sql('WHERE `role` = ? AND `active` = ?')->bStr('admin')->bBool(true) +); +// [['id' => 1, 'name' => 'Ada'], ...] + +// One row, or false if there's none +$user = $db->selectRow( + (new Statement($bindings)) + ->sql('SELECT * FROM `users` WHERE `id` = ?')->bInt($id) +); + +// One column of the first row, or a default +$name = $db->selectValue( + (new Statement($bindings))->sql('SELECT `name` FROM `users` WHERE `id` = ?')->bInt($id), + 'name', + default: 'unknown' +); ``` -### Data Binding Methods -Statement->bBool($value, optional boolean $null)
-Binds a value as bool(true, false), with optional NULL value return. +### Update and delete -Statement->bBoolInt($value, optional boolean $null)
-Binds a value as int(0, 1), with optional NULL value return. +```php +$changed = $db->queryUpdate( + (new Statement($bindings)) + ->sql('UPDATE `users` SET `active` = ?')->bBool(false) + ->sql('WHERE `created` < ?')->bDate('2026-01-01') +); +// $changed is the number of rows affected +``` -Statement->bDate($value, optional boolean $null)
-Binds a value as a date (string - validated for YYYY-MM-DD), with optional NULL return. +`queryDelete()` works the same way. -Statement->bDateTime($value, optional boolean $null)
-Binds a value as a date time (string - validated for YYYY-MM-DD HH:MM:SS), with optional NULL return. +### Transactions -Statement->bFloat($value, optional integer $decimals, optional boolean $null)
-Binds a value aa a float, with decimal place (default of 3) and optional NULL return. Use '%%' instead of '?'. +```php +$db->beginTransaction(); + +try { + $db->queryUpdate((new Statement($bindings)) + ->sql('UPDATE `users` SET `role` = ? WHERE `id` = ?')->bStr('editor')->bInt($id)); + $db->queryInsert((new Statement($bindings)) + ->sql('INSERT INTO `audit` (`user_id`, `action`) VALUES (?, ?)')->bInt($id)->bStr('demoted')); + + $db->commit(); +} catch (Throwable $e) { + $db->rollback(); + throw $e; +} +``` -Statement->bInt($value, optional boolean $null)
-Binds a value as an integer, with optional NULL return. Floats are truncated toward zero. Throws InvalidArgumentException for values outside the integer range. +## How statements work -Statement->bIntArray(array $data, integer $default)
-Converts an array of integers to a comma separated values. Will output $default (which is 0) if $data is not an array. Used with IN() statements. Use '%%' instead of '?'. +Build a query one line at a time with `sql()`, and put each value's binding right after the line with its placeholder. There are two kinds of placeholder: -Statement->bJSON($data, optional boolean $null)
-Binds a JSON object or string as a string, with optional NULL value. Throws JsonException. +| Placeholder | Filled by | How the value gets to MySQL | +|---|---|---| +| `?` | `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`, `bRaw` | Replaced in the SQL text: by a list of bound parameters (`bStrArr`), by validated numbers (`bIntArray`, `bFloat`), or as is (`bRaw`). | -Statement->bLike($value, boolean $ends, boolean $starts)
-Binds a value as a string for LIKE queries. $ends = "ends with", $starts = "starts with" +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 backticks, `%%` is still a placeholder, so `` `%%` `` with `bRaw()` can fill in a table name. -Statement->bStr($value, optional boolean $null, optional \PDO::PARAM_* $type)
-Binds a value as a string, with optional NULL value return and optional PDO binding type (default \PDO::PARAM_STR). +### See the final SQL -Statement->bStrArr(array $values, optional string $default)
-Binds an array of strings for use with IN() statements. Each value is bound as its own parameter. Use '%%' instead of '?'. If $values is empty, $default (an empty string by default) is inserted raw, unquoted and unescaped, so never pass untrusted input as $default. +`getComputed()` returns the statement with the values filled in, one `sql()` call per line: -Statement->bind($name, $value, \PDO::PARAM_* $type)
-Binds a value to a named parameter with option PDO binding type (default \PDO::PARAM_STR) +```php +$statement = (new Statement($bindings)) + ->sql('SELECT * FROM `users`') + ->sql('WHERE `role` IN (%%)')->bStrArr(['admin', 'editor']) + ->sql('AND `id` > ?')->bInt(5); + +echo $statement->getComputed(); +// SELECT * FROM `users` +// WHERE `role` IN ('admin', 'editor') +// AND `id` > 5 +``` -Statement->bRaw($value)
-Binds a raw value to '%%' in the sql statement. This is unquoted and unescaped. Good for tables names and functions. Can be dangerous if not handled correctly. +This is for reading only. It shows the values without escaping them, so don't run it. `echo $statement` and `var_dump($statement)` show the same thing. -### Query Methods -GLPDO->queryDelete(Statement $SQL)
-Runs a delete query and returns numbers of affected rows. +## Binding methods -GLPDO->queryInsert(Statement $SQL)
-Runs an insert query and returns the primary ID. +Every method returns the `Statement`, so calls chain. Methods with a `$null` parameter throw `InvalidArgumentException` when given `null`, unless `$null` is `true`; then they bind SQL `NULL`. -GLPDO->queryUpdate(Statement $SQL)
-Runs an update query and returns number of affect rows +| Method | Placeholder | Binds | Notes | +|---|---|---|---| +| `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`. | +| `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. | +| `bDate($value, $null = false)` | `?` | `YYYY-MM-DD` | See [Limitations](#limitations) for invalid dates. | +| `bDateTime($value, $null = false)` | `?` | `YYYY-MM-DD HH:MM:SS` | A date alone gets `00:00:00` added. | +| `bJSON($value, $null = false)` | `?` | JSON string | Takes an object or a JSON string. Invalid JSON, and arrays, throw `JsonException`. | +| `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`. | +| `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. | -GLPDO->selectRows(Statement $SQL)
-Run a normal query, returns multiple rows as an array of associative arrays, or false. +## Query methods -GLPDO->selectRow(Statement $SQL)
-Runs a normal query, returns a single row as an array, or false. +All of these are on `GLPDO2` and take a `Statement`. Errors come through as `PDOException`, as long as the connection uses `PDO::ERRMODE_EXCEPTION`. -GLPDO->selectValue(Statement $SQL, $column, $default)
-Runs a normal query, returns a single column ($column) and can return a default (mixed $default = null) value is no value is in the column. +| Method | Returns | +|---|---| +| `selectRows($statement)` | All rows, as an array of associative arrays. | +| `selectRow($statement)` | The first row as an associative array, or `false`. | +| `selectValue($statement, $column, $caseSensitive = false, $default = null)` | One column of the first row, or `$default`. The column name match ignores case unless `$caseSensitive` is `true`. | +| `queryInsert($statement)` | The new row's ID (from `lastInsertId()`) as a string, or `false` if nothing was inserted. | +| `queryUpdate($statement)` | The number of rows affected. | +| `queryDelete($statement)` | The number of rows affected. | +| `beginTransaction()`, `commit()`, `rollback()`, `inTransaction()` | Same as PDO's methods. | -GLPDO->selectRow(Statement $SQL)
-Runs a normal query, returns a single row as an array. +On `Statement` itself: -GLPDO->beginTransaction()
-Begins an SQL Transaction. +| Method | Does | +|---|---| +| `sql($text)` | Adds a line to the statement. | +| `reset()` | Clears the statement so it can be reused. | +| `execute($pdo)` | Prepares and runs the statement, and returns the `PDOStatement`. | +| `getComputed()` | Returns the SQL with values filled in, for debugging. | -GLPDO->commit()
-Commits an SQL Transaction. +## Security -GLPDO->inTransaction()
-Is there a transaction in progress, returns bool. +Most bindings send values to MySQL as PDO parameters, so they can't change the query. The `%%` bindings put text into the SQL itself, so it matters what they accept: -### Misc Methods -Statement->sql(string $text)
-Used to build up the SQL parameterized statement. Each call is one line of the statement. '?' and '%%' are placeholders only in SQL code: inside quoted strings ('...', "...") and comments (-- , #, /* */) they are left as plain text, and inside backtick identifiers only '%%' is a placeholder (for table names with bRaw()). +| 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. | +| `bStrArr()`'s `$default` | ❌ No | Inserted as is when the array is empty. | +| `bRaw()` | ❌ No | Inserted as is, by design. | -Statement->reset()
-Used to reset Statement private variables. Usefully for creating multiple queries without having to create a new Statement object. +Versions before 4.0.11 pasted `bStrArr()` values into the SQL without escaping them. Upgrade if you use it. + +## Custom bindings + +The bindings are grouped into five interfaces in `GeekLab\GLPDO2\Bindings`: date/time, logic, numeric, raw and string. `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: + +```php +use GeekLab\GLPDO2\Bindings\Bindings; +use GeekLab\GLPDO2\Bindings\MySQL; + +$bindings = new Bindings( + new MyDateTimeBindings(), // implements DateTimeBindingInterface + new MySQL\MySQLLogicBindings(), + new MySQL\MySQLNumericBindings(), + new MySQL\MySQLRawBindings(), + new MySQL\MySQLStringBindings() +); + +$statement = new Statement($bindings); +``` + +## Limitations + +- **MySQL and MariaDB only.** Other databases may work for simple queries, but aren't tested. +- **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. + +## Development + +Run the checks with Composer: + +```bash +composer phpstan # PHPStan, level 8 +composer phpcs # PSR-12 code style +composer test # PHPUnit +``` + +Most tests need a MySQL database, given by environment variables. One way, with Docker: + +```bash +docker run -d --rm --name glpdo2-mysql -p 3306:3306 \ + -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=glpdo2 mysql:8.4 + +MYSQLHOST=127.0.0.1 MYSQLDB=glpdo2 MYSQLUSER=root MYSQLPASS=root composer test +``` -Statement->execute(\PDO $PDO)
-Prepares and executes the statement +[CI](.github/workflows/ci.yml) runs the tests on PHP 8.1–8.5 against MySQL 8.4. -Statement->getComputed()
-Returns what the compiled SQL query string might look like for debugging purposes. +## Changelog and license -### Alternative Packages -* https://github.com/nkt/flame +See [CHANGELOG.md](CHANGELOG.md) for the release history. GLPDO2 is released under the [BSD 3-Clause License](LICENSE.BSD).