From 9dcef3e33d78e25f95f344924a9058b0547641e8 Mon Sep 17 00:00:00 2001 From: ellisgl Date: Wed, 25 Nov 2026 11:30:12 -0600 Subject: [PATCH] Add PostgreSQL support and bIdent() identifier quoting - Statement::bIdent() quotes table, column and database names for the database in use ('db.users.id', 'users.*', arrays for column lists). - IdentifierBindingInterface with QuotedIdentifierBindings, MySQLIdentifierBindings and PostgreSQLIdentifierBindings. - Dialect enum and PostgreSQLBindingFactory. With the PostgreSQL dialect, sql() reads standard '...' strings, E'...' strings, dollar quoting, "..." identifiers, "--" comments and nesting block comments; "#" is not a comment, and "??" is a literal "?" for the jsonb operators. - Bindings takes optional identifier and dialect arguments, defaulting to MySQL, so existing code is unchanged. - Fix raw ('%%') values containing '$1' or '\' being read as regex back references. - PostgreSQL integration tests, run in CI against a postgres:17 service. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 18 ++ CHANGELOG.md | 8 + README.md | 89 +++++++- src/Bindings/Bindings.php | 37 ++- src/Bindings/IdentifierBindingInterface.php | 21 ++ src/Bindings/MySQL/MySQLBindingFactory.php | 3 +- .../MySQL/MySQLIdentifierBindings.php | 17 ++ .../PostgreSQL/PostgreSQLBindingFactory.php | 31 +++ .../PostgreSQLIdentifierBindings.php | 17 ++ src/Bindings/QuotedIdentifierBindings.php | 108 +++++++++ src/Dialect.php | 39 ++++ src/Statement.php | 213 +++++++++++++++--- tests/GLPDO2PostgreSQLTest.php | 144 ++++++++++++ tests/IdentifierBindingsTest.php | 130 +++++++++++ tests/StatementPostgreSQLPlaceholderTest.php | 143 ++++++++++++ 15 files changed, 973 insertions(+), 45 deletions(-) create mode 100644 src/Bindings/IdentifierBindingInterface.php create mode 100644 src/Bindings/MySQL/MySQLIdentifierBindings.php create mode 100644 src/Bindings/PostgreSQL/PostgreSQLBindingFactory.php create mode 100644 src/Bindings/PostgreSQL/PostgreSQLIdentifierBindings.php create mode 100644 src/Bindings/QuotedIdentifierBindings.php create mode 100644 src/Dialect.php create mode 100644 tests/GLPDO2PostgreSQLTest.php create mode 100644 tests/IdentifierBindingsTest.php create mode 100644 tests/StatementPostgreSQLPlaceholderTest.php diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index efb900f..7c4a4fb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,17 +30,35 @@ jobs: --health-interval=5s --health-timeout=5s --health-retries=20 + postgres: + image: postgres:17 + env: + POSTGRES_PASSWORD: postgres + POSTGRES_DB: glpdo2 + ports: + - 5432:5432 + options: >- + --health-cmd="pg_isready -U postgres -d glpdo2" + --health-interval=5s + --health-timeout=5s + --health-retries=20 env: MYSQLHOST: 127.0.0.1 MYSQLDB: glpdo2 MYSQLUSER: root MYSQLPASS: root + PGHOST: 127.0.0.1 + PGPORT: 5432 + PGDB: glpdo2 + PGUSER: postgres + PGPASS: postgres steps: - uses: actions/checkout@v4 - uses: shivammathur/setup-php@v2 with: php-version: ${{ matrix.php }} + extensions: pdo_mysql, pdo_pgsql coverage: none - uses: ramsey/composer-install@v3 diff --git a/CHANGELOG.md b/CHANGELOG.md index d9e4dc7..1ed02e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,11 @@ +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 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. +* Fixed raw ('%%') values containing '$1' or '\' being read as regex back references when they were put into the SQL. + 2026-11-25 (4.1.0) * Requires PHP 8.3 or newer (was 8.1). CI tests PHP 8.3-8.5. * Dev tools updated: PHPUnit 12, PHP_CodeSniffer 4, PHPMD 3. Tests moved from @dataProvider annotations to attributes. diff --git a/README.md b/README.md index d9d4275..36695d4 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,7 @@ $users = $db->selectRows( - [Binding methods](#binding-methods) - [Query methods](#query-methods) - [Security](#security) +- [PostgreSQL](#postgresql) - [Custom bindings](#custom-bindings) - [Limitations](#limitations) - [Development](#development) @@ -69,7 +70,7 @@ With GLPDO2: composer require geeklab/glpdo2 ``` -Requires PHP 8.3 or newer with the `pdo_mysql` extension. The bindings are written for MySQL and MariaDB. +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). ## Quick start @@ -178,12 +179,31 @@ try { 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: -| Placeholder | Filled by | How the value gets to MySQL | +| 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`, `bRaw` | Replaced in the SQL text: by a list of bound parameters (`bStrArr`), by validated numbers (`bIntArray`, `bFloat`), or as is (`bRaw`). | +| `%%` | `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`). | -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. +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). + +### 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. + +```php +$statement + ->sql('SELECT %% FROM %% WHERE %% = ?') + ->bIdent(['id', 'users.name'])->bIdent('app.users')->bIdent('id')->bInt(5); + +// MySQL: SELECT `id`, `users`.`name` FROM `app`.`users` WHERE `id` = 5 +// PostgreSQL: SELECT "id", "users"."name" FROM "app"."users" WHERE "id" = 5 +``` + +- Dots split a name into parts, and each part is quoted on its own. A name that contains a dot can't be quoted with `bIdent()`. +- A `*` as the last part (`users.*`) is left unquoted. +- Aliases aren't parsed: `'users u'` becomes one quoted name. Write the alias in the SQL instead: `->sql('FROM %% u')`. +- An array becomes a comma-separated list, for `SELECT` and `INSERT` column lists. +- A quote character inside a name is doubled, so the name can't break out of its quotes. Even so, don't let users pick any table or column they like. Check names against a list you allow. ### See the final SQL @@ -220,6 +240,7 @@ 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`. | +| `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. | @@ -254,14 +275,52 @@ Most bindings send values to MySQL as PDO parameters, so they can't change the q |---|---|---| | `?` bindings, `bStrArr()` values | ✅ Yes | Sent as bound parameters. | | `bInt()`, `bFloat()`, `bIntArray()` | ✅ 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. | Versions before 4.0.11 pasted `bStrArr()` values into the SQL without escaping them. Upgrade if you use it. +## PostgreSQL + +Build the bindings with `PostgreSQLBindingFactory`. Everything else works as it does for MySQL: + +```php +use GeekLab\GLPDO2\Bindings\PostgreSQL\PostgreSQLBindingFactory; + +$pdo = new PDO('pgsql:host=localhost;dbname=app', 'user', 'pass', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]); +$db = new GLPDO2($pdo); +$statement = new Statement(PostgreSQLBindingFactory::build()); + +$tagged = $db->selectRows( + $statement + ->sql('SELECT %% FROM %%')->bIdent(['id', 'name'])->bIdent('public.users') + ->sql('WHERE "settings" ?? ?')->bStr('beta') + ->sql('AND "created" >= ?::date')->bDate('2026-01-01') +); +``` + +With it, `sql()` reads the text by PostgreSQL's rules rather than MySQL's: + +| | MySQL | PostgreSQL | +|---|---|---| +| Strings | `'...'` and `"..."`, with backslash escapes | `'...'` (backslash is a plain character), `E'...'` (backslash escapes), `$$...$$` and `$tag$...$tag$` | +| Quoted identifiers | `` `...` `` | `"..."` | +| Comments | `-- ` (needs whitespace after it), `#`, `/* */` | `--`, `/* */` (can nest) | +| Literal `?` | — | `??`, for the jsonb `?`, `?\|` and `?&` operators | + +`#` isn't a comment in PostgreSQL, so operators like `#>` and `#>>` work. For the jsonb operators, write `??` where you mean a literal `?`: `"data" ?? ?` checks whether the bound key exists. PDO turns `??` back into `?`, and `getComputed()` shows it as `?`. + +PDO scans the SQL again before sending it, and its scanner doesn't follow all of PostgreSQL's rules: + +- **PHP 8.3:** PDO doesn't recognise dollar-quoted strings, so a `?` or `:name` inside `$$...$$` fails with "mixed named and positional parameters". PHP 8.4 and newer handle them. +- **Nested comments:** PDO ends a comment at the first `*/`. Don't put `?`, `:name` or quotes in the outer comment after a nested one closes. + +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. + ## 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: +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: ```php use GeekLab\GLPDO2\Bindings\Bindings; @@ -278,9 +337,27 @@ $bindings = new Bindings( $statement = new Statement($bindings); ``` +Two more arguments are optional: + +- `$identifier`: how `bIdent()` quotes names. It defaults to the dialect's quoting. For other quote characters, use `QuotedIdentifierBindings`, such as `new QuotedIdentifierBindings('[', ']')` for SQL Server. +- `$dialect`: a `GeekLab\GLPDO2\Dialect`, which decides how `sql()` finds strings and comments. It defaults to `Dialect::MySQL`. + +```php +use GeekLab\GLPDO2\Dialect; + +$bindings = new Bindings( + new MyDateTimeBindings(), + new MySQL\MySQLLogicBindings(), + new MySQL\MySQLNumericBindings(), + new MySQL\MySQLRawBindings(), + new MySQL\MySQLStringBindings(), + dialect: Dialect::PostgreSQL +); +``` + ## Limitations -- **MySQL and MariaDB only.** Other databases may work for simple queries, but aren't tested. +- **MySQL, MariaDB and PostgreSQL.** 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. diff --git a/src/Bindings/Bindings.php b/src/Bindings/Bindings.php index 8a23c96..76fd109 100644 --- a/src/Bindings/Bindings.php +++ b/src/Bindings/Bindings.php @@ -4,7 +4,9 @@ use PDO; use Exception; +use InvalidArgumentException; use JsonException; +use GeekLab\GLPDO2\Dialect; class Bindings { @@ -13,19 +15,39 @@ class Bindings protected NumericBindingInterface $numeric; protected RawBindingInterface $raw; protected StringBindingInterface $string; + protected IdentifierBindingInterface $identifier; + protected Dialect $dialect; + /** + * $dialect defaults to MySQL, and $identifier to the dialect's quoting, + * so code written before they existed keeps working. + */ public function __construct( DateTimeBindingInterface $dateTime, LogicBindingInterface $logic, NumericBindingInterface $numeric, RawBindingInterface $raw, - StringBindingInterface $string + StringBindingInterface $string, + ?IdentifierBindingInterface $identifier = null, + ?Dialect $dialect = null ) { $this->dateTime = $dateTime; $this->logic = $logic; $this->numeric = $numeric; $this->raw = $raw; $this->string = $string; + $this->dialect = $dialect ?? Dialect::MySQL; + $this->identifier = $identifier ?? $this->dialect->identifierBindings(); + } + + /** + * The SQL dialect, which Statement::sql() uses to find quoted text and comments. + * + * @return Dialect + */ + public function getDialect(): Dialect + { + return $this->dialect; } /** @@ -129,6 +151,19 @@ public function bIntArray(array $data): array return $this->numeric->bIntArray($data); } + /** + * Quote an identifier (database, table, column), or a list of them, for the SQL text. + * + * @param string | array $value + * + * @return array{string} + * @throws InvalidArgumentException + */ + public function bIdent(string | array $value): array + { + return $this->identifier->bIdent($value); + } + /** * Bind an object or JSON string to a string * diff --git a/src/Bindings/IdentifierBindingInterface.php b/src/Bindings/IdentifierBindingInterface.php new file mode 100644 index 0000000..f539ddf --- /dev/null +++ b/src/Bindings/IdentifierBindingInterface.php @@ -0,0 +1,21 @@ + $value + * + * @return array{string} + * @throws InvalidArgumentException + */ + public function bIdent(string | array $value): array; +} diff --git a/src/Bindings/MySQL/MySQLBindingFactory.php b/src/Bindings/MySQL/MySQLBindingFactory.php index a20fb82..e2607f1 100644 --- a/src/Bindings/MySQL/MySQLBindingFactory.php +++ b/src/Bindings/MySQL/MySQLBindingFactory.php @@ -13,7 +13,8 @@ public static function build(): Bindings new MySQLLogicBindings(), new MySQLNumericBindings(), new MySQLRawBindings(), - new MySQLStringBindings() + new MySQLStringBindings(), + new MySQLIdentifierBindings() ); } } diff --git a/src/Bindings/MySQL/MySQLIdentifierBindings.php b/src/Bindings/MySQL/MySQLIdentifierBindings.php new file mode 100644 index 0000000..1de5c4a --- /dev/null +++ b/src/Bindings/MySQL/MySQLIdentifierBindings.php @@ -0,0 +1,17 @@ +open = $open; + $this->close = $close; + } + + /** + * Quote one identifier, or a list of them, for the SQL text. + * Dots split a name into parts ("db.users.id"), and each part is quoted on its own. + * A "*" as the last part ("users.*") is left as is. + * An array becomes a comma separated list, for column lists. + * + * @param string | array $value + * + * @return array{string} + * @throws InvalidArgumentException + */ + public function bIdent(string | array $value): array + { + $names = is_array($value) ? $value : [$value]; + + if (empty($names)) { + throw new InvalidArgumentException('Can not quote an empty list of identifiers.'); + } + + $quoted = []; + + foreach ($names as $name) { + if (!is_string($name)) { + throw new InvalidArgumentException('Identifiers must be strings.'); + } + + $quoted[] = $this->quoteName($name); + } + + return [implode(', ', $quoted)]; + } + + /** + * Quote a possibly qualified name, such as "db.users.id" or "users.*". + * + * @param string $name + * + * @return string + * @throws InvalidArgumentException + */ + private function quoteName(string $name): string + { + $parts = explode('.', $name); + $last = count($parts) - 1; + + foreach ($parts as $i => $part) { + if ($i === $last && $part === '*') { + continue; + } + + $parts[$i] = $this->quotePart($part); + } + + return implode('.', $parts); + } + + /** + * Quote a single identifier part. + * + * @param string $part + * + * @return string + * @throws InvalidArgumentException + */ + private function quotePart(string $part): string + { + if ($part === '') { + throw new InvalidArgumentException('Identifiers and their parts can not be empty.'); + } + + if (str_contains($part, "\0")) { + throw new InvalidArgumentException('Identifiers can not contain NUL bytes.'); + } + + return $this->open . str_replace($this->close, $this->close . $this->close, $part) . $this->close; + } +} diff --git a/src/Dialect.php b/src/Dialect.php new file mode 100644 index 0000000..8473f90 --- /dev/null +++ b/src/Dialect.php @@ -0,0 +1,39 @@ + new MySQLIdentifierBindings(), + self::PostgreSQL => new PostgreSQLIdentifierBindings(), + }; + } +} diff --git a/src/Statement.php b/src/Statement.php index 54fd44e..9258335 100644 --- a/src/Statement.php +++ b/src/Statement.php @@ -19,7 +19,11 @@ class Statement /** * @var array{} | array{mixed} $SQL */ - private array $SQL = []; // SQL Statement. + private array $SQL = []; // SQL Statement, as sent to PDO. + /** + * @var array{} | array{mixed} $shownSQL + */ + private array $shownSQL = []; // SQL Statement for getComputed(). Differs only where "??" stands for "?". private int $sqlPos = 0; // Position holder for statement processing. /** * @var array{} | array $rawNamed @@ -29,14 +33,19 @@ class Statement private int $rawSqlPos = 0; // Position holder for '%%' placeholders found by sql(). private int $arrPos = 0; // Position holder for array element binds (bStrArr). + private Dialect $dialect; // Decides how sql() finds quoted text and comments. + // Where sql() is in the statement text, so '?' and '%%' inside literals and comments are left alone. // Kept across sql() calls, since a quoted string can span several of them. private const LEX_CODE = 0; private const LEX_QUOTED = 1; // Inside '...', "..." or `...`; $lexQuote holds which. - private const LEX_LINE_COMMENT = 2; // After "-- " or "#", until the end of the line. - private const LEX_BLOCK_COMMENT = 3; // Inside /* ... */. + private const LEX_LINE_COMMENT = 2; // After "--" or "#", until the end of the line. + private const LEX_BLOCK_COMMENT = 3; // Inside /* ... */; $lexDepth counts nesting (PostgreSQL). + private const LEX_DOLLAR = 4; // Inside a PostgreSQL $tag$...$tag$ string; $lexQuote holds the tag. private int $lexState = self::LEX_CODE; private string $lexQuote = ''; + private bool $lexBackslash = false; // Whether a backslash escapes the next character in this quote. + private int $lexDepth = 0; // /** // * @var array{} | array{mixed} $rawSql // */ @@ -45,6 +54,7 @@ class Statement public function __construct(Bindings $bindings) { $this->bindings = $bindings; + $this->dialect = $bindings->getDialect(); } /** @@ -57,7 +67,12 @@ public function __construct(Bindings $bindings) private function rawPlaceholderFill(string $sql): string { foreach ($this->rawNamed as $name => $rVal) { - $sql = (string)preg_replace('/' . $name . '\b/', $rVal, $sql); + // A callback, so '$1' or '\' in the value is inserted as is rather than read as a back reference. + $sql = (string)preg_replace_callback( + '/' . preg_quote((string)$name, '/') . '\b/', + static fn (): string => (string)$rVal, + $sql + ); } return $sql; @@ -220,6 +235,27 @@ public function bIntArray(array $data): self return $this; } + /** + * Quote an identifier (database, table, column), or a list of them. Uses %% + * Quoting follows the bindings: backticks for MySQL, double quotes for PostgreSQL. + * 'db.users.id' quotes each part, 'users.*' leaves the '*' alone, + * and an array becomes a comma separated list, e.g. for INSERT column lists. + * Quoting makes any name safe to put in the SQL, but still don't let users pick + * arbitrary tables or columns: check names against a list you allow. + * + * @param string | array $name + * + * @return Statement + * @throws InvalidArgumentException + */ + public function bIdent(string | array $name): self + { + $binding = $this->bindings->bIdent($name); + $this->rawBind($this->getNextName('raw'), $binding[0]); + + return $this; + } + /** * Bind an object or JSON string to a string * @@ -446,8 +482,14 @@ private function placeholderGetName(): string /** * Builds up the SQL parameterized statement. * '?' becomes a named placeholder and '%%' a raw placeholder, except inside - * quoted strings ('...', "...") and comments (-- , #, /* * /). - * Inside backtick identifiers only '%%' is a placeholder, so `%%` with bRaw() can name a table. + * string literals and comments, which are found by the bindings' dialect: + * + * - MySQL: '...' and "..." strings, "-- " (whitespace after it), "#" and /* * / comments. + * - PostgreSQL: '...', E'...' and $tag$...$tag$ strings, "--" and nesting /* * / comments. + * "??" is a literal "?", for the jsonb ?, ?| and ?& operators. + * + * Inside identifier quotes (`...` for MySQL, "..." for PostgreSQL) only '%%' is a placeholder, + * so `%%` with bRaw() can name a table. * * @param string $text * @@ -455,31 +497,38 @@ private function placeholderGetName(): string */ public function sql(string $text): self { - $out = ''; + $out = ''; // For PDO. + $shown = ''; // For getComputed(). $len = strlen($text); + $pg = $this->dialect === Dialect::PostgreSQL; + $identQuote = $pg ? '"' : '`'; for ($i = 0; $i < $len; $i++) { $char = $text[$i]; $next = $i + 1 < $len ? $text[$i + 1] : ''; + $emit = $char; // What this step adds to $out. + $emitShown = null; // What it adds to $shown, when that differs. switch ($this->lexState) { case self::LEX_QUOTED: - if ($this->lexQuote === '`' && $char === '%' && $next === '%') { + if ($this->lexQuote === $identQuote && $char === '%' && $next === '%') { // `%%` with bRaw() fills in an identifier, such as a table name. - $out .= $this->getNextName('rawSql'); + $emit = $this->getNextName('rawSql'); $i++; - continue 2; - } - - if ($char === '\\' && $this->lexQuote !== '`') { + } elseif ($char === '\\' && $this->lexBackslash) { // Backslash escape: copy it and the escaped character as is. - $out .= $char . $next; + $emit = $char . $next; $i++; - continue 2; + } elseif ($char === $this->lexQuote) { + // A doubled quote ('') closes and immediately reopens, which works out the same. + $this->lexState = self::LEX_CODE; } + break; - if ($char === $this->lexQuote) { - // A doubled quote ('') closes and immediately reopens, which works out the same. + case self::LEX_DOLLAR: + if ($char === '$' && substr($text, $i, strlen($this->lexQuote)) === $this->lexQuote) { + $emit = $this->lexQuote; + $i += strlen($this->lexQuote) - 1; $this->lexState = self::LEX_CODE; } break; @@ -492,39 +541,61 @@ public function sql(string $text): self case self::LEX_BLOCK_COMMENT: if ($char === '*' && $next === '/') { - $out .= '*/'; + $emit = '*/'; $i++; - $this->lexState = self::LEX_CODE; - continue 2; + + if (--$this->lexDepth === 0) { + $this->lexState = self::LEX_CODE; + } + } elseif ($pg && $char === '/' && $next === '*') { + // PostgreSQL block comments nest. + $emit = '/*'; + $i++; + $this->lexDepth++; } break; default: - if ($char === '?') { - $out .= $this->placeholderGetName(); - continue 2; - } + $tag = $pg && $char === '$' ? $this->dollarTag($text, $i) : null; - if ($char === '%' && $next === '%') { - $out .= $this->getNextName('rawSql'); + if ($char === '?' && $pg && $next === '?') { + // "??" is PDO's escape for a literal "?" (PHP 7.4+), e.g. the jsonb "?" operator. + $emit = '??'; + $emitShown = '?'; $i++; - continue 2; - } - - if ($char === "'" || $char === '"' || $char === '`') { - $this->lexState = self::LEX_QUOTED; - $this->lexQuote = $char; - } elseif ($char === '#' || ($char === '-' && $next === '-' && $this->isCommentGap($text, $i + 2))) { + } elseif ($char === '?') { + $emit = $this->placeholderGetName(); + } elseif ($char === '%' && $next === '%') { + $emit = $this->getNextName('rawSql'); + $i++; + } elseif ($char === "'") { + // MySQL always reads backslash escapes in strings. PostgreSQL only in E'...'. + $this->startQuote($char, !$pg || $this->isEscapeStringPrefix($text, $i)); + } elseif ($char === '"') { + // A string in MySQL, an identifier in PostgreSQL. + $this->startQuote($char, !$pg); + } elseif ($char === '`' && !$pg) { + $this->startQuote($char, false); + } elseif ($tag !== null) { + $emit = $tag; + $i += strlen($tag) - 1; + $this->lexState = self::LEX_DOLLAR; + $this->lexQuote = $tag; + } elseif ( + ($char === '#' && !$pg) + || ($char === '-' && $next === '-' && ($pg || $this->isCommentGap($text, $i + 2))) + ) { $this->lexState = self::LEX_LINE_COMMENT; } elseif ($char === '/' && $next === '*') { - $out .= '/*'; + $emit = '/*'; $i++; $this->lexState = self::LEX_BLOCK_COMMENT; - continue 2; + $this->lexDepth = 1; } } - $out .= $char; + $out .= $emit; + $shown .= $emitShown ?? $emit; } // Each sql() call is its own line in getComputed(), so a line comment ends with it. @@ -533,10 +604,26 @@ public function sql(string $text): self } $this->SQL[] = $out; + $this->shownSQL[] = $shown; return $this; } + /** + * Enter a quoted string or identifier. + * + * @param string $quote + * @param bool $backslash Whether a backslash escapes the next character inside it. + * + * @return void + */ + private function startQuote(string $quote, bool $backslash): void + { + $this->lexState = self::LEX_QUOTED; + $this->lexQuote = $quote; + $this->lexBackslash = $backslash; + } + /** * MySQL only treats "--" as a comment when whitespace (or the end of the text) follows it. * @@ -550,6 +637,55 @@ private function isCommentGap(string $text, int $pos): bool return $pos >= strlen($text) || in_array($text[$pos], [' ', "\t", "\r", "\n"], true); } + /** + * Whether the quote at $pos opens a PostgreSQL E'...' string, where backslash escapes work. + * + * @param string $text + * @param int $pos position of the opening quote + * + * @return bool + */ + private function isEscapeStringPrefix(string $text, int $pos): bool + { + return $pos > 0 + && ($text[$pos - 1] === 'E' || $text[$pos - 1] === 'e') + && ($pos === 1 || !$this->isIdentifierChar($text[$pos - 2])); + } + + /** + * The PostgreSQL dollar quote tag ($$ or $tag$) starting at $pos, or null if there isn't one. + * A "$" inside a name (foo$bar) or a parameter ($1) doesn't start one. + * + * @param string $text + * @param int $pos position of the "$" + * + * @return string | null + */ + private function dollarTag(string $text, int $pos): ?string + { + if ($pos > 0 && $this->isIdentifierChar($text[$pos - 1])) { + return null; + } + + if (preg_match('/\G\$(?:[A-Za-z_\x80-\xff][A-Za-z0-9_\x80-\xff]*)?\$/', $text, $match, 0, $pos) !== 1) { + return null; + } + + return $match[0]; + } + + /** + * Whether a character can be part of an unquoted name. + * + * @param string $char + * + * @return bool + */ + private function isIdentifierChar(string $char): bool + { + return $char === '_' || $char === '$' || ctype_alnum($char) || ord($char) >= 0x80; + } + /** * Reset / Clear out properties. * @@ -560,6 +696,7 @@ public function reset(): self $this->bindPos = 0; $this->named = []; $this->SQL = []; + $this->shownSQL = []; $this->sqlPos = 0; $this->rawNamed = []; $this->rawPos = 0; @@ -567,6 +704,8 @@ public function reset(): self $this->arrPos = 0; $this->lexState = self::LEX_CODE; $this->lexQuote = ''; + $this->lexBackslash = false; + $this->lexDepth = 0; // $this->rawSql = []; return $this; @@ -583,7 +722,7 @@ public function getComputed(): string { // Merge SQL together, then fill raw placeholders first, as execute() does. // Raw values can contain named placeholders (bStrArr), which are filled below. - $sql = $this->rawPlaceholderFill(implode("\n", $this->SQL)); + $sql = $this->rawPlaceholderFill(implode("\n", $this->shownSQL)); // Replace positioned placeholders with named placeholders (first value). // Force to string, in the case of null. diff --git a/tests/GLPDO2PostgreSQLTest.php b/tests/GLPDO2PostgreSQLTest.php new file mode 100644 index 0000000..9da0f17 --- /dev/null +++ b/tests/GLPDO2PostgreSQLTest.php @@ -0,0 +1,144 @@ +markTestSkipped('Set PGHOST, PGDB, PGUSER and PGPASS to run the PostgreSQL tests.'); + } + + $pdo = new PDO( + 'pgsql:host=' . getenv('PGHOST') . ';port=' . (getenv('PGPORT') ?: '5432') . ';dbname=' . getenv('PGDB'), + (string)getenv('PGUSER'), + (string)getenv('PGPASS'), + [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION] + ); + $this->db = new GLPDO2($pdo); + + $this->db->queryUpdate($this->statement()->sql('DROP TABLE IF EXISTS %%')->bIdent('Test Items')); + $this->db->queryUpdate( + $this->statement() + ->sql('CREATE TABLE %% (')->bIdent('Test Items') + ->sql(' "id" SERIAL PRIMARY KEY,') + ->sql(' "Name" TEXT NOT NULL, -- quoted, so case sensitive?') + ->sql(' "data" JSONB NOT NULL') + ->sql(')') + ); + + foreach ([['Ann', '{"tags": ["a", "b"], "n": 1}'], ['Bob', '{"tags": ["c"], "x": 2}']] as [$name, $json]) { + $this->db->queryInsert( + $this->statement() + ->sql('INSERT INTO %% (%%)')->bIdent('Test Items')->bIdent(['Name', 'data']) + ->sql('VALUES (?, ?::jsonb)')->bStr($name)->bStr($json) + ); + } + } + + private function statement(): Statement + { + return new Statement(PostgreSQLBindingFactory::build()); + } + + public function testInsertReturnsTheNewId(): void + { + $id = $this->db->queryInsert( + $this->statement() + ->sql('INSERT INTO "Test Items" ("Name", "data") VALUES (?, ?::jsonb)')->bStr('Cy')->bStr('{}') + ); + + $this->assertSame('3', $id); + } + + public function testQuotedIdentifiersAndPlaceholders(): void + { + $rows = $this->db->selectRows( + $this->statement() + ->sql('SELECT %% FROM %%')->bIdent(['Test Items.id', 'Name'])->bIdent('public.Test Items') + ->sql('WHERE "Name" IN (%%) ORDER BY "id"')->bStrArr(['Ann', 'Bob']) + ); + + $this->assertSame([['id' => 1, 'Name' => 'Ann'], ['id' => 2, 'Name' => 'Bob']], $rows); + } + + public function testJsonbQuestionMarkOperators(): void + { + $value = $this->db->selectValue( + $this->statement() + ->sql('SELECT "Name" FROM "Test Items"') + ->sql('WHERE "data" ?? ? AND "data"->\'tags\' ??| ?::text[]')->bStr('x')->bStr('{c,z}'), + 'Name', + true + ); + + $this->assertSame('Bob', $value); + } + + public function testHashOperatorIsNotAComment(): void + { + $value = $this->db->selectValue( + $this->statement()->sql('SELECT "data" #>> ? AS v FROM "Test Items" WHERE "id" = ?') + ->bStr('{tags,1}')->bInt(1), + 'v' + ); + + $this->assertSame('b', $value); + } + + public function testLiteralsAndCommentsKeepTheirQuestionMarks(): void + { + // PDO's own scanner doesn't nest comments, so the outer comment has no "?" after the inner one closes. + $row = $this->db->selectRow( + $this->statement() + ->sql("SELECT 'Why?' AS a, E'it\\'s?' AS b, \"odd?\" AS c, d") + ->sql('FROM (SELECT 1 AS "odd?") t, /* outer? /* nested? */ */ (SELECT ?::int AS d) u --trailing?') + ->bInt(7) + ); + + $this->assertSame(['a' => 'Why?', 'b' => "it's?", 'c' => 1, 'd' => 7], $row); + } + + /** + * Before PHP 8.4, PDO's own scanner doesn't know dollar quoting and reads a "?" in one as a placeholder. + */ + #[RequiresPhp('>= 8.4.0')] + public function testDollarQuotedStringKeepsItsQuestionMarks(): void + { + $row = $this->db->selectRow( + $this->statement()->sql('SELECT $$ok? %%$$ AS a, $t$it\'s? $$ $t$ AS b, ?::int AS c')->bInt(7) + ); + + $this->assertSame(['a' => 'ok? %%', 'b' => "it's? \$\$ ", 'c' => 7], $row); + } + + #[RequiresPhp('>= 8.4.0')] + public function testDollarQuotedFunctionBody(): void + { + $this->db->queryUpdate( + $this->statement() + ->sql('CREATE OR REPLACE FUNCTION pg_temp.glpdo2_add(a int, b int) RETURNS int AS $fn$') + ->sql(' SELECT a + b; -- what? %%') + ->sql('$fn$ LANGUAGE sql') + ); + + $value = $this->db->selectValue( + $this->statement()->sql('SELECT pg_temp.glpdo2_add(?, ?) AS v')->bInt(2)->bInt(3), + 'v' + ); + + $this->assertSame('5', $value); + } +} diff --git a/tests/IdentifierBindingsTest.php b/tests/IdentifierBindingsTest.php new file mode 100644 index 0000000..34387a1 --- /dev/null +++ b/tests/IdentifierBindingsTest.php @@ -0,0 +1,130 @@ +, string, string}> + */ + public static function quotingProvider(): array + { + return [ + 'plain name' => ['users', '`users`', '"users"'], + 'qualified name' => ['db.users.id', '`db`.`users`.`id`', '"db"."users"."id"'], + 'star after table' => ['users.*', '`users`.*', '"users".*'], + 'bare star' => ['*', '*', '*'], + 'list' => [['id', 'u.name'], '`id`, `u`.`name`', '"id", "u"."name"'], + 'backtick in name' => ['we`ird', '`we``ird`', '"we`ird"'], + 'double quote in name' => ['we"ird', '`we"ird`', '"we""ird"'], + 'spaces and case' => ['Order Items', '`Order Items`', '"Order Items"'], + 'dollar and slash' => ['a$1\\b', '`a$1\\b`', '"a$1\\b"'], + ]; + } + + /** + * @param string | array $name + */ + #[DataProvider('quotingProvider')] + public function testQuotingPerDatabase(string | array $name, string $mysql, string $postgres): void + { + $this->assertSame([$mysql], (new MySQLIdentifierBindings())->bIdent($name)); + $this->assertSame([$postgres], (new PostgreSQLIdentifierBindings())->bIdent($name)); + } + + public function testSqlServerStyleBrackets(): void + { + $this->assertSame(['[dbo].[we]]ird]'], (new QuotedIdentifierBindings('[', ']'))->bIdent('dbo.we]ird')); + } + + public function testStatementUsesMySQLByDefault(): void + { + $statement = (new Statement(MySQLBindingFactory::build())) + ->sql('SELECT %% FROM %%')->bIdent(['id', 'name'])->bIdent('users') + ->sql('WHERE %% = ?')->bIdent('id')->bInt(5); + + $this->assertSame("SELECT `id`, `name` FROM `users`\nWHERE `id` = 5", $statement->getComputed()); + } + + public function testStatementUsesPostgreSQLQuoting(): void + { + $statement = (new Statement($this->postgresBindings())) + ->sql('INSERT INTO %% (%%)')->bIdent('public.users')->bIdent(['name', 'role']) + ->sql('VALUES (?, ?)')->bStr('Ann')->bStr('admin'); + + $this->assertSame( + "INSERT INTO \"public\".\"users\" (\"name\", \"role\")\nVALUES ('Ann', 'admin')", + $statement->getComputed() + ); + } + + public function testBindingsWithoutIdentifierArgumentDefaultToMySQL(): void + { + $bindings = new Bindings( + new MySQL\MySQLDateTimeBindings(), + new MySQL\MySQLLogicBindings(), + new MySQL\MySQLNumericBindings(), + new MySQL\MySQLRawBindings(), + new MySQL\MySQLStringBindings() + ); + + $this->assertSame(['`users`'], $bindings->bIdent('users')); + } + + public function testRawValueWithBackReferenceCharactersIsInsertedAsIs(): void + { + $statement = (new Statement(MySQLBindingFactory::build()))->sql('SELECT %%')->bIdent('a$1\\0b'); + + $this->assertSame('SELECT `a$1\\0b`', $statement->getComputed()); + } + + /** + * @return array}> + */ + public static function invalidProvider(): array + { + return [ + 'empty name' => [''], + 'empty part' => ['db..users'], + 'trailing dot' => ['users.'], + 'NUL byte' => ["us\0ers"], + 'empty list' => [[]], + 'non-string' => [[1]], + ]; + } + + /** + * @param string | array $name + */ + #[DataProvider('invalidProvider')] + public function testInvalidIdentifiersThrow(string | array $name): void + { + $this->expectException(InvalidArgumentException::class); + (new MySQLIdentifierBindings())->bIdent($name); + } +} diff --git a/tests/StatementPostgreSQLPlaceholderTest.php b/tests/StatementPostgreSQLPlaceholderTest.php new file mode 100644 index 0000000..862c499 --- /dev/null +++ b/tests/StatementPostgreSQLPlaceholderTest.php @@ -0,0 +1,143 @@ +__debugInfo()['Unbound SQL']); + } + + /** + * @return array + */ + public static function untouchedProvider(): array + { + return [ + 'single-quoted string' => ["SELECT 'Why?'"], + 'quoted identifier' => ['SELECT "odd?name" FROM t'], + 'doubled quote escape' => ["SELECT 'It''s ok?'"], + 'escape string' => ["SELECT E'a\\'b?'"], + 'lowercase escape string' => ["SELECT e'a\\'b?'"], + 'dollar string' => ['SELECT $$Why? %%$$'], + 'tagged dollar string' => ["SELECT \$fn\$ it's ? \$\$ %% \$fn\$"], + 'dash dash without space' => ['SELECT 1 --why? %%'], + 'block comment' => ['SELECT 1 /* why? %% */'], + 'nested block comment' => ['SELECT 1 /* a /* nested? */ still? %% */'], + 'percent pair in string' => ["SELECT * FROM t WHERE a LIKE '%%'"], + 'comment marker in string' => ["SELECT '-- ?', '/* ?', '\$\$ ?'"], + ]; + } + + #[DataProvider('untouchedProvider')] + public function testPlaceholderCharactersInLiteralsAndCommentsAreLeftAlone(string $sql): void + { + $this->assertSame($sql, $this->statement()->sql($sql)->getComputed()); + } + + public function testBackslashDoesNotEscapeInStandardStrings(): void + { + // 'a\' is a complete string in PostgreSQL, so the "?" after it is a placeholder. + $statement = $this->statement()->sql("SELECT 'a\\', ?")->bInt(1); + + $this->assertSame("SELECT 'a\\', 1", $statement->getComputed()); + } + + public function testNamesEndingInEAreNotEscapeStrings(): void + { + // "some'..." isn't E'...', so the backslash doesn't escape the closing quote. + $statement = $this->statement()->sql("SELECT some'a\\', ?")->bInt(1); + + $this->assertSame("SELECT some'a\\', 1", $statement->getComputed()); + } + + public function testHashIsNotAComment(): void + { + $statement = $this->statement()->sql('SELECT data #> ? FROM t')->bStr('{a,b}'); + + $this->assertSame("SELECT data #> '{a,b}' FROM t", $statement->getComputed()); + } + + public function testDoubleQuestionMarkIsALiteralOperator(): void + { + $statement = $this->statement() + ->sql('SELECT * FROM t WHERE data ?? ? AND data ??| ? AND id = ?') + ->bStr('a')->bStr('{b,c}')->bInt(3); + + // PDO turns "??" into "?" itself; getComputed() shows what the database gets. + $this->assertSame( + "SELECT * FROM t WHERE data ? 'a' AND data ?| '{b,c}' AND id = 3", + $statement->getComputed() + ); + $this->assertSame( + 'SELECT * FROM t WHERE data ?? :pos0 AND data ??| :pos1 AND id = :pos2', + $this->unbound($statement) + ); + } + + public function testDollarInNameDoesNotStartAString(): void + { + $statement = $this->statement()->sql('SELECT foo$bar$, ?')->bInt(1); + + $this->assertSame('SELECT foo$bar$, 1', $statement->getComputed()); + } + + public function testCastAfterPlaceholder(): void + { + $statement = $this->statement()->sql('SELECT ?::int')->bStr('5'); + + $this->assertSame("SELECT '5'::int", $statement->getComputed()); + } + + public function testRawPlaceholderInDoubleQuotesNamesATable(): void + { + $statement = $this->statement()->sql('SELECT "col?" FROM "%%"')->bRaw('test'); + + $this->assertSame('SELECT "col?" FROM "test"', $statement->getComputed()); + } + + public function testBIdentUsesDoubleQuotes(): void + { + $statement = $this->statement()->sql('SELECT %% FROM %%')->bIdent(['id', 'name'])->bIdent('public.t'); + + $this->assertSame('SELECT "id", "name" FROM "public"."t"', $statement->getComputed()); + } + + public function testDollarStringSpanningSqlCallsIsTracked(): void + { + $statement = $this->statement() + ->sql('CREATE FUNCTION f() RETURNS int AS $body$') + ->sql(' SELECT 1; -- why?') + ->sql('$body$ LANGUAGE sql; SELECT ?')->bInt(2); + + $this->assertSame( + "CREATE FUNCTION f() RETURNS int AS \$body\$\n SELECT 1; -- why?\n\$body\$ LANGUAGE sql; SELECT 2", + $statement->getComputed() + ); + } + + public function testResetClearsAnOpenNestedComment(): void + { + $statement = $this->statement()->sql('SELECT /* /* unterminated */'); + $statement->reset()->sql('SELECT ?')->bInt(5); + + $this->assertSame('SELECT 5', $statement->getComputed()); + } +}