diff --git a/packages/mysql-on-sqlite/src/sqlite/class-wp-mysql-on-sqlite.php b/packages/mysql-on-sqlite/src/sqlite/class-wp-mysql-on-sqlite.php index 248477afb..054edc3c6 100644 --- a/packages/mysql-on-sqlite/src/sqlite/class-wp-mysql-on-sqlite.php +++ b/packages/mysql-on-sqlite/src/sqlite/class-wp-mysql-on-sqlite.php @@ -6585,7 +6585,8 @@ private function translate_update_list( string $table_name, WP_Parser_Node $pare } // Apply type casting. - $value = $this->cast_value_for_saving( $data_type, $value ); + $target_column = $this->quote_sqlite_identifier( $table_alias ?? $table_name ) . '.' . $this->translate( end( $column_ref_parts ) ); + $value = $this->cast_value_for_saving( $data_type, $value, $target_column ); /* * In MySQL non-STRICT mode, when a column is declared as NOT NULL, @@ -7166,13 +7167,15 @@ private function validate_foreign_key_references( WP_Parser_Node $node ): void { * Emulate MySQL type casting for values to be saved to the database * using INSERT, REPLACE, or UPDATE statements. * - * @param string $mysql_data_type The MySQL data type. - * @param string $translated_value The original translated value. - * @return string The translated value. + * @param string $mysql_data_type The MySQL data type. + * @param string $translated_value The original translated value. + * @param string|null $target_column The qualified target column of an UPDATE. + * @return string The translated value. */ private function cast_value_for_saving( string $mysql_data_type, - string $translated_value + string $translated_value, + ?string $target_column = null ): string { // TODO: This is also a good place to implement checks for maximum column // lengths with truncating or bailing out depending on the SQL mode. @@ -7299,6 +7302,30 @@ private function cast_value_for_saving( '{fallback}' => $fallback, ) ); + case 'bit': + /* + * MySQL saves a binary string to a BIT column as the integer value + * of its bytes in big-endian order. For example, b'101', 0x05, and + * _binary '\x05' are all saved as 5. These literals are blobs in + * SQLite, which casts a blob to an integer as if it was text, so + * they need to be converted using a helper function. + * + * SQLite evaluates a subquery that references no column only once. + * In an UPDATE, the target column is referenced, so that the value + * is evaluated for each row. + */ + return sprintf( + "( + SELECT CASE + WHEN typeof(value) = 'blob' THEN _helper_binary_to_bit_value(value) + ELSE %s + END + FROM (SELECT %s AS value%s) + )", + $is_strict_mode ? 'value' : 'CAST(value AS INTEGER)', + $translated_value, + null === $target_column ? '' : ', ' . $target_column + ); default: /* * For all other data types, cast to the SQLite types as follows: diff --git a/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-pdo-user-defined-functions.php b/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-pdo-user-defined-functions.php index 91b40dea6..c6d980cf4 100644 --- a/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-pdo-user-defined-functions.php +++ b/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-pdo-user-defined-functions.php @@ -91,6 +91,7 @@ public static function register_for( $pdo ): self { // Internal helper functions. '_helper_like_to_glob_pattern' => '_helper_like_to_glob_pattern', + '_helper_binary_to_bit_value' => '_helper_binary_to_bit_value', ); /** @@ -1214,6 +1215,38 @@ public function _helper_like_to_glob_pattern( $pattern ) { return $pattern; } + /** + * A helper to convert a binary string to the value of a BIT column. + * + * The value is the integer that the bytes represent in big-endian order, + * as a decimal string. PDO SQLite in PHP < 8.4 truncates integers returned + * from user-defined functions to 32 bits, and a string avoids that. + * + * @param string|null $value The binary string. + * @return string|null The BIT value. + * @throws Exception When the value has more than 63 bits. + */ + public function _helper_binary_to_bit_value( $value ) { + if ( null === $value ) { + return null; + } + + $bytes = ltrim( $value, "\0" ); + if ( strlen( $bytes ) > 8 ) { + throw new Exception( 'Data too long for a BIT column.' ); + } + + /* + * SQLite integers are signed, so a value that uses the 64th bit can't be + * stored. A table without STRICT would silently save it as a REAL. + */ + $bit_value = unpack( 'J', str_pad( $bytes, 8, "\0", STR_PAD_LEFT ) )[1]; + if ( $bit_value < 0 ) { + throw new Exception( 'BIT values that use the 64th bit are not supported.' ); + } + return (string) $bit_value; + } + /** * Check that a match type has only known letters. * diff --git a/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Tests.php b/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Tests.php index 6ae0ef874..84e3568ba 100644 --- a/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Tests.php +++ b/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Tests.php @@ -2855,6 +2855,129 @@ public function testUpdateWithBitColumnDefaultValue(): void { $this->assertEquals( array( (object) array( 'maintenance' => '5' ) ), $results ); } + /** + * @dataProvider sqlModesForBitValues + */ + public function testSaveBinaryStringsToBitColumns( string $sql_mode ): void { + $this->assertQuery( "SET sql_mode = '$sql_mode'" ); + $this->assertQuery( 'CREATE TABLE t (id INT, b BIT(16))' ); + $this->assertQuery( + "INSERT INTO t (id, b) VALUES + (1, b'101'), + (2, 0x0102), + (3, _binary '\x01'), + (4, _binary '\\0'), + (5, x''), + (6, 7), + (7, NULL)" + ); + $this->assertQuery( "UPDATE t SET b = b'11' WHERE id = 6" ); + $this->assertQuery( 'INSERT INTO t (id, b) SELECT 8, 0x00ff00 FROM t WHERE id = 1' ); + + $result = $this->assertQuery( 'SELECT id, b + 0 AS b FROM t ORDER BY id' ); + $this->assertSame( + array( '5', '258', '1', '0', '0', '3', null, '65280' ), + array_column( $result, 'b' ) + ); + } + + public static function sqlModesForBitValues(): array { + return array( + 'non-strict mode' => array( 'NO_AUTO_VALUE_ON_ZERO' ), + 'strict mode' => array( 'STRICT_TRANS_TABLES' ), + ); + } + + public function testSaveMysqldumpRowWithBitColumns(): void { + // A row of the Ninja Forms "nf3_forms" table, as mysqldump writes it. + $this->assertQuery( "SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO'" ); + $this->assertQuery( + 'CREATE TABLE `wp_nf3_forms` ( + `id` int NOT NULL AUTO_INCREMENT, + `title` longtext, + `key` longtext, + `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `updated_at` datetime DEFAULT NULL, + `views` int DEFAULT NULL, + `subs` int DEFAULT NULL, + `form_title` longtext, + `default_label_pos` varchar(15), + `show_title` bit(1), + `clear_complete` bit(1), + `hide_complete` bit(1), + `logged_in` bit(1), + `seq_num` int, + PRIMARY KEY (`id`) + )' + ); + $this->assertQuery( + "INSERT INTO `wp_nf3_forms` VALUES (1,'Contact Me','','2016-08-24 16:39:20',NULL,NULL,NULL,'Contact Me','above',_binary '\x01',_binary '\x01',_binary '\x01',_binary '\\0',6)" + ); + + $result = $this->assertQuery( 'SELECT show_title + 0 AS show_title, logged_in + 0 AS logged_in FROM `wp_nf3_forms`' ); + $this->assertEquals( + array( + (object) array( + 'show_title' => '1', + 'logged_in' => '0', + ), + ), + $result + ); + } + + public function testRejectBinaryStringsOfMoreThan64BitsInBitColumns(): void { + $this->assertQuery( 'CREATE TABLE t (b BIT(64))' ); + + // Leading zero bytes of a binary string are ignored. + $this->assertQuery( "INSERT INTO t VALUES (_binary '\\0\x7f\xff\xff\xff\xff\xff\xff\xff')" ); + $this->assertSame( '9223372036854775807', $this->assertQuery( 'SELECT b + 0 AS b FROM t' )[0]->b ); + + $this->assertQueryError( + "INSERT INTO t VALUES (_binary '\x01\xff\xff\xff\xff\xff\xff\xff\xff')", + 'Data too long for a BIT column.' + ); + } + + public function testRejectBitValuesThatUseThe64thBit(): void { + $this->assertQuery( 'CREATE TABLE t (b BIT(64))' ); + $this->assertQuery( 'INSERT INTO t VALUES (0x7FFFFFFFFFFFFFFF)' ); + $this->assertSame( '9223372036854775807', $this->assertQuery( 'SELECT b + 0 AS b FROM t' )[0]->b ); + + foreach ( array( '0x8000000000000000', '0x8000000000000001', '0xFFFFFFFFFFFFFFFF' ) as $value ) { + $this->assertQueryError( + "INSERT INTO t VALUES ($value)", + 'BIT values that use the 64th bit are not supported.' + ); + } + } + + public function testEvaluateBitValuesForEachUpdatedRow(): void { + $calls = 0; + $callback = static function () use ( &$calls ) { + return ++$calls; + }; + if ( $this->sqlite instanceof Pdo\Sqlite ) { + $this->sqlite->createFunction( 'bit_test_counter', $callback, 0 ); + } else { + $this->sqlite->sqliteCreateFunction( 'bit_test_counter', $callback, 0 ); + } + + $this->assertQuery( 'CREATE TABLE t (id INT PRIMARY KEY, b BIT(8))' ); + $this->assertQuery( 'INSERT INTO t VALUES (1, 0), (2, 0), (3, 0)' ); + + $this->assertQuery( 'UPDATE t SET b = bit_test_counter()' ); + $this->assertSame( 3, $calls ); + $result = $this->assertQuery( 'SELECT b + 0 AS b FROM t ORDER BY id' ); + $this->assertSame( array( '1', '2', '3' ), array_column( $result, 'b' ) ); + + $calls = 0; + $this->assertQuery( 'INSERT INTO t VALUES (1, 0), (2, 0), (3, 0) ON DUPLICATE KEY UPDATE b = bit_test_counter()' ); + $this->assertSame( 3, $calls ); + $result = $this->assertQuery( 'SELECT b + 0 AS b FROM t ORDER BY id' ); + $this->assertSame( array( '1', '2', '3' ), array_column( $result, 'b' ) ); + } + public function testSelectIndexHintForce() { $this->assertQuery( "INSERT INTO _options (option_name) VALUES ('first');" ); $result = $this->assertQuery(