22h / questdb-client
A PHP rest client library for QuestDB time-series database
Installs: 37
Dependents: 1
Suggesters: 0
Security: 0
Stars: 2
Forks: 0
pkg:composer/22h/questdb-client
Requires
- php: ^8.4
- php-http/client-common: ^2.7
- php-http/discovery: ^1.0
- php-http/httplug: ^2.0
- php-http/multipart-stream-builder: ^1.4
- psr/http-client-implementation: ^1.0
- psr/http-factory: ^1.0
- psr/http-message: ^2.0
- psr/log: ^1.0|^2.0|^3.0
Requires (Dev)
- guzzlehttp/guzzle: ^7.9.2
- php-http/mock-client: ^1.0
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^11.0
- slevomat/coding-standard: ^8.20
- squizlabs/php_codesniffer: ^3.13
- symfony/var-dumper: ^7.3
README
A PHP REST client library for QuestDB time-series database.
This repository is experimental.
Overview
This library provides a simple way to interact with QuestDB's REST API. It allows you to execute SQL queries, import and export data in QuestDB. This client provides a clean and consistent interface for working with QuestDB.
Requirements
- PHP 8.4 or higher
- PSR-17 and PSR-18 compatible HTTP client
Installation
composer require 22h/questdb-client
This package is decoupled from any HTTP messaging client, you can visit HTTPlug for library users to get more information about installing HTTPlug related packages.
Usage
Client Initialization
use TwentyTwo\QuestDB\Client;
// Create a client instance
$client = new Client();
// Set the QuestDB server URL
$client->setUrl('http://localhost:9000');
// Alternatively, set the URL during initialization
$client = new Client(url: 'http://localhost:9000');
Executing SQL Queries
// Simple select query
$results = $client->execute()->select('SELECT * FROM trades LIMIT 10');
// Count query
$count = $client->execute()->count('SELECT COUNT(*) FROM trades');
// Execute with options (metadata, timings, explain)
$options = new ExecuteOptions();
$options->showMetadata();
$options->showTimings();
$options->showExplain();
$result = $client->execute()->selectWithOptions('SELECT * FROM trades LIMIT 10', $options);
// Create Tables, insert rows and update rows
$result = $client->execute()->execute('CREATE TABLE trades [...];');
SQL Helper (SqlHelper)
Use TwentyTwo\QuestDB\Utils\SqlHelper to build safe SQL strings or to bind parameters into existing queries. This is useful when you need to compose queries programmatically without a database driver.
Insert helper: SqlHelper::insert(string $table, array $data): string
- Accepts either a single associative array (one row) or an array of associative arrays (multiple rows).
- Quotes identifiers (table and column names) with double quotes.
- Quotes and escapes values. Numbers are not quoted, booleans become
true/false,nullbecomesNULL. - Missing columns in multi-row input are filled with
NULL.
use TwentyTwo\QuestDB\Utils\SqlHelper;
// Single row
$sql = SqlHelper::insert('trades', [
'symbol' => 'BTC',
'price' => 50000.5,
'side' => 'buy',
]);
// INSERT INTO "trades" ("symbol", "price", "side") VALUES ('BTC', 50000.5, 'buy')
// Multiple rows
$sql = SqlHelper::insert('trades', [
['symbol' => 'BTC', 'price' => 50000.0],
['symbol' => 'ETH', 'price' => 3000.0],
]);
// INSERT INTO "trades" ("symbol", "price") VALUES ('BTC', 50000), ('ETH', 3000)
// Execute the generated SQL
$client->execute()->execute($sql);
Parameter binding: SqlHelper::bindQuery(string $query, array $params = []): string
[!WARNING] Parameter binding is currently experimental and should be used with caution.
- Supports named placeholders (
:name) and positional placeholders (?). - Skips replacements inside string literals and quoted identifiers.
- Throws
InvalidArgumentExceptionwhen the number of?placeholders doesn't match the number of positional parameters.
use TwentyTwo\QuestDB\Utils\SqlHelper;
// Named parameters
$sql = SqlHelper::bindQuery(
'SELECT * FROM trades WHERE symbol = :symbol AND price > :price AND active = :active',
['symbol' => 'BTC', 'price' => 50000.5, 'active' => true]
);
// SELECT * FROM trades WHERE symbol = 'BTC' AND price > 50000.5 AND active = true
// Positional parameters
$sql = SqlHelper::bindQuery(
'SELECT * FROM trades WHERE symbol = ? AND amount > ?',
['BTC', 100]
);
// SELECT * FROM trades WHERE symbol = 'BTC' AND amount > 100
// Convenience via client
$sql = $client->prepare('SELECT * FROM trades WHERE symbol = :symbol', ['symbol' => 'BTC']);
$rows = $client->execute()->select($sql);
Note: SqlHelper is marked experimental and may change in future versions.
Table Operations
// Get a table instance
$table = $client->table('trades');
// Get table columns
$columns = $table->columns();
// Get table partitions
$partitions = $table->partitions();
// Get CREATE TABLE statement
$createStatement = $table->showCreate();
// Drop a table
$table->drop(); // With IF EXISTS
$table->drop(false); // Without IF EXISTS
Importing Data
// Import from a CSV file
$client->import()->file('/path/to/data.csv');
// Import with custom table name
$options = new ImportOptions();
$options->setName('custom_table_name');
$client->import()->file('/path/to/data.csv', options: $options);
// Import from a resource
$resource = fopen('/path/to/data.csv', 'r');
$client->import()->resource($resource, options: $options);
Exporting Data
// Export query results to a stream
$stream = $client->export()->resource('SELECT * FROM trades;');
// Export with limit and offset
$stream = $client->export()->resource('SELECT * FROM trades;', limit: 100, offset: 200);
// Export to a file
$client->export()->file('/path/to/output.csv', 'SELECT * FROM trades;');
Meta Information
// Get QuestDB server version
$version = $client->meta()->version();
// Get QuestDB build information
$build = $client->meta()->build();
// List all tables
$tables = $client->meta()->tables();
// Get detailed table metadata
$tablesWithMetadata = $client->meta()->tablesWithMetadata();
// Get server parameters
$parameters = $client->meta()->parameters();
// Get available functions
$functions = $client->meta()->functions();
// Get query activity
$queryActivity = $client->meta()->queryActivity();
// Get memory metrics
$memoryMetrics = $client->meta()->memoryMetrics();
// Flush query cache
$client->meta()->flushQueryCache();
Basic Auth
// Simple way
$client->authenticateWithBasicAuth('username', 'password');
// Another way
use Http\Client\Common\Plugin\AuthenticationPlugin;
use Http\Message\Authentication\BasicAuth;
$clientBuilder = new ClientBuilder();
$clientBuilder->addPlugin(new AuthenticationPlugin(new BasicAuth('username', 'password')));
$client = new Client($clientBuilder);
Documentation
For more information about QuestDB, please refer to the official documentation.
Credits
Inspired by the structure of GitLabPHP/Client.
License
This library is released under the MIT License. See the LICENSE file for details.