simpod/clickhouse-client 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

simpod/clickhouse-client

Composer 安装命令:

composer require simpod/clickhouse-client

包简介

PHP ClickHouse Client

README 文档

README

Build Status Code Coverage Downloads Infection MSI

Motivation

The library is trying not to hide any ClickHouse HTTP interface specific details. That said everything is as much transparent as possible and so object-oriented API is provided without inventing own abstractions.
Naming used here is the same as in ClickHouse docs.

Contents

Setup

composer require simpod/clickhouse-client  
  1. Read about ClickHouse Http Interface. It's short and useful for concept understanding.
  2. Create a new instance of ClickHouse client and pass PSR factories.
    1. Symfony HttpClient is recommended (performance, less bugs, maintenance)
    2. The plot twist is there's no endpoint/credentials etc. config in this library, provide it via client
  3. See tests
<?php

use Http\Client\Curl\Client;
use Nyholm\Psr7\Factory\Psr17Factory;
use SimPod\ClickHouseClient\Client\PsrClickHouseClient;
use SimPod\ClickHouseClient\Client\Http\RequestFactory;
use SimPod\ClickHouseClient\Param\ParamValueConverterRegistry;

$psr17Factory = new Psr17Factory;

$clickHouseClient = new PsrClickHouseClient(
    new Client(),
    new RequestFactory(
        new ParamValueConverterRegistry(),
        $psr17Factory,
        $psr17Factory
    ),
    new LoggerChain(),
    [],
);

Symfony HttpClient Example

Configure HTTP Client

As said in ClickHouse HTTP Interface spec, we use headers to auth and e.g. set default database via query.

framework:
    http_client:
        scoped_clients:
            click_house.client:
                base_uri: '%clickhouse.endpoint%'
                headers:
                    'X-ClickHouse-User': '%clickhouse.username%'
                    'X-ClickHouse-Key': '%clickhouse.password%'
                query:
                    database: '%clickhouse.database%'

PSR Factories who?

The library does not implement it's own HTTP. That has already been done via PSR-7, PSR-17 and PSR-18. This library respects it and allows you to plug your own implementation (eg. HTTPPlug or Guzzle).

Recommended are composer require nyholm/psr7 for PSR-17 and composer require php-http/curl-client for Curl PSR-18 implementation (used in example above).

Sync API

Select

ClickHouseClient::select()

Intended for SELECT and SHOW queries. Appends FORMAT to the query and returns response in selected output format:

<?php

use SimPod\ClickHouseClient\Client\ClickHouseClient;
use SimPod\ClickHouseClient\Format\JsonEachRow;
use SimPod\ClickHouseClient\Output;

/** @var ClickHouseClient $client */
/** @var Output\JsonEachRow $output */
$output = $client->select(
    'SELECT * FROM table',
    new JsonEachRow(),
    ['force_primary_key' => 1]
);

Select With Params

ClickHouseClient::selectWithParams()

Same as ClickHouseClient::select() except it also allows parameter binding.

<?php

use SimPod\ClickHouseClient\Client\ClickHouseClient;
use SimPod\ClickHouseClient\Format\JsonEachRow;
use SimPod\ClickHouseClient\Output;

/** @var ClickHouseClient $client */
/** @var Output\JsonEachRow $output */
$output = $client->selectWithParams(
    'SELECT * FROM :table',
    ['table' => 'table_name'],
    new JsonEachRow(),
    ['force_primary_key' => 1]
);

Insert

ClickHouseClient::insert()

<?php

use SimPod\ClickHouseClient\Client\ClickHouseClient;

/** @var ClickHouseClient $client */
$client->insert('table', $data, $columnNames);

If $columnNames is provided and is key->value array column names are generated based on it and values are passed as parameters:

