GithubHelp home page GithubHelp logo

kak-clickhouse's Introduction

Yii2 ClickHouse extension

Installation

Composer

The preferred way to install this extension is through Composer.

Either run

  • stable php composer.phar require kak/clickhouse ~1.1
  • dev php composer.phar require kak/clickhouse @dev

or add to composer.json manual

  • stable "kak/clickhouse": "~1.1
  • dev "kak/clickhouse": "@dev"

to the require section of your composer.json

Configuration example

   'components' => [
        'clickhouse' => [
            'class' => 'kak\clickhouse\Connection',
            'dsn' => '127.0.0.1',
            'port' => '8123',
           // 'database' => 'default',  // use other database name
            'username' => 'web',
            'password' => '123',
            'enableSchemaCache' => true,
            'schemaCache' => 'cache',
            'schemaCacheDuration' => 86400
        ],
   // ...     

Notes

  • If clickhouse server responds with no response == 200, then you will get the exception

Usage

   /** @var \kak\clickhouse\Connection $client */
    $client = \Yii::$app->clickhouse;
    $sql = 'select * from stat where counter_id=:counter_id';
    $client->createCommand($sql, [
        ':counter_id' => 122
    ])->queryAll();
    
    // ====== insert data ORM ======
    
    $client->createCommand(null)
    ->insert('stat', [
        'event_data' => date('Y-m-d'),
        'counter_id' => 122
    ])
    ->execute();	

batch insert files

    /** @var \kak\clickhouse\Connection $clickhouse */
    $clickhouse = \Yii::$app->clickhouse;

    $files = [
        'dump_20170502' => Yii::getAlias('@app/dump_20170502.csv'),
        'dump_20170503' => Yii::getAlias('@app/dump_20170503.csv'),
        'dump_20170504' => Yii::getAlias('@app/dump_20170504.csv'),
    ];	
    		
    $responses = $clickhouse->createCommand(null)
    ->batchInsertFiles('stat', null, [
        $files
    ], 'CSV');

    foreach ($responses as $keyId => $response) {
        var_dump($keyId . ' ' . $response->isOk);
    }	
    

batch insert files, batch size = 100 lines

    /** @var \kak\clickhouse\Connection $clickhouse */
    $clickhouse = \Yii::$app->clickhouse;

    $responses = $clickhouse->createCommand(null)
    ->batchInsertFilesDataSize('stat', null, [
        $files
    ], 'CSV', 100);	
     foreach ($responses as $keyId => $parts) {
        foreach ($parts as $partId => $response) {
            var_dump($keyId . '_' . $partId. ' ' . $response->isOk);
        }
     }	

old methods: meta, rows, countAll, statistics

   	
    $sql = 'SELECT 
        user_id, sum(income) AS sum_income
        FROM stat
        GROUP BY event_date
        WITH TOTALS
        LIMIT 10
    '; 	

    /** @var \kak\clickhouse\Connection $clickhouse */
    $clickhouse = \Yii::$app->clickhouse;
    
    $command = $clickhouse->createCommand($sql);  	
    $result = $command->queryAll();
    
    var_dump($command->getMeta());  	      // columns meta info (columnName, dataType)
    var_dump($command->getTotals());          // get totals rows to read
    var_dump($command->getData());  	      // get rows data
    var_dump($command->getRows());  	      // rows count current result
    var_dump($command->getCountAll());        // rows count before limit at least	
    var_dump($command->getExtremes());  	
    var_dump($command->getStatistics());      // stat query 
    
 //or
     
    $command = $clickhouse->createCommand($sql);  
    $result = $command->queryAll($command::FETCH_MODE_ALL);
    var_dump($result);
    

old examples ORM

use kak\clickhouse\Query;

$q = (new Query())
    ->from('stat')
    ->withTotals()
    ->where(['event_date' => '2017-05-01' , 'user_id' => 5])
    ->offset(2)
    ->limit(1);

$command = $q->createCommand();
$result  = $command->queryAll();
$total   = $command->getTotals();

var_dump($result);
var_dump($total); 

// -----
$command = (new Query())
    ->select(['event_stat', 'count()'])
    ->from('test_stat')
    ->groupBy('event_date')
    ->limit(1)
    ->withTotals();
    
$result =  $command->all();
var_dump($command->getTotals());

Group With Modifiers

use kak\clickhouse\Query;

$command = (new Query());
// ...
$command->withTotals();
// or
$command->withCube();
// or
$command->withRollup();

Set specific options

  /** @var \kak\clickhouse\Connection $client */
    $client = \Yii::$app->clickhouse;
    $sql = 'select * from stat where counter_id=:counter_id';
    $client->createCommand($sql, [
        ':counter_id' => 122
    ])->setOptions([
        'max_threads' => 2
    ])->queryAll();

// add options use method
// ->addOptions([])

Select with

    use kak\clickhouse\Query;
    // ...

    $db = \Yii::$app->clickhouse;
    $query = new Query();
    // first argument scalar var or Query object
    $query->withQuery($db->quoteValue('2021-10-05'), 'date1');
    $query->select('*');
    $query->from('stat');
    $query->where('event_stat < date1');
    $query->all();
/*
    WITH '2020-07-26' AS date1 SELECT * FROM stat WHERE event_stat < date1
*/

Save custom model

use yii\base\Model;

class Stat extends Model
{
    public $event_date; // Date;
    public $counter_id  = 0; // Int32,

    public function save($validate = true)
    {
        /** @var \kak\clickhouse\Connection $client */
        $client = \Yii::$app->clickhouse;
        $this->event_date = date('Y-m-d');

        if ($validate && !$this->validate()) {
            return false;
        }

        $attributes = $this->getAttributes();
        $client->createCommand(null)
            ->insert('stat', $attributes)
            ->execute();

        return true;	
    }
}

ActiveRecord model

use kak\clickhouse\ActiveRecord;
use app\models\User;

class Stat extends ActiveRecord
{
    // pls overwrite method is config section !=clickhouse
    // default clickhouse
	public static function getDb()
	{
	    return \Yii::$app->clickhouse;
	}


    public static function tableName()
    {
        return 'stat';
    }
    
    // use relation in mysql (Only with, do not use joinWith)
    public function getUser()
    {
    	return $this->hasOne(User::class, ['id' => 'user_id']);
    }
}

Using Gii generator

<?php
return [
    //....
    'modules' => [
        // ...
        'gii' => [
            'class' => 'yii\gii\Module',
            'allowedIPs' => [
                '127.0.0.1',
                '::1',
                '192.168.*',
                '10.*',
            ],
            'generators' => [
                'clickhouseDbModel' => [
                    'class' => 'kak\clickhouse\gii\model\Generator'
                ]
            ],
        ],
    ]
];

Using Debug panel

$config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = [
        'class' => 'yii\debug\Module',
        'allowedIPs' => [
            '127.0.0.1',
            '::1',
            '192.168.*',
            '10.*',
        ],
        'panels' => [
            'clickhouse' => [
                'class' => 'kak\clickhouse\debug\Panel',
                'db' => 'clickhouse'
            ],
        ]

    ];

Using SqlDataProvider

$sql = 'select * from stat where counter_id=:counter_id and event_date=:date';
$provider = new \kak\clickhouse\data\SqlDataProvider([
    'db' => 'clickhouse',
    'sql' => $sql,
    'params' => [
        ':counter_id' => 1,
        ':date' => date('Y-m-d')
    ]
]);

Using Migration Data

convert schema mysql >>> clickhouse
create custom console controller

    // ...
    public function actionIndex()
    {
        $exportSchemaCommand = new \kak\clickhouse\console\MigrationSchemaCommand([
            'sourceTable' => 'stat',
            'sourceDb' => \Yii::$app->db,
            'excludeSourceColumns' => [
                'id',
            ]
            'columns' => [
                '`event_date` Date' 
            ]
        ]);
        // result string SQL schema  
        $sql = $exportSchemaCommand->run();
        echo $sql;
    }    

migration mysql,mssql data >>> clickhouse
create custom console controller

  // ...
    public function actionIndex()
    {
        $exportDataCommand = new \kak\clickhouse\console\MigrationDataCommand([
            'sourceQuery' => (new Query())->select('*')->from('stat'),
            'sourceDb' => \Yii::$app->db,
            'storeTable' => 'test_stat',
            'storeDb' => \Yii::$app->clickhouse,
            'batchSize' => 10000,
            'filterSourceRow' => function($data){
                // if result false then skip save row
                $time = strtotime($data['hour_at']);
                return $time > 0;
            },
            'mapData' => [
                // key storeTable column => sourceTable column|call function 
                'event_date' => function($data){
                    return date('Y-m-d',strtotime($data['hour_at']));
                },
                'time' => function($data){
                    return strtotime($data['hour_at']);
                },
                'user_id' => 'partner_id'
            ]    
        ]);
        $exportDataCommand->run();  
     
    }

Result

php yii export-test/index

total count rows source table 38585
part data files count 4
save files dir: /home/user/test-project/www/runtime/clickhouse/stat
parts:
 >>> part0.data time 4.749
 >>> part1.data time 4.734
 >>> part2.data time 4.771
 >>> part3.data time 4.089
insert files
 <<< part0.data  time 3.289
 <<< part1.data  time 2.024
 <<< part2.data  time 1.938
 <<< part3.data  time 3.359
done

ClickHouse Reference Manual

https://clickhouse.yandex/reference_en.html

Summary of recommendations insert data

  • 1 Accumulated data and insert at one time, it will reduce the operations io disk
  • 2 @todo how that will add...

Run tests

  • 1 git clone repository https://github.com/sanchezzzhak/kak-clickhouse.git
  • 2 composer install --ignore-platform-reqs
  • 3 create the config clickhouse touch tests/_config/clickhouse.php if you non-standard access to the server connection
<?php

return [
    'class' => 'kak\clickhouse\Connection',
    'dsn' => '127.0.0.1',
    'port' => '8123',
    'username' => 'web',
    'password' => '123',
    'enableSchemaCache' => true,
    'schemaCache' => 'cache',
    'schemaCacheDuration' => 86400
];
  • 4 run tests php vendor/bin/codecept run

kak-clickhouse's People

Contributors

andreybolonin avatar angelikaborodina avatar demenkov avatar draconic avatar frops avatar rowdyroad avatar sanchezzzhak avatar taroff avatar wbarcovsky avatar zayec77 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

kak-clickhouse's Issues

Невозможность использования https подключения

Приветствую,

в Connection::open() некорректно собирается url для подключения. Независимо от требуемого типа подключения (http или https) добавляется http://

Логичным выглядит отказаться от параметров user, password и port, а вместо них использовать dsn по-полной:

[
    'dsn' => 'https://admin:*******@example.com:8444'
]

Incorrect response error code

Hi.
I've have a mistake in my clickhouse query and received 404 response code from clickhouse.

["_headers":"yii\httpclient\Message":private]=> object(yii\web\HeaderCollection)#40 (1) { ["_headers":"yii\web\HeaderCollection":private]=> array(6) { ["http-code"]=> array(1) { [0]=> string(3) "404" } ["date"]=> array(1) { [0]=> string(29) "Mon, 24 Apr 2017 10:32:16 GMT" } ["connection"]=> array(1) { [0]=> string(10) "Keep-Alive" } ["content-type"]=> array(1) { [0]=> string(25) "text/plain; charset=UTF-8" } ["transfer-encoding"]=> array(1) { [0]=> string(7) "chunked" } ["keep-alive"]=> array(1) { [0]=> string(9) "timeout=3" } } }

What's why code:
/** Raise exception when get 500s error */ if ($response->statusCode >= 500) { throw new DbException($response->getContent()); }

does't fire exception.

By the way, there is only 200 and 500 response code in HTTP interface of clickhouse In documentation.

Еще поддерживается?

Всем привет, хотел бы спросить поддерживается ли репозитория или нет?

Я хотел бы принять участие и помочь внести возможности, которые еще не реализонвы

Создание миграций

Привет! Помогите пожалуйста разобраться, как правильно создавать миграции? В обычных Yii2 миграциях используя raw sql, либо есть какие то другие способы?

Add content-type header for requestOptions

In PHP 7.2.25

I see notice: "Notice: fopen(): Content-type not specified assuming application/x-www-form-urlencoded"

ErrorException: Notice: fopen(): Content-type not specified assuming application/x-www-form-urlencoded
#8 /var/www/td/vendor/yiisoft/yii2-httpclient/src/StreamTransport.php(61): yii\httpclient\StreamTransport::send
#7 /var/www/td/vendor/yiisoft/yii2-httpclient/src/Client.php(233): yii\httpclient\Client::send
#6 /var/www/td/vendor/yiisoft/yii2-httpclient/src/Request.php(444): yii\httpclient\Request::send
#5 /var/www/td/vendor/kak/clickhouse/Command.php(150): kak\clickhouse\Command::execute
#4 /var/www/td/components/ChTarget.php(104): app\components\ChTarget::export
#3 /var/www/td/components/ChTarget.php(134): app\components\ChTarget::collect
#2 /var/www/td/vendor/yiisoft/yii2/log/Dispatcher.php(191): yii\log\Dispatcher::dispatch
#1 /var/www/td/vendor/yiisoft/yii2/log/Logger.php(177): yii\log\Logger::flush
#0 internal: null

Баг в SqlDataProvider . Getting unknown property: yii\db\Query::sample

В файл kak/clickhouse/data/SqlDataProvider.php

use kak\clickhouse\Query;
protected function prepareTotalCount()
    {
        return (new Query([
            'from' => ['sub' => "({$this->sql})"],
            'params' => $this->params,
        ]))->count('*', $this->db);
    }

Так как в версии yii 2.0.16
вот такая ошибка

Unknown Property – yii\base\UnknownPropertyException Getting unknown property: yii\db\Query::sample

Can't use other than default database

I tried to set the config parameter 'database' to my productive database and I also tried to set the table to 'db.table' which both returns an error.
How to set a database properly?

typecast() error

counter_id Nullable(UInt32)

$client->createCommand(null)
->insert('stat', [
'event_data' => date('Y-m-d'),
'counter_id' => 122
])->execute();

пытается вставить '122' вместо 122.

В случае если поле типа UInt32 - все нормально

Wrong escaping single quote sign

Hello!
I'm trying to batch insert some value with single quote sign using batchInsert command, f.e.:

<?php Yii::$app->clickhouse->
    createCommand()->
    batchInsert('table', ['column'], [["value with single ' quote inside"]])->
    execute();

What I expect? The value inside DB should be:
value with single ' quote inside
But instead I get:
value with single '' quote inside (two single quotes in DB value!)
I found in Schema.php next code:

    public function quoteValue($str)
    {
        if (!is_string($str)) {
            return $str;
        }
        return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032\047") . "'";
    }

First we doubling single quote with this code: str_replace("'", "''", $str) but after we adding backslashes to single quotes because of listing single quote sign in octal form: \047
So we get \'\' as the result, but we need \' OR '' [two single quote signs together].

I'm not so experienced in GitHub things and want to consult with you: I'm not sure, is it bug or I'm missing some important behaviour in escaping?
I think the right function should be:

public function quoteValue($str)
    {
        if (!is_string($str)) {
            return $str;
        }
        return "'" . addcslashes($str, "\000\n\r\\\032\047") . "'";
    }

or

public function quoteValue($str)
    {
        if (!is_string($str)) {
            return $str;
        }
        return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
    }

Am I right and can you fix this?
Thank you a lot for this library, it's very helpful!

Некорректная работа с UInt64 в batchInsert

Проблема схожая с #33 и #22 но касается batchInsert(): Yii пытается привратить число в строку и так и записать в CH.

Code: 53, e.displayText() = DB::Exception: Type mismatch in IN or VALUES section. Expected: UInt64. Got: String, e.what() = DB::Exception

Возможное решение - переопределить Schema::getColumnPhpType($column) (на bigint возвращать integer независимо от signed/unsigned типа при условии что PHP_INT_SIZE === 8):

protected function getColumnPhpType($column) {
        static $typeMap = [
            // abstract type => php type
            self::TYPE_TINYINT => 'integer',
            self::TYPE_SMALLINT => 'integer',
            self::TYPE_INTEGER => 'integer',
            self::TYPE_BIGINT => 'integer',
            self::TYPE_BOOLEAN => 'boolean',
            self::TYPE_FLOAT => 'double',
            self::TYPE_DOUBLE => 'double',
            self::TYPE_BINARY => 'resource',
            self::TYPE_JSON => 'array',
        ];
        if (isset($typeMap[$column->type])) {
            if ($column->type === 'bigint') {
                return PHP_INT_SIZE === 8 ? 'integer' : 'string';
            }
            if ($column->type === 'integer') {
                return PHP_INT_SIZE === 4 && $column->unsigned ? 'string' : 'integer';
            }

            return $typeMap[$column->type];
        }

        return 'string';
    }

why disable query cache?

When creating query command, this component's code disable cache.

Here is the code in \yii\db\Query:

$command = $db->createCommand($sql, $params);
$this->setCommandCache($command);

the code in \kak\clickhouse\Query:

$this->_command = $db->createCommand($sql, $params);

Are there any problems about this component's supporting for query cache?

How to add timeout option?

Currently yii\httpclient\CurlTransport is used in order to make a request.
Unfortunately I was unable to find a way to pass CURLOPT_TIMEOUT to the transport and/or 'timeout' option to the Request. Is there such a way?

If no, I may try to work upon a solution for global client/transport config in class configuration options.

подскажите как исправить ошибку при создании бэкапа clickhouse

При создании бэкапа выводится много записей:
Received exception from server (version 19.6.2):
Code: 53. DB::Exception: Received from localhost:9000, 127.0.0.1. DB::Exception: Type mismatch in IN or VALUES section. Expected: Date. Got: Int64.
Скажите насколько критично данное сообщение и как исправить.

CentOS Linux release 7.6.1810 (Core)
ClickHouse client version 19.6.2.1
ClickHouse server version 19.6.2

скрипт создания бэкапов:
clickhouse-client --query="SELECT partition, table, database FROM system.parts WHERE active;" > /tmp/.clickhouse_temp_dbs.txt

while read STRING; do
CH_DB=$(echo ${STRING} | awk '{print $3}')
CH_TBL=$(echo ${STRING} | awk '{print $2}')
CH_PT=$(echo ${STRING} | awk '{print $1}')

clickhouse-client --query="ALTER TABLE $CH_DB.$CH_TBL FREEZE PARTITION $CH_PT";

done < /tmp/.clickhouse_temp_dbs.txt
tar czhpf - /var/lib/clickhouse/shadow/ /var/lib/clickhouse/metadata/ > /var/lib/clickhouse/dir

WITH statement missed

Hi there,
thank you for the awesome library.

I found $withQueries is not working. The call to buildWithQueries in QueryBuilder::build looks missed.
Is it expected behavior or a bug?

thank you

The code polishing

Let's make the code more beautiful and compact :)

  1. You extended \yii\db\Command. It is ok. But you copy-pasted a lot of unnecessary code from a parent class to your child class. You should clean it up.

for example, properties
public $db;
public $params = [];
...
and so on
must be removed from your class
some unnecessary methods should be removed as well

I checked only Command class, but I guess other classes may be affected as well.
Please fix it.

  1. https://github.com/sanchezzzhak/kak-clickhouse/blob/master/Command.php#L332
    I guess preg_match may be replaced with stripos here

  2. to be continued :)

