Passed
Push — master ( ed7ae4...c715a2 )
by Igor
04:38 queued 02:11
created

Client::executeAsync()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 3
rs 10
ccs 2
cts 2
cp 1
cc 1
eloc 1
nc 1
nop 0
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace ClickHouseDB;
6
7
use ClickHouseDB\Exception\QueryException;
8
use ClickHouseDB\Query\Degeneration;
9
use ClickHouseDB\Query\Degeneration\Bindings;
10
use ClickHouseDB\Query\Degeneration\Conditions;
11
use ClickHouseDB\Query\WhereInFile;
12
use ClickHouseDB\Query\WriteToFile;
13
use ClickHouseDB\Quote\FormatLine;
14
use ClickHouseDB\Transport\Http;
15
use ClickHouseDB\Transport\Stream;
16
use function array_flip;
0 ignored issues
show
introduced by
Type array_flip is not used in this file.
Loading history...
17
use function array_keys;
18
use function array_rand;
0 ignored issues
show
introduced by
Type array_rand is not used in this file.
Loading history...
19
use function array_values;
20
use function count;
21
use function date;
22
use function implode;
23
use function in_array;
24
use function is_array;
25
use function is_callable;
26
use function is_file;
27
use function is_readable;
28
use function is_string;
29
use function sprintf;
30
use function stripos;
31
use function strtotime;
32
use function trim;
33
34
class Client
35
{
36
    const SUPPORTED_FORMATS = ['TabSeparated', 'TabSeparatedWithNames', 'CSV', 'CSVWithNames', 'JSONEachRow'];
0 ignored issues
show
introduced by
Constant \ClickHouseDB\Client::SUPPORTED_FORMATS visibility missing.
Loading history...
37
38
    /** @var Http */
39
    private $transport;
40
41
    /** @var string */
42
    private $connectUsername;
43
44
    /** @var string */
45
    private $connectPassword;
46
47
    /** @var string */
48
    private $connectHost;
49
50
    /** @var string */
51
    private $connectPort;
52
53
    /** @var bool */
54
    private $connectUserReadonly = false;
55
56
    /**
57
     * @param mixed[] $connectParams
58
     * @param mixed[] $settings
59
     */
60 63
    public function __construct(array $connectParams, array $settings = [])
61
    {
62 63
        if (! isset($connectParams['username'])) {
63
            throw  new \InvalidArgumentException('not set username');
0 ignored issues
show
introduced by
Class \InvalidArgumentException should not be referenced via a fully qualified name, but via a use statement.
Loading history...
64
        }
65
66 63
        if (! isset($connectParams['password'])) {
67
            throw  new \InvalidArgumentException('not set password');
0 ignored issues
show
introduced by
Class \InvalidArgumentException should not be referenced via a fully qualified name, but via a use statement.
Loading history...
68
        }
69
70 63
        if (! isset($connectParams['port'])) {
71
            throw  new \InvalidArgumentException('not set port');
0 ignored issues
show
introduced by
Class \InvalidArgumentException should not be referenced via a fully qualified name, but via a use statement.
Loading history...
72
        }
73
74 63
        if (! isset($connectParams['host'])) {
75
            throw  new \InvalidArgumentException('not set host');
0 ignored issues
show
introduced by
Class \InvalidArgumentException should not be referenced via a fully qualified name, but via a use statement.
Loading history...
76
        }
77
78 63
        $this->connectUsername = $connectParams['username'];
79 63
        $this->connectPassword = $connectParams['password'];
80 63
        $this->connectPort     = $connectParams['port'];
81 63
        $this->connectHost     = $connectParams['host'];
82
83
        // init transport class
84 63
        $this->transport = new Http(
85 63
            $this->connectHost,
86 63
            $this->connectPort,
87 63
            $this->connectUsername,
88 63
            $this->connectPassword
89
        );
90
91 63
        $this->transport->addQueryDegeneration(new Bindings());
92
93
        // apply settings to transport class
94 63
        $this->settings()->database('default');
95 63
        if (! empty($settings)) {
96 1
            $this->settings()->apply($settings);
97
        }
98
99 63
        if (isset($connectParams['readonly'])) {
100
            $this->setReadOnlyUser($connectParams['readonly']);
101
        }
102
103 63
        if (isset($connectParams['https'])) {
104
            $this->https($connectParams['https']);
105
        }
106
107 63
        $this->enableHttpCompression();
108 63
    }
109
110
    /**
111
     * if the user has only read in the config file
112
     */
113
    public function setReadOnlyUser(bool $flag)
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::setReadOnlyUser() does not have void return type hint.
Loading history...
114
    {
115
        $this->connectUserReadonly = $flag;
116
        $this->settings()->setReadOnlyUser($this->connectUserReadonly);
117
    }
118
119
    /**
120
     * Clear Degeneration processing request [template ]
121
     *
122
     * @return bool
123
     */
124 1
    public function cleanQueryDegeneration()
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::cleanQueryDegeneration() does not have return type hint for its return value but it should be possible to add it based on @return annotation "bool".
Loading history...
125
    {
126 1
        return $this->transport->cleanQueryDegeneration();
127
    }
128
129
    /**
130
     * add Degeneration processing
131
     *
132
     * @return bool
133
     */
134
    public function addQueryDegeneration(Degeneration $degeneration)
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::addQueryDegeneration() does not have return type hint for its return value but it should be possible to add it based on @return annotation "bool".
Loading history...
135
    {
136
        return $this->transport->addQueryDegeneration($degeneration);
137
    }
138
139
    /**
140
     * add Conditions in query
141
     *
142
     * @return bool
143
     */
144 1
    public function enableQueryConditions()
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::enableQueryConditions() does not have return type hint for its return value but it should be possible to add it based on @return annotation "bool".
Loading history...
145
    {
146 1
        return $this->transport->addQueryDegeneration(new Conditions());
147
    }
148
149
    /**
150
     * Set connection host
151
     *
152
     * @param string $host
153
     */
154
    public function setHost($host)
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::setHost() does not have parameter type hint for its parameter $host but it should be possible to add it based on @param annotation "string".
Loading history...
introduced by
Method \ClickHouseDB\Client::setHost() does not have void return type hint.
Loading history...
155
    {
156
        $this->connectHost = $host;
157
        $this->transport()->setHost($host);
158
    }
159
160
    /**
161
     * @return Settings
162
     */
163 2
    public function setTimeout(float $timeout)
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::setTimeout() does not have return type hint for its return value but it should be possible to add it based on @return annotation "Settings".
Loading history...
164
    {
165 2
        return $this->settings()->max_execution_time($timeout);
0 ignored issues
show
Bug introduced by
$timeout of type double is incompatible with the type integer expected by parameter $time of ClickHouseDB\Settings::max_execution_time(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

165
        return $this->settings()->max_execution_time(/** @scrutinizer ignore-type */ $timeout);
Loading history...
166
    }
167
168
    /**
169
     * @return mixed
170
     */
171 1
    public function getTimeout()
172
    {
173 1
        return $this->settings()->getTimeOut();
174
    }
175
176
    /**
177
     * ConnectTimeOut in seconds ( support 1.5 = 1500ms )
178
     */
179 2
    public function setConnectTimeOut(float $connectTimeOut)
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::setConnectTimeOut() does not have void return type hint.
Loading history...
180
    {
181 2
        $this->transport()->setConnectTimeOut($connectTimeOut);
0 ignored issues
show
Bug introduced by
$connectTimeOut of type double is incompatible with the type integer expected by parameter $connectTimeOut of ClickHouseDB\Transport\Http::setConnectTimeOut(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

181
        $this->transport()->setConnectTimeOut(/** @scrutinizer ignore-type */ $connectTimeOut);
Loading history...
182 2
    }
183
184
    /**
185
     * @return int
186
     */
187 1
    public function getConnectTimeOut()
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::getConnectTimeOut() does not have return type hint for its return value but it should be possible to add it based on @return annotation "int".
Loading history...
188
    {
189 1
        return $this->transport()->getConnectTimeOut();
190
    }
191
192
    /**
193
     * @return Http
194
     */
195 63
    public function transport()
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::transport() does not have return type hint for its return value but it should be possible to add it based on @return annotation "Http".
Loading history...
196
    {
197 63
        if (! $this->transport) {
198
            throw  new \InvalidArgumentException('Empty transport class');
0 ignored issues
show
introduced by
Class \InvalidArgumentException should not be referenced via a fully qualified name, but via a use statement.
Loading history...
199
        }
200
201 63
        return $this->transport;
202
    }
203
204
    /**
205
     * @return string
206
     */
207
    public function getConnectHost()
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::getConnectHost() does not have return type hint for its return value but it should be possible to add it based on @return annotation "string".
Loading history...
208
    {
209
        return $this->connectHost;
210
    }
211
212
    /**
213
     * @return string
214
     */
215
    public function getConnectPassword()
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::getConnectPassword() does not have return type hint for its return value but it should be possible to add it based on @return annotation "string".
Loading history...
216
    {
217
        return $this->connectPassword;
218
    }
219
220
    /**
221
     * @return string
222
     */
223
    public function getConnectPort()
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::getConnectPort() does not have return type hint for its return value but it should be possible to add it based on @return annotation "string".
Loading history...
224
    {
225
        return $this->connectPort;
226
    }
227
228
    /**
229
     * @return string
230
     */
231
    public function getConnectUsername()
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::getConnectUsername() does not have return type hint for its return value but it should be possible to add it based on @return annotation "string".
Loading history...
232
    {
233
        return $this->connectUsername;
234
    }
235
236
    /**
237
     * @return Http
238
     */
239
    public function getTransport()
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::getTransport() does not have return type hint for its return value but it should be possible to add it based on @return annotation "Http".
Loading history...
240
    {
241
        return $this->transport;
242
    }
243
244
    /**
245
     * @return mixed
246
     */
247
    public function verbose()
248
    {
249
        return $this->transport()->verbose(true);
250
    }
251
252
    /**
253
     * @return Settings
254
     */
255 63
    public function settings()
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::settings() does not have return type hint for its return value but it should be possible to add it based on @return annotation "Settings".
Loading history...
256
    {
257 63
        return $this->transport()->settings();
258
    }
259
260
    /**
261
     * @return static
262
     */
263 2
    public function useSession(bool $useSessionId = false)
264
    {
265 2
        if (! $this->settings()->getSessionId()) {
266 2
            if (! $useSessionId) {
267 2
                $this->settings()->makeSessionId();
268
            } else {
269
                $this->settings()->session_id($useSessionId);
0 ignored issues
show
Bug introduced by
$useSessionId of type true is incompatible with the type string expected by parameter $session_id of ClickHouseDB\Settings::session_id(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

269
                $this->settings()->session_id(/** @scrutinizer ignore-type */ $useSessionId);
Loading history...
270
            }
271
        }
272
273 2
        return $this;
274
    }
275
276
    /**
277
     * @return mixed
278
     */
279 2
    public function getSession()
280
    {
281 2
        return $this->settings()->getSessionId();
282
    }
283
284
    /**
285
     * Query CREATE/DROP
286
     *
287
     * @param mixed[] $bindings
0 ignored issues
show
introduced by
Incorrect annotations group.
Loading history...
288
     * @return Statement
289
     */
290 26
    public function write(string $sql, array $bindings = [], bool $exception = true)
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::write() does not have return type hint for its return value but it should be possible to add it based on @return annotation "Statement".
Loading history...
291
    {
292 26
        return $this->transport()->write($sql, $bindings, $exception);
293
    }
294
295
    /**
296
     * set db name
297
     * @return static
0 ignored issues
show
introduced by
Expected 1 lines between description and annotations, found 0.
Loading history...
298
     */
299 63
    public function database(string $db)
300
    {
301 63
        $this->settings()->database($db);
302
303 63
        return $this;
304
    }
305
306
    /**
307
     * Write to system.query_log
308
     *
309
     * @return static
310
     */
311
    public function enableLogQueries(bool $flag = true)
312
    {
313
        $this->settings()->set('log_queries', (int) $flag);
314
315
        return $this;
316
    }
317
318
    /**
319
     * Compress the result if the HTTP client said that it understands data compressed with gzip or deflate
320
     *
321
     * @return static
322
     */
323 63
    public function enableHttpCompression(bool $flag = true)
324
    {
325 63
        $this->settings()->enableHttpCompression($flag);
326
327 63
        return $this;
328
    }
329
330
    /**
331
     * Enable / Disable HTTPS
332
     *
333
     * @return static
334
     */
335 1
    public function https(bool $flag = true)
336
    {
337 1
        $this->settings()->https($flag);
338
339 1
        return $this;
340
    }
341
342
    /**
343
     * Read extremes of the result columns. They can be output in JSON-formats.
344
     *
345
     * @return static
346
     */
347 2
    public function enableExtremes(bool $flag = true)
348
    {
349 2
        $this->settings()->set('extremes', (int) $flag);
350
351 2
        return $this;
352
    }
353
354
    /**
355
     * @param mixed[] $bindings
0 ignored issues
show
introduced by
Incorrect annotations group.
Loading history...
356
     * @return Statement
357
     */
358 29
    public function select(
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::select() does not have return type hint for its return value but it should be possible to add it based on @return annotation "Statement".
Loading history...
359
        string $sql,
360
        array $bindings = [],
361
        WhereInFile $whereInFile = null,
0 ignored issues
show
introduced by
Parameter $whereInFile has null default value, but is not marked as nullable.
Loading history...
362
        WriteToFile $writeToFile = null
0 ignored issues
show
introduced by
Parameter $writeToFile has null default value, but is not marked as nullable.
Loading history...
363
    ) {
364 29
        return $this->transport()->select($sql, $bindings, $whereInFile, $writeToFile);
365
    }
366
367
    /**
368
     * @return bool
369
     */
370 10
    public function executeAsync()
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::executeAsync() does not have return type hint for its return value but it should be possible to add it based on @return annotation "bool".
Loading history...
371
    {
372 10
        return $this->transport()->executeAsync();
373
    }
374
375
    /**
376
     * set progressFunction
377
     */
378 1
    public function progressFunction(callable $callback)
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::progressFunction() does not have void return type hint.
Loading history...
379
    {
380 1
        if (! is_callable($callback)) {
381
            throw new \InvalidArgumentException('Not is_callable progressFunction');
0 ignored issues
show
introduced by
Class \InvalidArgumentException should not be referenced via a fully qualified name, but via a use statement.
Loading history...
382
        }
383
384 1
        if (! $this->settings()->is('send_progress_in_http_headers')) {
385 1
            $this->settings()->set('send_progress_in_http_headers', 1);
386
        }
387 1
        if (! $this->settings()->is('http_headers_progress_interval_ms')) {
388 1
            $this->settings()->set('http_headers_progress_interval_ms', 100);
389
        }
390
391 1
        $this->transport()->setProgressFunction($callback);
392 1
    }
393
394
    /**
395
     * prepare select
396
     *
397
     * @param mixed[] $bindings
0 ignored issues
show
introduced by
Incorrect annotations group.
Loading history...
398
     * @return Statement
399
     */
400 5
    public function selectAsync(
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::selectAsync() does not have return type hint for its return value but it should be possible to add it based on @return annotation "Statement".
Loading history...
401
        string $sql,
402
        array $bindings = [],
403
        WhereInFile $whereInFile = null,
0 ignored issues
show
introduced by
Parameter $whereInFile has null default value, but is not marked as nullable.
Loading history...
404
        WriteToFile $writeToFile = null
0 ignored issues
show
introduced by
Parameter $writeToFile has null default value, but is not marked as nullable.
Loading history...
405
    ) {
406 5
        return $this->transport()->selectAsync($sql, $bindings, $whereInFile, $writeToFile);
407
    }
408
409
    /**
410
     * SHOW PROCESSLIST
411
     *
412
     * @return array
0 ignored issues
show
introduced by
@return annotation of method \ClickHouseDB\Client::showProcesslist() does not specify type hint for items of its traversable return value.
Loading history...
413
     */
414
    public function showProcesslist()
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::showProcesslist() does not have return type hint for its return value but it should be possible to add it based on @return annotation "array".
Loading history...
415
    {
416
        return $this->select('SHOW PROCESSLIST')->rows();
417
    }
418
419
    /**
420
     * show databases
421
     *
422
     * @return array
0 ignored issues
show
introduced by
@return annotation of method \ClickHouseDB\Client::showDatabases() does not specify type hint for items of its traversable return value.
Loading history...
423
     */
424
    public function showDatabases()
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::showDatabases() does not have return type hint for its return value but it should be possible to add it based on @return annotation "array".
Loading history...
425
    {
426
        return $this->select('show databases')->rows();
427
    }
428
429
    /**
430
     * statement = SHOW CREATE TABLE
431
     *
432
     * @return mixed
433
     */
434
    public function showCreateTable(string $table)
435
    {
436
        return $this->select('SHOW CREATE TABLE ' . $table)->fetchOne('statement');
437
    }
438
439
    /**
440
     * SHOW TABLES
441
     *
442
     * @return mixed[]
443
     */
444 1
    public function showTables()
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::showTables() does not have return type hint for its return value but it should be possible to add it based on @return annotation "mixed[]".
Loading history...
445
    {
446 1
        return $this->select('SHOW TABLES')->rowsAsTree('name');
447
    }
448
449
    /**
450
     * Get the number of simultaneous/Pending requests
451
     *
452
     * @return int
453
     */
454 12
    public function getCountPendingQueue()
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::getCountPendingQueue() does not have return type hint for its return value but it should be possible to add it based on @return annotation "int".
Loading history...
455
    {
456 12
        return $this->transport()->getCountPendingQueue();
457
    }
458
459
    /**
460
     * @param mixed[][] $values
0 ignored issues
show
introduced by
Incorrect annotations group.
Loading history...
461
     * @param string[]  $columns
462
     * @return Statement
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::insert() has useless @return annotation.
Loading history...
463
     * @throws Exception\TransportException
464
     */
465 9
    public function insert(string $table, array $values, array $columns = []) : Statement
466
    {
467 9
        if (empty($values)) {
468 1
            throw QueryException::cannotInsertEmptyValues();
469
        }
470
471 8
        if (stripos($table, '`') === false && stripos($table, '.') === false) {
472 5
            $table = '`' . $table . '`'; //quote table name for dot names
473
        }
474 8
        $sql = 'INSERT INTO ' . $table;
475
476 8
        if (count($columns) !== 0) {
477 7
            $sql .= ' (`' . implode('`,`', $columns) . '`) ';
478
        }
479
480 8
        $sql .= ' VALUES ';
481
482 8
        foreach ($values as $row) {
483 8
            $sql .= ' (' . FormatLine::Insert($row) . '), ';
484
        }
485 8
        $sql = trim($sql, ', ');
486
487 8
        return $this->transport()->write($sql);
488
    }
489
490
    /**
491
     *       * Prepares the values to insert from the associative array.
492
     *       * There may be one or more lines inserted, but then the keys inside the array list must match (including in the sequence)
493
     *       *
494
     *       * @param mixed[] $values - array column_name => value (if we insert one row) or array list column_name => value if we insert many lines
495
     *       * @return mixed[][] - list of arrays - 0 => fields, 1 => list of value arrays for insertion
496
     *       */
497 3
    public function prepareInsertAssocBulk(array $values)
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::prepareInsertAssocBulk() does not have @param annotation for its traversable parameter $values.
Loading history...
introduced by
Method \ClickHouseDB\Client::prepareInsertAssocBulk() does not have return type hint nor @return annotation for its return value.
Loading history...
498
    {
499 3
        if (isset($values[0]) && is_array($values[0])) { //случай, когда много строк вставляется
500 2
            $preparedFields = array_keys($values[0]);
501 2
            $preparedValues = [];
502 2
            foreach ($values as $idx => $row) {
503 2
                $_fields = array_keys($row);
504 2
                if ($_fields !== $preparedFields) {
505 1
                    throw new QueryException(
506 1
                        sprintf(
507 1
                            'Fields not match: %s and %s on element %s',
508 1
                            implode(',', $_fields),
509 1
                            implode(',', $preparedFields),
510 1
                            $idx
511
                        )
512
                    );
513
                }
514 2
                $preparedValues[] = array_values($row);
515
            }
516
        } else {
517 1
            $preparedFields = array_keys($values);
518 1
            $preparedValues = [array_values($values)];
519
        }
520
521 2
        return [$preparedFields, $preparedValues];
522
    }
523
524
    /**
525
     * Inserts one or more rows from an associative array.
526
     * If there is a discrepancy between the keys of the value arrays (or their order) - throws an exception.
527
     *
528
     * @param mixed[] $values - array column_name => value (if we insert one row) or array list column_name => value if we insert many lines
0 ignored issues
show
introduced by
Incorrect annotations group.
Loading history...
529
     * @return Statement
530
     */
531
    public function insertAssocBulk(string $tableName, array $values)
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::insertAssocBulk() does not have return type hint for its return value but it should be possible to add it based on @return annotation "Statement".
Loading history...
532
    {
533
        list($columns, $vals) = $this->prepareInsertAssocBulk($values);
0 ignored issues
show
introduced by
list(...) is forbidden, use [...] instead.
Loading history...
534
535
        return $this->insert($tableName, $vals, $columns);
536
    }
537
538
    /**
539
     * insert TabSeparated files
540
     *
541
     * @param string|string[] $fileNames
0 ignored issues
show
introduced by
Incorrect annotations group.
Loading history...
542
     * @param string[]        $columns
543
     * @return mixed
544
     */
545 1
    public function insertBatchTSVFiles(string $tableName, $fileNames, array $columns = [])
546
    {
547 1
        return $this->insertBatchFiles($tableName, $fileNames, $columns, 'TabSeparated');
548
    }
549
550
    /**
551
     * insert Batch Files
552
     *
553
     * @param string|string[] $fileNames
0 ignored issues
show
introduced by
Incorrect annotations group.
Loading history...
554
     * @param string[]        $columns
555
     * @param string          $format ['TabSeparated','TabSeparatedWithNames','CSV','CSVWithNames']
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
556
     * @return Statement[]
557
     * @throws Exception\TransportException
558
     */
559 8
    public function insertBatchFiles(string $tableName, $fileNames, array $columns = [], string $format = 'CSV')
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::insertBatchFiles() does not have return type hint for its return value but it should be possible to add it based on @return annotation "Statement[]".
Loading history...
560
    {
561 8
        if (is_string($fileNames)) {
562
            $fileNames = [$fileNames];
563
        }
564 8
        if ($this->getCountPendingQueue() > 0) {
565
            throw new QueryException('Queue must be empty, before insertBatch, need executeAsync');
566
        }
567
568 8
        if (! in_array($format, self::SUPPORTED_FORMATS, true)) {
569
            throw new QueryException('Format not support in insertBatchFiles');
570
        }
571
572 8
        $result = [];
573
574 8
        foreach ($fileNames as $fileName) {
575 8
            if (! is_file($fileName) || ! is_readable($fileName)) {
576
                throw  new QueryException('Cant read file: ' . $fileName . ' ' . (is_file($fileName) ? '' : ' is not file'));
577
            }
578
579 8
            if (empty($columns)) {
580
                $sql = 'INSERT INTO ' . $tableName . ' FORMAT ' . $format;
581
            } else {
582 8
                $sql = 'INSERT INTO ' . $tableName . ' ( ' . implode(',', $columns) . ' ) FORMAT ' . $format;
583
            }
584 8
            $result[$fileName] = $this->transport()->writeAsyncCSV($sql, $fileName);
585
        }
586
587
        // exec
588 8
        $this->executeAsync();
589
590
        // fetch resutl
591 8
        foreach ($fileNames as $fileName) {
592 8
            if (! $result[$fileName]->isError()) {
593 6
                continue;
594
            }
595
596 2
            $result[$fileName]->error();
597
        }
598
599 6
        return $result;
600
    }
601
602
    /**
603
     * insert Batch Stream
604
     *
605
     * @param string[] $columns
0 ignored issues
show
introduced by
Incorrect annotations group.
Loading history...
606
     * @param string   $format ['TabSeparated','TabSeparatedWithNames','CSV','CSVWithNames']
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
607
     * @return Transport\CurlerRequest
608
     */
609 2
    public function insertBatchStream(string $tableName, array $columns = [], string $format = 'CSV')
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::insertBatchStream() does not have return type hint for its return value but it should be possible to add it based on @return annotation "Transport\CurlerRequest".
Loading history...
610
    {
611 2
        if ($this->getCountPendingQueue() > 0) {
612
            throw new QueryException('Queue must be empty, before insertBatch, need executeAsync');
613
        }
614
615 2
        if (! in_array($format, self::SUPPORTED_FORMATS, true)) {
616
            throw new QueryException('Format not support in insertBatchFiles');
617
        }
618
619 2
        if (empty($columns)) {
620
            $sql = 'INSERT INTO ' . $tableName . ' FORMAT ' . $format;
621
        } else {
622 2
            $sql = 'INSERT INTO ' . $tableName . ' ( ' . implode(',', $columns) . ' ) FORMAT ' . $format;
623
        }
624
625 2
        return $this->transport()->writeStreamData($sql);
626
    }
627
628
    /**
629
     * stream Write
630
     *
631
     * @param string[] $bind
0 ignored issues
show
introduced by
Incorrect annotations group.
Loading history...
632
     * @return Statement
633
     * @throws Exception\TransportException
634
     */
635 1
    public function streamWrite(Stream $stream, string $sql, array $bind = [])
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::streamWrite() does not have return type hint for its return value but it should be possible to add it based on @return annotation "Statement".
Loading history...
636
    {
637 1
        if ($this->getCountPendingQueue() > 0) {
638
            throw new QueryException('Queue must be empty, before streamWrite');
639
        }
640
641 1
        return $this->transport()->streamWrite($stream, $sql, $bind);
642
    }
643
644
    /**
645
     * stream Read
646
     *
647
     * @param string[] $bind
0 ignored issues
show
introduced by
Incorrect annotations group.
Loading history...
648
     * @return Statement
649
     */
650 1
    public function streamRead(Stream $streamRead, string $sql, array $bind = [])
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::streamRead() does not have return type hint for its return value but it should be possible to add it based on @return annotation "Statement".
Loading history...
651
    {
652 1
        if ($this->getCountPendingQueue() > 0) {
653
            throw new QueryException('Queue must be empty, before streamWrite');
654
        }
655
656 1
        return $this->transport()->streamRead($streamRead, $sql, $bind);
657
    }
658
659
    /**
660
     * Size of database
661
     *
662
     * @return mixed|null
663
     */
664
    public function databaseSize()
665
    {
666
        $b = $this->settings()->getDatabase();
667
668
        return $this->select(
669
            '
670
            SELECT database,formatReadableSize(sum(bytes)) as size
671
            FROM system.parts
672
            WHERE active AND database=:database
673
            GROUP BY database
674
            ',
675
            ['database' => $b]
676
        )->fetchOne();
677
    }
678
679
    /**
680
     * Size of tables
681
     *
682
     * @return mixed
683
     */
684 1
    public function tableSize(string $tableName)
685
    {
686 1
        $tables = $this->tablesSize();
687
688 1
        if (isset($tables[$tableName])) {
689 1
            return $tables[$tableName];
690
        }
691
692
        return null;
693
    }
694
695
    /**
696
     * Ping server
697
     *
698
     * @return bool
699
     */
700 39
    public function ping()
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::ping() does not have return type hint for its return value but it should be possible to add it based on @return annotation "bool".
Loading history...
701
    {
702 39
        return $this->transport()->ping();
703
    }
704
705
    /**
706
     * Tables sizes
707
     *
708
     * @param bool $flatList
0 ignored issues
show
introduced by
Incorrect annotations group.
Loading history...
709
     * @return mixed[][]
710
     */
711 1
    public function tablesSize($flatList = false)
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::tablesSize() does not have parameter type hint for its parameter $flatList but it should be possible to add it based on @param annotation "bool".
Loading history...
introduced by
Method \ClickHouseDB\Client::tablesSize() does not have return type hint for its return value but it should be possible to add it based on @return annotation "mixed[][]".
Loading history...
712
    {
713 1
        $result = $this->select('
714
        SELECT name as table,database,
715
            max(sizebytes) as sizebytes,
716
            max(size) as size,
717
            min(min_date) as min_date,
718
            max(max_date) as max_date
719
            FROM system.tables
720
            ANY LEFT JOIN 
721
            (
722
            SELECT table,database,
723
                        formatReadableSize(sum(bytes)) as size,
724
                        sum(bytes) as sizebytes,
725
                        min(min_date) as min_date,
726
                        max(max_date) as max_date
727
                        FROM system.parts 
728
                        WHERE active AND database=:database
729
                        GROUP BY table,database
730
            ) USING ( table,database )
731
            WHERE database=:database
732
            GROUP BY table,database
733
        ',
734 1
            ['database' => $this->settings()->getDatabase()]);
735
736 1
        if ($flatList) {
737
            return $result->rows();
738
        }
739
740 1
        return $result->rowsAsTree('table');
741
    }
742
743
    /**
744
     * isExists
745
     *
746
     * @return array
0 ignored issues
show
introduced by
@return annotation of method \ClickHouseDB\Client::isExists() does not specify type hint for items of its traversable return value.
Loading history...
747
     */
748
    public function isExists(string $database, string $table)
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::isExists() does not have return type hint for its return value but it should be possible to add it based on @return annotation "array".
Loading history...
749
    {
750
        return $this->select(
751
            '
752
            SELECT *
753
            FROM system.tables 
754
            WHERE name=\'' . $table . '\' AND database=\'' . $database . '\''
755
        )->rowsAsTree('name');
756
    }
757
758
    /**
759
     * List of partitions
760
     *
761
     * @return mixed[][]
762
     */
763
    public function partitions(string $table, int $limit = null, bool $active = null)
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::partitions() does not have return type hint for its return value but it should be possible to add it based on @return annotation "mixed[][]".
Loading history...
introduced by
Parameter $limit has null default value, but is not marked as nullable.
Loading history...
introduced by
Parameter $active has null default value, but is not marked as nullable.
Loading history...
764
    {
765
        $database          = $this->settings()->getDatabase();
766
        $whereActiveClause = $active === null ? '' : sprintf(' AND active = %s', (int) $active);
767
        $limitClause       = $limit !== null ? ' LIMIT ' . $limit : '';
768
769
        return $this->select(<<<CLICKHOUSE
770
SELECT *
771
FROM system.parts 
772
WHERE like(table,'%$table%') AND database='$database'$whereActiveClause
773
ORDER BY max_date $limitClause
774
CLICKHOUSE
775
        )->rowsAsTree('name');
776
    }
777
778
    /**
779
     * dropPartition
780
     * @deprecated
0 ignored issues
show
introduced by
Expected 1 lines between description and annotations, found 0.
Loading history...
introduced by
Incorrect annotations group.
Loading history...
781
     * @return Statement
782
     */
783
    public function dropPartition(string $dataBaseTableName, string $partition_id)
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::dropPartition() does not have return type hint for its return value but it should be possible to add it based on @return annotation "Statement".
Loading history...
784
    {
0 ignored issues
show
Coding Style introduced by
Expected 0 blank lines after opening function brace; 1 found
Loading history...
785
786
        $partition_id = trim($partition_id, '\'');
787
        $this->settings()->set('replication_alter_partitions_sync', 2);
788
        $state = $this->write('ALTER TABLE {dataBaseTableName} DROP PARTITION :partion_id',
0 ignored issues
show
introduced by
Useless variable $state.
Loading history...
789
            [
790
                'dataBaseTableName' => $dataBaseTableName,
791
                'partion_id'        => $partition_id,
792
            ]);
793
794
        return $state;
795
    }
796
797
    /**
798
     * Truncate ( drop all partitions )
799
     * @deprecated
0 ignored issues
show
introduced by
Expected 1 lines between description and annotations, found 0.
Loading history...
introduced by
Incorrect annotations group.
Loading history...
800
     * @return array
0 ignored issues
show
introduced by
@return annotation of method \ClickHouseDB\Client::truncateTable() does not specify type hint for items of its traversable return value.
Loading history...
801
     */
802
    public function truncateTable(string $tableName)
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::truncateTable() does not have return type hint for its return value but it should be possible to add it based on @return annotation "array".
Loading history...
803
    {
804
        $partions = $this->partitions($tableName);
805
        $out      = [];
806
        foreach ($partions as $part_key => $part) {
807
            $part_id       = $part['partition'];
808
            $out[$part_id] = $this->dropPartition($tableName, $part_id);
0 ignored issues
show
Deprecated Code introduced by
The function ClickHouseDB\Client::dropPartition() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

808
            $out[$part_id] = /** @scrutinizer ignore-deprecated */ $this->dropPartition($tableName, $part_id);
Loading history...
809
        }
810
811
        return $out;
812
    }
813
814
    /**
815
     * Returns the server's uptime in seconds.
816
     *
817
     * @return int
0 ignored issues
show
introduced by
Incorrect annotations group.
Loading history...
818
     * @throws Exception\TransportException
819
     */
820 1
    public function getServerUptime()
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::getServerUptime() does not have return type hint for its return value but it should be possible to add it based on @return annotation "int".
Loading history...
821
    {
822 1
        return $this->select('SELECT uptime() as uptime')->fetchOne('uptime');
823
    }
824
825
    /**
826
     * Returns string with the server version.
827
     */
828 1
    public function getServerVersion() : string
829
    {
830 1
        return (string) $this->select('SELECT version() as version')->fetchOne('version');
831
    }
832
833
    /**
834
     * Read system.settings table
835
     *
836
     * @return mixed[][]
837
     */
838 1
    public function getServerSystemSettings(string $like = '')
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::getServerSystemSettings() does not have return type hint for its return value but it should be possible to add it based on @return annotation "mixed[][]".
Loading history...
839
    {
840 1
        $l    = [];
841 1
        $list = $this->select('SELECT * FROM system.settings' . ($like ? ' WHERE name LIKE :like' : ''),
842 1
            ['like' => '%' . $like . '%'])->rows();
843 1
        foreach ($list as $row) {
844 1
            if (isset($row['name'])) {
0 ignored issues
show
introduced by
Use early exit to reduce code nesting.
Loading history...
845 1
                $n = $row['name'];
846 1
                unset($row['name']);
847 1
                $l[$n] = $row;
848
            }
849
        }
850
851 1
        return $l;
852
    }
853
854
    /**
855
     * dropOldPartitions by day_ago
856
     * @deprecated
0 ignored issues
show
introduced by
Expected 1 lines between description and annotations, found 0.
Loading history...
857
     *
858
     * @return array
0 ignored issues
show
introduced by
Incorrect annotations group.
Loading history...
introduced by
@return annotation of method \ClickHouseDB\Client::dropOldPartitions() does not specify type hint for items of its traversable return value.
Loading history...
859
     * @throws Exception\TransportException
860
     * @throws \Exception
0 ignored issues
show
introduced by
Class \Exception should not be referenced via a fully qualified name, but via a use statement.
Loading history...
861
     */
862
    public function dropOldPartitions(string $table_name, int $days_ago, int $count_partitons_per_one = 100)
0 ignored issues
show
introduced by
Method \ClickHouseDB\Client::dropOldPartitions() does not have return type hint for its return value but it should be possible to add it based on @return annotation "array".
Loading history...
863
    {
864
        $days_ago = strtotime(date('Y-m-d 00:00:00', strtotime('-' . $days_ago . ' day')));
865
866
        $drop           = [];
867
        $list_patitions = $this->partitions($table_name, $count_partitons_per_one);
868
869
        foreach ($list_patitions as $partion_id => $partition) {
870
            if (stripos($partition['engine'], 'mergetree') === false) {
871
                continue;
872
            }
873
874
            // $min_date = strtotime($partition['min_date']);
875
            $max_date = strtotime($partition['max_date']);
876
877
            if ($max_date < $days_ago) {
0 ignored issues
show
introduced by
Use early exit to reduce code nesting.
Loading history...
878
                $drop[] = $partition['partition'];
879
            }
880
        }
881
882
        $result = [];
883
        foreach ($drop as $partition_id) {
884
            $result[$partition_id] = $this->dropPartition($table_name, $partition_id);
0 ignored issues
show
Deprecated Code introduced by
The function ClickHouseDB\Client::dropPartition() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

884
            $result[$partition_id] = /** @scrutinizer ignore-deprecated */ $this->dropPartition($table_name, $partition_id);
Loading history...
885
        }
886
887
        return $result;
888
    }
889
}
890