-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathClickHouse.php
More file actions
2311 lines (1989 loc) · 80.5 KB
/
Copy pathClickHouse.php
File metadata and controls
2311 lines (1989 loc) · 80.5 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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace Utopia\Usage\Adapter;
use Exception;
use Utopia\Query\Query;
use Utopia\Fetch\Client;
use Utopia\Usage\Metric;
use Utopia\Usage\Usage;
use Utopia\Validator\Hostname;
/**
* ClickHouse Adapter for Usage
*
* This adapter stores usage metrics in ClickHouse using HTTP interface.
* ClickHouse is optimized for analytical queries and can handle massive amounts of metrics data.
*
* Features:
* - Dynamic schema based on SQL adapter attributes (no hardcoded columns)
* - Safe SQL injection prevention using ClickHouse parameter binding
* - Support for find() and count() operations with Query objects
* - Multi-tenant support with optional shared tables
* - Namespace support for table name prefixes
* - Proper index creation for optimized analytical queries
* - Bloom filter indexes for efficient filtering
* - MergeTree engine with monthly partitioning by time
*/
class ClickHouse extends SQL
{
private const DEFAULT_PORT = 8123;
private const DEFAULT_DATABASE = 'default';
private const DEFAULT_TABLE = self::COLLECTION;
private const DEFAULT_SNAPSHOT_TABLE = self::COLLECTION . '_snapshot';
private const INSERT_BATCH_SIZE = 1_000;
private string $host;
private int $port;
private string $database = self::DEFAULT_DATABASE;
private string $table = self::DEFAULT_TABLE;
private string $username;
private string $password;
/** @var bool Whether to use HTTPS for ClickHouse HTTP interface */
private bool $secure = false;
private Client $client;
/** @var bool Whether to use FINAL in SELECT queries to force merge-on-read (tests) */
private bool $useFinal = true;
protected ?int $tenant = null;
protected bool $sharedTables = false;
protected string $namespace = '';
/** @var int|null Retention in days; when set, setup() applies a TTL to the snapshot table. Null disables TTL. */
private ?int $retention = null;
/** @var bool Whether to log queries for debugging */
private bool $enableQueryLogging = false;
/** @var array<array{sql: string, params: array<string, mixed>, duration: float, timestamp: float, success: bool, error?: string}> Query execution log */
private array $queryLog = [];
/** @var bool Whether to enable gzip compression for HTTP requests/responses */
private bool $enableCompression = false;
/** @var bool Whether to enable HTTP keep-alive for connection pooling */
private bool $enableKeepAlive = true;
/** @var int Number of requests made using this adapter instance */
private int $requestCount = 0;
/** @var int Maximum number of retry attempts for failed requests (0 = no retries) */
private int $maxRetries = 3;
/** @var int Initial retry delay in milliseconds (doubles with each retry) */
private int $retryDelay = 100;
/** @var string|null Current operation context for better error messages */
private ?string $operationContext = null;
/** @var bool Whether to enable ClickHouse async inserts (server-side batching) */
private bool $asyncInserts = false;
/** @var bool Whether to wait for async insert confirmation before returning */
private bool $asyncInsertWait = true;
/**
* @param string $host ClickHouse host
* @param string $username ClickHouse username (default: 'default')
* @param string $password ClickHouse password (default: '')
* @param int $port ClickHouse HTTP port (default: 8123)
* @param bool $secure Whether to use HTTPS (default: false)
*/
public function __construct(
string $host,
string $username = 'default',
string $password = '',
int $port = self::DEFAULT_PORT,
bool $secure = false
) {
$this->validateHost($host);
$this->validatePort($port);
$this->host = $host;
$this->port = $port;
$this->username = $username;
$this->password = $password;
$this->secure = $secure;
// Initialize the HTTP client for connection reuse
$this->client = new Client();
$this->client->addHeader('X-ClickHouse-User', $this->username);
$this->client->addHeader('X-ClickHouse-Key', $this->password);
$this->client->setTimeout(30_000); // 30 seconds
}
/**
* Enable or disable using FINAL in SELECT queries.
*/
public function setUseFinal(bool $useFinal): self
{
$this->useFinal = $useFinal;
return $this;
}
/**
* Set the HTTP request timeout in milliseconds.
*
* @param int $milliseconds Timeout in milliseconds (min: 1000ms, max: 600000ms)
* @return self
* @throws Exception If timeout is out of valid range
*/
public function setTimeout(int $milliseconds): self
{
if ($milliseconds < 1000) {
throw new Exception('Timeout must be at least 1000 milliseconds (1 second)');
}
if ($milliseconds > 600000) {
throw new Exception('Timeout cannot exceed 600000 milliseconds (10 minutes)');
}
$this->client->setTimeout($milliseconds);
return $this;
}
/**
* Enable or disable query logging for debugging.
*
* @param bool $enable Whether to enable query logging
* @return self
*/
public function enableQueryLogging(bool $enable = true): self
{
$this->enableQueryLogging = $enable;
return $this;
}
/**
* Enable or disable gzip compression for HTTP requests/responses.
* When enabled, responses from ClickHouse will be gzip-compressed, reducing bandwidth usage.
*
* @param bool $enable Whether to enable compression
* @return self
*/
public function setCompression(bool $enable): self
{
$this->enableCompression = $enable;
return $this;
}
/**
* Enable or disable HTTP keep-alive for connection pooling.
* When enabled, HTTP connections are reused across multiple requests, reducing latency.
*
* @param bool $enable Whether to enable keep-alive (default: true)
* @return self
*/
public function setKeepAlive(bool $enable): self
{
$this->enableKeepAlive = $enable;
return $this;
}
/**
* Set maximum number of retry attempts for failed requests.
*
* @param int $maxRetries Maximum retry attempts (0-10, 0 = no retries)
* @return self
* @throws Exception If maxRetries is out of valid range
*/
public function setMaxRetries(int $maxRetries): self
{
if ($maxRetries < 0 || $maxRetries > 10) {
throw new Exception('Max retries must be between 0 and 10');
}
$this->maxRetries = $maxRetries;
return $this;
}
/**
* Set initial retry delay in milliseconds.
* Delay doubles with each retry attempt (exponential backoff).
*
* @param int $milliseconds Initial delay in milliseconds (10-5000ms)
* @return self
* @throws Exception If delay is out of valid range
*/
public function setRetryDelay(int $milliseconds): self
{
if ($milliseconds < 10 || $milliseconds > 5000) {
throw new Exception('Retry delay must be between 10 and 5000 milliseconds');
}
$this->retryDelay = $milliseconds;
return $this;
}
/**
* Enable or disable ClickHouse async inserts (server-side batching).
*
* When enabled, ClickHouse buffers small inserts server-side and flushes them
* together, significantly improving throughput for high-frequency small inserts.
*
* @param bool $enable Whether to enable async inserts
* @param bool $waitForConfirmation Whether to wait for server-side flush before returning (default: true).
* - true: INSERT returns after data is flushed to storage (durable, recommended for production)
* - false: INSERT returns immediately (fire-and-forget, risk of data loss on crash)
* @return self
*/
public function setAsyncInserts(bool $enable, bool $waitForConfirmation = true): self
{
$this->asyncInserts = $enable;
$this->asyncInsertWait = $waitForConfirmation;
return $this;
}
/**
* Get connection statistics for monitoring.
*
* @return array{request_count: int, keep_alive_enabled: bool, compression_enabled: bool, query_logging_enabled: bool, max_retries: int, retry_delay: int, async_inserts: bool, async_insert_wait: bool}
*/
public function getConnectionStats(): array
{
return [
'request_count' => $this->requestCount,
'keep_alive_enabled' => $this->enableKeepAlive,
'compression_enabled' => $this->enableCompression,
'query_logging_enabled' => $this->enableQueryLogging,
'max_retries' => $this->maxRetries,
'retry_delay' => $this->retryDelay,
'async_inserts' => $this->asyncInserts,
'async_insert_wait' => $this->asyncInsertWait,
];
}
/**
* Get the query execution log.
*
* @return array<array{sql: string, params: array<string, mixed>, duration: float, timestamp: float, success: bool, error?: string}>
*/
public function getQueryLog(): array
{
return $this->queryLog;
}
/**
* Clear the query execution log.
*
* @return self
*/
public function clearQueryLog(): self
{
$this->queryLog = [];
return $this;
}
/**
* Get adapter name.
*/
public function getName(): string
{
return 'ClickHouse';
}
/**
* Check ClickHouse connection health and get server information.
*
* @return array{healthy: bool, host: string, port: int, database: string, secure: bool, version?: string, uptime?: int, error?: string, response_time?: float}
*/
public function healthCheck(): array
{
$this->setOperationContext('healthCheck()');
$startTime = microtime(true);
$result = [
'healthy' => false,
'host' => $this->host,
'port' => $this->port,
'database' => $this->database,
'secure' => $this->secure,
];
try {
// Simple connectivity test
$response = $this->query('SELECT 1 as ping FORMAT JSON');
$json = json_decode($response, true);
if (!is_array($json) || !isset($json['data'][0]['ping'])) {
$result['error'] = 'Invalid response format';
return $result;
}
// Get server version and uptime
try {
$versionResponse = $this->query('SELECT version() as version, uptime() as uptime FORMAT JSON');
$versionJson = json_decode($versionResponse, true);
if (is_array($versionJson) && isset($versionJson['data'][0])) {
$result['version'] = (string) $versionJson['data'][0]['version'];
$result['uptime'] = (int) $versionJson['data'][0]['uptime'];
}
} catch (Exception $e) {
// Version info is optional, don't fail health check
}
$result['healthy'] = true;
$result['response_time'] = round(microtime(true) - $startTime, 3);
return $result;
} catch (Exception $e) {
$result['error'] = $e->getMessage();
$result['response_time'] = round(microtime(true) - $startTime, 3);
return $result;
}
}
/**
* Validate host parameter.
*
* @param string $host
* @throws Exception
*/
private function validateHost(string $host): void
{
$validator = new Hostname();
if (!$validator->isValid($host)) {
throw new Exception('ClickHouse host is not a valid hostname or IP address');
}
}
/**
* Validate port parameter.
*
* @param int $port
* @throws Exception
*/
private function validatePort(int $port): void
{
if ($port < 1 || $port > 65535) {
throw new Exception('ClickHouse port must be between 1 and 65535');
}
}
/**
* Validate identifier (database, table, namespace).
* ClickHouse identifiers follow SQL standard rules.
*
* @param string $identifier
* @param string $type Name of the identifier type for error messages
* @throws Exception
*/
private function validateIdentifier(string $identifier, string $type = 'Identifier'): void
{
if (empty($identifier)) {
throw new Exception("{$type} cannot be empty");
}
if (strlen($identifier) > 255) {
throw new Exception("{$type} cannot exceed 255 characters");
}
// ClickHouse identifiers: alphanumeric, underscores, cannot start with number
if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $identifier)) {
throw new Exception("{$type} must start with a letter or underscore and contain only alphanumeric characters and underscores");
}
// Check against SQL keywords (common ones)
$keywords = ['SELECT', 'INSERT', 'UPDATE', 'DELETE', 'DROP', 'CREATE', 'ALTER', 'TABLE', 'DATABASE'];
if (in_array(strtoupper($identifier), $keywords, true)) {
throw new Exception("{$type} cannot be a reserved SQL keyword");
}
}
/**
* Escape an identifier (database name, table name, column name) for safe use in SQL.
* Uses backticks as per SQL standard for identifier quoting.
*
* @param string $identifier
* @return string
*/
private function escapeIdentifier(string $identifier): string
{
// Backtick escaping: replace any backticks in the identifier with double backticks
return '`' . str_replace('`', '``', $identifier) . '`';
}
/**
* Set the namespace for multi-project support.
* Namespace is used as a prefix for table names.
*
* @param string $namespace
* @return self
* @throws Exception
*/
public function setNamespace(string $namespace): self
{
if (!empty($namespace)) {
$this->validateIdentifier($namespace, 'Namespace');
}
$this->namespace = $namespace;
return $this;
}
/**
* Set the database name for subsequent operations.
*
* @param string $database
* @return self
* @throws Exception
*/
public function setDatabase(string $database): self
{
$this->validateIdentifier($database, 'Database');
$this->database = $database;
return $this;
}
/**
* Enable or disable HTTPS for ClickHouse HTTP interface.
*/
public function setSecure(bool $secure): self
{
$this->secure = $secure;
return $this;
}
/**
* Get the namespace.
*
* @return string
*/
public function getNamespace(): string
{
return $this->namespace;
}
/**
* Set the tenant ID for multi-tenant support.
* Tenant is used to isolate metrics by tenant.
*
* @param int|null $tenant
* @return self
*/
public function setTenant(?int $tenant): self
{
$this->tenant = $tenant;
return $this;
}
/**
* Get the tenant ID.
*
* @return int|null
*/
public function getTenant(): ?int
{
return $this->tenant;
}
/**
* Set whether tables are shared across tenants.
* When enabled, a tenant column is added to the table for data isolation.
*
* @param bool $sharedTables
* @return self
*/
public function setSharedTables(bool $sharedTables): self
{
$this->sharedTables = $sharedTables;
return $this;
}
/**
* Get whether tables are shared across tenants.
*
* @return bool
*/
public function isSharedTables(): bool
{
return $this->sharedTables;
}
/**
* Set the retention window in days. When set, setup() applies a TTL to the
* snapshot table so rows older than the window are dropped by background
* merges. The aggregated table is left untouched. Pass null to disable
* (the default).
*
* @param int|null $days
* @return self
* @throws Exception If $days is not positive
*/
public function setRetention(?int $days): self
{
if ($days !== null && $days < 1) {
throw new Exception('Retention must be a positive number of days');
}
$this->retention = $days;
return $this;
}
/**
* Get the retention window in days, or null when TTL is disabled.
*
* @return int|null
*/
public function getRetention(): ?int
{
return $this->retention;
}
/**
* Get the table name with namespace prefix.
* Namespace is used to isolate tables for different projects/applications.
*
* @return string
*/
private function getTableName(): string
{
$tableName = $this->table;
if (!empty($this->namespace)) {
$tableName = $this->namespace . '_' . $tableName;
}
return $tableName;
}
/**
* Get the snapshot table name with namespace prefix.
* Snapshot table uses ReplacingMergeTree for replace-upsert semantics.
*
* @return string
*/
private function getSnapshotTableName(): string
{
$tableName = self::DEFAULT_SNAPSHOT_TABLE;
if (!empty($this->namespace)) {
$tableName = $this->namespace . '_' . $tableName;
}
return $tableName;
}
/**
* Build a fully qualified table reference with database, escaping, and optional FINAL clause.
*
* @param string $tableName The table name (with namespace already applied)
* @param bool $useFinal Whether to append FINAL clause (defaults to adapter's useFinal setting)
* @return string Fully qualified table reference
*/
private function buildTableReference(string $tableName, ?bool $useFinal = null): string
{
$useFinal = $useFinal ?? $this->useFinal;
$escapedTable = $this->escapeIdentifier($this->database) . '.' . $this->escapeIdentifier($tableName);
return $escapedTable . ($useFinal ? ' FINAL' : '');
}
/**
* Log a query execution for debugging purposes.
*
* @param string $sql SQL query executed
* @param array<string, mixed> $params Query parameters
* @param float $duration Execution duration in seconds
* @param bool $success Whether the query succeeded
* @param string|null $error Error message if query failed
* @param int $retryAttempt Current retry attempt number (0 = first attempt)
*/
private function logQuery(string $sql, array $params, float $duration, bool $success, ?string $error = null, int $retryAttempt = 0): void
{
if (!$this->enableQueryLogging) {
return;
}
$logEntry = [
'sql' => $sql,
'params' => $params,
'duration' => $duration,
'timestamp' => microtime(true),
'success' => $success,
];
if ($retryAttempt > 0) {
$logEntry['retry_attempt'] = $retryAttempt;
}
if ($error !== null) {
$logEntry['error'] = $error;
}
$this->queryLog[] = $logEntry;
}
/**
* Determine if an error is retryable based on HTTP status code or error message.
*
* @param int|null $httpCode HTTP status code if available
* @param string $errorMessage Error message
* @return bool True if the error is retryable
*/
private function isRetryableError(?int $httpCode, string $errorMessage): bool
{
// Retry on server errors and specific client errors
if ($httpCode !== null) {
// Retry on: 408 (Timeout), 429 (Too Many Requests), 500, 502, 503, 504
if (in_array($httpCode, [408, 429, 500, 502, 503, 504], true)) {
return true;
}
// Don't retry on client errors (4xx except 408, 429)
if ($httpCode >= 400 && $httpCode < 500) {
return false;
}
}
// Retry on connection/network errors
$retryablePatterns = [
'connection',
'timeout',
'timed out',
'refused',
'reset',
'broken pipe',
'network',
'temporary',
'unavailable',
];
$lowerMessage = strtolower($errorMessage);
foreach ($retryablePatterns as $pattern) {
if (strpos($lowerMessage, $pattern) !== false) {
return true;
}
}
return false;
}
/**
* Set the current operation context for better error messages.
*
* @param string|null $context Operation context (e.g., "find()", "incrementBatch()", "setup()")
* @return void
*/
private function setOperationContext(?string $context): void
{
$this->operationContext = $context;
}
/**
* Execute an operation with automatic retry logic and exponential backoff.
*
* @template T
* @param callable(int): T $operation Callback that performs the operation, receives attempt number
* @param callable(Exception, int|null): bool $shouldRetry Callback to determine if error is retryable
* @param callable(Exception, int): Exception $buildException Callback to build final exception with context
* @return T The result from the operation
* @throws Exception
*/
private function executeWithRetry(callable $operation, callable $shouldRetry, callable $buildException): mixed
{
$attempt = 0;
$lastException = null;
while ($attempt <= $this->maxRetries) {
try {
return $operation($attempt);
} catch (Exception $e) {
$lastException = $e;
// Check if we should retry
if ($attempt < $this->maxRetries && $shouldRetry($e, $attempt)) {
$attempt++;
$delay = $this->retryDelay * (2 ** ($attempt - 1)); // Exponential backoff
usleep($delay * 1000); // Convert ms to microseconds
continue;
}
// Not retryable or max retries reached
throw $buildException($e, $attempt);
}
}
// Should never reach here, but just in case
throw $buildException(
$lastException ?? new Exception('Unknown error occurred'),
$this->maxRetries
);
}
/**
* Build a contextual error message with operation, table, and query info.
*
* @param string $baseMessage The base error message
* @param string|null $table Table name if applicable
* @param string|null $sql SQL query (will be truncated if too long)
* @return string Enhanced error message with context
*/
private function buildErrorMessage(string $baseMessage, ?string $table = null, ?string $sql = null): string
{
$parts = [];
if ($this->operationContext !== null) {
$parts[] = "Operation: {$this->operationContext}";
}
if ($table !== null) {
$parts[] = "Table: {$table}";
}
if ($sql !== null) {
// Truncate SQL if too long (keep first 200 chars)
$truncatedSql = strlen($sql) > 200 ? substr($sql, 0, 200) . '...' : $sql;
// Normalize whitespace for readability
$truncatedSql = preg_replace('/\s+/', ' ', $truncatedSql);
$parts[] = "Query: {$truncatedSql}";
}
$context = !empty($parts) ? ' [' . implode(', ', $parts) . ']' : '';
return $baseMessage . $context;
}
/**
* Execute a ClickHouse query via HTTP interface using Fetch Client.
*
* Uses ClickHouse query parameters (sent as POST multipart form data) to prevent SQL injection.
* This is ClickHouse's native parameter mechanism - parameters are safely
* transmitted separately from the query structure.
*
* Parameters are referenced in the SQL using the syntax: {paramName:Type}.
* For example: SELECT * WHERE id = {id:String}
*
* ClickHouse handles all parameter escaping and type conversion internally,
* making this approach fully injection-safe without needing manual escaping.
*
* Using POST body avoids URL length limits for batch operations with many parameters.
* Equivalent to: curl -X POST -F 'query=...' -F 'param_key=value' http://host/
*
* @param array<string, mixed> $params Key-value pairs for query parameters
* @throws Exception
*/
private function query(string $sql, array $params = []): string
{
return $this->executeWithRetry(
// Operation to execute
function (int $attempt) use ($sql, $params): string {
$startTime = microtime(true);
$scheme = $this->secure ? 'https' : 'http';
$url = "{$scheme}://{$this->host}:{$this->port}/";
// Update the database header for each query (in case setDatabase was called)
$this->client->addHeader('X-ClickHouse-Database', $this->database);
// Enable keep-alive for connection pooling
if ($this->enableKeepAlive) {
$this->client->addHeader('Connection', 'keep-alive');
} else {
$this->client->addHeader('Connection', 'close');
}
// Enable compression if configured
if ($this->enableCompression) {
$this->client->addHeader('Accept-Encoding', 'gzip');
}
// Track request count for statistics (only on first attempt)
if ($attempt === 0) {
$this->requestCount++;
}
// Build multipart form data body with query and parameters
// The Fetch client will automatically encode arrays as multipart/form-data
$body = ['query' => $sql];
foreach ($params as $key => $value) {
$body['param_' . $key] = $this->formatParamValue($value);
}
$response = $this->client->fetch(
url: $url,
method: Client::METHOD_POST,
body: $body
);
$httpCode = $response->getStatusCode();
if ($httpCode !== 200) {
$bodyStr = $response->getBody();
$bodyStr = is_string($bodyStr) ? $bodyStr : '';
$duration = microtime(true) - $startTime;
$baseError = "ClickHouse query failed with HTTP {$httpCode}: {$bodyStr}";
$errorMsg = $this->buildErrorMessage($baseError, null, $sql);
$this->logQuery($sql, $params, $duration, false, $errorMsg, $attempt);
throw new Exception($errorMsg . '|HTTP_CODE:' . $httpCode);
}
$body = $response->getBody();
$result = is_string($body) ? $body : '';
$duration = microtime(true) - $startTime;
$this->logQuery($sql, $params, $duration, true, null, $attempt);
return $result;
},
// Should retry predicate
function (Exception $e, ?int $httpCode): bool {
// Extract HTTP code from exception message if embedded
$exceptionHttpCode = null;
if (preg_match('/\|HTTP_CODE:(\d+)$/', $e->getMessage(), $matches)) {
$exceptionHttpCode = (int) $matches[1];
}
return $this->isRetryableError($exceptionHttpCode, $e->getMessage());
},
// Build final exception
function (Exception $e, int $attempt) use ($sql): Exception {
// Clean up HTTP code marker if present
$cleanMessage = preg_replace('/\|HTTP_CODE:\d+$/', '', $e->getMessage());
$cleanMessage = is_string($cleanMessage) ? $cleanMessage : $e->getMessage();
// If message already has context, return as-is
if (strpos($cleanMessage, '[Operation:') !== false) {
return new Exception($cleanMessage, 0, $e);
}
// Otherwise, build context
$baseError = "ClickHouse query execution failed after " . ($attempt + 1) . " attempt(s): {$cleanMessage}";
$errorMsg = $this->buildErrorMessage($baseError, null, $sql);
return new Exception($errorMsg, 0, $e);
}
);
}
/**
* Execute a ClickHouse INSERT using JSONEachRow format.
*
* This is significantly more efficient than SQL parameter binding for batch inserts.
*
* @param string $table Table name
* @param array<string> $data Array of JSON strings (one per row)
* @throws Exception
*/
private function insert(string $table, array $data): void
{
if (empty($data)) {
return;
}
$this->executeWithRetry(
// Operation to execute
function (int $attempt) use ($table, $data): void {
$startTime = microtime(true);
$scheme = $this->secure ? 'https' : 'http';
$escapedTable = $this->escapeIdentifier($table);
// Build URL with query and optional async insert settings
$queryParams = ['query' => "INSERT INTO {$escapedTable} FORMAT JSONEachRow"];
if ($this->asyncInserts) {
$queryParams['async_insert'] = '1';
$queryParams['wait_for_async_insert'] = $this->asyncInsertWait ? '1' : '0';
}
$url = "{$scheme}://{$this->host}:{$this->port}/?" . http_build_query($queryParams);
// Update the database header
$this->client->addHeader('X-ClickHouse-Database', $this->database);
$this->client->addHeader('Content-Type', 'application/x-ndjson');
// Enable keep-alive for connection pooling
if ($this->enableKeepAlive) {
$this->client->addHeader('Connection', 'keep-alive');
} else {
$this->client->addHeader('Connection', 'close');
}
// Enable compression if configured
if ($this->enableCompression) {
$this->client->addHeader('Accept-Encoding', 'gzip');
}
// Track request count for statistics (only on first attempt)
if ($attempt === 0) {
$this->requestCount++;
}
// Join JSON strings with newlines
$body = implode("\n", $data);
$sql = "INSERT INTO {$escapedTable} FORMAT JSONEachRow";
$params = ['rows' => count($data), 'bytes' => strlen($body)];
try {
$response = $this->client->fetch(
url: $url,
method: Client::METHOD_POST,
body: $body
);
$httpCode = $response->getStatusCode();
if ($httpCode !== 200) {
$bodyStr = $response->getBody();
$bodyStr = is_string($bodyStr) ? $bodyStr : '';
$duration = microtime(true) - $startTime;
$rowCount = count($data);
$baseError = "ClickHouse insert failed with HTTP {$httpCode}: {$bodyStr}";
$errorMsg = $this->buildErrorMessage($baseError, $table, "INSERT INTO {$table} ({$rowCount} rows)");
$this->logQuery($sql, $params, $duration, false, $errorMsg, $attempt);
throw new Exception($errorMsg . '|HTTP_CODE:' . $httpCode);
}
$duration = microtime(true) - $startTime;
$this->logQuery($sql, $params, $duration, true, null, $attempt);
} finally {
// Always clean up Content-Type header
$this->client->removeHeader('Content-Type');
}
},
// Should retry predicate
function (Exception $e, ?int $httpCode): bool {
// Extract HTTP code from exception message if embedded
$exceptionHttpCode = null;
if (preg_match('/\|HTTP_CODE:(\d+)$/', $e->getMessage(), $matches)) {
$exceptionHttpCode = (int) $matches[1];
}
return $this->isRetryableError($exceptionHttpCode, $e->getMessage());
},
// Build final exception
function (Exception $e, int $attempt) use ($table, $data): Exception {
// Clean up HTTP code marker if present
$cleanMessage = preg_replace('/\|HTTP_CODE:\d+$/', '', $e->getMessage());
$cleanMessage = is_string($cleanMessage) ? $cleanMessage : $e->getMessage();
// If message already has context, return as-is
if (strpos($cleanMessage, '[Operation:') !== false) {
return new Exception($cleanMessage, 0, $e);
}
// Otherwise, build context
$rowCount = count($data);
$baseError = "ClickHouse insert execution failed after " . ($attempt + 1) . " attempt(s): {$cleanMessage}";
$errorMsg = $this->buildErrorMessage($baseError, $table, "INSERT INTO {$table} ({$rowCount} rows)");
return new Exception($errorMsg, 0, $e);
}
);
}
/**
* Format a parameter value for safe transmission to ClickHouse.
*
* Converts PHP values to their string representation without SQL quoting.
* ClickHouse's query parameter mechanism handles type conversion and escaping.
*
* @param mixed $value
* @return string
*/
private function formatParamValue(mixed $value): string
{
if (is_int($value) || is_float($value)) {
return (string) $value;
}
if ($value === null) {
return '';
}
if (is_bool($value)) {
return $value ? '1' : '0';
}
if (is_array($value)) {
$encoded = json_encode($value);