derp.orm – ORM¶
Derp ORM - A strongly-typed async Python ORM for PostgreSQL.
Example usage:
from derp.orm import Table, Serial, Text, Varchar, Timestamp, Field
class User(Table, table="users"):
id: Serial = Field(primary=True)
name: Text = Field()
email: Varchar[255] = Field(unique=True)
created_at: Timestamp = Field(default="now()")
async with DatabaseEngine("postgresql://...") as db:
users = await db.select(User).where(User.name == "Alice").execute()
- class derp.orm.DatabaseConfig[source]
Bases:
_StrictModelDatabase configuration.
- db_url: str
- schema_path: str
- migrations_dir: str
- introspect_schemas: Sequence[str]
- introspect_exclude_tables: Sequence[str]
- ignore_rls: bool
- pool_min_size: int
- pool_max_size: int
- statement_cache_size: int
- replica_max_lag_bytes: int
- replica_write_fence_seconds: float
- replica_lag_check_interval_seconds: float
- model_config = {'extra': 'forbid'}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class derp.orm.DatabaseEngine[source]
Bases:
_QueryBaseMain async database engine for Derp ORM.
Example
db = DatabaseEngine(“postgresql://user:pass@localhost:5432/mydb”)
- async with db:
users = await db.select(User).where(User.name == “Alice”).execute()
# Or manual lifecycle await db.connect() users = await db.select(User).execute() await db.disconnect()
- __init__(dsn, *, min_size=2, max_size=10, statement_cache_size=None)[source]
Initialize Derp engine.
- Parameters:
dsn (str) – PostgreSQL connection string
min_size (int) – Minimum connection pool size
max_size (int) – Maximum connection pool size
statement_cache_size (int | None) – Size of the prepared statement cache per connection. Set to 0 to disable, which is required when connecting through PgBouncer in transaction mode. None uses asyncpg’s default.
- async connect()[source]
Establish connection pool.
- Return type:
None
- async disconnect()[source]
Close connection pool.
- Return type:
None
- set_cache(store)[source]
Set the KV store for query result caching.
- Parameters:
store (KVClient | None)
- Return type:
None
- set_router(router)[source]
Set the replica router for automatic read routing.
- Parameters:
router (ReplicaRouter | None)
- Return type:
None
- property pool: Pool
Get the connection pool.
- table(table_name)[source]
Start a non ORM query from a table name or Table class.
- async execute(query, params=None)[source]
Execute a raw SQL query.
- Parameters:
- Returns:
List of row dicts
- Return type:
Example
result = await db.execute(“SELECT * FROM users WHERE id = $1”, [user_id])
- async execute_many(query, params_list)[source]
Execute a query with multiple parameter sets.
- transaction()[source]
Start a transaction.
Example
- async with db.transaction():
await db.insert(User).values(…).execute() await db.update(Post).set(…).execute()
- Return type:
- acquire()[source]
Acquire a connection from the pool.
Example
- async with db.acquire() as conn:
await conn.execute(”…”)
- Return type:
AsyncIterator[Connection]
- class derp.orm.Table[source]
Bases:
objectBase class for all Derp table definitions.
Example:
class User(Table, table="users"): id: Serial = Field(primary=True) name: Text = Field() email: Varchar[255] = Field(unique=True) # Query building — direct class access: db.select(User).where(User.name == "Alice")
- classmethod indexes()[source]
Override to define indexes for this table.
- Return type:
Sequence[Index]
- classmethod get_primary_key()[source]
Get the primary key column if any.
- classmethod from_dict(data)[source]
Construct an instance from a dict (ignores unknown keys).
- classmethod from_json(data)[source]
Construct an instance from a JSON string.
- class derp.orm.Column[source]
Bases:
Expression,GenericBase descriptor for all table columns.
Extends Expression so columns can be used directly in query building. Implements the descriptor protocol for typed class/instance access.
Subclasses set
_sql_typeas a class variable. Parameterized types (e.g.,Varchar[255]) overridesql_type()to include parameters.- __init__(spec)[source]
- Parameters:
spec (FieldSpec)
- Return type:
None
- property primary_key: bool
- property unique: bool
- property nullable: bool
- property default: Any
- property has_default: bool
- property on_delete: FK | None
- property on_update: FK | None
- to_sql(params)[source]
Generate SQL string with parameterized values.
- derp.orm.Field(*, primary=False, unique=False, default=<dataclasses._MISSING_TYPE object>, generated=None, foreign_key=None, on_delete=None, on_update=None)[source]
Declare column constraints.
Foreign keys:
Field(foreign_key=User.id, on_delete="cascade") Field(foreign_key="users.id")
Generated columns:
Field(generated="price * quantity")
- class derp.orm.FieldSpec[source]
Bases:
objectColumn constraints returned by
Field().This is a placeholder that
Table.__init_subclass__replaces with a realColumndescriptor after resolving the type annotation.- __init__(*, primary=False, unique=False, default=<dataclasses._MISSING_TYPE object>, generated=None, foreign_key=None, on_delete=None, on_update=None)[source]
- primary
- unique
- default
- generated
- foreign_key
- on_delete
- on_update
- class derp.orm.FK[source]
Bases:
StrEnumActions for foreign key ON DELETE / ON UPDATE clauses.
- CASCADE = 'CASCADE'
- SET_NULL = 'SET NULL'
- SET_DEFAULT = 'SET DEFAULT'
- RESTRICT = 'RESTRICT'
- __new__(value)
- class derp.orm.Varchar[source]
-
Variable-length string with limit (VARCHAR).
Accepts both
Varchar[255]andVarchar[Literal[255]].
- class derp.orm.Char[source]
Bases:
Column[str]Fixed-length string (CHAR).
Accepts both
Char[10]andChar[Literal[10]].
- class derp.orm.TimestampTZ[source]
Bases:
Column[datetime]Timestamp with timezone (TIMESTAMP WITH TIME ZONE).
- class derp.orm.Numeric[source]
Bases:
Column[Decimal]Exact numeric with precision and scale (NUMERIC).
- class derp.orm.DoublePrecision[source]
Bases:
Column[float]8-byte floating point (DOUBLE PRECISION).
- class derp.orm.Vector[source]
-
Vector type for embeddings (pgvector).
Distance methods for use in ORDER BY or WHERE clauses:
db.select(Doc).order_by(Doc.embedding.cosine_distance(vec)).limit(10)
- cosine_distance(other)[source]
Cosine distance (
<=>). Sort ASC for most similar.
- l2_distance(other)[source]
L2 / Euclidean distance (
<->). Sort ASC for most similar.
- class derp.orm.Nullable[source]
-
Nullable column wrapper.
Use as a type annotation to indicate a column that allows NULL:
age: Nullable[Integer] = Field()
At the class level
User.ageis a Column (supports query operators). At the instance leveluser.ageisint | None.Nullable[Varchar[255]]also works for parameterized types.
- class derp.orm.Enum[source]
Bases:
Column,GenericPostgreSQL enum column.
Usage:
class Status(StrEnum): ACTIVE = "active" INACTIVE = "inactive" status: Enum[Status] = Field(default="active")
- class derp.orm.JoinType[source]
Bases:
StrEnumSQL JOIN types.
- INNER = 'INNER'
- LEFT = 'LEFT'
- RIGHT = 'RIGHT'
- FULL = 'FULL OUTER'
- CROSS = 'CROSS'
- __new__(value)
- class derp.orm.LockMode[source]
Bases:
StrEnumSQL row-level locking modes.
- UPDATE = 'FOR UPDATE'
- NO_KEY_UPDATE = 'FOR NO KEY UPDATE'
- SHARE = 'FOR SHARE'
- KEY_SHARE = 'FOR KEY SHARE'
- __new__(value)
- class derp.orm.SortOrder[source]
Bases:
StrEnumColumn sort order within an index.
- ASC = 'ASC'
- DESC = 'DESC'
- __new__(value)
- class derp.orm.LogicalOperator[source]
Bases:
StrEnumSQL logical operators.
- AND = 'AND'
- OR = 'OR'
- __new__(value)
- class derp.orm.ComparisonOperator[source]
Bases:
StrEnumSQL comparison operators.
- EQ = '='
- NE = '<>'
- GT = '>'
- GTE = '>='
- LT = '<'
- LTE = '<='
- __new__(value)
- class derp.orm.Expression[source]
Bases:
ABCBase class for SQL expressions.
- abstractmethod to_sql(params)[source]
Generate SQL string with parameterized values.
- matches(query, *, language='english', style='websearch', stored=False)[source]
Full-text search match using
@@.stored: set to
Truewhen the column is a pre-computed tsvector (skips theto_tsvector()wrapper). style:"websearch"(default),"plain", or"phrase".
- ts_rank(query, *, language='english', style='websearch', stored=False)[source]
Full-text search rank for ORDER BY.
stored: set to
Truewhen the column is a pre-computed tsvector (skips theto_tsvector()wrapper).
- ts_headline(query, *, language='english', style='websearch', max_words=None, min_words=None, max_fragments=None, start_sel=None, stop_sel=None, fragment_delimiter=None, highlight_all=None, short_word=None)[source]
Highlighted search snippet for display in results.
- Parameters:
- Return type:
- derp.orm.sql(template, *values)[source]
Create a raw SQL expression fragment.
Use
{}as placeholder for parameterized values:sql("NOW()") sql("age > {}", 18) sql("CONCAT({}, name)", "Dr. ")
- class derp.orm.Index[source]
Bases:
objectFull PostgreSQL index definition.
Accepts flexible column input:
Index("email") Index("created_at", "name") Index(IndexColumn("email", order=SortOrder.DESC))
Index-level options:
Index("embedding", method=IndexMethod.HNSW, opclass="vector_cosine_ops") Index("status", where=MyTable.is_active == True) Index("id", include=("name",)) Index(expression="lower(email)", unique=True)
- __init__(*columns, method=IndexMethod.BTREE, unique=False, where=None, include=(), nulls_distinct=True, with_params=None, tablespace=None, concurrently=False, name=None, opclass=None, order=None, nulls=None, collation=None, expression=None)[source]
- method
- unique
- where
- include
- nulls_distinct
- with_params
- tablespace
- concurrently
- name
- opclass
- property columns: tuple[IndexColumn, ...]
- auto_name(table_name)[source]
Generate a conventional index name.
- class derp.orm.IndexColumn[source]
Bases:
objectPer-column configuration within an index.
Either name or expression must be provided:
IndexColumn("email") IndexColumn("email", order=SortOrder.DESC, nulls=NullsPosition.LAST) IndexColumn(expression="lower(email)") IndexColumn("embedding", opclass="vector_cosine_ops")
- nulls: NullsPosition | None = None