skip to content

In SQLAlchemy, how do you write a TypeDecorator that stores a Decimal price as integer cents, and what does its cache_ok flag control?

level: middleimportance: should knowfreq 30%

answer

  1. wrap an existing type
  2. impl names the column type
  3. one hook for binds, one for results
  4. statement cache key and an SAWarning

basics

~20 s

Subclass TypeDecorator with impl = Integer, convert Decimal to cents in process_bind_param and back in process_result_value, passing None through. Set cache_ok = True so statements using it are cached; left at None, SQLAlchemy warns and skips caching.

solid answer

~40 s

`TypeDecorator` wraps an existing type: the class attribute `impl = Integer` decides the column's DDL and driver handling, and two hooks convert values. `process_bind_param(value, dialect)` runs at statement execution for every bound value (inserts, updates, and literals compared with the column), so `Decimal('9.99')` becomes `999`. `process_result_value(value, dialect)` runs when rows are fetched and turns `999` back into `Decimal('9.99')`. Both can receive `None` for NULL and should pass it through. `cache_ok` says whether the type is safe to put in the compiled-statement cache key: `True` keys it on the class plus the attributes named after `__init__` parameters; `False` disables caching for statements using it, silently; the default `None` emits an `SAWarning` ("will not produce a cache key") and also disables caching.

code

python · 43 lines
python
from decimal import Decimal

from sqlalchemy import Integer, TypeDecorator, create_engine, select, text
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column


class Cents(TypeDecorator):
    """A Decimal amount in Python, an integer number of cents in the column."""

    impl = Integer
    cache_ok = True  # no per-instance state changes the SQL or the conversion

    def process_bind_param(self, value, dialect):
        if value is None:
            return None
        return int((value * 100).to_integral_value())

    def process_result_value(self, value, dialect):
        if value is None:
            return None
        return Decimal(value) / 100


class Base(DeclarativeBase):
    pass


class Plan(Base):
    __tablename__ = "plan"

    id: Mapped[int] = mapped_column(primary_key=True)
    price: Mapped[Decimal] = mapped_column(Cents)


engine = create_engine("sqlite://")
Base.metadata.create_all(engine)
with Session(engine) as session, session.begin():
    session.add(Plan(price=Decimal("9.99")))

with Session(engine) as session:
    print(session.execute(text("SELECT price FROM plan")).scalar_one())
    # the Decimal literal is coerced to Cents, so it is bound as 500
    print(session.scalars(select(Plan.price).where(Plan.price > Decimal("5"))).one())

go deeper

for a junior

Recall the parts: impl, process_bind_param for values going in, process_result_value for values coming out, and cache_ok = True.

for a middle

Explain when each hook runs, why both must handle None, and what the three cache_ok settings do to statement caching.

for a senior

Show you would treat the cache_ok warning as a performance defect, check which state enters the cache key, and verify comparison coercion.

for a principal

Decide which conversions a team allows in custom types versus in service code, given that raw SQL and other readers see only the stored form.

