Skip to content

Commit a47c6b6

Browse files
Sergii KryvonosSergii Kryvonos
authored andcommitted
Add WP_D1_Connection class and D1 compatibility tests
1 parent 973810c commit a47c6b6

4 files changed

Lines changed: 449 additions & 0 deletions

File tree

‎packages/mysql-on-sqlite/src/load.php‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
require_once __DIR__ . '/mysql/class-wp-mysql-lexer.php';
2121
require_once __DIR__ . '/mysql/class-wp-mysql-parser.php';
2222
require_once __DIR__ . '/sqlite/class-wp-sqlite-connection.php';
23+
require_once __DIR__ . '/sqlite/class-wp-d1-connection.php';
2324
require_once __DIR__ . '/sqlite/class-wp-sqlite-configurator.php';
2425
require_once __DIR__ . '/sqlite/class-wp-sqlite-driver.php';
2526
require_once __DIR__ . '/sqlite/class-wp-mysql-on-sqlite-exception.php';
Lines changed: 362 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,362 @@
1+
<?php declare(strict_types = 1);
2+
3+
/**
4+
* Cloudflare D1 connection.
5+
*
6+
* This class provides a minimal PDO-like wrapper around the Cloudflare D1
7+
* HTTP API so that the MySQL-on-SQLite driver can target a remote D1 database.
8+
*
9+
* @access private
10+
*/
11+
class WP_D1_Connection {
12+
/**
13+
* Cloudflare account ID.
14+
*
15+
* @var string
16+
*/
17+
private $account_id;
18+
19+
/**
20+
* Cloudflare D1 database ID.
21+
*
22+
* @var string
23+
*/
24+
private $database_id;
25+
26+
/**
27+
* Cloudflare API token.
28+
*
29+
* @var string
30+
*/
31+
private $api_token;
32+
33+
/**
34+
* Base API URL.
35+
*
36+
* @var string
37+
*/
38+
private $api_base;
39+
40+
/**
41+
* Last inserted row ID.
42+
*
43+
* @var int|string
44+
*/
45+
private $last_insert_id = 0;
46+
47+
/**
48+
* Constructor.
49+
*
50+
* @param array $options {
51+
* @type string $account_id Cloudflare account ID.
52+
* @type string $database_id Cloudflare D1 database ID.
53+
* @type string $api_token Cloudflare API token.
54+
* @type string $api_base Optional API base URL.
55+
* }
56+
*
57+
* @throws InvalidArgumentException When required options are missing.
58+
*/
59+
public function __construct( array $options ) {
60+
if ( empty( $options['account_id'] ) || ! is_string( $options['account_id'] ) ) {
61+
throw new InvalidArgumentException( 'Option "account_id" is required.' );
62+
}
63+
if ( empty( $options['database_id'] ) || ! is_string( $options['database_id'] ) ) {
64+
throw new InvalidArgumentException( 'Option "database_id" is required.' );
65+
}
66+
if ( empty( $options['api_token'] ) || ! is_string( $options['api_token'] ) ) {
67+
throw new InvalidArgumentException( 'Option "api_token" is required.' );
68+
}
69+
70+
$this->account_id = $options['account_id'];
71+
$this->database_id = $options['database_id'];
72+
$this->api_token = $options['api_token'];
73+
$this->api_base = $options['api_base'] ?? 'https://api.cloudflare.com/client/v4';
74+
}
75+
76+
/**
77+
* Execute a SQL query against D1.
78+
*
79+
* @param string $sql SQL statement.
80+
* @param array $params Bound parameters.
81+
*
82+
* @return WP_D1_Statement
83+
*/
84+
public function query( string $sql, array $params = array() ): WP_D1_Statement {
85+
return new WP_D1_Statement( $this, $sql, $params );
86+
}
87+
88+
/**
89+
* Prepare a SQL statement.
90+
*
91+
* @param string $sql SQL statement.
92+
*
93+
* @return WP_D1_Statement
94+
*/
95+
public function prepare( string $sql ): WP_D1_Statement {
96+
return new WP_D1_Statement( $this, $sql, array() );
97+
}
98+
99+
/**
100+
* Quote a value (basic).
101+
*
102+
* @param mixed $value Value to quote.
103+
* @param int $type PDO type.
104+
*
105+
* @return string
106+
*/
107+
public function quote( $value, int $type = 2 ): string {
108+
if ( is_null( $value ) ) {
109+
return 'NULL';
110+
}
111+
if ( is_bool( $value ) ) {
112+
return $value ? '1' : '0';
113+
}
114+
if ( is_int( $value ) || is_float( $value ) ) {
115+
return (string) $value;
116+
}
117+
return "'" . str_replace( "'", "''", (string) $value ) . "'";
118+
}
119+
120+
/**
121+
* Quote an identifier.
122+
*
123+
* @param string $identifier Identifier.
124+
*
125+
* @return string
126+
*/
127+
public function quote_identifier( string $identifier ): string {
128+
return '`' . str_replace( '`', '``', $identifier ) . '`';
129+
}
130+
131+
/**
132+
* Get last insert ID.
133+
*
134+
* @return int|string
135+
*/
136+
public function get_last_insert_id() {
137+
return $this->last_insert_id;
138+
}
139+
140+
/**
141+
* Set query logger (no-op for now).
142+
*
143+
* @param callable|null $logger Logger.
144+
*/
145+
public function set_query_logger( $logger ): void {
146+
// No-op.
147+
}
148+
149+
/**
150+
* Execute a request against the D1 API.
151+
*
152+
* @param string $sql SQL statement.
153+
* @param array $params Parameters.
154+
*
155+
* @return array
156+
*
157+
* @throws RuntimeException On HTTP or API error.
158+
*/
159+
public function execute_remote( string $sql, array $params = array() ): array {
160+
$url = rtrim( $this->api_base, '/' ) . '/accounts/' . rawurlencode( $this->account_id ) . '/d1/database/' . rawurlencode( $this->database_id ) . '/query';
161+
$body = json_encode( array( 'sql' => $sql, 'params' => array_values( $params ) ) );
162+
163+
$raw = null;
164+
$code = 0;
165+
if ( function_exists( 'curl_init' ) ) {
166+
$ch = curl_init( $url );
167+
curl_setopt( $ch, CURLOPT_POST, true );
168+
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
169+
curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
170+
'Authorization: Bearer ' . $this->api_token,
171+
'Content-Type: application/json',
172+
) );
173+
curl_setopt( $ch, CURLOPT_POSTFIELDS, $body );
174+
curl_setopt( $ch, CURLOPT_TIMEOUT, 30 );
175+
$raw = curl_exec( $ch );
176+
$code = (int) curl_getinfo( $ch, CURLINFO_HTTP_CODE );
177+
if ( false === $raw ) {
178+
$err = curl_error( $ch );
179+
curl_close( $ch );
180+
throw new RuntimeException( 'Failed to contact D1 API: ' . $err );
181+
}
182+
curl_close( $ch );
183+
} else {
184+
$context = stream_context_create(
185+
array(
186+
'http' => array(
187+
'method' => 'POST',
188+
'header' => "Authorization: Bearer {$this->api_token}\r\nContent-Type: application/json\r\n",
189+
'content' => $body,
190+
'timeout' => 30,
191+
),
192+
)
193+
);
194+
$raw = @file_get_contents( $url, false, $context );
195+
if ( false === $raw ) {
196+
throw new RuntimeException( 'Failed to contact D1 API.' );
197+
}
198+
$code = 0;
199+
if ( isset( $http_response_header[0] ) ) {
200+
preg_match( '#HTTP/\S+\s+(\d+)#', $http_response_header[0], $m );
201+
$code = isset( $m[1] ) ? (int) $m[1] : 0;
202+
}
203+
}
204+
205+
if ( $code >= 400 ) {
206+
throw new RuntimeException( 'D1 API HTTP error: ' . $code );
207+
}
208+
209+
$decoded = json_decode( $raw, true );
210+
if ( ! is_array( $decoded ) ) {
211+
throw new RuntimeException( 'Invalid D1 API response.' );
212+
}
213+
if ( empty( $decoded['success'] ) ) {
214+
$message = isset( $decoded['errors'][0]['message'] ) ? $decoded['errors'][0]['message'] : 'D1 API error.';
215+
throw new RuntimeException( $message );
216+
}
217+
218+
$result = $decoded['result'][0] ?? array();
219+
if ( isset( $result['meta']['last_row_id'] ) ) {
220+
$this->last_insert_id = $result['meta']['last_row_id'];
221+
}
222+
223+
return $result;
224+
}
225+
}
226+
227+
/**
228+
* Minimal statement wrapper for D1 results.
229+
*/
230+
class WP_D1_Statement {
231+
/**
232+
* Connection.
233+
*
234+
* @var WP_D1_Connection
235+
*/
236+
private $connection;
237+
238+
/**
239+
* SQL.
240+
*
241+
* @var string
242+
*/
243+
private $sql;
244+
245+
/**
246+
* Parameters.
247+
*
248+
* @var array
249+
*/
250+
private $params;
251+
252+
/**
253+
* Cached result.
254+
*
255+
* @var array|null
256+
*/
257+
private $result = null;
258+
259+
/**
260+
* Constructor.
261+
*/
262+
public function __construct( WP_D1_Connection $connection, string $sql, array $params = array() ) {
263+
$this->connection = $connection;
264+
$this->sql = $sql;
265+
$this->params = $params;
266+
}
267+
268+
/**
269+
* Bind a value (positional).
270+
*
271+
* @param int|string $key Key.
272+
* @param mixed $value Value.
273+
* @param int $type Type.
274+
*
275+
* @return bool
276+
*/
277+
public function bindValue( $key, $value, $type = 0 ): bool {
278+
$this->params[ $key ] = $value;
279+
return true;
280+
}
281+
282+
/**
283+
* Bind (alias).
284+
*/
285+
public function bind( $key, $value ) {
286+
$this->params[ $key ] = $value;
287+
return $this;
288+
}
289+
290+
/**
291+
* Execute.
292+
*
293+
* @param array|null $params Params.
294+
*
295+
* @return bool
296+
*/
297+
public function execute( $params = null ): bool {
298+
if ( is_array( $params ) ) {
299+
$this->params = array_values( $params );
300+
}
301+
$this->result = $this->connection->execute_remote( $this->sql, $this->params );
302+
return true;
303+
}
304+
305+
/**
306+
* Fetch all rows.
307+
*
308+
* @param int $mode Mode (ignored).
309+
*
310+
* @return array
311+
*/
312+
public function fetchAll( $mode = 0 ): array {
313+
if ( null === $this->result ) {
314+
$this->execute();
315+
}
316+
return $this->result['results'] ?? array();
317+
}
318+
319+
/**
320+
* Fetch column.
321+
*
322+
* @param int $column Column index.
323+
*
324+
* @return mixed
325+
*/
326+
public function fetchColumn( $column = 0 ) {
327+
$rows = $this->fetchAll();
328+
if ( empty( $rows ) ) {
329+
return false;
330+
}
331+
$row = array_values( $rows[0] );
332+
return $row[ $column ] ?? null;
333+
}
334+
335+
/**
336+
* Row count.
337+
*
338+
* @return int
339+
*/
340+
public function rowCount(): int {
341+
if ( null === $this->result ) {
342+
return 0;
343+
}
344+
return (int) ( $this->result['meta']['changes'] ?? 0 );
345+
}
346+
347+
/**
348+
* Column count.
349+
*
350+
* @return int
351+
*/
352+
public function columnCount(): int {
353+
$rows = $this->fetchAll();
354+
if ( empty( $rows ) ) {
355+
return 0;
356+
}
357+
return count( $rows[0] );
358+
}
359+
}
360+
361+
// Backwards/alternative names.
362+
class_alias( 'WP_D1_Connection', 'WP_Cloudflare_D1_Connection' );

‎tests/d1/README.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# D1 compatibility tests
2+
3+
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.
4+
5+
From the repository root, with Node.js 22 and npm:
6+
7+
```sh
8+
d1_test_deps=$(mktemp -d)
9+
npm install --prefix "$d1_test_deps" --no-save miniflare@5.20261118.0-beta
10+
NODE_PATH="$d1_test_deps/node_modules" node --test tests/d1/compatibility.test.cjs
11+
```
12+
13+
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.

0 commit comments

Comments
 (0)