forked from smi2/phpClickHouse
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttp.php
More file actions
972 lines (823 loc) · 27.2 KB
/
Copy pathHttp.php
File metadata and controls
972 lines (823 loc) · 27.2 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
<?php
namespace ClickHouseDB\Transport;
use ClickHouseDB\Exception\TransportException;
use ClickHouseDB\Query\Degeneration;
use ClickHouseDB\Query\Query;
use ClickHouseDB\Query\WhereInFile;
use ClickHouseDB\Query\WriteToFile;
use ClickHouseDB\Settings;
use ClickHouseDB\Statement;
use const PHP_EOL;
class Http
{
const AUTH_METHOD_NONE = 0;
const AUTH_METHOD_HEADER = 1;
const AUTH_METHOD_QUERY_STRING = 2;
const AUTH_METHOD_BASIC_AUTH = 3;
const AUTH_METHODS_LIST = [
self::AUTH_METHOD_NONE,
self::AUTH_METHOD_HEADER,
self::AUTH_METHOD_QUERY_STRING,
self::AUTH_METHOD_BASIC_AUTH,
];
/**
* @var string
*/
private string $_username;
/**
* @var string
*/
private string $_password;
/**
* The username and password can be indicated in one of three ways:
* - Using HTTP Basic Authentication.
* - In the 'user' and 'password' URL parameters.
* - Using 'X-ClickHouse-User' and 'X-ClickHouse-Key' headers (by default)
*
* @see https://clickhouse.tech/docs/en/interfaces/http/
* @var int
*/
private int $_authMethod = self::AUTH_METHOD_HEADER;
/**
* @var string
*/
private string $_host = '';
/**
* @var int
*/
private int $_port = 0;
/**
* @var bool
*/
private bool $_verbose = false;
/**
* @var CurlerRolling|null
*/
private ?CurlerRolling $_curler = null;
/**
* @var Settings
*/
private Settings $_settings;
/**
* @var array
*/
private array $_query_degenerations = [];
/**
* Count seconds (int)
*
* @var float
*/
private float $_connectTimeOut = 5.0;
/**
* @var mixed
*/
private mixed $xClickHouseProgress = null;
/**
* @var null|string
*/
private ?string $sslCA = null;
/**
* @var array
*/
private array $curlOptions = [];
/**
* @var mixed
*/
private mixed $stdErrOut = null;
/**
* @var mixed
*/
private mixed $handle = null;
/**
* Http constructor.
* @param string $host
* @param int $port
* @param string $username
* @param string $password
* @param int|null $authMethod
*/
public function __construct(string $host, int $port, string $username, string $password, ?int $authMethod = null)
{
$this->setHost($host, $port);
$this->_username = $username;
$this->_password = $password;
if ($authMethod) {
$this->_authMethod = $authMethod;
}
$this->_settings = new Settings();
$this->setCurler();
}
public function setCurler() : void
{
$this->_curler = new CurlerRolling();
}
/**
* @param CurlerRolling $curler
*/
public function setDirtyCurler(CurlerRolling $curler) : void
{
if ($curler instanceof CurlerRolling) {
$this->_curler = $curler;
}
}
/**
* @return CurlerRolling|null
*/
public function getCurler(): ?CurlerRolling
{
return $this->_curler;
}
/**
* @param string $host
* @param int $port
*/
public function setHost(string $host, int $port = -1) : void
{
if ($port > 0) {
$this->_port = $port;
}
$this->_host = $host;
}
/**
* Sets client SSL certificate for Yandex Cloud
*
* @param string $caPath
*/
public function setSslCa(string $caPath) : void
{
$this->sslCA = $caPath;
}
/**
* @param array $options
*/
public function setCurlOptions(array $options) : void
{
$this->curlOptions = $options;
}
/**
* @return string
*/
public function getUri(): string
{
$proto = 'http';
if ($this->settings()->isHttps()) {
$proto = 'https';
}
$host = $this->_host;
// IPv6 address detection: contains ":" but no "/" (not a path)
if (stripos($host, ':') !== false && stripos($host, '/') === false && !str_starts_with($host, '[')) {
// Check if it's IPv6 (more than one colon) vs host:port
if (substr_count($host, ':') > 1) {
$host = '[' . $host . ']';
}
}
$uri = $proto . '://' . $host;
if (stripos($host, '/') !== false) {
return $uri;
}
// Already has port (host:port or [ipv6]:port)
if (preg_match('/:\d+$/', $host)) {
return $uri;
}
if (intval($this->_port) > 0) {
return $uri . ':' . $this->_port;
}
return $uri;
}
/**
* @return Settings
*/
public function settings(): Settings
{
return $this->_settings;
}
/**
* @param bool $flag
* @return bool
*/
public function verbose(bool $flag): bool
{
$this->_verbose = $flag;
return $flag;
}
/**
* @param array $params
* @param array $querySettings Per-query settings override
* @return string
*/
private function getUrl(array $params = [], array $querySettings = []): string
{
$settings = $this->settings()->getSettings();
if (is_array($params) && sizeof($params)) {
$settings = array_merge($settings, $params);
}
// Per-query settings override global settings
if (!empty($querySettings)) {
$settings = array_merge($settings, $querySettings);
}
if ($this->settings()->isReadOnlyUser()) {
unset($settings['extremes']);
unset($settings['readonly']);
unset($settings['enable_http_compression']);
unset($settings['max_execution_time']);
}
unset($settings['https']);
return $this->getUri() . '?' . http_build_query($settings);
}
/**
* @param array $extendinfo
* @return CurlerRequest
*/
private function newRequest(array $extendinfo): CurlerRequest
{
$new = new CurlerRequest();
switch ($this->_authMethod) {
case self::AUTH_METHOD_QUERY_STRING:
/* @todo: Move this implementation to CurlerRequest class. Possible options: the authentication method
* should be applied in method `CurlerRequest:prepareRequest()`.
*/
$this->settings()->set('user', $this->_username);
$this->settings()->set('password', $this->_password);
break;
case self::AUTH_METHOD_BASIC_AUTH:
$new->authByBasicAuth($this->_username, $this->_password);
break;
case self::AUTH_METHOD_NONE:
// No authentication
break;
default:
// Auth with headers by default
$new->authByHeaders($this->_username, $this->_password);
break;
}
$new->POST()->setRequestExtendedInfo($extendinfo);
$new->httpCompression($this->settings()->isEnableHttpCompression());
if ($this->settings()->getSessionId()) {
$new->persistent();
}
if ($this->sslCA) {
$new->setSslCa($this->sslCA);
}
foreach ($this->curlOptions as $key => $value) {
$new->option($key, $value);
}
$new->timeOut($this->settings()->getTimeOut());
$new->connectTimeOut($this->_connectTimeOut);
$new->keepAlive();
$new->verbose(boolval($this->_verbose));
return $new;
}
/**
* @param Query $query
* @param array $urlParams
* @param bool $query_as_string
* @param array $querySettings
* @return CurlerRequest
* @throws \ClickHouseDB\Exception\TransportException
*/
private function makeRequest(Query $query, array $urlParams = [], bool $query_as_string = false, array $querySettings = []): CurlerRequest
{
$sql = $query->toSql();
if ($query_as_string) {
$urlParams['query'] = $sql;
}
$extendInfo = [
'sql' => $sql,
'query' => $query,
'format' => $query->getFormat()
];
$new = $this->newRequest($extendInfo);
/*
* Build URL after request making, since URL may contain auth data. This will not matter after the
* implantation of the todo in the `HTTP:newRequest()` method.
*/
if ($query->isUseInUrlBindingsParams()) {
$urlParams = array_replace_recursive($urlParams, $query->getUrlBindingsParams());
}
$url = $this->getUrl($urlParams, $querySettings);
$new->url($url);
if (!$query_as_string) {
$new->parameters_json($sql);
}
$new->httpCompression($this->settings()->isEnableHttpCompression());
return $new;
}
/**
* @param mixed $stream
* @return void
*/
public function setStdErrOut(mixed $stream): void
{
if (is_resource($stream)) {
$this->stdErrOut=$stream;
}
}
/**
* @param string|Query $sql
* @return CurlerRequest
*/
public function writeStreamData(Query|string $sql): CurlerRequest
{
if ($sql instanceof Query) {
$query = $sql;
} else {
$query = new Query($sql);
}
$extendInfo = [
'sql' => $sql,
'query' => $query,
'format' => $query->getFormat()
];
$request = $this->newRequest($extendInfo);
/*
* Build URL after request making, since URL may contain auth data. This will not matter after the
* implantation of the todo in the `HTTP:newRequest()` method.
*/
$url = $this->getUrl([
'readonly' => 0,
'query' => $query->toSql()
]);
$request->url($url);
return $request;
}
/**
* @param string $sql
* @param string $file_name
* @return Statement
* @throws \ClickHouseDB\Exception\TransportException
*/
public function writeAsyncCSV(string $sql, string $file_name): Statement
{
$query = new Query($sql);
$extendinfo = [
'sql' => $sql,
'query' => $query,
'format' => $query->getFormat()
];
$request = $this->newRequest($extendinfo);
/*
* Build URL after request making, since URL may contain auth data. This will not matter after the
* implantation of the todo in the `HTTP:newRequest()` method.
*/
$url = $this->getUrl([
'readonly' => 0,
'query' => $query->toSql()
]);
$request->url($url);
$request->setCallbackFunction(function (CurlerRequest $request) {
$handle = $request->getInfileHandle();
if (is_resource($handle)) {
fclose($handle);
}
});
$request->setInfile($file_name);
$this->_curler->addQueLoop($request);
return new Statement($request);
}
/**
* get Count Pending Query in Queue
*
* @return int
*/
public function getCountPendingQueue(): int
{
return $this->_curler->countPending();
}
/**
* set Connect TimeOut in seconds [CURLOPT_CONNECTTIMEOUT] ( int )
*
* @param float $connectTimeOut
*/
public function setConnectTimeOut(float $connectTimeOut): void
{
$this->_connectTimeOut = $connectTimeOut;
}
/**
* get ConnectTimeOut in seconds
*
* @return float
*/
public function getConnectTimeOut(): float
{
return $this->_connectTimeOut;
}
public function __findXClickHouseProgress($handle): bool
{
$code = curl_getinfo($handle, CURLINFO_HTTP_CODE);
// Search X-ClickHouse-Progress
if ($code == 200) {
$response = curl_multi_getcontent($handle);
$header_size = curl_getinfo($handle, CURLINFO_HEADER_SIZE);
if (!$header_size) {
return false;
}
$header = substr($response, 0, $header_size);
if (!$header) {
return false;
}
$match = [];
if (preg_match_all('/^X-ClickHouse-(?:Progress|Summary):(.*?)$/im', $header, $match)) {
$data = @json_decode(end($match[1]), true);
if ($data && is_callable($this->xClickHouseProgress)) {
if (is_array($this->xClickHouseProgress)) {
call_user_func_array($this->xClickHouseProgress, [$data]);
} else {
call_user_func($this->xClickHouseProgress, $data);
}
}
}
}
return false;
}
/**
* @param Query $query
* @param null|WhereInFile $whereInFile
* @param null|WriteToFile $writeToFile
* @param array $querySettings
* @return CurlerRequest
* @throws \Exception
*/
public function getRequestRead(Query $query, $whereInFile = null, $writeToFile = null, array $querySettings = []): CurlerRequest
{
$urlParams = ['readonly' => 2];
$query_as_string = false;
// ---------------------------------------------------------------------------------
if ($whereInFile instanceof WhereInFile && $whereInFile->size()) {
// $request = $this->prepareSelectWhereIn($request, $whereInFile);
$structure = $whereInFile->fetchUrlParams();
// $structure = [];
$urlParams = array_merge($urlParams, $structure);
$query_as_string = true;
}
// ---------------------------------------------------------------------------------
// if result to file
if ($writeToFile instanceof WriteToFile && $writeToFile->fetchFormat()) {
$query->setFormat($writeToFile->fetchFormat());
unset($urlParams['extremes']);
}
// ---------------------------------------------------------------------------------
// makeRequest read
$request = $this->makeRequest($query, $urlParams, $query_as_string, $querySettings);
// ---------------------------------------------------------------------------------
// attach files
if ($whereInFile instanceof WhereInFile && $whereInFile->size()) {
$request->attachFiles($whereInFile->fetchFiles());
}
// ---------------------------------------------------------------------------------
// result to file
if ($writeToFile instanceof WriteToFile && $writeToFile->fetchFormat()) {
$fout = fopen($writeToFile->fetchFile(), 'w');
if (is_resource($fout)) {
$isGz = $writeToFile->getGzip();
if ($isGz) {
// write gzip header
// "\x1f\x8b\x08\x00\x00\x00\x00\x00"
// fwrite($fout, "\x1F\x8B\x08\x08".pack("V", time())."\0\xFF", 10);
// write the original file name
// $oname = str_replace("\0", "", basename($writeToFile->fetchFile()));
// fwrite($fout, $oname."\0", 1+strlen($oname));
fwrite($fout, "\x1f\x8b\x08\x00\x00\x00\x00\x00");
}
$request->setResultFileHandle($fout, $isGz)->setCallbackFunction(function (CurlerRequest $request) {
fclose($request->getResultFileHandle());
});
}
}
if ($this->stdErrOut) {
$request->setStdErrOut($this->stdErrOut);
}
if ($this->xClickHouseProgress) {
$request->setFunctionProgress([$this, '__findXClickHouseProgress']);
}
// ---------------------------------------------------------------------------------
return $request;
}
public function cleanQueryDegeneration(): bool
{
$this->_query_degenerations = [];
return true;
}
public function addQueryDegeneration(Degeneration $degeneration): bool
{
$this->_query_degenerations[] = $degeneration;
return true;
}
/**
* @param Query $query
* @param array $querySettings
* @return CurlerRequest
* @throws \ClickHouseDB\Exception\TransportException
*/
public function getRequestWrite(Query $query, array $querySettings = []): CurlerRequest
{
$urlParams = ['readonly' => 0];
return $this->makeRequest($query, $urlParams, false, $querySettings);
}
/**
* @throws TransportException
*/
public function ping(): bool
{
$request = new CurlerRequest();
$request->url($this->getUri())->verbose(false)->GET()->timeOut($this->settings()->getTimeOut())->connectTimeOut($this->getConnectTimeOut());
$this->_curler->execOne($request);
return trim($request->response()->body()) === 'Ok.';
}
/**
* @param string $sql
* @param mixed[] $bindings
* @return Query
*/
private function prepareQuery(string $sql, array $bindings): Query
{
// add Degeneration query
foreach ($this->_query_degenerations as $degeneration) {
$degeneration->bindParams($bindings);
}
return new Query($sql, $this->_query_degenerations);
}
/**
* @param Query|string $sql
* @param mixed[] $bindings
* @param null|WhereInFile $whereInFile
* @param null|WriteToFile $writeToFile
* @param array $querySettings
* @return CurlerRequest
* @throws \Exception
*/
private function prepareSelect($sql, array $bindings, $whereInFile, $writeToFile = null, array $querySettings = []): CurlerRequest
{
if ($sql instanceof Query) {
return $this->getRequestWrite($sql);
}
$query = $this->prepareQuery($sql, $bindings);
$query->setFormat('JSON');
return $this->getRequestRead($query, $whereInFile, $writeToFile, $querySettings);
}
/**
* @param Query|string $sql
* @param mixed[] $bindings
* @param array $querySettings
* @return CurlerRequest
* @throws \ClickHouseDB\Exception\TransportException
*/
private function prepareWrite($sql, array $bindings = [], array $querySettings = []): CurlerRequest
{
if ($sql instanceof Query) {
return $this->getRequestWrite($sql, $querySettings);
}
$query = $this->prepareQuery($sql, $bindings);
if (strpos($sql, 'ON CLUSTER') === false) {
return $this->getRequestWrite($query, $querySettings);
}
if (
!str_starts_with($sql, 'CREATE')
&& !str_starts_with($sql, 'DROP')
&& !str_starts_with($sql, 'ALTER')
&& !str_starts_with($sql, 'RENAME')
) {
$query->setFormat('JSON');
}
return $this->getRequestWrite($query, $querySettings);
}
/**
* @return bool
* @throws \ClickHouseDB\Exception\TransportException
*/
public function executeAsync(): bool
{
return $this->_curler->execLoopWait();
}
/**
* @param Query|string $sql
* @param mixed[] $bindings
* @param null|WhereInFile $whereInFile
* @param null|WriteToFile $writeToFile
* @param array $querySettings
* @return Statement
* @throws \ClickHouseDB\Exception\TransportException
* @throws \Exception
*/
public function select($sql, array $bindings = [], $whereInFile = null, $writeToFile = null, array $querySettings = []): Statement
{
$request = $this->prepareSelect($sql, $bindings, $whereInFile, $writeToFile, $querySettings);
$this->_curler->execOne($request);
return new Statement($request);
}
/**
* @param Query|string $sql
* @param mixed[] $bindings
* @param null|WhereInFile $whereInFile
* @param null|WriteToFile $writeToFile
* @param array $querySettings
* @return Statement
* @throws \ClickHouseDB\Exception\TransportException
* @throws \Exception
*/
public function selectAsync($sql, array $bindings = [], $whereInFile = null, $writeToFile = null, array $querySettings = []): Statement
{
$request = $this->prepareSelect($sql, $bindings, $whereInFile, $writeToFile, $querySettings);
$this->_curler->addQueLoop($request);
return new Statement($request);
}
/**
* @param callable $callback
*/
public function setProgressFunction(callable $callback) : void
{
$this->xClickHouseProgress = $callback;
}
/**
* SELECT with native ClickHouse typed parameters.
* SQL uses {name:Type} placeholders, values passed as param_name in URL.
*
* @param string $sql
* @param array<string, mixed> $params
* @param array $querySettings
* @return Statement
*/
public function selectWithParams(string $sql, array $params, array $querySettings = []): Statement
{
$query = new Query($sql);
$query->setFormat('JSON');
$urlParams = ['readonly' => 2];
foreach ($params as $name => $value) {
$urlParams['param_' . $name] = $this->convertParamValue($value);
}
$request = $this->makeRequest($query, $urlParams, true, $querySettings);
$this->_curler->execOne($request);
return new Statement($request);
}
/**
* Write with native ClickHouse typed parameters.
*
* @param string $sql
* @param array<string, mixed> $params
* @param bool $exception
* @param array $querySettings
* @return Statement
*/
public function writeWithParams(string $sql, array $params, bool $exception = true, array $querySettings = []): Statement
{
$query = new Query($sql);
$urlParams = ['readonly' => 0];
foreach ($params as $name => $value) {
$urlParams['param_' . $name] = $this->convertParamValue($value);
}
$request = $this->makeRequest($query, $urlParams, true, $querySettings);
$this->_curler->execOne($request);
$response = new Statement($request);
if ($exception) {
if ($response->isError()) {
$response->error();
}
}
return $response;
}
/**
* Convert PHP value to string for native ClickHouse parameter.
*
* @param mixed $value
* @return string
*/
private function convertParamValue(mixed $value): string
{
if ($value instanceof \ClickHouseDB\Type\DateTime64) {
return $value->value;
}
if ($value instanceof \ClickHouseDB\Type\Date32) {
return $value->value;
}
if ($value instanceof \ClickHouseDB\Type\UUID) {
return $value->value;
}
if ($value instanceof \ClickHouseDB\Type\IPv4 || $value instanceof \ClickHouseDB\Type\IPv6) {
return $value->value;
}
if ($value instanceof \ClickHouseDB\Type\MapType) {
return json_encode($value->value);
}
if ($value instanceof \ClickHouseDB\Type\TupleType) {
return '(' . implode(',', array_map(fn($v) => $this->convertParamValue($v), $value->value)) . ')';
}
if ($value instanceof \ClickHouseDB\Type\Type) {
return (string) $value->getValue();
}
if ($value instanceof \DateTimeInterface) {
return $value->format('Y-m-d H:i:s');
}
if (is_bool($value)) {
return $value ? '1' : '0';
}
if (is_array($value)) {
$arrayValues = [];
foreach ($value as $val) {
if (is_string($val)) {
$arrayValues[] = sprintf("'%s'", $val);
continue;
}
$arrayValues[] = $this->convertParamValue($val);
}
return sprintf('[%s]', implode(',', $arrayValues));
}
if ($value === null) {
return '\\N';
}
return (string) $value;
}
/**
* @param string $sql
* @param mixed[] $bindings
* @param bool $exception
* @param array $querySettings
* @return Statement
* @throws \ClickHouseDB\Exception\TransportException
*/
public function write($sql, array $bindings = [], $exception = true, array $querySettings = []): Statement
{
$request = $this->prepareWrite($sql, $bindings, $querySettings);
$this->_curler->execOne($request);
$response = new Statement($request);
if ($exception) {
if ($response->isError()) {
$response->error();
}
}
return $response;
}
/**
* @param Stream $streamRW
* @param CurlerRequest $request
* @return Statement
* @throws \ClickHouseDB\Exception\TransportException
*/
private function streaming(Stream $streamRW, CurlerRequest $request): Statement
{
$callable = $streamRW->getClosure();
$stream = $streamRW->getStream();
try {
if (!is_callable($callable)) {
if ($streamRW->isWrite()) {
$callable = function ($ch, $fd, $length) use ($stream) {
return ($line = fread($stream, $length)) ? $line : '';
};
} else {
$callable = function ($ch, $fd) use ($stream) {
return fwrite($stream, $fd);
};
}
}
if ($streamRW->isGzipHeader()) {
if ($streamRW->isWrite()) {
$request->header('Content-Encoding', 'gzip');
$request->header('Content-Type', 'application/x-www-form-urlencoded');
} else {
$request->header('Accept-Encoding', 'gzip');
}
}
$request->header('Transfer-Encoding', 'chunked');
if ($streamRW->isWrite()) {
$request->setReadFunction($callable);
} else {
$request->setWriteFunction($callable);
// $request->setHeaderFunction($callableHead);
}
$this->_curler->execOne($request, true);
$response = new Statement($request);
if ($response->isError()) {
$response->error();
}
return $response;
} finally {
if ($streamRW->isWrite())
fclose($stream);
}
}
/**
* @param Stream $streamRead
* @param string $sql
* @param mixed[] $bindings
* @param array $querySettings
* @return Statement
* @throws \ClickHouseDB\Exception\TransportException
*/
public function streamRead(Stream $streamRead, $sql, $bindings = [], array $querySettings = []): Statement
{
$sql = $this->prepareQuery($sql, $bindings);
$request = $this->getRequestRead($sql, null, null, $querySettings);
return $this->streaming($streamRead, $request);
}
/**
* @param Stream $streamWrite
* @param string $sql
* @param mixed[] $bindings
* @return Statement
* @throws \ClickHouseDB\Exception\TransportException
*/
public function streamWrite(Stream $streamWrite, $sql, $bindings = []): Statement
{
$sql = $this->prepareQuery($sql, $bindings);
$request = $this->writeStreamData($sql);
return $this->streaming($streamWrite, $request);
}
}