diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a019a37..ad90080 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -58,7 +58,7 @@ jobs: - uses: shivammathur/setup-php@v2 with: php-version: ${{ matrix.php }} - extensions: pdo_mysql, pdo_pgsql + extensions: pdo_mysql, pdo_pgsql, pdo_sqlite coverage: none - uses: ramsey/composer-install@v4 diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f33952..cae9572 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,8 @@ Unreleased +* Added SQLite 3 support: Dialect::SQLite and SQLiteBindingFactory. With it, Statement::sql() reads '...' strings without backslash escapes, "...", `...` and [...] identifiers, "--" comments without a following space and non-nesting block comments, and "#" isn't a comment. +* Added SQLiteNumericBindings: bUInt() and bUIntArray() stop at 9223372036854775807, SQLite's integer maximum, since SQLite reads larger numbers as floats and can't tell them apart. +* MySQLNumericBindings' unsigned maximum is now the protected UINT_MAX constant, so subclasses can lower it. +* CI installs pdo_sqlite; GLPDO2SQLiteTest runs against an in-memory database. * Added Statement::bIdent() to quote table, column and database names for the database in use, with a '%%' placeholder. 'db.users.id' quotes each part, 'users.*' keeps the star, and an array gives a column list. * Added IdentifierBindingInterface, with QuotedIdentifierBindings (any quote characters), MySQLIdentifierBindings (backticks) and PostgreSQLIdentifierBindings (double quotes). Bindings takes it as an optional sixth argument and defaults to MySQL, so existing code doesn't change. * Added Statement::bUInt() and bUIntArray() for unsigned integers, 0 to 18446744073709551615 (BIGINT UNSIGNED). They reject negative values, accept values above PHP_INT_MAX as integer strings, and use '%%' so the value is compared exactly. A string parameter would be compared as a float in MySQL expressions and IN() lists. diff --git a/README.md b/README.md index 8bf1cc3..592bd9d 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ $users = $db->selectRows( - [Query methods](#query-methods) - [Security](#security) - [PostgreSQL](#postgresql) +- [SQLite](#sqlite) - [Custom bindings](#custom-bindings) - [Limitations](#limitations) - [Development](#development) @@ -70,7 +71,7 @@ With GLPDO2: composer require geeklab/glpdo2 ``` -Requires PHP 8.3 or newer, with the `pdo_mysql` extension for MySQL and MariaDB or `pdo_pgsql` for PostgreSQL. PHP 8.4 or newer is recommended for PostgreSQL; see [PostgreSQL](#postgresql). +Requires PHP 8.3 or newer, with the `pdo_mysql` extension for MySQL and MariaDB, `pdo_pgsql` for PostgreSQL, or `pdo_sqlite` for SQLite 3. PHP 8.4 or newer is recommended for PostgreSQL; see [PostgreSQL](#postgresql). ## Quick start @@ -184,11 +185,11 @@ Build a query one line at a time with `sql()`, and put each value's binding righ | `?` | `bStr`, `bInt`, `bBool`, `bBoolInt`, `bDate`, `bDateTime`, `bJSON`, `bLike` | Bound as a PDO parameter. The value is never part of the SQL text. | | `%%` | `bStrArr`, `bIntArray`, `bUInt`, `bUIntArray`, `bFloat`, `bIdent`, `bRaw` | Replaced in the SQL text: by a list of bound parameters (`bStrArr`), by validated numbers (`bIntArray`, `bUInt`, `bUIntArray`, `bFloat`), by quoted identifiers (`bIdent`), or as is (`bRaw`). | -Placeholders are filled in order: the first `?` gets the first `?`-type binding, and the first `%%` gets the first `%%`-type binding. Inside quoted strings and comments, `?` and `%%` are plain text, so `WHERE note = 'Why?'` works. Inside quoted identifiers (backticks for MySQL, double quotes for PostgreSQL), `%%` is still a placeholder, so `` `%%` `` with `bRaw()` can fill in a table name. What counts as a string or comment depends on the database; see [PostgreSQL](#postgresql). +Placeholders are filled in order: the first `?` gets the first `?`-type binding, and the first `%%` gets the first `%%`-type binding. Inside quoted strings and comments, `?` and `%%` are plain text, so `WHERE note = 'Why?'` works. Inside quoted identifiers (backticks for MySQL, double quotes for PostgreSQL, any of `"..."`, `` `...` `` and `[...]` for SQLite), `%%` is still a placeholder, so `` `%%` `` with `bRaw()` can fill in a table name. What counts as a string or comment depends on the database; see [PostgreSQL](#postgresql) and [SQLite](#sqlite). ### Quoting table and column names -The examples here quote names with MySQL backticks. To leave quoting to the library, put `%%` where the name goes and bind it with `bIdent()`. The bindings decide how to quote it: backticks for MySQL, double quotes for PostgreSQL. +The examples here quote names with MySQL backticks. To leave quoting to the library, put `%%` where the name goes and bind it with `bIdent()`. The bindings decide how to quote it: backticks for MySQL, double quotes for PostgreSQL and SQLite. ```php $statement @@ -260,6 +261,8 @@ They use `%%` and put the validated digits into the SQL text, rather than bindin PostgreSQL has no unsigned types. There, `bUInt()` checks that a value isn't negative, and values above 2⁶³−1 need a `numeric` column. +SQLite integers are signed 64-bit, and SQLite reads any larger number as a float, so 2⁶⁴−1 and 2⁶⁴−2 would be stored as the same value. With the SQLite bindings, `bUInt()` and `bUIntArray()` therefore stop at `9223372036854775807` and throw above it. Store larger values as text with `bStr()`. + ## Query methods All of these are on `GLPDO2` and take a `Statement`. Errors come through as `PDOException`, as long as the connection uses `PDO::ERRMODE_EXCEPTION`. @@ -334,6 +337,36 @@ PDO scans the SQL again before sending it, and its scanner doesn't follow all of The value bindings are the same as for MySQL. PostgreSQL is stricter about types, so add a cast where it can't infer one, such as `?::date`, `?::jsonb` or `?::int` in a select list. `bBoolInt()` binds `0` or `1`, which a PostgreSQL `boolean` column won't accept; use `bBool()` there. +## SQLite + +Build the bindings with `SQLiteBindingFactory`. Everything else works as it does for MySQL: + +```php +use GeekLab\GLPDO2\Bindings\SQLite\SQLiteBindingFactory; + +$pdo = new PDO('sqlite:/path/to/app.db', null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]); +$db = new GLPDO2($pdo); +$statement = new Statement(SQLiteBindingFactory::build()); + +$rows = $db->selectRows( + $statement + ->sql('SELECT %% FROM %%')->bIdent(['id', 'name'])->bIdent('users') + ->sql('WHERE "settings" ->> ? = ?')->bStr('$.theme')->bStr('dark') +); +``` + +With it, `sql()` reads the text by SQLite's rules: + +| | SQLite | +|---|---| +| Strings | `'...'`. A backslash is a plain character; `''` is a quote. | +| Quoted identifiers | `"..."`, `` `...` `` and `[...]` | +| Comments | `--` (no whitespace needed after it) and `/* */` (doesn't nest) | + +`#` and `$` have no special meaning, and `??` is two placeholders, since SQLite has no `?` operator. + +SQLite handles PDO placeholders itself, so none of the PDO limits described under [PostgreSQL](#postgresql) apply. SQLite has no boolean type: `bBool()` stores `1` or `0`. Dates from `bDate()` and `bDateTime()` are stored as text, which SQLite's date functions read. For unsigned integers above 2⁶³−1, see [Unsigned integers](#unsigned-integers). + ## Custom bindings The bindings are grouped into six interfaces in `GeekLab\GLPDO2\Bindings`: date/time, logic, numeric, raw, string and identifier. `MySQLBindingFactory::build()` creates the MySQL set. To change how a type is bound, implement the matching interface (or extend the MySQL class) and pass your own set in. `bUInt()` and `bUIntArray()` are in `UnsignedNumericBindingInterface`, which extends the numeric interface. If your numeric bindings only implement `NumericBindingInterface`, those two use the MySQL versions: @@ -373,7 +406,7 @@ $bindings = new Bindings( ## Limitations -- **MySQL, MariaDB and PostgreSQL.** Other databases may work for simple queries, but aren't tested. See [PostgreSQL](#postgresql) for limits that come from PDO. +- **MySQL, MariaDB, PostgreSQL and SQLite 3.** Other databases may work for simple queries, but aren't tested. See [PostgreSQL](#postgresql) for limits that come from PDO. - **Invalid dates don't throw.** `bDate()` and `bDateTime()` bind `1970-01-01` (`1970-01-01 00:00:00`) for a value that isn't in the expected format, and only accept years 1900–2099. Validate dates first if that matters. - **`bLike()` doesn't escape wildcards.** A `%` or `_` in the value acts as a wildcard. - **`getComputed()` is approximate.** It shows string values in quotes without escaping them. diff --git a/src/Bindings/MySQL/MySQLNumericBindings.php b/src/Bindings/MySQL/MySQLNumericBindings.php index 4c71696..35c3047 100644 --- a/src/Bindings/MySQL/MySQLNumericBindings.php +++ b/src/Bindings/MySQL/MySQLNumericBindings.php @@ -8,8 +8,8 @@ class MySQLNumericBindings implements UnsignedNumericBindingInterface { - /** @const string UINT64_MAX The largest BIGINT UNSIGNED value, 2^64 - 1. */ - private const UINT64_MAX = '18446744073709551615'; + /** @const string UINT_MAX The largest value bUInt() accepts: BIGINT UNSIGNED's maximum, 2^64 - 1. */ + protected const UINT_MAX = '18446744073709551615'; /** * Bind a float. @@ -189,7 +189,9 @@ private function toUInt(float | bool | int | string $value): string if (is_string($value) && preg_match('/^\s*\+?0*(\d+)\s*$/', $value, $match) === 1) { $digits = $match[1]; - if (strlen($digits) > 20 || (strlen($digits) === 20 && strcmp($digits, self::UINT64_MAX) > 0)) { + $max = static::UINT_MAX; + + if (strlen($digits) > strlen($max) || (strlen($digits) === strlen($max) && strcmp($digits, $max) > 0)) { throw new InvalidArgumentException( 'Can not bind ' . var_export($value, true) . ' in unsigned integer spot: out of range.' ); diff --git a/src/Bindings/SQLite/SQLiteBindingFactory.php b/src/Bindings/SQLite/SQLiteBindingFactory.php new file mode 100644 index 0000000..dbd1d2a --- /dev/null +++ b/src/Bindings/SQLite/SQLiteBindingFactory.php @@ -0,0 +1,31 @@ + new MySQLIdentifierBindings(), self::PostgreSQL => new PostgreSQLIdentifierBindings(), + self::SQLite => new SQLiteIdentifierBindings(), }; } } diff --git a/src/Statement.php b/src/Statement.php index b44e942..8143974 100644 --- a/src/Statement.php +++ b/src/Statement.php @@ -38,13 +38,14 @@ class Statement // 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_QUOTED = 1; // Inside a quoted string or identifier; $lexQuote holds its closing quote. 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 bool $lexIdent = false; // Whether this quote is an identifier, where '%%' is still a placeholder. private int $lexDepth = 0; // /** // * @var array{} | array{mixed} $rawSql @@ -523,8 +524,10 @@ private function placeholderGetName(): string * - 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. + * - SQLite: '...' strings (no backslash escapes), "--" and /* * / comments. * - * Inside identifier quotes (`...` for MySQL, "..." for PostgreSQL) only '%%' is a placeholder, + * Inside identifier quotes (`...` for MySQL, "..." for PostgreSQL, "...", `...` and [...] for SQLite) + * only '%%' is a placeholder, * so `%%` with bRaw() can name a table. * * @param string $text @@ -536,10 +539,11 @@ public function sql(string $text): self $out = ''; // For PDO. $shown = ''; // For getComputed(). $len = strlen($text); + $mysql = $this->dialect === Dialect::MySQL; $pg = $this->dialect === Dialect::PostgreSQL; - $identQuote = $pg ? '"' : '`'; + $sqlite = $this->dialect === Dialect::SQLite; - for ($i = 0; $i < $len; $i++) { + for ($i = 0; $i < $len; ++$i) { $char = $text[$i]; $next = $i + 1 < $len ? $text[$i + 1] : ''; $emit = $char; // What this step adds to $out. @@ -547,14 +551,14 @@ public function sql(string $text): self switch ($this->lexState) { case self::LEX_QUOTED: - if ($this->lexQuote === $identQuote && $char === '%' && $next === '%') { + if ($this->lexIdent && $char === '%' && $next === '%') { // `%%` with bRaw() fills in an identifier, such as a table name. $emit = $this->getNextName('rawSql'); - $i++; + ++$i; } elseif ($char === '\\' && $this->lexBackslash) { // Backslash escape: copy it and the escaped character as is. $emit = $char . $next; - $i++; + ++$i; } elseif ($char === $this->lexQuote) { // A doubled quote ('') closes and immediately reopens, which works out the same. $this->lexState = self::LEX_CODE; @@ -578,7 +582,7 @@ public function sql(string $text): self case self::LEX_BLOCK_COMMENT: if ($char === '*' && $next === '/') { $emit = '*/'; - $i++; + ++$i; if (--$this->lexDepth === 0) { $this->lexState = self::LEX_CODE; @@ -586,8 +590,8 @@ public function sql(string $text): self } elseif ($pg && $char === '/' && $next === '*') { // PostgreSQL block comments nest. $emit = '/*'; - $i++; - $this->lexDepth++; + ++$i; + ++$this->lexDepth; } break; @@ -598,33 +602,36 @@ public function sql(string $text): self // "??" is PDO's escape for a literal "?" (PHP 7.4+), e.g. the jsonb "?" operator. $emit = '??'; $emitShown = '?'; - $i++; + ++$i; } elseif ($char === '?') { $emit = $this->placeholderGetName(); } elseif ($char === '%' && $next === '%') { $emit = $this->getNextName('rawSql'); - $i++; + ++$i; } elseif ($char === "'") { - // MySQL always reads backslash escapes in strings. PostgreSQL only in E'...'. - $this->startQuote($char, !$pg || $this->isEscapeStringPrefix($text, $i)); + // Backslash escapes: always in MySQL, only in E'...' in PostgreSQL, never in SQLite. + $this->startQuote($char, $mysql || ($pg && $this->isEscapeStringPrefix($text, $i)), false); } elseif ($char === '"') { - // A string in MySQL, an identifier in PostgreSQL. - $this->startQuote($char, !$pg); + // A string in MySQL, an identifier in PostgreSQL and SQLite. + $this->startQuote($char, $mysql, !$mysql); } elseif ($char === '`' && !$pg) { - $this->startQuote($char, false); + $this->startQuote($char, false, true); + } elseif ($char === '[' && $sqlite) { + // SQLite also accepts [name] identifiers. Nothing escapes inside them. + $this->startQuote(']', false, true); } 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))) + ($char === '#' && $mysql) + || ($char === '-' && $next === '-' && (!$mysql || $this->isCommentGap($text, $i + 2))) ) { $this->lexState = self::LEX_LINE_COMMENT; } elseif ($char === '/' && $next === '*') { $emit = '/*'; - $i++; + ++$i; $this->lexState = self::LEX_BLOCK_COMMENT; $this->lexDepth = 1; } @@ -648,16 +655,18 @@ public function sql(string $text): self /** * Enter a quoted string or identifier. * - * @param string $quote - * @param bool $backslash Whether a backslash escapes the next character inside it. + * @param string $close The quote that closes it. + * @param bool $backslash Whether a backslash escapes the next character inside it. + * @param bool $identifier Whether it's an identifier, where '%%' is still a placeholder. * * @return void */ - private function startQuote(string $quote, bool $backslash): void + private function startQuote(string $close, bool $backslash, bool $identifier): void { $this->lexState = self::LEX_QUOTED; - $this->lexQuote = $quote; + $this->lexQuote = $close; $this->lexBackslash = $backslash; + $this->lexIdent = $identifier; } /** @@ -741,6 +750,7 @@ public function reset(): self $this->lexState = self::LEX_CODE; $this->lexQuote = ''; $this->lexBackslash = false; + $this->lexIdent = false; $this->lexDepth = 0; // $this->rawSql = []; diff --git a/tests/GLPDO2SQLiteTest.php b/tests/GLPDO2SQLiteTest.php new file mode 100644 index 0000000..3e59533 --- /dev/null +++ b/tests/GLPDO2SQLiteTest.php @@ -0,0 +1,102 @@ +db = new GLPDO2(new PDO('sqlite::memory:', null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION])); + + $this->db->queryUpdate( + $this->statement() + ->sql('CREATE TABLE %% (')->bIdent('Test Items') + ->sql(' [id] INTEGER PRIMARY KEY,') + ->sql(' `Name` TEXT NOT NULL, -- any of the three identifier quotes?') + ->sql(' "active" INTEGER NOT NULL,') + ->sql(' "data" TEXT NOT NULL,') + ->sql(' "day" TEXT NOT NULL') + ->sql(')') + ); + + foreach ([['Ann', true, '{"n": 1}'], ['Bob', false, '{"n": 2}']] as [$name, $active, $json]) { + $this->db->queryInsert( + $this->statement() + ->sql('INSERT INTO %% (%%)')->bIdent('Test Items')->bIdent(['Name', 'active', 'data', 'day']) + ->sql('VALUES (?, ?, ?, ?)')->bStr($name)->bBool($active)->bStr($json)->bDate('2026-01-02') + ); + } + } + + private function statement(): Statement + { + return new Statement(SQLiteBindingFactory::build()); + } + + public function testInsertReturnsTheNewId(): void + { + $id = $this->db->queryInsert( + $this->statement() + ->sql('INSERT INTO "Test Items" ("Name", "active", "data", "day") VALUES (?, ?, ?, ?)') + ->bStr('Cy')->bBool(true)->bStr('{}')->bDate('2026-01-03') + ); + + $this->assertSame('3', $id); + } + + public function testQuotedIdentifiersAndPlaceholders(): void + { + $rows = $this->db->selectRows( + $this->statement() + ->sql('SELECT %% FROM %%')->bIdent(['Test Items.id', 'Name'])->bIdent('main.Test Items') + ->sql('WHERE [Name] IN (%%) AND `active` = ? ORDER BY "id"')->bStrArr(['Ann', 'Bob'])->bBool(true) + ); + + $this->assertSame([['id' => 1, 'Name' => 'Ann']], $rows); + } + + public function testLiteralsAndCommentsKeepTheirQuestionMarks(): void + { + $row = $this->db->selectRow( + $this->statement() + ->sql("SELECT 'Why?' AS a, 'a\\' AS b, 1 AS [c?], ? AS d --trailing?")->bInt(7) + ->sql('/* why? */') + ); + + $this->assertSame(['a' => 'Why?', 'b' => 'a\\', 'c?' => 1, 'd' => 7], $row); + } + + public function testJsonArrowOperators(): void + { + $value = $this->db->selectValue( + $this->statement()->sql('SELECT "data" ->> ? AS n FROM "Test Items" WHERE "id" = ?') + ->bStr('$.n')->bInt(2), + 'n' + ); + + $this->assertSame('2', $value); + } + + public function testUnsignedValuesWithinTheIntegerRange(): void + { + $count = $this->db->selectValue( + $this->statement() + ->sql('SELECT COUNT(*) AS c FROM "Test Items" WHERE "id" IN (%%) OR "id" = %%') + ->bUIntArray([1, '2'])->bUInt(PHP_INT_MAX), + 'c' + ); + + $this->assertSame('2', $count); + } +} diff --git a/tests/StatementSQLitePlaceholderTest.php b/tests/StatementSQLitePlaceholderTest.php new file mode 100644 index 0000000..a508b2a --- /dev/null +++ b/tests/StatementSQLitePlaceholderTest.php @@ -0,0 +1,136 @@ + + */ + public static function untouchedProvider(): array + { + return [ + 'single-quoted string' => ["SELECT 'Why?'"], + 'doubled quote escape' => ["SELECT 'It''s ok?'"], + 'double-quoted identifier' => ['SELECT "odd?name" FROM t'], + 'backtick identifier' => ['SELECT `odd?name` FROM t'], + 'bracket identifier' => ['SELECT [odd?name] FROM t'], + 'quote in brackets' => ["SELECT [it's?] FROM t"], + 'dash dash without space' => ['SELECT 1 --why? %%'], + 'block comment' => ['SELECT 1 /* why? %% */'], + '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 testBackslashDoesNotEscapeInStrings(): void + { + // 'a\' is a complete string in SQLite, so the "?" after it is a placeholder. + $statement = $this->statement()->sql("SELECT 'a\\', ?")->bInt(1); + + $this->assertSame("SELECT 'a\\', 1", $statement->getComputed()); + } + + public function testEscapeStringPrefixMeansNothing(): void + { + // E'...' is PostgreSQL only; in SQLite E is a name and the backslash is a plain character. + $statement = $this->statement()->sql("SELECT E'a\\', ?")->bInt(1); + + $this->assertSame("SELECT E'a\\', 1", $statement->getComputed()); + } + + public function testHashIsNotAComment(): void + { + $statement = $this->statement()->sql('SELECT ? # ?')->bInt(1)->bInt(2); + + $this->assertSame('SELECT 1 # 2', $statement->getComputed()); + } + + public function testBlockCommentsDoNotNest(): void + { + // The first "*/" ends the comment, so the "?" after it is a placeholder. + $statement = $this->statement()->sql('SELECT /* a /* b */ ?')->bInt(3); + + $this->assertSame('SELECT /* a /* b */ 3', $statement->getComputed()); + } + + public function testDollarSignsAreNotQuotes(): void + { + $statement = $this->statement()->sql('SELECT $$, ?')->bInt(4); + + $this->assertSame('SELECT $$, 4', $statement->getComputed()); + } + + public function testDoubleQuestionMarkIsTwoPlaceholders(): void + { + // SQLite has no "?" operator, so "??" isn't an escape here. + $statement = $this->statement()->sql('SELECT ??')->bInt(1)->bInt(2); + + $this->assertSame('SELECT 12', $statement->getComputed()); + } + + /** + * @return array + */ + public static function rawIdentifierProvider(): array + { + return [ + 'double quotes' => ['SELECT "col?" FROM "%%"', 'SELECT "col?" FROM "test"'], + 'backticks' => ['SELECT `col?` FROM `%%`', 'SELECT `col?` FROM `test`'], + 'brackets' => ['SELECT [col?] FROM [%%]', 'SELECT [col?] FROM [test]'], + ]; + } + + #[DataProvider('rawIdentifierProvider')] + public function testRawPlaceholderInIdentifierQuotesNamesATable(string $sql, string $expected): void + { + $this->assertSame($expected, $this->statement()->sql($sql)->bRaw('test')->getComputed()); + } + + public function testBIdentUsesDoubleQuotes(): void + { + $statement = $this->statement()->sql('SELECT %% FROM %%')->bIdent(['id', 'name'])->bIdent('main.t'); + + $this->assertSame('SELECT "id", "name" FROM "main"."t"', $statement->getComputed()); + } + + public function testBracketIdentifierSpanningSqlCallsIsTracked(): void + { + $statement = $this->statement() + ->sql('SELECT [odd') + ->sql('name?]') + ->sql(', ?')->bInt(5); + + $this->assertSame("SELECT [odd\nname?]\n, 5", $statement->getComputed()); + } + + public function testBUIntStopsAtSQLitesIntegerMaximum(): void + { + $this->assertSame( + 'SELECT 9223372036854775807', + $this->statement()->sql('SELECT %%')->bUInt('9223372036854775807')->getComputed() + ); + + $this->expectException(\InvalidArgumentException::class); + $this->statement()->bUIntArray([1, '9223372036854775808']); + } +}