Passed
Push — master ( 7b4f81...84e0ca )
by Igor
03:22
created

Client::showProcesslist()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 3
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
namespace ClickHouseDB;
4
5
use ClickHouseDB\Exception\QueryException;
6
use ClickHouseDB\Query\Degeneration\Bindings;
7
use ClickHouseDB\Query\WhereInFile;
8
use ClickHouseDB\Query\WriteToFile;
9
use ClickHouseDB\Quote\FormatLine;
10
use ClickHouseDB\Transport\Http;
11
use ClickHouseDB\Transport\Stream;
12
13
class Client
14
{
15
    /**
16
     * @var Http
17
     */
18
    private $_transport = null;
19
20
    /**
21
     * @var string
22
     */
23
    private $_connect_username = '';
24
25
    /**
26
     * @var string
27
     */
28
    private $_connect_password = '';
29
30
    /**
31
     * @var string
32
     */
33
    private $_connect_host = '';
34
35
    /**
36
     * @var string
37
     */
38
    private $_connect_port = '';
39
40
    /**
41
     * @var bool
42
     */
43
    private $_connect_user_readonly = false;
44
    /**
45
     * @var array
46
     */
47
    private $_support_format = ['TabSeparated', 'TabSeparatedWithNames', 'CSV', 'CSVWithNames', 'JSONEachRow'];
48
49
    /**
50
     * Client constructor.
51
     * @param array $connect_params
52
     * @param array $settings
53
     */
54 51
    public function __construct($connect_params, $settings = [])
55
    {
56 51
        if (!isset($connect_params['username'])) {
57
            throw  new \InvalidArgumentException('not set username');
58
        }
59
60 51
        if (!isset($connect_params['password'])) {
61
            throw  new \InvalidArgumentException('not set password');
62
        }
63
64 51
        if (!isset($connect_params['port'])) {
65
            throw  new \InvalidArgumentException('not set port');
66
        }
67
68 51
        if (!isset($connect_params['host'])) {
69
            throw  new \InvalidArgumentException('not set host');
70
        }
71
72 51
        if (isset($connect_params['settings']) && is_array($connect_params['settings'])) {
73 2
            if (empty($settings)) {
74 2
                $settings = $connect_params['settings'];
75
            }
76
        }
77
78 51
        $this->_connect_username    = $connect_params['username'];
79 51
        $this->_connect_password    = $connect_params['password'];
80 51
        $this->_connect_port        = $connect_params['port'];
81 51
        $this->_connect_host        = $connect_params['host'];
82
83
84
        // init transport class
85 51
        $this->_transport = new Http(
86 51
            $this->_connect_host,
87 51
            $this->_connect_port,
88 51
            $this->_connect_username,
89 51
            $this->_connect_password
90
        );
91
92
93 51
        $this->_transport->addQueryDegeneration(new Bindings());
94
95
        // apply settings to transport class
96 51
        $this->settings()->database('default');
97 51
        if (sizeof($settings)) {
98 2
            $this->settings()->apply($settings);
99
        }
100
101
102 51
        if (isset($connect_params['readonly']))
103
        {
104
            $this->setReadOnlyUser($connect_params['readonly']);
105
        }
106
107 51
        if (isset($connect_params['https']))
108
        {
109
            $this->https($connect_params['https']);
110
        }
111
112 51
        $this->enableHttpCompression();
113
114
115 51
    }
116
117
    /**
118
     * if the user has only read in the config file
119
     *
120
     * @param bool $flag
121
     */
122
    public function setReadOnlyUser($flag)
123
    {
124
        $this->_connect_user_readonly = $flag;
125
        $this->settings()->setReadOnlyUser($this->_connect_user_readonly);
126
    }
127
    /**
128
     * Clear Degeneration processing request [template ]
129
     *
130
     * @return bool
131
     */
132 1
    public function cleanQueryDegeneration()
133
    {
134 1
        return $this->_transport->cleanQueryDegeneration();
135
    }
136
137
    /**
138
     * add Degeneration processing
139
     *
140
     * @param Query\Degeneration $degeneration
141
     * @return bool
142
     */
143
    public function addQueryDegeneration(Query\Degeneration $degeneration)
144
    {
145
        return $this->_transport->addQueryDegeneration($degeneration);
146
    }
147
148
    /**
149
     * add Conditions in query
150
     *
151
     * @return bool
152
     */
153 1
    public function enableQueryConditions()
154
    {
155 1
        return $this->_transport->addQueryDegeneration(new \ClickHouseDB\Query\Degeneration\Conditions());
156
    }
157
    /**
158
     * Set connection host
159
     *
160
     * @param string|array $host
161
     */
162
    public function setHost($host)
163
    {
164
165
        if (is_array($host))
166
        {
167
            $host = array_rand(array_flip($host));
168
        }
169
170
        $this->_connect_host = $host;
171
        $this->transport()->setHost($host);
172
    }
173
174
    /**
175
     * Таймаут
176
     *
177
     * @param int $timeout
178
     * @return Settings
179
     */
180 2
    public function setTimeout($timeout)
181
    {
182 2
        return $this->settings()->max_execution_time($timeout);
183
    }
184
185
    /**
186
     * Timeout
187
     *
188
     * @return mixed
189
     */
190 1
    public function getTimeout()
191
    {
192 1
        return $this->settings()->getTimeOut();
193
    }
194
195
    /**
196
     * ConnectTimeOut in seconds ( support 1.5 = 1500ms )
197
     *
198
     * @param int $connectTimeOut
199
     */
200 2
    public function setConnectTimeOut($connectTimeOut)
201
    {
202 2
        $this->transport()->setConnectTimeOut($connectTimeOut);
203 2
    }
204
205
    /**
206
     * get ConnectTimeOut
207
     *
208
     * @return int
209
     */
210 1
    public function getConnectTimeOut()
211
    {
212 1
        return $this->transport()->getConnectTimeOut();
213
    }
214
215
216
    /**
217
     * transport
218
     *
219
     * @return Http
220
     */
221 51
    public function transport()
222
    {
223 51
        if (!$this->_transport) {
224
            throw  new \InvalidArgumentException('Empty transport class');
225
        }
226 51
        return $this->_transport;
227
    }
228
229
    /**
230
     * @return string
231
     */
232
    public function getConnectHost()
233
    {
234
        return $this->_connect_host;
235
    }
236
237
    /**
238
     * @return string
239
     */
240
    public function getConnectPassword()
241
    {
242
        return $this->_connect_password;
243
    }
244
245
    /**
246
     * @return string
247
     */
248
    public function getConnectPort()
249
    {
250
        return $this->_connect_port;
251
    }
252
253
    /**
254
     * @return string
255
     */
256
    public function getConnectUsername()
257
    {
258
        return $this->_connect_username;
259
    }
260
261
    /**
262
     * transport
263
     *
264
     * @return Http
265
     */
266
    public function getTransport()
267
    {
268
        return $this->_transport;
269
    }
270
271
272
    /**
273
     * Режим отладки CURL
274
     *
275
     * @return mixed
276
     */
277
    public function verbose()
278
    {
279
        return $this->transport()->verbose(true);
280
    }
281
282
    /**
283
     * @return Settings
284
     */
285 51
    public function settings()
286
    {
287 51
        return $this->transport()->settings();
288
    }
289
290
    /**
291
     * @return $this
292
     */
293 2
    public function useSession($useSessionId = false)
294
    {
295 2
        if (!$this->settings()->getSessionId())
296
        {
297 2
            if (!$useSessionId)
298
            {
299 2
                $this->settings()->makeSessionId();
300
            } else
301
            {
302
                $this->settings()->session_id($useSessionId);
303
            }
304
305
        }
306 2
        return $this;
307
    }
308
    /**
309
     * @return mixed
310
     */
311 2
    public function getSession()
312
    {
313 2
        return $this->settings()->getSessionId();
314
    }
315
316
    /**
317
     * Query CREATE/DROP
318
     *
319
     * @param string $sql
320
     * @param array $bindings
321
     * @param bool $exception
322
     * @return Statement
323
     * @throws Exception\TransportException
324
     */
325 19
    public function write($sql, $bindings = [], $exception = true)
326
    {
327 19
        return $this->transport()->write($sql, $bindings, $exception);
328
    }
329
330
    /**
331
     * set db name
332
     * @param string $db
333
     * @return $this
334
     */
335 1
    public function database($db)
336
    {
337 1
        $this->settings()->database($db);
338 1
        return $this;
339
    }
340
341
    /**
342
     * Write to system.query_log
343
     *
344
     * @param bool $flag
345
     * @return $this
346
     */
347
    public function enableLogQueries($flag = true)
348
    {
349
        $this->settings()->set('log_queries', intval($flag));
350
        return $this;
351
    }
352
353
    /**
354
     * Compress the result if the HTTP client said that it understands data compressed with gzip or deflate
355
     *
356
     * @param bool $flag
357
     * @return $this
358
     */
359 51
    public function enableHttpCompression($flag = true)
360
    {
361 51
        $this->settings()->enableHttpCompression($flag);
362 51
        return $this;
363
    }
364
365
    /**
366
     * Enable / Disable HTTPS
367
     *
368
     * @param bool $flag
369
     * @return $this
370
     */
371
    public function https($flag = true)
372
    {
373
        $this->settings()->https($flag);
374
        return $this;
375
    }
376
377
    /**
378
     * Read extremes of the result columns. They can be output in JSON-formats.
379
     *
380
     * @param bool $flag
381
     * @return $this
382
     */
383 2
    public function enableExtremes($flag = true)
384
    {
385 2
        $this->settings()->set('extremes', intval($flag));
386 2
        return $this;
387
    }
388
389
    /**
390
     * SELECT
391
     *
392
     * @param string $sql
393
     * @param array $bindings
394
     * @param null|WhereInFile $whereInFile
395
     * @param null|WriteToFile $writeToFile
396
     * @return Statement
397
     * @throws Exception\TransportException
398
     * @throws \Exception
399
     */
400 39
    public function select($sql, $bindings = [], $whereInFile = null, $writeToFile = null)
401
    {
402 39
        return $this->transport()->select($sql, $bindings, $whereInFile, $writeToFile);
403
    }
404
405
    /**
406
     * execute run
407
     *
408
     * @return bool
409
     * @throws Exception\TransportException
410
     */
411 8
    public function executeAsync()
412
    {
413 8
        return $this->transport()->executeAsync();
414
    }
415
416
    /**
417
     * set progressFunction
418
     *
419
     * @param callable $callback
420
     */
421 1
    public function progressFunction($callback)
422
    {
423 1
        if (!is_callable($callback)) {
424
            throw new \InvalidArgumentException('Not is_callable progressFunction');
425
        }
426
427 1
        if (!$this->settings()->is('send_progress_in_http_headers'))
428
        {
429 1
            $this->settings()->set('send_progress_in_http_headers', 1);
430
        }
431 1
        if (!$this->settings()->is('http_headers_progress_interval_ms'))
432
        {
433 1
            $this->settings()->set('http_headers_progress_interval_ms', 100);
434
        }
435
436
437 1
        $this->transport()->setProgressFunction($callback);
438 1
    }
439
440
    /**
441
     * prepare select
442
     *
443
     * @param string $sql
444
     * @param array $bindings
445
     * @param null|WhereInFile $whereInFile
446
     * @param null|WriteToFile $writeToFile
447
     * @return Statement
448
     * @throws Exception\TransportException
449
     * @throws \Exception
450
     */
451 4
    public function selectAsync($sql, $bindings = [], $whereInFile = null, $writeToFile = null)
452
    {
453 4
        return $this->transport()->selectAsync($sql, $bindings, $whereInFile, $writeToFile);
454
    }
455
456
    /**
457
     * SHOW PROCESSLIST
458
     *
459
     * @return array
460
     * @throws Exception\TransportException
461
     * @throws \Exception
462
     */
463
    public function showProcesslist()
464
    {
465
        return $this->select('SHOW PROCESSLIST')->rows();
466
    }
467
468
    /**
469
     * show databases
470
     *
471
     * @return array
472
     * @throws Exception\TransportException
473
     * @throws \Exception
474
     */
475
    public function showDatabases()
476
    {
477
        return $this->select('show databases')->rows();
478
    }
479
480
    /**
481
     * statement = SHOW CREATE TABLE
482
     *
483
     * @param string $table
484
     * @return mixed
485
     * @throws Exception\TransportException
486
     * @throws \Exception
487
     */
488
    public function showCreateTable($table)
489
    {
490
        return ($this->select('SHOW CREATE TABLE ' . $table)->fetchOne('statement'));
491
    }
492
493
    /**
494
     * SHOW TABLES
495
     *
496
     * @return array
497
     * @throws Exception\TransportException
498
     * @throws \Exception
499
     */
500 1
    public function showTables()
501
    {
502 1
        return $this->select('SHOW TABLES')->rowsAsTree('name');
503
    }
504
505
    /**
506
     * Get the number of simultaneous/Pending requests
507
     *
508
     * @return int
509
     */
510 11
    public function getCountPendingQueue()
511
    {
512 11
        return $this->transport()->getCountPendingQueue();
513
    }
514
515
    /**
516
     * Insert Array
517
     *
518
     * @param string $table
519
     * @param array $values
520
     * @param array $columns
521
     * @return Statement
522
     * @throws Exception\TransportException
523
     */
524 5
    public function insert($table, $values, $columns = [])
525
    {
526 5
        $sql = 'INSERT INTO ' . $table;
527
528 5
        if (0 !== count($columns)) {
529 5
            $sql .= ' (' . implode(',', $columns) . ') ';
530
        }
531
532 5
        $sql .= ' VALUES ';
533
534 5
        foreach ($values as $row) {
535 5
            $sql .= ' (' . FormatLine::Insert($row) . '), ';
536
        }
537 5
        $sql = trim($sql, ', ');
538 5
        return $this->transport()->write($sql);
539
    }
540
541
    /**
542
      * Prepares the values to insert from the associative array.
543
      * There may be one or more lines inserted, but then the keys inside the array list must match (including in the sequence)
544
      *
545
      * @param array $values - array column_name => value (if we insert one row) or array list column_name => value if we insert many lines
546
      * @return array - list of arrays - 0 => fields, 1 => list of value arrays for insertion
547
      */
548 3
    public function prepareInsertAssocBulk(array $values)
549
    {
550 3
        if (isset($values[0]) && is_array($values[0])) { //случай, когда много строк вставляется
551 2
            $preparedFields = array_keys($values[0]);
552 2
            $preparedValues = [];
553 2
            foreach ($values as $idx => $row) {
554 2
                $_fields = array_keys($row);
555 2
                if ($_fields !== $preparedFields) {
556 1
                    throw new QueryException("Fields not match: " . implode(',', $_fields) . " and " . implode(',', $preparedFields) . " on element $idx");
557
                }
558 2
                $preparedValues[] = array_values($row);
559
            }
560
        } else { //одна строка
561 1
            $preparedFields = array_keys($values);
562 1
            $preparedValues = [array_values($values)];
563
        }
564 2
        return [$preparedFields, $preparedValues];
565
    }
566
567
    /**
568
     * Inserts one or more rows from an associative array.
569
     * If there is a discrepancy between the keys of the value arrays (or their order) - throws an exception.
570
     *
571
     * @param string $table - table name
572
     * @param array $values - array column_name => value (if we insert one row) or array list column_name => value if we insert many lines
573
     * @return Statement
574
     * @throws QueryException
575
     * @throws Exception\TransportException
576
     */
577
    public function insertAssocBulk($table, array $values)
578
    {
579
        list($columns, $vals) = $this->prepareInsertAssocBulk($values);
580
        return $this->insert($table, $vals, $columns);
581
    }
582
583
    /**
584
     * insert TabSeparated files
585
     *
586
     * @param string $table_name
587
     * @param string|array $file_names
588
     * @param array $columns_array
589
     * @return mixed
590
     * @throws Exception\TransportException
591
     */
592 1
    public function insertBatchTSVFiles($table_name, $file_names, $columns_array=[])
593
    {
594 1
        return $this->insertBatchFiles($table_name, $file_names, $columns_array, 'TabSeparated');
595
    }
596
597
    /**
598
     * insert Batch Files
599
     *
600
     * @param string $table_name
601
     * @param string|array $file_names
602
     * @param array $columns_array
603
     * @param string $format ['TabSeparated','TabSeparatedWithNames','CSV','CSVWithNames']
604
     * @return array
605
     * @throws Exception\TransportException
606
     */
607 7
    public function insertBatchFiles($table_name, $file_names, $columns_array=[], $format = "CSV")
608
    {
609 7
        if (is_string($file_names))
610
        {
611
            $file_names = [$file_names];
612
        }
613 7
        if ($this->getCountPendingQueue() > 0) {
614
            throw new QueryException('Queue must be empty, before insertBatch, need executeAsync');
615
        }
616
617 7
        if (!in_array($format, $this->_support_format))
618
        {
619
            throw new QueryException('Format not support in insertBatchFiles');
620
        }
621
622 7
        $result = [];
623
624 7
        foreach ($file_names as $fileName) {
625 7
            if (!is_file($fileName) || !is_readable($fileName)) {
626
                throw  new QueryException('Cant read file: ' . $fileName . ' ' . (is_file($fileName) ? '' : ' is not file'));
627
            }
628
629 7
            if (empty($columns_array))
630
            {
631
                $sql = 'INSERT INTO ' . $table_name . ' FORMAT ' . $format;
632
633
            } else
634
            {
635 7
                $sql = 'INSERT INTO ' . $table_name . ' ( ' . implode(',', $columns_array) . ' ) FORMAT ' . $format;
636
637
            }
638 7
            $result[$fileName] = $this->transport()->writeAsyncCSV($sql, $fileName);
639
        }
640
641
        // exec
642 7
        $this->executeAsync();
643
644
        // fetch resutl
645 7
        foreach ($file_names as $fileName) {
646 7
            if ($result[$fileName]->isError()) {
647 7
                $result[$fileName]->error();
648
            }
649
        }
650
651 5
        return $result;
652
    }
653
654
    /**
655
     * insert Batch Stream
656
     *
657
     * @param string $table_name
658
     * @param array $columns_array
659
     * @param string $format ['TabSeparated','TabSeparatedWithNames','CSV','CSVWithNames']
660
     * @return Transport\CurlerRequest
661
     */
662 2
    public function insertBatchStream($table_name, $columns_array=[], $format = "CSV")
663
    {
664 2
        if ($this->getCountPendingQueue() > 0) {
665
            throw new QueryException('Queue must be empty, before insertBatch, need executeAsync');
666
        }
667
668 2
        if (!in_array($format, $this->_support_format))
669
        {
670
            throw new QueryException('Format not support in insertBatchFiles');
671
        }
672
673 2
        if (empty($columns_array))
674
        {
675
            $sql = 'INSERT INTO ' . $table_name . ' FORMAT ' . $format;
676
677
        } else
678
        {
679 2
            $sql = 'INSERT INTO ' . $table_name . ' ( ' . implode(',', $columns_array) . ' ) FORMAT ' . $format;
680
681
        }
682
683 2
        return $this->transport()->writeStreamData($sql);
684
    }
685
686
687
    /**
688
     * stream Write
689
     *
690
     * @param Stream $stream
691
     * @param string $sql
692
     * @param array $bind
693
     * @return Statement
694
     * @throws Exception\TransportException
695
     */
696 1
    public function streamWrite(Stream $stream,$sql,$bind=[])
697
    {
698 1
        if ($this->getCountPendingQueue() > 0) {
699
            throw new QueryException('Queue must be empty, before streamWrite');
700
        }
701 1
        return $this->transport()->streamWrite($stream,$sql,$bind);
702
    }
703
704
705
    /**
706
     * stream Read
707
     *
708
     * @param Stream $streamRead
709
     * @param string $sql
710
     * @param array $bind
711
     * @return Statement
712
     * @throws Exception\TransportException
713
     */
714 1
    public function streamRead(Stream $streamRead,$sql,$bind=[])
715
    {
716 1
        if ($this->getCountPendingQueue() > 0) {
717
            throw new QueryException('Queue must be empty, before streamWrite');
718
        }
719 1
        return $this->transport()->streamRead($streamRead,$sql,$bind);
720
    }
721
722
    /**
723
     * Size of database
724
     *
725
     * @return mixed|null
726
     * @throws Exception\TransportException
727
     * @throws \Exception
728
     */
729
    public function databaseSize()
730
    {
731
        $b = $this->settings()->getDatabase();
732
733
        return $this->select('
734
            SELECT database,formatReadableSize(sum(bytes)) as size
735
            FROM system.parts
736
            WHERE active AND database=:database
737
            GROUP BY database
738
        ', ['database' => $b])->fetchOne();
739
    }
740
741
    /**
742
     * Size of tables
743
     *
744
     * @param string $tableName
745
     * @return mixed
746
     * @throws Exception\TransportException
747
     * @throws \Exception
748
     */
749 1
    public function tableSize($tableName)
750
    {
751 1
        $tables = $this->tablesSize();
752
753 1
        if (isset($tables[$tableName])) {
754 1
            return $tables[$tableName];
755
        }
756
757
        return null;
758
    }
759
760
    /**
761
     * ping & check
762
     *
763
     * @return bool
764
     * @throws Exception\TransportException
765
     * @throws \Exception
766
     */
767 35
    public function ping()
768
    {
769 35
        $result = $this->select('SELECT 1 as ping')->fetchOne('ping');
770 35
        return ($result == 1);
771
    }
772
773
    /**
774
     * Tables sizes
775
     *
776
     * @param bool $flatList
777
     * @return array
778
     * @throws Exception\TransportException
779
     * @throws \Exception
780
     */
781 1
    public function tablesSize($flatList = false)
782
    {
783 1
        $z = $this->select('
784
        SELECT name as table,database,
785
            max(sizebytes) as sizebytes,
786
            max(size) as size,
787
            min(min_date) as min_date,
788
            max(max_date) as max_date
789
            FROM system.tables
790
            ANY LEFT JOIN 
791
            (
792
            SELECT table,database,
793
                        formatReadableSize(sum(bytes)) as size,
794
                        sum(bytes) as sizebytes,
795
                        min(min_date) as min_date,
796
                        max(max_date) as max_date
797
                        FROM system.parts 
798
                        WHERE active AND database=:database
799
                        GROUP BY table,database
800
            ) USING ( table,database )
801
            WHERE database=:database
802
            GROUP BY table,database
803 1
        ', ['database'=>$this->settings()->getDatabase()]);
804
805 1
        if ($flatList) {
806
            return $z->rows();
807
        }
808
809
810 1
        return $z->rowsAsTree('table');
811
812
813
    }
814
815
816
    /**
817
     * isExists
818
     *
819
     * @param string $database
820
     * @param string $table
821
     * @return array
822
     * @throws Exception\TransportException
823
     * @throws \Exception
824
     */
825
    public function isExists($database, $table)
826
    {
827
        return $this->select('
828
            SELECT *
829
            FROM system.tables 
830
            WHERE name=\''.$table . '\' AND database=\'' . $database . '\''
831
        )->rowsAsTree('name');
832
    }
833
834
835
    /**
836
     * List of partitions
837
     *
838
     * @param string $table
839
     * @param int $limit
840
     * @return array
841
     * @throws Exception\TransportException
842
     * @throws \Exception
843
     */
844
    public function partitions($table, $limit = -1)
845
    {
846
        return $this->select('
847
            SELECT *
848
            FROM system.parts 
849
            WHERE like(table,\'%' . $table . '%\') AND database=\'' . $this->settings()->getDatabase() . '\' 
850
            ORDER BY max_date ' . ($limit > 0 ? ' LIMIT ' . intval($limit) : '')
851
        )->rowsAsTree('name');
852
    }
853
854
    /**
855
     * dropPartition
856
     * @deprecated
857
     * @param string $dataBaseTableName database_name.table_name
858
     * @param string $partition_id
859
     * @return Statement
860
     * @throws Exception\TransportException
861
     */
862
    public function dropPartition($dataBaseTableName, $partition_id)
863
    {
864
865
        $partition_id = trim($partition_id, '\'');
866
        $this->settings()->set('replication_alter_partitions_sync', 2);
867
        $state = $this->write('ALTER TABLE {dataBaseTableName} DROP PARTITION :partion_id', [
868
            'dataBaseTableName'  => $dataBaseTableName,
869
            'partion_id' => $partition_id
870
        ]);
871
        return $state;
872
    }
873
874
    /**
875
     * Truncate ( drop all partitions )
876
     * @deprecated
877
     * @param string $tableName
878
     * @return array
879
     * @throws Exception\TransportException
880
     * @throws \Exception
881
     */
882
    public function truncateTable($tableName)
883
    {
884
        $partions = $this->partitions($tableName);
885
        $out = [];
886
        foreach ($partions as $part_key=>$part)
887
        {
888
            $part_id = $part['partition'];
889
            $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

889
            $out[$part_id] = /** @scrutinizer ignore-deprecated */ $this->dropPartition($tableName, $part_id);
Loading history...
890
        }
891
        return $out;
892
    }
893
894
    /**
895
     * Returns the server's uptime in seconds.
896
     *
897
     * @return array
898
     * @throws Exception\TransportException
899
     */
900 1
    public function getServerUptime()
901
    {
902 1
        return $this->select('SELECT uptime() as uptime')->fetchOne('uptime');
903
    }
904
905
906
    /**
907
     * Read system.settings table
908
     *
909
     * @param string $like
910
     * @return array
911
     * @throws Exception\TransportException
912
     */
913 1
    public function getServerSystemSettings($like='')
914
    {
915 1
        $l=[];
916 1
        $list=$this->select('SELECT * FROM system.settings'.($like ? ' WHERE name LIKE :like':'' ),['like'=>'%'.$like.'%'])->rows();
917 1
        foreach ($list as $row) {
918 1
            if (isset($row['name'])) {$n=$row['name']; unset($row['name']) ; $l[$n]=$row;}
919
        }
920 1
        return $l;
921
    }
922
923
924
925
    /**
926
     * dropOldPartitions by day_ago
927
     * @deprecated
928
     *
929
     * @param string $table_name
930
     * @param int $days_ago
931
     * @param int $count_partitons_per_one
932
     * @return array
933
     * @throws Exception\TransportException
934
     * @throws \Exception
935
     */
936
    public function dropOldPartitions($table_name, $days_ago, $count_partitons_per_one = 100)
937
    {
938
        $days_ago = strtotime(date('Y-m-d 00:00:00', strtotime('-' . $days_ago . ' day')));
939
940
        $drop = [];
941
        $list_patitions = $this->partitions($table_name, $count_partitons_per_one);
942
943
        foreach ($list_patitions as $partion_id => $partition) {
944
            if (stripos($partition['engine'], 'mergetree') === false) {
945
                continue;
946
            }
947
948
            // $min_date = strtotime($partition['min_date']);
949
            $max_date = strtotime($partition['max_date']);
950
951
            if ($max_date < $days_ago) {
952
                $drop[] = $partition['partition'];
953
            }
954
        }
955
956
        $result = [];
957
        foreach ($drop as $partition_id) {
958
            $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

958
            $result[$partition_id] = /** @scrutinizer ignore-deprecated */ $this->dropPartition($table_name, $partition_id);
Loading history...
959
        }
960
961
        return $result;
962
    }
963
}
964