nafigator/dbal-clickhouse

Doctrine DBAL ClickHouse 驱动

v1.5.2 2018-07-27 09:12 UTC

This package is auto-updated.

Last update: 2024-09-19 00:17:13 UTC


README

如果您想成为此包的维护者 -- 请通过a@mochalygin.ru联系我

Build Status Total Downloads Latest Stable Version License

Doctrine DBAL ClickHouse 驱动

Doctrine DBAL ClickHouse 驱动 -- 由 Yandex 开发的开源列式数据库管理系统 (https://clickhouse.yandex/)

该驱动程序适用于使用 Doctrine 的 Symfony 或任何其他框架。

安装

composer require friendsofdoctrine/dbal-clickhouse

初始化

自定义 PHP 脚本

$connectionParams = [
    'host' => 'localhost',
    'port' => 8123,
    'user' => 'default',
    'password' => '',
    'dbname' => 'default',
    'driverClass' => 'FOD\DBALClickHouse\Driver',
    'wrapperClass' => 'FOD\DBALClickHouse\Connection',
    'driverOptions' => [
        'extremes' => false,
        'readonly' => true,
        'max_execution_time' => 30,
        'enable_http_compression' => 0,
        'https' => false,
    ],
];
$conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, new \Doctrine\DBAL\Configuration());

driverOptions 是特殊的 smi2/phpclickhouse 客户端 设置

Symfony

配置...

# app/config/config.yml
doctrine:
    dbal:
        connections:
            clickhouse:
                host:     localhost
                port:     8123
                user:     default
                password: ""
                dbname:   default
                driver_class: FOD\DBALClickHouse\Driver
                wrapper_class: FOD\DBALClickHouse\Connection
                options:
                    enable_http_compression: 1
                    max_execution_time: 60
            #mysql:
            #   ...

...然后从服务容器中获取

$conn = $this->get('doctrine.dbal.clickhouse_connection');

用法

创建新表

// ***quick start***
$fromSchema = $conn->getSchemaManager()->createSchema();
$toSchema = clone $fromSchema;


// create new table object
$newTable = $toSchema->createTable('new_table');

// add columns
$newTable->addColumn('id', 'integer', ['unsigned' => true]);
$newTable->addColumn('payload', 'string', ['notnull' => false]);
// *option 'notnull' in false mode allows you to insert NULL into the column; 
//                   in this case, the column will be represented in the ClickHouse as Nullable(String)
$newTable->addColumn('hash', 'string', ['length' => 32, 'fixed' => true]);
// *option 'fixed' sets the fixed length of a string column as specified; 
//                 if specified, the type of the column is FixedString

//set primary key
$newTable->setPrimaryKey(['id']);


// execute migration SQLs to create table in ClickHouse
$sqlArray = $fromSchema->getMigrateToSql($toSchema, $conn->getDatabasePlatform());
foreach ($sqlArray as $sql) {
    $conn->exec($sql);
}
// ***more options (optional)***

//specify table engine
$newTable->addOption('engine', 'MergeTree');
// *if not specified -- default engine 'ReplacingMergeTree' will be used


// add Date column for partitioning
$newTable->addColumn('event_date', 'date', ['default' => 'toDate(now())']);
$newTable->addOption('eventDateColumn', 'event_date');
// *if not specified -- default Date column named EventDate will be added
$newTable->addOption('eventDateProviderColumn', 'updated_at');
// *if specified -- event date column will be added with default value toDate(updated_at); 
//    if the type of the provider column is `string`, the valid format of provider column values must be either `YYYY-MM-DD` or `YYYY-MM-DD hh:mm:ss`
//    if the type of provider column is neither `string`, nor `date`, nor `datetime`, provider column values must contain a valid UNIX Timestamp
$newTable->addOption('samplingExpression', 'intHash32(id)');
// samplingExpression -- a tuple that defines the table's primary key, and the index granularity

//specify index granularity
$newTable->addOption('indexGranularity', 4096);
// *if not specified -- default value 8192 will be used

插入