Strict field types

Реализую выдачу из ClickHouse в GridView с фильтрацией. Соответственно, использую SearchModel, расширяющую модель соответствующей таблицы.
В этой SearchModel есть следующий абстрактный код:
$query = Stat::find()->where(['user_string_id' => Yii::$app->user->identity->user_custom_id), 'user_int_id' => Yii::$app->user->identity->user_id,]);

Если в таком случае user_custom_id будет строкой, идентичной числу, в модель будет передано число и в запросе значение экранироваться не будет, не смотря на указание для этого поля в rules (['user_string_id','string']), что вызовет ошибку движка ClickHouse

DB::Exception: Illegal types of arguments (String, UInt8) of function equals.

Если возможно, приведение к типам, указанным в rules, было бы весьма полезным.

Multiple UNION ALL, Syntax error: failed at position XXX ('ALL'): ALL SELECT

In case of multiple UNIONS with HAVING conditions inside, there is an error:

Query error: Code: 62. DB::Exception: Syntax error: failed at position 968 ('ALL'): ALL SELECT a, b, c Expected one of: token, Dot, UUID, DoubleColon, MOD, DIV, NOT, BETWEEN, LIKE, ILIKE, NOT LIKE, NOT ILIKE, IN, NOT IN, GLOBAL IN, GLOBAL NOT IN, IS, AND, OR, QuestionMark, alias, AS, WINDOW, ORDER BY, LIMIT, OFFSET, SETTINGS, UNION, EXCEPT, INTERSECT. (SYNTAX_ERROR) (version 22.7.1.2484 (official build))