## What TypeDecorator is for A **type** in SQLAlchemy decides two things for a column: the DDL it renders and how Python values are converted on their way to and from the driver. `TypeDecorator` lets you add conversion on top of an existing type without re-implementing it. The documentation prefers it to subclassing a built-in type such as `Integer` directly, because the wrapped type keeps all of its dialect-specific behaviour. When the database type itself is new to SQLAlchemy, `UserDefinedType` is the tool instead, since you must render its DDL. ## Building the cents type 1. Subclass `sqlalchemy.TypeDecorator`. 2. Set the class attribute **`impl = Integer`**; the column is created as `INTEGER`. 3. Implement **`process_bind_param(self, value, dialect)`**: return `None` for `None`, otherwise `int((value * 100).to_integral_value())`. 4. Implement **`process_result_value(self, value, dialect)`**: return `None` for `None`, otherwise `Decimal(value) / 100`. 5. Set **`cache_ok = True`** once you have checked that no instance state changes the SQL or the conversion. 6. Map it: `price: Mapped[Decimal] = mapped_column(Cents)`. ## When each hook runs | Hook | Runs | Receives | Returns | |---|---|---|---| | `process_bind_param` | at statement execution, for each bound parameter of this type | the Python value, possibly `None` | what the driver should send | | `process_result_value` | when a result row is fetched | the driver's value, possibly `None` | the Python value the attribute holds | | `process_literal_param` | when a value is rendered inline, as with `literal_binds` | the Python value | the value to render | Neither hook runs when you assign an attribute in Python; conversion happens only at the boundary with the database. ## cache_ok and the statement cache SQLAlchemy caches the compiled form of each statement under a **cache key** built from the statement's structure, including the types of its columns and parameters. A custom type must say whether it can be part of that key: | `cache_ok` | Effect | |---|---| | `None` (default) | an `SAWarning` saying the type "will not produce a cache key", and statements using it are not cached | | `True` | the key includes the class and the values of attributes named after `__init__` parameters | | `False` | statements using the type are not cached, with no warning | Points that follow from this: - Leaving it unset is not just noise: every statement that touches the column is compiled again on each execution. - With `True`, only attributes whose names match `__init__` parameters enter the key. State stored under other names is ignored, so two differently configured instances could share a cached statement. - Those attributes must be hashable; publish a dict argument as a sorted tuple of pairs instead. - A type whose SQL or conversion can differ between uses with the same arguments should set `False`. ## Comparisons go through the type too By default a `TypeDecorator` coerces the **untyped side of a comparison** to itself. In `select(Plan).where(Plan.price > Decimal("5"))` the literal is bound with `Cents`, so the driver receives `500`, not `5`. Override `coerce_compared_value(op, value)` when that is wrong: - for arithmetic where the other operand is a different kind of value, return a different type for that value; - for a decorator around `JSON` or `ARRAY`, return `self.impl.coerce_compared_value(op, value)` so index operations such as `col["key"]` are not run through your hook. ## Seeing the type at work The engine's SQL log (`echo=True`) shows both effects of the decorator: - **Bound values after conversion.** The INSERT logs `(999,)` and the filter logs `(500,)`: parameters are shown as the driver receives them, after `process_bind_param`. - **Cache status per statement.** Each logged statement carries a bracketed note: `[generated in 0.00006s]` means it was compiled and stored in the cache, `[cached since ...]` means it was reused, and `[no key ...]` means it could not be cached. A type with `cache_ok` unset or `False` gives every statement that uses it a `[no key ...]` note. A run of `[no key ...]` notes on hot queries is the clearest sign that a custom type is costing compile time on every execution. ## Pitfalls checklist - A hook that does not handle `None` fails on the first NULL. - Rounding belongs in `process_bind_param`; a `Decimal` with more than two places must be rounded deliberately, not truncated by `int()`. - `cache_ok = True` on a type with unlisted state produces wrong cached SQL that is hard to trace. - The conversion is invisible to raw SQL: `text("SELECT price FROM plan")` returns the stored cents.

  • When is cache_ok = True wrong for a TypeDecorator?
    When the type holds state that changes the SQL or the conversion but is not stored under an `__init__` parameter name, or is unhashable, such as a dict of lookups. The key is built from the class and the attributes named after `__init__` parameters, so differently configured instances could share a cached statement. Publish such state as hashable attributes named after the arguments, or set `cache_ok = False`.
  • Why is Decimal('5') bound as 500 in Plan.price > Decimal('5')?
    A `TypeDecorator` coerces the untyped side of a comparison to itself by default, so the literal goes through `process_bind_param` like an inserted value. Override `coerce_compared_value()` when that is wrong; for a decorator around `JSON` or `ARRAY`, return `self.impl.coerce_compared_value(op, value)` so index values are not encoded by your hook.
  • When would you use UserDefinedType instead?
    When the database type is one SQLAlchemy has no type for, so you must render its DDL yourself through `get_col_spec()`. When an existing type such as `Integer`, `String` or `JSON` can hold the data, `TypeDecorator` is preferred because it keeps that type's dialect behaviour.

  • process_bind_param never receives None, so it needs no None check
  • TypeDecorator subclasses are safe to cache by default
  • Leaving cache_ok unset only prints a harmless warning
  • process_result_value runs when the attribute is assigned in Python
  • Subclassing Integer directly is the preferred way to add a conversion