Skip to content

Commit eafef7d

Browse files
committed
Add D1 connection and compatibility tests
Refs #288
1 parent 973810c commit eafef7d

6 files changed

Lines changed: 645 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: 241 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,241 @@
1+
<?php declare(strict_types = 1);
2+
3+
require_once __DIR__ . '/class-wp-d1-statement.php';
4+
5+
/**
6+
* Cloudflare D1 connection.
7+
*
8+
* A standalone client for executing SQLite statements through the Cloudflare D1
9+
* HTTP API.
10+
*
11+
* @access private
12+
*/
13+
class WP_D1_Connection {
14+
/**
15+
* Cloudflare account ID.
16+
*
17+
* @var string
18+
*/
19+
private $account_id;
20+
21+
/**
22+
* Cloudflare D1 database ID.
23+
*
24+
* @var string
25+
*/
26+
private $database_id;
27+
28+
/**
29+
* Cloudflare API token.
30+
*
31+
* @var string
32+
*/
33+
private $api_token;
34+
35+
/**
36+
* Base API URL.
37+
*
38+
* @var string
39+
*/
40+
private $api_base;
41+
42+
/**
43+
* Last inserted row ID.
44+
*
45+
* @var int|string
46+
*/
47+
private $last_insert_id = 0;
48+
49+
/**
50+
* Constructor.
51+
*
52+
* @param array $options {
53+
* @type string $account_id Cloudflare account ID.
54+
* @type string $database_id Cloudflare D1 database ID.
55+
* @type string $api_token Cloudflare API token.
56+
* @type string $api_base Optional API base URL.
57+
* }
58+
*
59+
* @throws InvalidArgumentException When required options are missing.
60+
*/
61+
public function __construct( array $options ) {
62+
if ( empty( $options['account_id'] ) || ! is_string( $options['account_id'] ) ) {
63+
throw new InvalidArgumentException( 'Option "account_id" is required.' );
64+
}
65+
if ( empty( $options['database_id'] ) || ! is_string( $options['database_id'] ) ) {
66+
throw new InvalidArgumentException( 'Option "database_id" is required.' );
67+
}
68+
if ( empty( $options['api_token'] ) || ! is_string( $options['api_token'] ) ) {
69+
throw new InvalidArgumentException( 'Option "api_token" is required.' );
70+
}
71+
72+
$this->account_id = $options['account_id'];
73+
$this->database_id = $options['database_id'];
74+
$this->api_token = $options['api_token'];
75+
$this->api_base = $options['api_base'] ?? 'https://api.cloudflare.com/client/v4';
76+
}
77+
78+
/**
79+
* Execute a SQL query against D1.
80+
*
81+
* @param string $sql SQL statement.
82+
* @param array $params Bound parameters.
83+
*
84+
* @return WP_D1_Statement
85+
*/
86+
public function query( string $sql, array $params = array() ): WP_D1_Statement {
87+
$statement = $this->prepare( $sql );
88+
$statement->execute( $params );
89+
return $statement;
90+
}
91+
92+
/**
93+
* Prepare a SQL statement.
94+
*
95+
* @param string $sql SQL statement.
96+
*
97+
* @return WP_D1_Statement
98+
*/
99+
public function prepare( string $sql ): WP_D1_Statement {
100+
return new WP_D1_Statement( $this, $sql, array() );
101+
}
102+
103+
/**
104+
* Quote a value (basic).
105+
*
106+
* @param mixed $value Value to quote.
107+
* @param int $type PDO type.
108+
*
109+
* @return string
110+
*/
111+
public function quote( $value, int $type = 2 ): string {
112+
if ( is_null( $value ) ) {
113+
return 'NULL';
114+
}
115+
if ( is_bool( $value ) ) {
116+
return $value ? '1' : '0';
117+
}
118+
if ( is_int( $value ) || is_float( $value ) ) {
119+
return (string) $value;
120+
}
121+
return "'" . str_replace( "'", "''", (string) $value ) . "'";
122+
}
123+
124+
/**
125+
* Quote an identifier.
126+
*
127+
* @param string $identifier Identifier.
128+
*
129+
* @return string
130+
*/
131+
public function quote_identifier( string $identifier ): string {
132+
return '`' . str_replace( '`', '``', $identifier ) . '`';
133+
}
134+
135+
/**
136+
* Get last insert ID.
137+
*
138+
* @return int|string
139+
*/
140+
public function get_last_insert_id() {
141+
return $this->last_insert_id;
142+
}
143+
144+
/**
145+
* Set query logger (no-op for now).
146+
*
147+
* @param callable|null $logger Logger.
148+
*/
149+
public function set_query_logger( $logger ): void {
150+
// No-op.
151+
}
152+
153+
/**
154+
* Execute a request against the D1 API.
155+
*
156+
* @param string $sql SQL statement.
157+
* @param array $params Parameters.
158+
*
159+
* @return array
160+
*
161+
* @throws RuntimeException On HTTP or API error.
162+
*/
163+
public function execute_remote( string $sql, array $params = array() ): array {
164+
$url = rtrim( $this->api_base, '/' ) . '/accounts/' . rawurlencode( $this->account_id ) . '/d1/database/' . rawurlencode( $this->database_id ) . '/query';
165+
$body = json_encode(
166+
array(
167+
'sql' => $sql,
168+
'params' => array_values( $params ),
169+
)
170+
);
171+
172+
$raw = null;
173+
$code = 0;
174+
if ( function_exists( 'curl_init' ) ) {
175+
$ch = curl_init( $url );
176+
curl_setopt( $ch, CURLOPT_POST, true );
177+
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
178+
curl_setopt(
179+
$ch,
180+
CURLOPT_HTTPHEADER,
181+
array(
182+
'Authorization: Bearer ' . $this->api_token,
183+
'Content-Type: application/json',
184+
)
185+
);
186+
curl_setopt( $ch, CURLOPT_POSTFIELDS, $body );
187+
curl_setopt( $ch, CURLOPT_TIMEOUT, 30 );
188+
$raw = curl_exec( $ch );
189+
$code = (int) curl_getinfo( $ch, CURLINFO_HTTP_CODE );
190+
if ( false === $raw ) {
191+
$err = curl_error( $ch );
192+
curl_close( $ch );
193+
throw new RuntimeException( 'Failed to contact D1 API: ' . $err );
194+
}
195+
curl_close( $ch );
196+
} else {
197+
$context = stream_context_create(
198+
array(
199+
'http' => array(
200+
'method' => 'POST',
201+
'header' => "Authorization: Bearer {$this->api_token}\r\nContent-Type: application/json\r\n",
202+
'content' => $body,
203+
'timeout' => 30,
204+
),
205+
)
206+
);
207+
$raw = @file_get_contents( $url, false, $context );
208+
if ( false === $raw ) {
209+
throw new RuntimeException( 'Failed to contact D1 API.' );
210+
}
211+
$code = 0;
212+
if ( isset( $http_response_header[0] ) ) {
213+
preg_match( '#HTTP/\S+\s+(\d+)#', $http_response_header[0], $m );
214+
$code = isset( $m[1] ) ? (int) $m[1] : 0;
215+
}
216+
}
217+
218+
if ( $code >= 400 ) {
219+
throw new RuntimeException( 'D1 API HTTP error: ' . $code );
220+
}
221+
222+
$decoded = json_decode( $raw, true );
223+
if ( ! is_array( $decoded ) ) {
224+
throw new RuntimeException( 'Invalid D1 API response.' );
225+
}
226+
if ( empty( $decoded['success'] ) ) {
227+
$message = isset( $decoded['errors'][0]['message'] ) ? $decoded['errors'][0]['message'] : 'D1 API error.';
228+
throw new RuntimeException( $message );
229+
}
230+
231+
$result = $decoded['result'][0] ?? array();
232+
if ( isset( $result['meta']['last_row_id'] ) ) {
233+
$this->last_insert_id = $result['meta']['last_row_id'];
234+
}
235+
236+
return $result;
237+
}
238+
}
239+
240+
// Backwards/alternative names.
241+
class_alias( 'WP_D1_Connection', 'WP_Cloudflare_D1_Connection' );

0 commit comments

Comments
 (0)