It happens because of missing space before UNION keyword.
Generated SQL looks like this:

...
SELECT a, b, c
FROM table.page_query_country pdgwt 
WHERE (date >= '2022-01-11' and date <= '2022-04-10') HAVING sum((column)) = 100UNION ALL SELECT a, b, c ...

$result .= 'UNION ' . ($union['all'] ? 'ALL ' : '') . $unions[$i]['query'];

I propose to change line 305 with:
$result .= 'UNION ' . ($union['all'] ? 'ALL ' : '') . '( ' . $unions[$i]['query'] . ' ) ';

->batch() and ->each() not working

I'm trying to go through a lot of records from my database to do some calculations, but to keep php memory low, I've tried using $query->batch() and $query->each(), note that $query is \kak\clickhouse\ActiveRecord instance and it throws the following exception
Exception 'Error' with message 'Call to a member function close() on array' on the line where ->batch() or ->each() were called.

I'm also using MySQL database in the same project and when getting data in batches from MySQL it works as expected.

Since this is a console part of the application, here's the full stach trace
Exception 'Error' with message 'Call to a member function close() on array'

in /websites/PROJECT/vendor/yiisoft/yii2/db/BatchQueryResult.php:87

Stack trace:
#0 /websites/PROJECT/vendor/yiisoft/yii2/db/BatchQueryResult.php(77): yii\db\BatchQueryResult->reset()
#1 /websites/PROJECT/console/controllers/SomeCronController.php(1249): yii\db\BatchQueryResult->__destruct()
#2 [internal function]: console\controllers\SomeCronController->actionSaveNgrams('48')
#3 /websites/PROJECT/vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array)
#4 /websites/PROJECT/vendor/yiisoft/yii2/base/Controller.php(157): yii\base\InlineAction->runWithParams(Array)
#5 /websites/PROJECT/vendor/yiisoft/yii2/console/Controller.php(148): yii\base\Controller->runAction('save-ngrams', Array)
#6 /websites/PROJECT/vendor/yiisoft/yii2/base/Module.php(528): yii\console\Controller->runAction('save-ngrams', Array)
#7 /websites/PROJECT/vendor/yiisoft/yii2/console/Application.php(180): yii\base\Module->runAction('expected-value-...', Array)
#8 /websites/PROJECT/vendor/yiisoft/yii2/console/Application.php(147): yii\console\Application->runAction('expected-value-...', Array)
#9 /websites/PROJECT/vendor/yiisoft/yii2/base/Application.php(386): yii\console\Application->handleRequest(Object(yii\console\Request))
#10 /websites/PROJECT/yii(31): yii\base\Application->run()
#11 {main}

