22h / questdb-client
PHP client for the REST API of the QuestDB time-series database
Requires
- php: ^8.4
- php-http/client-common: ^2.7
- php-http/discovery: ^1.0
- php-http/httplug: ^2.0
- php-http/message: ^1.16
- php-http/multipart-stream-builder: ^1.4
- psr/http-client-implementation: ^1.0
- psr/http-factory: ^1.1
- psr/http-message: ^2.0
- psr/log: ^1.1 || ^2.0 || ^3.0
Requires (Dev)
- carthage-software/mago: ^1.60.1
- guzzlehttp/guzzle: ^7.9.2 || ^8
- infection/infection: ^0.35.11
- php-http/mock-client: ^1.0
- phpstan/extension-installer: ^1.4
- phpstan/phpstan: ^2.3.5
- phpstan/phpstan-deprecation-rules: ^2.0.5
- phpstan/phpstan-phpunit: ^2.1.2
- phpstan/phpstan-strict-rules: ^2.1.1
- phpunit/phpunit: ^13.4
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
A PHP client for the REST API of the QuestDB time-series database: run SQL, import CSV files and export query results.
The library is still in the 0.x phase, minor versions may contain breaking changes (see CHANGELOG and UPGRADE-0.3).
Requirements
- PHP 8.4 or higher
- QuestDB 9.3 or newer (tested with 9.3.3, 9.4.3 and 10.0.1)
- A PSR-18 HTTP client and PSR-17 factories, e.g.
guzzlehttp/guzzleorsymfony/http-client+nyholm/psr7
Installation
composer require 22h/questdb-client
The HTTP client is discovered automatically, see HTTPlug for library users.
Usage
Client
use TwentyTwo\QuestDB\Client;
$client = new Client('http://localhost:9000');
// behind a reverse proxy, the path is kept
$client = new Client('https://example.com/questdb');
// authentication, use HTTPS
$client->authenticateWithBasicAuth('admin', 'quest');
$client->authenticateWithToken('rest-token'); // QuestDB Enterprise
To use a specific HTTP client or additional HTTPlug plugins
(retry, logging, ...), pass a ClientBuilder:
use Http\Client\Common\Plugin\RetryPlugin;
use TwentyTwo\QuestDB\Http\ClientBuilder;
$builder = new ClientBuilder($psr18Client);
$builder->addPlugin(new RetryPlugin());
$client = new Client('http://localhost:9000', $builder);
Logging
Pass a PSR-3 logger to see what the client does. In Symfony the logger is
injected automatically, the client implements LoggerAwareInterface.
$client = new Client('http://localhost:9000', logger: $logger);
$client->setLogger($logger);
| Level | Logged when | Context |
|---|---|---|
debug | every successful request | method, endpoint, sql, status, duration_ms |
info | QuestDB rejects a request (HTTP 4xx), the call throws anyway | as above plus error |
info | an import finished | table, rows_imported, rows_rejected |
warning | QuestDB is not reachable or answers with HTTP 5xx | method, endpoint, sql, error, duration_ms |
warning | an import rejected rows | table, rows_imported, rows_rejected |
Headers are never logged, so credentials stay out of the logs. The sql contains the bound values (cut after
1024 characters), keep that in mind before enabling the debug level for sensitive data.
Queries
All query methods accept parameters, either positional (? with a list) or named (:name with an associative
array). The REST API of QuestDB has no server-side binding, the values are quoted by SqlHelper (see below).
$execute = $client->execute();
$rows = $execute->fetchAllAssociative('SELECT * FROM trades WHERE symbol = ?', ['BTC-USD']);
// [['symbol' => 'BTC-USD', 'side' => 'sell', 'price' => 39269.98, ...], ...]
$rows = $execute->fetchAllNumeric('SELECT symbol, price FROM trades LIMIT 10');
// [['BTC-USD', 39269.98], ...]
$prices = $execute->fetchFirstColumn('SELECT price FROM trades WHERE ts IN :day', ['day' => '2024-01-01']);
$trade = $execute->fetchAssociative('SELECT * FROM trades WHERE id = :id', ['id' => 42]); // first row or null
$count = $execute->fetchOne('SELECT count() FROM trades'); // first value or null
select() returns a QueryResult with rows, column metadata, timings and query plan:
use TwentyTwo\QuestDB\Request\ExecuteOptions;
$options = new ExecuteOptions()
->limit(100, 200) // 100 rows, skip the first 200
->withTotalCount() // getCount() returns the number of all rows, ignoring the limit
->withTimings()
->withExplain();
$result = $execute->select('SELECT * FROM trades', [], $options);
$result->getAssociativeRows();
$result->getRows();
$result->getColumns(); // [['name' => 'symbol', 'type' => 'SYMBOL'], ...]
$result->getCount();
$result->getTimings();
$result->getExplain();
count($result); // number of returned rows
Statements without rows (DDL, INSERT, UPDATE, ...) return a StatementResult:
$execute->execute('CREATE TABLE trades (symbol SYMBOL, price DOUBLE, ts TIMESTAMP) TIMESTAMP(ts) PARTITION BY DAY');
$result = $execute->execute('UPDATE trades SET price = :price WHERE symbol = :symbol', ['price' => 1.5, 'symbol' => 'BTC']);
$result->getMessage(); // "OK"
$result->getUpdatedRows();
Inserts
$execute->insert('trades', ['symbol' => 'BTC', 'price' => 50000.5, 'ts' => new DateTimeImmutable()]);
$execute->insert('trades', [
['symbol' => 'BTC', 'price' => 50000.5, 'ts' => new DateTimeImmutable()],
['symbol' => 'ETH', 'price' => 3000.0, 'ts' => new DateTimeImmutable()],
]);
/exec only accepts the query in the URL, so large inserts are split into several statements of at most 8000
URL-encoded bytes (third argument of insert()). The statements are not atomic. For bulk loads use the CSV
import or the ILP protocol.
SqlHelper
TwentyTwo\QuestDB\Sql\SqlHelper builds SQL strings with quoted values, the query methods above use it.
use TwentyTwo\QuestDB\Sql\SqlHelper;
SqlHelper::bind('SELECT * FROM trades WHERE symbol = :symbol AND price > :price', ['symbol' => 'BTC', 'price' => 1.5]);
// SELECT * FROM trades WHERE symbol = 'BTC' AND price > 1.5
SqlHelper::bind('SELECT * FROM trades WHERE symbol IN (?)', [['BTC', 'ETH']]);
// SELECT * FROM trades WHERE symbol IN ('BTC', 'ETH')
SqlHelper::insert('trades', ['symbol' => 'BTC', 'price' => 50000.5]);
// INSERT INTO "trades" ("symbol", "price") VALUES ('BTC', 50000.5)
SqlHelper::quoteValue(new DateTimeImmutable('2024-01-01 10:00:00.123456+01:00'));
// '2024-01-01T09:00:00.123456Z'
SqlHelper::quoteIdentifier('trades');
// "trades"
- Placeholders inside string literals, quoted identifiers and comments are not replaced,
::casts are kept. - Every placeholder needs a parameter and every parameter must be used, otherwise an
InvalidArgumentExceptionis thrown. Positional and named placeholders cannot be mixed. - Supported values:
null,bool,int, finitefloat,string,DateTimeInterface(UTC with microseconds),BackedEnum,Stringableand non-empty arrays of those (comma separated, forIN). - Identifiers containing
"or control characters are rejected, QuestDB has no escape sequence for them.
Tables, views and materialized views
$table = $client->table('trades');
$table->exists();
$table->info(); // row of tables(): partitioning, WAL, dedup, TTL, row count, ...
$table->storage(); // partition count, row count, disk size
$table->walStatus(); // suspended flag, writer/sequencer transactions, errors
$table->columns(); // [['column' => 'symbol', 'type' => 'SYMBOL', ...], ...]
$table->partitions();
$table->showCreate();
$table->waitForWal(); // wait until committed WAL transactions are visible
$table->resumeWal(); // resume a suspended WAL table, optionally from a transaction
$table->truncate();
$table->vacuum();
$table->drop(); // throws TableNotExistsException when it does not exist
$table->dropIfExists();
$view = $client->materializedView('trades_1h');
$view->exists();
$view->info(); // row of materialized_views(): base table, status, invalidation reason, ...
$view->storage();
$view->columns();
$view->partitions();
$view->showCreate();
$view->refresh(); // incremental
$view->refreshFull();
$view->refreshRange(new DateTimeImmutable('2024-01-01'), new DateTimeImmutable('2024-01-02'));
$view->waitForRefresh(); // wait until the view contains all commits of the base table
$view->resumeWal();
$view->drop(); // throws ViewNotExistsException when it does not exist
$view->dropIfExists();
$view = $client->view('latest_trades');
$view->exists();
$view->info(); // row of views(): SQL, status, invalidation reason
$view->columns();
$view->showCreate();
$view->compile();
$view->drop();
$view->dropIfExists();
Materialized views refresh asynchronously, use waitForRefresh() before reading data you just inserted into the
base table. It throws when the view is invalid (e.g. after a TRUNCATE of the base table, fix it with
refreshFull()). Explicit full and range refreshes cannot be awaited, QuestDB reports no reliable completion
for them.
Import
use TwentyTwo\QuestDB\Request\Atomicity;
use TwentyTwo\QuestDB\Request\ImportOptions;
use TwentyTwo\QuestDB\Request\PartitionBy;
// the file name becomes the table name
$result = $client->import()->file('/path/to/trades.csv');
$options = new ImportOptions()
->name('trades')
->timestamp('ts')
->partitionBy(PartitionBy::DAY)
->column('ts', 'TIMESTAMP', 'yyyy-MM-dd HH:mm:ss')
->column('price', 'DOUBLE')
->atomicity(Atomicity::SKIP_ROW);
$result = $client->import()->file('/path/to/trades.csv', $options);
$result = $client->import()->stream(fopen('php://temp', 'r+'), 'trades.csv', $options);
$result->getTable();
$result->getRowsImported();
$result->getRowsRejected();
file() only accepts local files. Do not pass unvalidated user input, the file is uploaded to QuestDB. Failed
imports throw an ImportException, rejected rows (see Atomicity) are reported in the result.
Tables created by an import with a designated timestamp are WAL tables, their rows become visible asynchronously.
Export
use TwentyTwo\QuestDB\Request\ExportOptions;
$stream = $client->export()->stream('SELECT * FROM trades WHERE symbol = ?', ['BTC']); // CSV as PSR-7 stream
$client->export()->toFile('/path/to/trades.csv', 'SELECT * FROM trades', [], new ExportOptions()->limit(1000, 2000));
Server information
$meta = $client->meta();
$meta->version();
$meta->build();
$meta->dataId(); // UUID of the database
$meta->currentUser();
$meta->tables(); // names of all tables, views and materialized views
$meta->tablesWithMetadata();
$meta->materializedViews();
$meta->views();
$meta->liveViews(); // QuestDB 10+
$meta->walTables();
$meta->tableStorage();
$meta->databaseSchema(); // CREATE statements of everything, QuestDB 10+
$meta->parameters();
$meta->functions();
$meta->queryActivity();
$meta->cancelQuery($queryId); // query_id from queryActivity()
$meta->memoryMetrics();
$meta->readerPool();
$meta->writerPool();
$meta->flushQueryCache();
$meta->reloadConfig();
Errors
All exceptions implement TwentyTwo\QuestDB\Exception\ExceptionInterface:
| Exception | Thrown when |
|---|---|
TransportException | QuestDB is not reachable (DNS, connection, timeout) |
HttpException | QuestDB answers with an HTTP error, e.g. 401 |
QueryException (extends HttpException) | QuestDB rejects a query, with getQuery()/getPosition() |
TableNotExistsException (extends QueryException) | the table does not exist |
ViewNotExistsException (extends QueryException) | the view or materialized view does not exist |
QueryCancelledException (extends QueryException) | the query was cancelled, e.g. with cancelQuery() |
ImportException | an import fails |
UnexpectedResponseException | the response does not match the call, e.g. select() on DDL |
InvalidArgumentException (extends \InvalidArgumentException) | invalid input, e.g. a placeholder without parameter |
Development
composer check # Mago lint, format check and guard, PHPStan, unit tests
composer cs-fix # format the code with Mago
docker compose up -d # QuestDB on port 9000, QUESTDB_HTTP_PORT=19000 to use another port
QUESTDB_URL=http://localhost:9000 composer test-integration
Quality gates, all enforced in CI:
- Mago formats the code, lints it with additional rules and checks the
dependency direction between the parts of the library, see
mago.toml. - PHPStan at level max with bleeding edge, strict, deprecation and PHPUnit rules and
checked exceptions, see
phpstan.neon. The@throwstags of the public API are verified. - Unit tests (coverage reported in CI), and integration tests against QuestDB 9.3, 9.4 and 10.0 with basic auth enabled. The latest QuestDB release runs once a week on a schedule as an early warning.
Working with an AI coding agent: the guidelines for agents are in AGENTS.md. Install the official
QuestDB agent skill (npx skills add questdb/skills), it teaches Claude
Code and Codex QuestDB's SQL dialect.
Set QUESTDB_USER and QUESTDB_PASSWORD when the instance requires basic auth (started with QDB_HTTP_USER and
QDB_HTTP_PASSWORD), this also runs the authentication tests.
The integration tests create and drop tables prefixed with questdb_client_test_. They are skipped without
QUESTDB_URL, never point it to a database with data you need.
Credits
Inspired by the structure of GitLabPHP/Client.
License
This library is released under the MIT License. See the LICENSE file for details.