$client->insert( 'table', [[1,2]], ['a' => 'Int8, 'b' => 'String'] ); generates INSERT INTO table (a,b) VALUES ({p1:Int8},{p2:String}) and values are passed along the query.

If $columnNames is provided column names are generated based on it:

$client->insert( 'table', [[1,2]], ['a', 'b'] ); generates INSERT INTO table (a,b) VALUES (1,2).

If $columnNames is omitted column names are read from $data:

$client->insert( 'table', [['a' => 1,'b' => 2]]); generates INSERT INTO table (a,b) VALUES (1,2).

Column names are read only from the first item:

$client->insert( 'table', [['a' => 1,'b' => 2], ['c' => 3,'d' => 4]]); generates INSERT INTO table (a,b) VALUES (1,2),(3,4).

If not provided they're not passed either:

$client->insert( 'table', [[1,2]]); generates INSERT INTO table VALUES (1,2).

Async API

Select

Parameters "binding"

<?php

use SimPod\ClickHouseClient\Sql\SqlFactory;
use SimPod\ClickHouseClient\Sql\ValueFormatter;

$sqlFactory = new SqlFactory(new ValueFormatter());

$sql = $sqlFactory->createWithParameters(
    'SELECT :param',
    ['param' => 'value']
);

This produces SELECT 'value' and it can be passed to ClickHouseClient::select().

Supported types are:

  • scalars
  • DateTimeInterface
  • Expression
  • objects implementing __toString()

Native Query Parameters

Tip

Official docs

<?php

use SimPod\ClickHouseClient\Client\PsrClickHouseClient;

$client = new PsrClickHouseClient(...);

$output = $client->selectWithParams(
    'SELECT {p1:String}',
    ['param' => 'value']
);

All types are supported (except AggregateFunction, SimpleAggregateFunction and Nothing by design). You can also pass DateTimeInterface into Date* types or native array into Array, Tuple, Native and Geo types

Custom Query Parameter Value Conversion

Query parameters passed to selectWithParams() are converted into an HTTP-API-compatible format. To overwrite an existing value converter or provide a converter for a type that the library does not (yet) support, pass these to the SimPod\ClickHouseClient\Param\ParamValueConverterRegistry constructor:

<?php

use SimPod\ClickHouseClient\Client\Http\RequestFactory;
use SimPod\ClickHouseClient\Client\PsrClickHouseClient;
use SimPod\ClickHouseClient\Exception\UnsupportedParamValue;
use SimPod\ClickHouseClient\Param\ParamValueConverterRegistry;

$paramValueConverterRegistry = new ParamValueConverterRegistry([
    'datetime' => static fn (mixed $v) => $v instanceof DateTimeInterface ? $v->format('c') : throw UnsupportedParamValue::type($value)
]);

$client = new PsrClickHouseClient(..., new RequestFactory($paramValueConverterRegistry, ...));

Be aware that the library can not ensure that passed values have a certain type. They are passed as-is and closures must accept mixed values.

Throw an exception of type UnsupportedParamValue if your converter does not support the passed value type.

Expression

To represent complex expressions there's SimPod\ClickHouseClient\Sql\Expression class. When passed to SqlFactory its value gets evaluated.

To pass eg. UUIDStringToNum('6d38d288-5b13-4714-b6e4-faa59ffd49d8') to SQL:

<?php

use SimPod\ClickHouseClient\Sql\Expression;

Expression::new("UUIDStringToNum('6d38d288-5b13-4714-b6e4-faa59ffd49d8')");
<?php

use SimPod\ClickHouseClient\Sql\ExpressionFactory;
use SimPod\ClickHouseClient\Sql\ValueFormatter;

$expressionFactory = new ExpressionFactory(new ValueFormatter());

$expression = $expressionFactory->templateAndValues(
    'UUIDStringToNum(%s)',
    '6d38d288-5b13-4714-b6e4-faa59ffd49d8'
);

Snippets

There are handy queries like getting database size, table list, current database etc.

To prevent Client API pollution, those are extracted into Snippets.

Example to obtain current database name:

<?php

use SimPod\ClickHouseClient\Snippet\CurrentDatabase;

$currentDatabaseName = CurrentDatabase::run($client);

List

  • CurrentDatabase
  • DatabaseSize
  • Parts
  • ShowCreateTable
  • ShowDatabases
  • TableSizes
  • Version

simpod/clickhouse-client 适用场景与选型建议

simpod/clickhouse-client 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 130.62k 次下载、GitHub Stars 达 19, 最近一次更新时间为 2020 年 01 月 18 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「php」 「http」 「http client」 「client」 「clickhouse」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 simpod/clickhouse-client 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 simpod/clickhouse-client 我们能提供哪些服务?
定制开发 / 二次开发

基于 simpod/clickhouse-client 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 130.62k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 19
  • 点击次数: 20
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 19
  • Watchers: 1
  • Forks: 3
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2020-01-18