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