Обработка {{%table_name}}

Похоже, что не работает обработка таблиц на подобии {{%table_name}}.

Запуск миграций выдает следующую ошибку:

Yii Migration Tool (based on Yii v2.0.17)

Creating migration history table "migration"...Exception 'yii\db\Exception' with message 'Need set specific settings for engine table'

in /vendor/kak/clickhouse/QueryBuilder.php:159

Stack trace:
#0 /vendor/yiisoft/yii2/db/Command.php(638): kak\clickhouse\QueryBuilder->createTable('{{%migration}}', Array, NULL)
#1 /vendor/yiisoft/yii2/console/controllers/MigrateController.php(271): yii\db\Command->createTable('{{%migration}}', Array)
#2 /vendor/yiisoft/yii2/console/controllers/MigrateController.php(211): yii\console\controllers\MigrateController->createMigrationHistoryTable()
#3 /vendor/yiisoft/yii2/console/controllers/BaseMigrateController.php(875): yii\console\controllers\MigrateController->getMigrationHistory(NULL)
#4 /vendor/yiisoft/yii2/console/controllers/BaseMigrateController.php(166): yii\console\controllers\BaseMigrateController->getNewMigrations()
#5 [internal function]: yii\console\controllers\BaseMigrateController->actionUp(0)
#6 /vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array)
#7 /vendor/yiisoft/yii2/base/Controller.php(157): yii\base\InlineAction->runWithParams(Array)
#8 /vendor/yiisoft/yii2/console/Controller.php(148): yii\base\Controller->runAction('up', Array)
#9 /vendor/yiisoft/yii2/base/Module.php(528): yii\console\Controller->runAction('up', Array)
#10 /vendor/yiisoft/yii2/console/Application.php(180): yii\base\Module->runAction('migrate/up', Array)
#11 /vendor/yiisoft/yii2/console/Application.php(147): yii\console\Application->runAction('migrate/up', Array)
#12 /vendor/yiisoft/yii2/base/Application.php(386): yii\console\Application->handleRequest(Object(yii\console\Request))
#13 /yii(23): yii\base\Application->run()
#14 {main}

