GitHub

API reference for client.

The PostgreSQL client (Effect's @effect/sql-pg PgClient): an SqlClient on psycopg, with json values and LISTEN / NOTIFY.

make builds it on a pool (pyfect.sql.pg.pool), make_client on one session shared by every fiber (statements wait for it in turn, and a transaction or a stream holds it until it ends)::

program.pipe(fx.provide(pg.layer(pg.PgPoolConfig(url=redacted.make(url)))))

Re-exports

Classes

Functions

make_compiler

make_compiler(transform=None, transform_json=True) -> Compiler

PostgreSQL's compiler: $1 placeholders, "quoted" names (renamed with transform), update_values as a VALUES list and json values as jsonb.

ParameterTypeDescription
transformCallable[[str], str] | None = None
transform_jsonbool = True

Returns Compiler

def make_compiler(
    transform: Callable[[str], str] | None = None, transform_json: bool = True
) -> Compiler:
    """PostgreSQL's compiler: ``$1`` placeholders, ``"quoted"`` names
    (renamed with ``transform``), ``update_values`` as a ``VALUES`` list
    and ``json`` values as ``jsonb``."""
    transform_value = (
        default_transforms(transform).value if transform_json and transform is not None else None
    )

    def on_identifier(value: str, without_transform: bool) -> str:
        if transform is None or without_transform:
            return _escape(value)
        return _escape(transform(value))

    def on_record_update(
        placeholders: str,
        alias: str,
        columns: str,
        values: Sequence[Sequence[object]],
        returning: Compiled | None,
    ) -> Compiled:
        sql = f"(values {placeholders}) AS {alias}{columns}"
        binds = [value for row in values for value in row]
        if returning is not None:
            sql += f" RETURNING {returning[0]}"
            binds.extend(returning[1])
        return sql, tuple(binds)

    def on_custom(
        segment: Custom[Any, Any, Any, Any], placeholder: Placeholder, without_transform: bool
    ) -> Compiled:
        from psycopg.types.json import Jsonb

        if segment.kind != "PgJson":
            raise TypeError(f"PostgreSQL has no custom segment {segment.kind!r}")
        value = (
            segment.param_a
            if without_transform or transform_value is None
            else transform_value(segment.param_a)
        )
        return placeholder(None), (Jsonb(value),)

    return make_statement_compiler(
        dialect="pg",
        placeholder=lambda index, _value: f"${index}",
        on_identifier=on_identifier,
        on_record_update=on_record_update,
        on_custom=on_custom,
    )

make

make(config) -> Effect[PgClientService, SqlError, Scope | Reactivity]

A client on a pool of sessions; it closes with the scope.

ParameterTypeDescription
configPgPoolConfig

Returns Effect[PgClientService, SqlError, Scope | Reactivity]

def make(config: PgPoolConfig) -> Effect[PgClientService, SqlError, Scope | Reactivity]:
    """A client on a pool of sessions; it closes with the scope."""

    def build(pool: pg_pool.PgPoolService) -> Effect[PgClientService, SqlError, Reactivity]:
        def borrow[A, E, R](
            f: Callable[[Connection], Effect[A, E, R]],
        ) -> Effect[A, E | SqlError, R]:
            return pool.use(lambda connection: f(_wrap(connection)))

        return _make_impl(
            acquirer=pool.get.map(_wrap),
            borrower=borrow,
            transaction_acquirer=pool.reserve.map(_wrap),
            listen_acquirer=pool.reserve,
            config=config,
            pool_stats=pool.stats,
        )

    return pg_pool.make(config).flat_map(build)

make_client

make_client(config, *, acquire_for_stream=False) -> Effect[PgClientService, SqlError, Scope | Reactivity]

A client on one session; with acquire_for_stream, each stream and listener opens a session of its own.

ParameterTypeDescription
configPgClientConfig
acquire_for_streambool = False

Returns Effect[PgClientService, SqlError, Scope | Reactivity]

def make_client(
    config: PgClientConfig, *, acquire_for_stream: bool = False
) -> Effect[PgClientService, SqlError, Scope | Reactivity]:
    """A client on one session; with ``acquire_for_stream``, each stream
    and listener opens a session of its own."""

    def build(connection: PgConnection) -> Effect[PgClientService, SqlError, Reactivity]:
        side = make_connection(config) if acquire_for_stream else None
        return _make_impl(
            acquirer=succeed(PgSqlConnection(connection, side)),
            borrower=None,
            transaction_acquirer=connection.pin.map(_wrap),
            listen_acquirer=side if side is not None else connection.pin,
            config=config,
            # The one session is leased for the client's lifetime.
            pool_stats=succeed(_LEASED),
        )

    return make_connection(config).flat_map(build)

layer_from

layer_from[E](acquire) -> Layer[PgClient | SqlClient, E]

Provides the client acquire makes as PgClient and SqlClient, with its own Reactivity.

ParameterTypeDescription
acquireEffect[PgClientService, E, Scope | Reactivity]

Returns Layer[PgClient | SqlClient, E]

def layer_from[E](
    acquire: Effect[PgClientService, E, Scope | Reactivity],
) -> Layer[PgClient | SqlClient, E]:
    """Provides the client ``acquire`` makes as ``PgClient`` and
    ``SqlClient``, with its own ``Reactivity``."""
    require_effect(acquire, "acquire")
    return layer_effect_context(acquire.map(_contexts)).pipe(provide(reactivity_layer))

layer

layer(config) -> Layer[PgClient | SqlClient, SqlError]

Provides a pooled client (make).

ParameterTypeDescription
configPgPoolConfig

Returns Layer[PgClient | SqlClient, SqlError]

def layer(config: PgPoolConfig) -> Layer[PgClient | SqlClient, SqlError]:
    """Provides a pooled client (``make``)."""
    return layer_from(make(config))

layer_config

layer_config(config) -> Layer[PgClient | SqlClient, ConfigError | SqlError]

layer with the config read from the ConfigProvider: a Config of the whole config, or a mapping from field names to their Config (Effect's Config.Wrap)::

pg.layer_config({"url": fx.config.redacted("DATABASE_URL")})
ParameterTypeDescription
configConfig[PgPoolConfig] | Mapping[str, Any]

Returns Layer[PgClient | SqlClient, ConfigError | SqlError]

def layer_config(
    config: Config[PgPoolConfig] | Mapping[str, Any],
) -> Layer[PgClient | SqlClient, ConfigError | SqlError]:
    """``layer`` with the config read from the ``ConfigProvider``: a
    ``Config`` of the whole config, or a mapping from field names to their
    ``Config`` (Effect's ``Config.Wrap``)::

        pg.layer_config({"url": fx.config.redacted("DATABASE_URL")})
    """
    read: Effect[PgPoolConfig, ConfigError] = (
        config
        if isinstance(config, Config)
        else unwrap(config).map(lambda fields: PgPoolConfig(**fields))
    )
    return layer_from(read.flat_map(make))