GitHub

API reference for options.

The transport options of @clickhouse/client a ClickhouseClientConfig takes, under their createClient names: compression, keep_alive, tls, log and json (with max_open_connections, use_multipart_params and use_multipart_params_auto, plain fields of the config). Each is checked when the config is made and parsed here into what the driver and the httpx client use.

  • compression: {"response": True} asks the server for a gzip response (enable_http_compression=1, Accept-Encoding); {"response": {"codec": "zstd"}} names the codec. {"request": True} gzips the bodies of inserts, commands and exec; {"request": {"codec": "br", "quality": 4}} picks the codec and its level (level for gzip and zstd, quality for Brotli, 4 by default). A zstd request body needs Python 3.14 (compression.zstd), Brotli the brotli extra; on the httpx client make creates, a zstd response needs zstandard and a Brotli one the brotli extra.
  • keep_alive: enabled (True) and idle_socket_ttl, how long an idle connection is kept (2500 ms; 0 keeps it until the server closes it).
  • tls: {"ca_cert": pem} to trust a CA, with cert and key for a client certificate; on an https URL the credentials then go in X-ClickHouse-User / X-ClickHouse-Key (and X-ClickHouse-SSL-Certificate-Auth: on with a certificate).
  • log: {"level": "WARN"}, the least severe of the client's own logs that are written, through the fiber's loggers.
  • json: {"parse": ..., "stringify": ...} read result rows and write inserted rows.