Command::batchInsertFiles doesn't work

get error for table with name "stat":

Code: 36, e.displayText() = DB::Exception: Neither structure nor types have not been provided for external table stat. Use fields stat_structure or stat_types to do so., e.what() = DB::Exception

Добавить БД в \kak\clickhouse\Schema::loadTableSchema

Примерно так - http://joxi.ru/BA00j0TB4vJzAy

В процессе разработки набор и тип полей меняется, а в старых БД остается старая версия

  • string, а в новой UInt64.

Делая запрос SELECT * FROM system.columns WHERE table='tbl' FORMAT JSON

Оно получается данные сразу по всем БД и выпадает старый вариант, в итоге идет неправильный каст и ошибка

Code: 53, e.displayText() = DB::Exception: Type mismatch in IN or VALUES section. Expected: UInt64. Got: String, e.what() = DB::Exception

activerecord не загружает модели

При любом раскладе возвращает массив
как пример
TestModel::find()->one(); вернет массив
TestModel::find()->all(); вернет массив массивов
моделька ни разу не прогрузилась.

TestModel - https://github.com/sanchezzzhak/kak-clickhouse#activerecord-model
как тут, ничего лишнего только rules добавил, связей нет.

пока смог решить добавлением двух методов в класс kak\clickhouse\ActiveQuery из yii\db\ActiveQuery, методы one и populate

