diff --git a/packages/mysql-on-sqlite/src/load.php b/packages/mysql-on-sqlite/src/load.php index 93e6b4f09..ff954b032 100644 --- a/packages/mysql-on-sqlite/src/load.php +++ b/packages/mysql-on-sqlite/src/load.php @@ -20,6 +20,7 @@ require_once __DIR__ . '/mysql/class-wp-mysql-lexer.php'; require_once __DIR__ . '/mysql/class-wp-mysql-parser.php'; require_once __DIR__ . '/sqlite/class-wp-sqlite-connection.php'; +require_once __DIR__ . '/sqlite/class-wp-d1-connection.php'; require_once __DIR__ . '/sqlite/class-wp-sqlite-configurator.php'; require_once __DIR__ . '/sqlite/class-wp-sqlite-driver.php'; require_once __DIR__ . '/sqlite/class-wp-mysql-on-sqlite-exception.php'; diff --git a/packages/mysql-on-sqlite/src/sqlite/class-wp-d1-connection.php b/packages/mysql-on-sqlite/src/sqlite/class-wp-d1-connection.php new file mode 100644 index 000000000..a7c59bc13 --- /dev/null +++ b/packages/mysql-on-sqlite/src/sqlite/class-wp-d1-connection.php @@ -0,0 +1,249 @@ +account_id = $options['account_id']; + $this->database_id = $options['database_id']; + $this->api_token = $options['api_token']; + $this->api_base = $options['api_base'] ?? 'https://api.cloudflare.com/client/v4'; + } + + /** + * Execute a SQL query against D1. + * + * @param string $sql SQL statement. + * @param array $params Bound parameters. + * + * @return WP_D1_Statement + */ + public function query( string $sql, array $params = array() ): WP_D1_Statement { + $statement = $this->prepare( $sql ); + $statement->execute( $params ); + return $statement; + } + + /** + * Prepare a SQL statement. + * + * @param string $sql SQL statement. + * + * @return WP_D1_Statement + */ + public function prepare( string $sql ): WP_D1_Statement { + return new WP_D1_Statement( $this, $sql, array() ); + } + + /** + * Quote a value (basic). + * + * @param mixed $value Value to quote. + * @param int $type PDO type. + * + * @return string + */ + public function quote( $value, int $type = 2 ): string { + if ( is_null( $value ) ) { + return 'NULL'; + } + if ( is_bool( $value ) ) { + return $value ? '1' : '0'; + } + if ( is_int( $value ) || is_float( $value ) ) { + return (string) $value; + } + return "'" . str_replace( "'", "''", (string) $value ) . "'"; + } + + /** + * Quote an identifier. + * + * @param string $identifier Identifier. + * + * @return string + */ + public function quote_identifier( string $identifier ): string { + return '`' . str_replace( '`', '``', $identifier ) . '`'; + } + + /** + * Get last insert ID. + * + * @return int|string + */ + public function get_last_insert_id() { + return $this->last_insert_id; + } + + /** + * Set query logger (no-op for now). + * + * @param callable|null $logger Logger. + */ + public function set_query_logger( $logger ): void { + // No-op. + } + + /** + * Execute a request against the D1 API. + * + * @param string $sql SQL statement. + * @param array $params Parameters. + * + * @return array + * + * @throws RuntimeException On HTTP or API error. + */ + public function execute_remote( string $sql, array $params = array() ): array { + $url = rtrim( $this->api_base, '/' ) . '/accounts/' . rawurlencode( $this->account_id ) . '/d1/database/' . rawurlencode( $this->database_id ) . '/raw'; + $body = json_encode( + array( + 'sql' => $sql, + 'params' => array_values( $params ), + ) + ); + + $raw = null; + $code = 0; + if ( function_exists( 'curl_init' ) ) { + $ch = curl_init( $url ); + curl_setopt( $ch, CURLOPT_POST, true ); + curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); + curl_setopt( + $ch, + CURLOPT_HTTPHEADER, + array( + 'Authorization: Bearer ' . $this->api_token, + 'Content-Type: application/json', + ) + ); + curl_setopt( $ch, CURLOPT_POSTFIELDS, $body ); + curl_setopt( $ch, CURLOPT_TIMEOUT, 30 ); + $raw = curl_exec( $ch ); + $code = (int) curl_getinfo( $ch, CURLINFO_HTTP_CODE ); + if ( false === $raw ) { + $err = curl_error( $ch ); + curl_close( $ch ); + throw new RuntimeException( 'Failed to contact D1 API: ' . $err ); + } + curl_close( $ch ); + } else { + $context = stream_context_create( + array( + 'http' => array( + 'method' => 'POST', + 'header' => "Authorization: Bearer {$this->api_token}\r\nContent-Type: application/json\r\n", + 'content' => $body, + 'timeout' => 30, + ), + ) + ); + $raw = @file_get_contents( $url, false, $context ); + if ( false === $raw ) { + throw new RuntimeException( 'Failed to contact D1 API.' ); + } + $code = 0; + if ( isset( $http_response_header[0] ) ) { + preg_match( '#HTTP/\S+\s+(\d+)#', $http_response_header[0], $m ); + $code = isset( $m[1] ) ? (int) $m[1] : 0; + } + } + + if ( $code >= 400 ) { + throw new RuntimeException( 'D1 API HTTP error: ' . $code ); + } + + $decoded = json_decode( $raw, true ); + if ( ! is_array( $decoded ) ) { + throw new RuntimeException( 'Invalid D1 API response.' ); + } + if ( empty( $decoded['success'] ) ) { + $message = isset( $decoded['errors'][0]['message'] ) ? $decoded['errors'][0]['message'] : 'D1 API error.'; + throw new RuntimeException( $message ); + } + + $result = $decoded['result'][0] ?? array(); + if ( isset( $result['meta']['last_row_id'] ) ) { + $this->last_insert_id = $result['meta']['last_row_id']; + } + + $columns = $result['results']['columns'] ?? array(); + $rows = $result['results']['rows'] ?? array(); + $result['column_count'] = count( $columns ); + $result['results'] = array(); + foreach ( $rows as $row ) { + $result['results'][] = array_combine( $columns, $row ); + } + + return $result; + } +} + +// Backwards/alternative names. +class_alias( 'WP_D1_Connection', 'WP_Cloudflare_D1_Connection' ); diff --git a/packages/mysql-on-sqlite/src/sqlite/class-wp-d1-statement.php b/packages/mysql-on-sqlite/src/sqlite/class-wp-d1-statement.php new file mode 100644 index 000000000..6cb376557 --- /dev/null +++ b/packages/mysql-on-sqlite/src/sqlite/class-wp-d1-statement.php @@ -0,0 +1,185 @@ +connection = $connection; + $this->sql = $sql; + $this->params = array_values( $params ); + } + + /** + * Bind a value (positional). + * + * @param int|string $key One-based parameter position. + * @param mixed $value Value. + * @param int|null $type PDO::PARAM_NULL, or null to infer the type from the value. + * + * @return bool + */ + // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid -- Match the PDOStatement API. + public function bindValue( $key, $value, $type = null ): bool { + if ( is_string( $key ) && (string) (int) $key === $key ) { + $key = (int) $key; + } + if ( ! is_int( $key ) || $key < 1 ) { + throw new InvalidArgumentException( 'D1 bindings require a positive parameter position.' ); + } + if ( null !== $type && PDO::PARAM_NULL !== $type ) { + throw new InvalidArgumentException( 'D1 bindings support inferred types and PDO::PARAM_NULL.' ); + } + $this->params[ $key - 1 ] = PDO::PARAM_NULL === $type ? null : $value; + return true; + } + + /** + * Bind (alias). + */ + public function bind( $key, $value ) { + $this->bindValue( $key, $value ); + return $this; + } + + /** + * Execute. + * + * @param array|null $params Params. + * + * @return bool + */ + public function execute( $params = null ): bool { + $this->result = array(); + $this->row_position = 0; + + if ( is_array( $params ) ) { + $this->params = array_values( $params ); + } + ksort( $this->params, SORT_NUMERIC ); + $values = array_values( $this->params ); + if ( array_keys( $this->params ) !== array_keys( $values ) ) { + throw new InvalidArgumentException( 'D1 bindings must use consecutive parameter positions.' ); + } + $this->result = $this->connection->execute_remote( $this->sql, $values ); + return true; + } + + /** + * Fetch all remaining rows. + * + * @param int $mode 0 for the default, PDO::FETCH_ASSOC, or PDO::FETCH_COLUMN. + * + * @return array + */ + // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid -- Match the PDOStatement API. + public function fetchAll( $mode = 0 ): array { + if ( 0 !== $mode && PDO::FETCH_ASSOC !== $mode && PDO::FETCH_COLUMN !== $mode ) { + throw new InvalidArgumentException( 'D1 fetch modes are 0, PDO::FETCH_ASSOC, and PDO::FETCH_COLUMN.' ); + } + + $rows = $this->get_rows(); + $remaining = array_slice( $rows, $this->row_position ); + $this->row_position = count( $rows ); + if ( PDO::FETCH_COLUMN === $mode ) { + return array_map( + static function ( array $row ) { + return reset( $row ); + }, + $remaining + ); + } + return $remaining; + } + + /** + * Fetch a column from the next row. + * + * @param int $column Column index. + * + * @return mixed + */ + // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid -- Match the PDOStatement API. + public function fetchColumn( $column = 0 ) { + $rows = $this->get_rows(); + if ( ! isset( $rows[ $this->row_position ] ) ) { + return false; + } + $row = array_values( $rows[ $this->row_position++ ] ); + return $row[ $column ] ?? null; + } + + /** + * Row count. + * + * @return int + */ + // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid -- Match the PDOStatement API. + public function rowCount(): int { + if ( null === $this->result ) { + return 0; + } + return (int) ( $this->result['meta']['changes'] ?? 0 ); + } + + /** + * Column count. + * + * @return int + */ + // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid -- Match the PDOStatement API. + public function columnCount(): int { + $rows = $this->result['results'] ?? array(); + return $this->result['column_count'] ?? ( isset( $rows[0] ) ? count( $rows[0] ) : 0 ); + } + + /** + * Get the result rows, executing the statement if necessary. + * + * @return array + */ + private function get_rows(): array { + if ( null === $this->result ) { + $this->execute(); + } + return $this->result['results'] ?? array(); + } +} diff --git a/packages/mysql-on-sqlite/tests/WP_D1_Connection_Tests.php b/packages/mysql-on-sqlite/tests/WP_D1_Connection_Tests.php new file mode 100644 index 000000000..ec7249d0e --- /dev/null +++ b/packages/mysql-on-sqlite/tests/WP_D1_Connection_Tests.php @@ -0,0 +1,181 @@ +mock_connection(); + $connection->expects( $this->once() ) + ->method( 'execute_remote' ) + ->with( $sql, array( 'Title' ) ) + ->willReturn( array( 'meta' => array( 'changes' => 1 ) ) ); + + $statement = $connection->query( $sql, array( 'Title' ) ); + $this->assertSame( 1, $statement->rowCount() ); + } + + public function testBindingsAreSentInPlaceholderOrder(): void { + $sql = 'INSERT INTO posts (title, slug) VALUES (?, ?)'; + $connection = $this->mock_connection(); + $connection->expects( $this->once() ) + ->method( 'execute_remote' ) + ->with( $sql, array( 'Title', 'slug' ) ) + ->willReturn( array() ); + + $statement = $connection->prepare( $sql ); + $this->assertSame( 0, $statement->rowCount() ); + $statement->bind( '2', 'slug' ); + $statement->bindValue( 1, 'Title' ); + $this->assertTrue( $statement->execute() ); + } + + public function testExecutePreservesExplicitParameterOrder(): void { + $sql = 'INSERT INTO posts (title, slug) VALUES (?, ?)'; + $connection = $this->mock_connection(); + $connection->expects( $this->once() ) + ->method( 'execute_remote' ) + ->with( $sql, array( 'Title', 'slug' ) ) + ->willReturn( array() ); + + $statement = $connection->prepare( $sql ); + $statement->bindValue( 2, 'old-slug' ); + $this->assertTrue( $statement->execute( array( 'Title', 'slug' ) ) ); + } + + public function testSparseBindingsAreRejectedBeforeSending(): void { + $connection = $this->mock_connection(); + $connection->expects( $this->never() )->method( 'execute_remote' ); + + $statement = $connection->prepare( 'SELECT ?, ?' ); + $statement->bindValue( 2, 'second' ); + $this->expectException( InvalidArgumentException::class ); + $statement->execute(); + } + + public function testExplicitNullBindingSendsNull(): void { + $connection = $this->mock_connection(); + $connection->expects( $this->once() ) + ->method( 'execute_remote' ) + ->with( 'SELECT ?', array( null ) ) + ->willReturn( array() ); + + $statement = $connection->prepare( 'SELECT ?' ); + $statement->bindValue( 1, 'unused', PDO::PARAM_NULL ); + $statement->execute(); + } + + public function testUnsupportedBindingTypeIsRejected(): void { + $statement = $this->mock_connection()->prepare( 'SELECT ?' ); + $this->expectException( InvalidArgumentException::class ); + $statement->bindValue( 1, '123', PDO::PARAM_INT ); + } + + public function testFetchMethodsShareCursorAndExecutionResetsIt(): void { + $connection = $this->mock_connection(); + $rows = array( + array( 'id' => 1 ), + array( 'id' => 2 ), + array( 'id' => 3 ), + ); + $connection->expects( $this->exactly( 2 ) ) + ->method( 'execute_remote' ) + ->willReturn( array( 'results' => $rows ) ); + + $statement = $connection->query( 'SELECT id FROM posts ORDER BY id' ); + $this->assertSame( 1, $statement->fetchColumn() ); + $this->assertSame( 2, $statement->fetchColumn() ); + $this->assertSame( array( $rows[2] ), $statement->fetchAll() ); + $this->assertFalse( $statement->fetchColumn() ); + $this->assertSame( array(), $statement->fetchAll() ); + $this->assertSame( 1, $statement->columnCount() ); + + $statement->execute(); + $this->assertSame( 1, $statement->fetchColumn() ); + } + + public function testFailedExecutionClearsResultsWithoutRetrying(): void { + $connection = $this->mock_connection(); + $connection->expects( $this->exactly( 2 ) ) + ->method( 'execute_remote' ) + ->willReturnOnConsecutiveCalls( + array( + 'results' => array( array( 'id' => 1 ) ), + 'meta' => array( 'changes' => 1 ), + ), + $this->throwException( new RuntimeException( 'D1 request failed' ) ) + ); + + $statement = $connection->query( 'SELECT 1 AS id' ); + $this->assertSame( 1, $statement->columnCount() ); + try { + $statement->execute(); + $this->fail( 'Expected the second execution to fail.' ); + } catch ( RuntimeException $error ) { + $this->assertSame( 'D1 request failed', $error->getMessage() ); + } + $this->assertSame( 0, $statement->columnCount() ); + $this->assertSame( 0, $statement->rowCount() ); + $this->assertFalse( $statement->fetchColumn() ); + $this->assertSame( array(), $statement->fetchAll() ); + } + + public function testColumnCountDoesNotExecutePreparedStatement(): void { + $connection = $this->mock_connection(); + $connection->expects( $this->never() )->method( 'execute_remote' ); + + $statement = $connection->prepare( 'INSERT INTO posts (title) VALUES (?)' ); + $statement->bindValue( 1, 'Title' ); + $this->assertSame( 0, $statement->columnCount() ); + } + + public function testFetchAllSupportsExplicitModes(): void { + $connection = $this->mock_connection(); + $rows = array( + array( 'id' => 1 ), + array( 'id' => null ), + array( 'id' => 3 ), + ); + $connection->method( 'execute_remote' )->willReturn( array( 'results' => $rows ) ); + + $statement = $connection->query( 'SELECT id FROM posts' ); + $this->assertSame( 1, $statement->fetchColumn() ); + $this->assertSame( array( null, 3 ), $statement->fetchAll( PDO::FETCH_COLUMN ) ); + $this->assertSame( array(), $statement->fetchAll( PDO::FETCH_ASSOC ) ); + $statement->execute(); + $this->assertSame( $rows, $statement->fetchAll( PDO::FETCH_ASSOC ) ); + } + + public function testFetchAllRejectsUnsupportedModeBeforeExecuting(): void { + $connection = $this->mock_connection(); + $connection->expects( $this->never() )->method( 'execute_remote' ); + + $statement = $connection->prepare( 'SELECT 1' ); + $this->expectException( InvalidArgumentException::class ); + $statement->fetchAll( PDO::FETCH_OBJ ); + } + + public function testColumnCountUsesMetadataForEmptyResults(): void { + $connection = $this->mock_connection(); + $connection->method( 'execute_remote' )->willReturn( + array( + 'column_count' => 1, + 'results' => array(), + ) + ); + + $statement = $connection->query( 'SELECT 1 AS id WHERE 0' ); + $this->assertSame( 1, $statement->columnCount() ); + $this->assertSame( array(), $statement->fetchAll() ); + } + + private function mock_connection(): WP_D1_Connection { + return $this->getMockBuilder( WP_D1_Connection::class ) + ->disableOriginalConstructor() + ->onlyMethods( array( 'execute_remote' ) ) + ->getMock(); + } +} diff --git a/tests/d1/README.md b/tests/d1/README.md new file mode 100644 index 000000000..d3b72628f --- /dev/null +++ b/tests/d1/README.md @@ -0,0 +1,13 @@ +# D1 compatibility tests + +These local tests accompany [issue #288](https://github.com/WordPress/sqlite-database-integration/issues/288). They exercise the SQLite operations a D1 backend would need. Miniflare creates an in-memory database with synthetic data. + +From the repository root, with Node.js 22 and npm: + +```sh +d1_test_deps=$(mktemp -d) +npm install --prefix "$d1_test_deps" --no-save miniflare@5.20261118.0-beta +NODE_PATH="$d1_test_deps/node_modules" node --test tests/d1/compatibility.test.cjs +``` + +The tests cover prepared statements, write metadata, atomic batches, and the D1 behavior for transaction commands and the PHP-backed `md5()` function used by the local driver. diff --git a/tests/d1/compatibility.test.cjs b/tests/d1/compatibility.test.cjs new file mode 100644 index 000000000..5c3ee8eff --- /dev/null +++ b/tests/d1/compatibility.test.cjs @@ -0,0 +1,73 @@ +const assert = require( 'node:assert/strict' ); +const { after, before, test } = require( 'node:test' ); +const { Miniflare, convertV4MiniflareOptions } = require( 'miniflare' ); + +const runtime = new Miniflare( convertV4MiniflareOptions( { + cf: false, + modules: true, + script: 'export default {}', + compatibilityDate: '2026-11-19', + d1Databases: [ 'DB' ], +} ) ); + +let db; + +before( async () => { + db = await runtime.getD1Database( 'DB' ); + await db.prepare( + 'CREATE TABLE posts (id INTEGER PRIMARY KEY, slug TEXT UNIQUE, title TEXT NOT NULL)' + ).run(); +} ); + +after( async () => { + await runtime.dispose(); +} ); + +test( 'prepared statements preserve post content and report insert metadata', async () => { + const title = "WordPress post with an apostrophe: it's published"; + const result = await db.prepare( 'INSERT INTO posts (slug, title) VALUES (?, ?)' ) + .bind( 'published', title ) + .run(); + + assert.equal( result.meta.changes, 1 ); + assert.ok( result.meta.last_row_id > 0 ); + assert.deepEqual( + await db.prepare( 'SELECT slug, title FROM posts WHERE id = ?' ).bind( result.meta.last_row_id ).first(), + { slug: 'published', title } + ); +} ); + +test( 'a failed D1 batch rolls back earlier statements', async () => { + const insert = db.prepare( 'INSERT INTO posts (slug, title) VALUES (?, ?)' ); + + await assert.rejects( + db.batch( [ insert.bind( 'duplicate', 'First write' ), insert.bind( 'duplicate', 'Second write' ) ] ), + /UNIQUE constraint failed/i + ); + assert.equal( + await db.prepare( 'SELECT title FROM posts WHERE slug = ?' ).bind( 'duplicate' ).first(), + null + ); +} ); + +test( 'an atomic batch applies a post change and reads it back', async () => { + const [ write, read ] = await db.batch( [ + db.prepare( 'INSERT INTO posts (slug, title) VALUES (?, ?)' ).bind( 'batched-post', 'Batch write' ), + db.prepare( 'SELECT title FROM posts WHERE slug = ?' ).bind( 'batched-post' ), + ] ); + + assert.equal( write.meta.changes, 1 ); + assert.deepEqual( read.results, [ { title: 'Batch write' } ] ); +} ); + +test( 'D1 rejects the transaction commands used by the local PDO driver', async () => { + await assert.rejects( db.prepare( 'BEGIN IMMEDIATE' ).run(), /transaction/i ); + await assert.rejects( db.prepare( 'SAVEPOINT nested' ).run(), /transaction|savepoint/i ); +} ); + +test( 'D1 lacks the MD5 function registered by the local PDO driver', async () => { + await assert.rejects( + db.prepare( 'SELECT md5(?)' ).bind( 'sample' ).run(), + /no such function: md5/i + ); +} );