Metadata-Version: 2.4
Name: whenever-sqlalchemy
Version: 0.2.0
Summary: SQLAlchemy column types for the whenever datetime library
Author-email: Arie Bovenberg <a.c.bovenberg@gmail.com>
Maintainer-email: Arie Bovenberg <a.c.bovenberg@gmail.com>
License-Expression: MIT
Project-URL: Repository, https://github.com/ariebovenberg/whenever-sqlalchemy
Project-URL: Issues, https://github.com/ariebovenberg/whenever-sqlalchemy/issues
Project-URL: Changelog, https://github.com/ariebovenberg/whenever-sqlalchemy/blob/main/CHANGELOG.md
Keywords: whenever,sqlalchemy,datetime,date,time,orm
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: Implementation :: PyPy
Classifier: Typing :: Typed
Classifier: Topic :: Database
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: whenever>=0.11.0
Requires-Dist: sqlalchemy>=2.0
Dynamic: license-file

# whenever-sqlalchemy

SQLAlchemy column types for the [whenever](https://github.com/ariebovenberg/whenever) datetime library.

## Installation

```bash
pip install whenever-sqlalchemy
```

## Type mapping

| whenever type    | SQL type                    |
|------------------|-----------------------------|
| `Instant`        | `TIMESTAMP WITH TIME ZONE`  |
| `PlainDateTime`  | `TIMESTAMP` (no timezone)   |
| `Date`           | `DATE`                      |
| `Time`           | `TIME`                      |

## Usage

### ORM: `Mapped[]` annotations (recommended)

Register `type_annotation_map` on your `DeclarativeBase` once, then use
`Mapped[Instant]` exactly like you would use `Mapped[datetime]`:

```python
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from whenever import Date, Instant, PlainDateTime, Time
from whenever_sqlalchemy import type_annotation_map

class Base(DeclarativeBase):
    type_annotation_map = type_annotation_map  # merge with your own if needed

class Event(Base):
    __tablename__ = "events"
    id: Mapped[int] = mapped_column(primary_key=True)
    timestamp: Mapped[Instant]
    scheduled: Mapped[PlainDateTime | None]
    date: Mapped[Date | None]
    time: Mapped[Time | None]
```

### Core: explicit column types

Pass the column types to `Column()`, or to `mapped_column()` in the ORM:

```python
from sqlalchemy import Column, Integer, MetaData, Table
from whenever_sqlalchemy import DateType, InstantType, PlainDateTimeType, TimeType

events = Table(
    "events",
    MetaData(),
    Column("id", Integer, primary_key=True),
    Column("timestamp", InstantType, nullable=False),
    Column("scheduled", PlainDateTimeType),
    Column("date", DateType),
    Column("time", TimeType),
)
```

### Store a `ZonedDateTime`

Most databases have no column type that keeps a time zone ID, and most don't
keep a UTC offset either: PostgreSQL's `TIMESTAMP WITH TIME ZONE` converts
values to UTC and discards the offset. Store the local date and time, the
offset, and the time zone ID in three columns:

```python
from whenever import PlainDateTime, TimeDelta, ZonedDateTime

class Meeting(Base):
    __tablename__ = "meetings"
    id: Mapped[int] = mapped_column(primary_key=True)
    start_local: Mapped[PlainDateTime]
    start_offset: Mapped[int]  # seconds east of UTC
    start_tz: Mapped[str]

    @property
    def start(self) -> ZonedDateTime:
        offset = TimeDelta(seconds=self.start_offset)
        return self.start_local.assume_fixed_offset(offset).assume_tz(
            self.start_tz,
            offset_mismatch="keep_local",
            disambiguation="compatible",
        )

    @start.setter
    def start(self, value: ZonedDateTime) -> None:
        self.start_local = value.to_plain()
        self.start_offset = int(value.offset.total("seconds"))
        self.start_tz = value.tz_id
```

If the time zone's rules change between writing and reading a row, the stored
offset no longer matches the time zone. `offset_mismatch` decides what
happens then:

- `"keep_local"` keeps the local time and moves the instant. Use it for
  events planned in local time, such as a meeting at 9:00.
- `"keep_instant"` keeps the instant and moves the local time. Use it for
  events that already happened, such as a log entry.
- `"raise"` raises `InvalidOffsetError`.

With `"keep_local"`, the local time can fall in an hour that the new rules
repeat or skip. `disambiguation` then picks the instant.

The row keeps all three values, so you can change this choice later without
migrating data. To filter or sort rows by instant in SQL, add an
`InstantType` column as well.

## Notes

**Strict types** — each column type accepts only its own `whenever` type and
raises `TypeError` for anything else. To store a `ZonedDateTime` or
`OffsetDateTime` in an `InstantType` column, convert it with `.to_instant()`
first.

**Precision** — `whenever` types have nanosecond precision. Values reach the
database driver truncated to microseconds, matching `to_stdlib()`. The column
type that SQLAlchemy creates on your database can store less: check your
database's documentation.

An object that you add to a session keeps its nanoseconds until SQLAlchemy
loads it again from the database. To make both hold the same value, round it
before you store it, for example with
`instant.round("microsecond", mode="floor")`.

To use a more precise column type, subclass and override `impl`:

```python
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
from whenever_sqlalchemy import InstantType

class PreciseInstantType(InstantType):
    impl = sa.DateTime(timezone=True).with_variant(
        mysql.DATETIME(fsp=6), "mysql"
    )
    cache_ok = True
```

Don't call `InstantType().with_variant(...)`: on the variant's database,
SQLAlchemy uses the variant type instead of `InstantType`, so values skip the
conversion to and from `whenever` types.

**Time zones** — on PostgreSQL, `InstantType` creates a
`TIMESTAMP WITH TIME ZONE` column. On SQL Server, it creates `DATETIMEOFFSET`.
SQLite, MySQL, MariaDB, and Oracle store the column without a time zone:
`InstantType` writes UTC and reads values without a time zone as UTC.

On any other database, `InstantType` raises `ValueError` when it reads a
value without a time zone. This usually means that the column has no time
zone, for example a `TIMESTAMP WITHOUT TIME ZONE` column in an existing
PostgreSQL schema. Its values aren't necessarily UTC, so `InstantType`
doesn't guess.

**`server_default`** — the database sets the value and SQLAlchemy converts it
to the `whenever` type when it reads the row. With `InstantType`, the value
must be in UTC on databases that store the column without a time zone. MySQL's
`NOW()` returns the session time zone's local time, so it gives wrong
instants unless the session time zone is UTC.

## Compatibility

- Python 3.11+
- whenever 0.11+
- SQLAlchemy 2.0+