// 1
$conn->exec("INSERT INTO new_table (id, payload) VALUES (1, 'dummyPayload1')");
// 2
$conn->insert('new_table', ['id' => 2, 'payload' => 'dummyPayload2']);
// INSERT INTO new_table (id, payload) VALUES (?, ?) [2, 'dummyPayload2']
// 3 via QueryBuilder
$qb = $conn->createQueryBuilder();

$qb
    ->insert('new_table')
    ->setValue('id', ':id')
    ->setValue('payload', ':payload')
    ->setParameter('id', 3, \PDO::PARAM_INT) // need to explicitly set param type to `integer`, because default type is `string` and ClickHouse doesn't like types mismatchings
    ->setParameter('payload', 'dummyPayload3');

$qb->execute();

选择

echo $conn->fetchColumn('SELECT SUM(views) FROM articles');

使用动态参数和预处理语句选择

$stmt = $conn->prepare('SELECT authorId, SUM(views) AS total_views FROM articles WHERE category_id = :categoryId AND publish_date = :publishDate GROUP BY authorId');

$stmt->bindValue('categoryId', 123);
$stmt->bindValue('publishDate', new \DateTime('2017-02-29'), 'datetime');
$stmt->execute();

while ($row = $stmt->fetch()) {
    echo $row['authorId'] . ': ' . $row['total_views'] . PHP_EOL;
}

使用数组作为值的占位符选择

$stmt = $conn->prepare('SELECT authorId FROM articles WHERE categoryId IN (:categoryIds)');

$stmt->bindValue('categoryIds', [123, 124], \Doctrine\DBAL\Connection::PARAM_INT_ARRAY);
$stmt->execute();
$result = $stmt->fetchAll();
$stmt = $conn->prepare('SELECT authorId FROM articles WHERE categoryName IN (:categoryNames)');

$stmt->bindValue('categoryNames', ['Auto', 'News'], \Doctrine\DBAL\Connection::PARAM_STR_ARRAY);
$stmt->execute();
$result = $stmt->fetchAll();

附加类型

如果您想使用 Array(T) 类型,请注册额外的 DBAL 类型到您的代码中

// register all custom DBAL Array types
ArrayType::registerArrayTypes($conn->getDatabasePlatform());
// register one custom DBAL Array(Int8) type
Type::addType('array(int8)', 'FOD\DBALClickHouse\Types\ArrayInt8Type');

或在 Symfony 配置文件中注册它们

# app/config/config.yml
doctrine:
    dbal:
        connections:
        ...
        types:
            array(int8): FOD\DBALClickHouse\Types\ArrayInt8Type
            array(int16): FOD\DBALClickHouse\Types\ArrayInt16Type
            array(int32): FOD\DBALClickHouse\Types\ArrayInt32Type
            array(int64): FOD\DBALClickHouse\Types\ArrayInt64Type
            array(uint8): FOD\DBALClickHouse\Types\ArrayUInt8Type
            array(uint16): FOD\DBALClickHouse\Types\ArrayUInt16Type
            array(uint32): FOD\DBALClickHouse\Types\ArrayUInt32Type
            array(uint64): FOD\DBALClickHouse\Types\ArrayUInt64Type
            array(float32): FOD\DBALClickHouse\Types\ArrayFloat32Type
            array(float64): FOD\DBALClickHouse\Types\ArrayFloat64Type
            array(string): FOD\DBALClickHouse\Types\ArrayStringType
            array(datetime): FOD\DBALClickHouse\Types\ArrayDateTimeType
            array(date): FOD\DBALClickHouse\Types\ArrayDateType

附加类型 BigIntType 帮助您将 bigint 值存储为 ClickHouse 中的 Int64/UInt64 值类型。您可以在代码中覆盖 DBAL 类型

Type::overrideType(Type::BIGINT, 'FOD\DBALClickHouse\Types\BigIntType');

或使用自定义映射类型在 Symfony 配置中

# app/config/config.yml
doctrine:
    dbal:
        types:
            bigint:  FOD\DBALClickHouse\Types\BigIntType
            ...

更多详细信息请参阅 Doctrine DBAL 文档