Skip to content

PostgreSQL Adapter

Tip

turu-postgres depends on psycopg.

Installation

pip install "turu[postgres]"

Usage

Basic Usage

import pydantic
import turu.postgres


class User(pydantic.BaseModel):
    id: int
    name: str


connection = turu.postgres.connect_from_env()

with connection.cursor() as cursor:
    user = cursor.execute_map(User, "SELECT 1, 'taro'").fetchone()

    assert user == User(id=1, name="taro")

Parameters Usage

format style

import pydantic
import turu.postgres


class User(pydantic.BaseModel):
    id: int
    name: str


connection = turu.postgres.connect_from_env()

with connection.cursor() as cursor:
    user = cursor.execute_map(
        User,
        "SELECT %s, %s",
        [1, "taro"],
    ).fetchone()

    assert user == User(id=1, name="taro")

Warning

The variables placeholder must always be a %s, even if a different placeholder (such as a %d for integers or %f for floats) may look more appropriate for the type.

Keyword Parameters Usage

pyformat style

import pydantic
import turu.postgres


class User(pydantic.BaseModel):
    id: int
    name: str


connection = turu.postgres.connect_from_env()

with connection.cursor() as cursor:
    user = cursor.execute_map(
        User,
        "SELECT %(id)s, %(name)s",
        {"id": 1, "name": "taro"},
    ).fetchone()

    assert user == User(id=1, name="taro")