hyvor/clickhouse-php

PHP的ClickhouseDB客户端

1.0.1 2023-03-14 10:09 UTC

This package is auto-updated.

Last update: 2024-09-13 17:37:37 UTC


README

这是一个针对PHP的Clickhouse HTTP接口的包装器。它支持会话、选择和插入,以及带参数的查询。

安装

composer require hyvor/clickhouse-php

连接

<?php
use Hyvor\Clickhouse\Clickhouse;

$clickhouse = new Clickhouse(
    host: 'localhost',
    port: 8123,
    user: 'default',
    password: '',
    database: 'default',
);

选择

选择多行

$results = $clickhouse->select(
    'SELECT * FROM users WHERE id < {id: UInt32}',
     ['id' => 10]
);

// get rows as arrays
$results->all(); // [[1, 'John'], [2, 'Jane']]

// get the first row
$results->first(); // [1, 'John']

// get the first column of the first row
// useful for aggregations like COUNT(*)
$results->value(); // 2

// loop through the rows
foreach ($results as $row) {
    // $row is an array
}

// properties
$results->rows; // int (same as $results->count())
$results->rowsBeforeLimitAtLeast; // null | int
$results->elapsedTimeSeconds; // float
$results->rowsRead; // int
$results->bytesRead; // int

插入

插入单行

使用insert方法插入新行。

参数

参数1:表名 参数2:列和值的类型键值对 参数3...:要插入的行

$clickhouse->insert(
    'users',
    [
        'id' => 'UInt64',
        'name' => 'String',
        'age' => 'UInt8',
    ],
    [
        'id' => 1, 
        'name' => 'John', 
        'age' => 42
    ]
)

在SQL中,这将是

INSERT INTO users (id, name, age) VALUES ({id: Int64}, {name: String}, {age: Int64})

插入多行

要插入多行,请将多个参数(数组)传递到末尾

$clickhouse->insert(
    'users',
    [
        'id' => 'UInt64',
        'name' => 'String',
        'age' => 'UInt8',
    ],
    ['id' => 1, 'name' => 'John', 'age' => 42],
    ['id' => 2, 'name' => 'Jane', 'age' => 37],
    ['id' => 3, 'name' => 'Bob', 'age' => 21],
)

其他查询

您可以使用query()运行任何其他查询。响应以Clickhouse的JSONCompact格式返回。

$clickhouse->query('DROP TABLE users');
// with params
$clickhouse->query('QUERY', ['param' => 1]);

会话

每个Hyvor\Clickhouse\Clickhouse对象创建一个新的会话ID。您可以使用此ID在多个请求之间共享会话。

$clickhouse = new Clickhouse();

// example:
// by default, Clickhouse update mutations are async
// here, we set mutations to sync
$clickhouse->query('SET mutations_sync = 1');

// all queries in this session (using the same $clickhouse object) will be sync
$clickhouse->query(
    'ALTER TABLE users UPDATE name = {name: String} WHERE id = 1', 
    ['name' => 'John']
);