keep_alive, max_open_connections and tls configure the httpx client make creates, and have no effect on an http_client given in the config (as on @clickhouse/client's http_agent).

Values

AttributeTypeDescription
LOG_LEVELSdict[LogLevel, int] = {'TRACE': 0, 'DEBUG': 1, 'INFO': 2, 'WARN': 3, 'ERROR': 4, 'OFF': 127}

ClickHouseLogLevel's values.

Types

TypeDefinitionDescription
CompressionCodectype CompressionCodec = Literal['gzip', 'zstd', 'br']

A codec @clickhouse/client compresses with.

RequestCompressiontype RequestCompression = GzipRequestCompression | ZstdRequestCompression | BrotliRequestCompression
Tlstype Tls = BasicTls | MutualTls
LogLeveltype LogLevel = Literal['TRACE', 'DEBUG', 'INFO', 'WARN', 'ERROR', 'OFF']

Classes

Functions

json_handling

json_handling(given) -> Json
ParameterTypeDescription
givenJsonHandling | None

Returns Json

def json_handling(given: JsonHandling | None) -> Json:
    given = given or {}
    return Json(given.get("parse", _json_text.parse), given.get("stringify"))

request_codec

request_codec(value) -> RequestCodec | None

normalizeRequestCompression and ensureRequestCodecSupported.

ParameterTypeDescription
valuebool | RequestCompression | None

Returns RequestCodec | None

def request_codec(value: bool | RequestCompression | None) -> RequestCodec | None:
    """``normalizeRequestCompression`` and ``ensureRequestCodecSupported``."""
    if not value:
        return None
    if value is True:
        return RequestCodec("gzip")
    codec = cast("object", value.get("codec"))
    match codec:
        case "gzip" | "zstd":
            found = RequestCodec(
                "gzip" if codec == "gzip" else "zstd", cast("int | None", value.get("level"))
            )
        case "br":
            found = RequestCodec("br", cast("int | None", value.get("quality")))
        case _:
            raise _unknown_codec(codec, "request")
    if found.codec == "zstd" and not _has_module("compression.zstd"):
        raise _zstd_unsupported("compressing needs Python 3.14 (`compression.zstd`)")
    if found.codec == "br":
        import pyfect.http._brotli  # noqa: F401  # pyright: ignore[reportUnusedImport]
    return found

response_codec

response_codec(value, *, default_client) -> CompressionCodec | None

normalizeResponseCompression and ensureResponseCodecSupported: on the httpx client make creates, the codec must be one httpx can decode.

ParameterTypeDescription
valuebool | ResponseCompression | None
default_clientbool

Returns CompressionCodec | None

def response_codec(
    value: bool | ResponseCompression | None, *, default_client: bool
) -> CompressionCodec | None:
    """``normalizeResponseCompression`` and ``ensureResponseCodecSupported``:
    on the httpx client ``make`` creates, the codec must be one httpx can
    decode."""
    if not value:
        return None
    if value is True:
        return "gzip"
    codec = cast("object", value.get("codec"))
    if codec not in _CODECS:
        raise _unknown_codec(codec, "response")
    found: CompressionCodec = codec
    if default_client and found == "zstd" and not _has_module("zstandard"):
        raise _zstd_unsupported("httpx decompresses zstd with the `zstandard` package")
    if (
        default_client
        and found == "br"
        and not _has_module("brotlicffi")
        and not _has_module("brotli")
    ):
        raise ImportError(
            "Brotli responses need the 'brotli' extra for httpx to decompress them: "
            "pip install 'pyfect-dev[brotli]'"
        )
    return found

tls_context

tls_context(tls) -> TlsContext

An SSL context trusting ca_cert (only it, as Node's ca), with the client certificate when cert and key are given.

ParameterTypeDescription
tlsTls

Returns TlsContext

def tls_context(tls: Tls) -> TlsContext:
    """An SSL context trusting ``ca_cert`` (only it, as Node's ``ca``), with
    the client certificate when ``cert`` and ``key`` are given."""
    context = ssl.create_default_context(cadata=tls["ca_cert"].decode("ascii"))
    cert, key = tls.get("cert"), tls.get("key")
    mutual = cert is not None and key is not None
    if mutual:
        # ``ssl`` loads a certificate chain only from files.
        with tempfile.TemporaryDirectory() as directory:
            cert_path = os.path.join(directory, "cert.pem")
            key_path = os.path.join(directory, "key.pem")
            for path, data in ((cert_path, cert), (key_path, key)):
                descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
                with os.fdopen(descriptor, "wb") as file:
                    file.write(cast("bytes", data))
            context.load_cert_chain(cert_path, key_path)
    return TlsContext(context, mutual)

url_boolean

url_boolean(key, value) -> bool

booleanConfigURLValue.

ParameterTypeDescription
keystr
valuestr

Returns bool

def url_boolean(key: str, value: str) -> bool:
    """``booleanConfigURLValue``."""
    trimmed = value.strip()
    if trimmed in ("true", "1"):
        return True
    if trimmed in ("false", "0"):
        return False
    raise ValueError(
        f'"{key}" has invalid boolean value: {trimmed}. Expected one of: 0, 1, true, false.'
    )

url_number

url_number(key, value, minimum) -> float

numberConfigURLValue: read as JavaScript's Number.

ParameterTypeDescription
keystr
valuestr
minimumfloat

Returns float

def url_number(key: str, value: str, minimum: float) -> float:
    """``numberConfigURLValue``: read as JavaScript's ``Number``."""
    import math

    from pyfect.schema.getter._coerce import to_number

    trimmed = value.strip()
    number = to_number(trimmed)
    if math.isnan(number):
        raise ValueError(f'"{key}" has invalid numeric value: {trimmed}')
    if number < minimum:
        raise ValueError(f'"{key}" value {trimmed} is less than min allowed {minimum:g}')
    return number

url_log_level

url_log_level(key, value) -> LogLevel

enumConfigURLValue over ClickHouseLogLevel.

ParameterTypeDescription
keystr
valuestr

Returns LogLevel

def url_log_level(key: str, value: str) -> LogLevel:
    """``enumConfigURLValue`` over ``ClickHouseLogLevel``."""
    trimmed = value.strip()
    if trimmed not in LOG_LEVELS:
        raise ValueError(
            f'"{key}" has invalid value: {trimmed}. Expected one of: {", ".join(LOG_LEVELS)}.'
        )
    return trimmed

form_encoded_length

form_encoded_length(entries) -> int

new URLSearchParams(entries).toString().length.

ParameterTypeDescription
entrieslist[tuple[str, str]]

Returns int

def form_encoded_length(entries: list[tuple[str, str]]) -> int:
    """``new URLSearchParams(entries).toString().length``."""
    total = max(len(entries) - 1, 0)
    for name, value in entries:
        for text in (name, value):
            total += sum(1 if c in _SAFE_FORM else 3 * len(text_encode(c)) for c in text)
        total += 1
    return total