Repository navigation
Expand file tree
/
Copy pathclass-wp-d1-connection.php
More file actions
249 lines (227 loc) · 6.16 KB
/
Copy pathclass-wp-d1-connection.php
File metadata and controls
249 lines (227 loc) · 6.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
<?php declare(strict_types = 1);
require_once __DIR__ . '/class-wp-d1-statement.php';
/**
* Cloudflare D1 connection.
*
* A standalone client for executing SQLite statements through the Cloudflare D1
* HTTP API.
*
* @access private
*/
class WP_D1_Connection {
/**
* Cloudflare account ID.
*
* @var string
*/
private $account_id;
/**
* Cloudflare D1 database ID.
*
* @var string
*/
private $database_id;
/**
* Cloudflare API token.
*
* @var string
*/
private $api_token;
/**
* Base API URL.
*
* @var string
*/
private $api_base;
/**
* Last inserted row ID.
*
* @var int|string
*/
private $last_insert_id = 0;
/**
* Constructor.
*
* @param array $options {
* @type string $account_id Cloudflare account ID.
* @type string $database_id Cloudflare D1 database ID.
* @type string $api_token Cloudflare API token.
* @type string $api_base Optional API base URL.
* }
*
* @throws InvalidArgumentException When required options are missing.
*/
public function __construct( array $options ) {
if ( empty( $options['account_id'] ) || ! is_string( $options['account_id'] ) ) {
throw new InvalidArgumentException( 'Option "account_id" is required.' );
}
if ( empty( $options['database_id'] ) || ! is_string( $options['database_id'] ) ) {
throw new InvalidArgumentException( 'Option "database_id" is required.' );
}
if ( empty( $options['api_token'] ) || ! is_string( $options['api_token'] ) ) {
throw new InvalidArgumentException( 'Option "api_token" is required.' );
}
$this->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' );