Что я не так делаю ? :(

Реализовать поддержку Array в batchInsert

В clickhouse можно создать колонки типа Array(UInt64) или массивы других типов. На данный момент в обертке в частности методе batchInsert нет поддержки таких колонок, было бы не плохо ее сделать.

Fix an exception message in the Command class

Fix
public function query() { throw new \yii\db\Exception('Clichouse unsupport cursor'); }
to
public function query() { throw new \yii\db\Exception('Clickhouse unsupported cursor'); }

UInt64 update/insert

В yii2\db\Schema.php:633 в функции getColumnPhpType() для UInt64 выставляется значение string. Это мешает вставлять и обновлять значения.
php не может работать с подобными числами, как вариант можно заменять такие строки на 'toUInt64($value)'

batchInsert сonverts float numbers to a string

Hello,
Im create array, in which there are numbers with a floating point
array(
null,
"94.180.249.59",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36",
"/test/test/test/",
200,
"GET",
"ddfdfdf",
55.796539,
49.1082,
"RU",
"Республика Татарстан",
"Казань",
1501228567
)
and I see raw sql $command->getRawSql();
"INSERT INTO logs (user_id, ip, agent, url, status, request_method, params, lat, lng, country, region, city, created_at) VALUES (NULL, '94.180.249.59', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36', '/test/test/test/', 200, 'GET', 'ddfdfdf', '55.796539', '49.1082', 'RU', 'Республика Татарстан', 'Казань', '1501228567'), (NULL, '94.180.249.59', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36', '/test/test/test/', 200, 'GET', 'ddfdfdf', '55.796539', '49.1082', 'RU', 'Республика Татарстан', 'Казань', '1501229092'), (NULL, '94.180.249.59', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36', '/test/test/test/', 200, 'GET', 'ddfdfdf', '55.796539', '49.1082', 'RU', 'Республика Татарстан', 'Казань', '1501229094')"

Incorrect response on ActiveRecord->count()

Hi, again.

I've found this issue when working with ActiveRestController.

Index action makes count(*) query (for pagination). So, your component return an array not scalar int value.

Little Example:
class Measuring extends \yii\db\ActiveRecord
class MeasuringReport extends \kak\clickhouse\ActiveRecord

var_dump(\app\models\Measuring::find()->count()); var_dump(\app\models\MeasuringReport::find()->count());
Response is:

int(4308936)
array(1) { [0]=> array(1) { ["COUNT()"]=> string(7) "4308936" } }

Now I'm thinking about way to fix it, we can think together))

Use of undefined constant CURLOPT_HTTP_VERSION - assumed 'CURLOPT_HTTP_VERSION' (this will throw an Error in a future version of PHP)

Не удается использовать миграцию из-за следующей ошибки в консоли:

Exception 'yii\base\Exception' with message 'Query error: Use of undefined constant CURLOPT_HTTP_VERSION - assumed 'CURLOPT_HTTP_VERSION' (this will throw an Error in a future version of PHP)'

in /vendor/kak/clickhouse/Command.php:271

Stack trace:
#0 /vendor/yiisoft/yii2/db/Command.php(399): kak\clickhouse\Command->queryInternal('fetchAll', NULL)
#1 /vendor/kak/clickhouse/Schema.php(168): yii\db\Command->queryAll()
#2 /vendor/yiisoft/yii2/db/Schema.php(744): kak\clickhouse\Schema->loadTableSchema('migration')
#3 /vendor/yiisoft/yii2/db/Schema.php(194): yii\db\Schema->getTableMetadata('{{%migration}}', 'schema', true)
#4 /vendor/yiisoft/yii2/console/controllers/MigrateController.php(210): yii\db\Schema->getTableSchema('{{%migration}}', true)
#5 /vendor/yiisoft/yii2/console/controllers/BaseMigrateController.php(875): yii\console\controllers\MigrateController->getMigrationHistory(NULL)
#6 /vendor/yiisoft/yii2/console/controllers/BaseMigrateController.php(166): yii\console\controllers\BaseMigrateController->getNewMigrations()
#7 [internal function]: yii\console\controllers\BaseMigrateController->actionUp(0)
#8 /vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array)
#9 /vendor/yiisoft/yii2/base/Controller.php(157): yii\base\InlineAction->runWithParams(Array)
#10 /vendor/yiisoft/yii2/console/Controller.php(148): yii\base\Controller->runAction('up', Array)
#11 /vendor/yiisoft/yii2/base/Module.php(528): yii\console\Controller->runAction('up', Array)
#12 /vendor/yiisoft/yii2/console/Application.php(180): yii\base\Module->runAction('migrate/up', Array)
#13 /vendor/yiisoft/yii2/console/Application.php(147): yii\console\Application->runAction('migrate/up', Array)
#14 /vendor/yiisoft/yii2/base/Application.php(386): yii\console\Application->handleRequest(Object(yii\console\Request))
#15 /yii(23): yii\base\Application->run()
#16 {main}

В чем может быть проблема?

"with totals" and rows_before_limit_at_least implementation

Let's imagine you need to show some stats in a table. The last row of the table must contain Total values. The table must have pagination as well.

Clickhouse allows to fetch all needed data in one query. for example

SELECT
    idsite,
    sum(impressions) AS impressions
FROM stat
GROUP BY idsite
WITH TOTALS
LIMIT 10
FORMAT JSON

as result you will get this json:
...
"totals":
{
"idsite": 0,
"impressions": "73886972"
},
"rows": 10,
"rows_before_limit_at_least": 226,
...

Consider to implement these very useful features.

Добавить нормальную реализацию join для КХ для QueryBuilder

К текущему join сделать ExeptionNotSupport так как структура запроса не работоспособная, ждем улучшения со стороны яндекса может они допилят работу join до стандарта

новый join будет работать согласно спецификации (по другому не умеет)

SELECT
   CounterID,
   hits,
   visits
FROM
(
   SELECT
       CounterID,
       count() AS hits
   FROM test.hits
   GROUP BY CounterID
) ANY LEFT JOIN
(
   SELECT
       CounterID,
       sum(Sign) AS visits
   FROM test.visits
   GROUP BY CounterID
) USING CounterID
ORDER BY hits DESC
LIMIT 10

Создадим 2 метода
using($columns) где $columns - это строка или массив колонк
queryJoin($type, $query) где $type [GLOBAL] ANY|ALL INNER|LEFT [OUTER]

Problem with batch/each on php8.1

During inheritance of Iterator: Uncaught yii\base\ErrorException: Return type of kak\clickhouse\BatchQueryResult::current() should either be compatible with Iterator::current(): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/html/app/vendor/kak/clickhouse/BatchQueryResult.php:153

composer install

andreybolonin@andreybolonin-MS-7817:~/www/kak-clickhouse$ composer inst
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - yiisoft/yii2 2.0.9 requires bower-asset/jquery 2.2.*@stable | 2.1.*@stable | 1.11.*@stable | 1.12.*@stable -> no matching package found.
    - yiisoft/yii2 2.0.8 requires bower-asset/jquery 2.2.*@stable | 2.1.*@stable | 1.11.*@stable -> no matching package found.
    - yiisoft/yii2 2.0.7 requires bower-asset/jquery 2.2.*@stable | 2.1.*@stable | 1.11.*@stable -> no matching package found.
    - yiisoft/yii2 2.0.6 requires bower-asset/jquery 2.1.*@stable | 1.11.*@stable -> no matching package found.
    - yiisoft/yii2 2.0.5 requires bower-asset/jquery 2.1.*@stable | 1.11.*@stable -> no matching package found.
    - yiisoft/yii2 2.0.4 requires bower-asset/jquery 2.1.*@stable | 1.11.*@stable -> no matching package found.
    - yiisoft/yii2 2.0.3 requires bower-asset/jquery 2.1.*@stable | 1.11.*@stable -> no matching package found.
    - yiisoft/yii2 2.0.2 requires bower-asset/jquery 2.1.*@stable | 1.11.*@stable -> no matching package found.
    - yiisoft/yii2 2.0.12 requires bower-asset/jquery 2.2.*@stable | 2.1.*@stable | 1.11.*@stable | 1.12.*@stable -> no matching package found.
    - yiisoft/yii2 2.0.11.2 requires bower-asset/jquery 2.2.*@stable | 2.1.*@stable | 1.11.*@stable | 1.12.*@stable -> no matching package found.
    - yiisoft/yii2 2.0.11.1 requires bower-asset/jquery 2.2.*@stable | 2.1.*@stable | 1.11.*@stable | 1.12.*@stable -> no matching package found.
    - yiisoft/yii2 2.0.11 requires bower-asset/jquery 2.2.*@stable | 2.1.*@stable | 1.11.*@stable | 1.12.*@stable -> no matching package found.
    - yiisoft/yii2 2.0.10 requires bower-asset/jquery 2.2.*@stable | 2.1.*@stable | 1.11.*@stable | 1.12.*@stable -> no matching package found.
    - yiisoft/yii2 2.0.1 requires bower-asset/jquery 2.1.*@stable | 1.11.*@stable -> no matching package found.
    - yiisoft/yii2 2.0.0 requires bower-asset/jquery 2.1.*@stable | 1.11.*@stable -> no matching package found.
    - Installation request for yiisoft/yii2 * -> satisfiable by yiisoft/yii2[2.0.0, 2.0.1, 2.0.10, 2.0.11, 2.0.11.1, 2.0.11.2, 2.0.12, 2.0.2, 2.0.3, 2.0.4, 2.0.5, 2.0.6, 2.0.7, 2.0.8, 2.0.9].

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.