python-ulid 4.1.0__tar.gz → 4.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. {python_ulid-4.1.0 → python_ulid-4.2.0}/.github/workflows/lint-and-test.yml +1 -1
  2. {python_ulid-4.1.0 → python_ulid-4.2.0}/.gitignore +2 -0
  3. {python_ulid-4.1.0 → python_ulid-4.2.0}/.pre-commit-config.yaml +1 -1
  4. {python_ulid-4.1.0 → python_ulid-4.2.0}/.readthedocs.yml +2 -0
  5. {python_ulid-4.1.0 → python_ulid-4.2.0}/CHANGELOG.rst +37 -1
  6. {python_ulid-4.1.0 → python_ulid-4.2.0}/CONTRIBUTING.md +11 -2
  7. {python_ulid-4.1.0 → python_ulid-4.2.0}/PKG-INFO +59 -1
  8. {python_ulid-4.1.0 → python_ulid-4.2.0}/README.rst +56 -1
  9. {python_ulid-4.1.0 → python_ulid-4.2.0}/docs/source/api.rst +10 -0
  10. {python_ulid-4.1.0 → python_ulid-4.2.0}/docs/source/conf.py +4 -1
  11. {python_ulid-4.1.0 → python_ulid-4.2.0}/docs/source/index.rst +4 -0
  12. {python_ulid-4.1.0 → python_ulid-4.2.0}/pyproject.toml +18 -10
  13. {python_ulid-4.1.0 → python_ulid-4.2.0}/tests/test_cli.py +44 -0
  14. python_ulid-4.2.0/tests/test_sqlalchemy.py +235 -0
  15. {python_ulid-4.1.0 → python_ulid-4.2.0}/tests/test_ulid.py +162 -0
  16. {python_ulid-4.1.0 → python_ulid-4.2.0}/ulid/__init__.py +42 -12
  17. {python_ulid-4.1.0 → python_ulid-4.2.0}/ulid/__main__.py +7 -2
  18. python_ulid-4.2.0/ulid/_version.py +24 -0
  19. python_ulid-4.2.0/ulid/sqlalchemy.py +132 -0
  20. {python_ulid-4.1.0 → python_ulid-4.2.0}/uv.lock +419 -324
  21. {python_ulid-4.1.0 → python_ulid-4.2.0}/.envrc +0 -0
  22. {python_ulid-4.1.0 → python_ulid-4.2.0}/.github/workflows/publish.yml +0 -0
  23. {python_ulid-4.1.0 → python_ulid-4.2.0}/.ruff_defaults.toml +0 -0
  24. {python_ulid-4.1.0 → python_ulid-4.2.0}/AGENTS.md +0 -0
  25. {python_ulid-4.1.0 → python_ulid-4.2.0}/CONTEXT.md +0 -0
  26. {python_ulid-4.1.0 → python_ulid-4.2.0}/LICENSE +0 -0
  27. {python_ulid-4.1.0 → python_ulid-4.2.0}/docs/Makefile +0 -0
  28. {python_ulid-4.1.0 → python_ulid-4.2.0}/docs/requirements.txt +0 -0
  29. {python_ulid-4.1.0 → python_ulid-4.2.0}/docs/source/changelog.rst +0 -0
  30. {python_ulid-4.1.0 → python_ulid-4.2.0}/logo.png +0 -0
  31. {python_ulid-4.1.0 → python_ulid-4.2.0}/tests/__init__.py +0 -0
  32. {python_ulid-4.1.0 → python_ulid-4.2.0}/tests/test_base32.py +0 -0
  33. {python_ulid-4.1.0 → python_ulid-4.2.0}/ulid/base32.py +0 -0
  34. {python_ulid-4.1.0 → python_ulid-4.2.0}/ulid/constants.py +0 -0
  35. {python_ulid-4.1.0 → python_ulid-4.2.0}/ulid/py.typed +0 -0
@@ -47,7 +47,7 @@ jobs:
47
47
  name: Run tests
48
48
  strategy:
49
49
  matrix:
50
- python-version: ["3.11", "3.12", "3.13", "3.14"]
50
+ python-version: ["3.11", "3.12", "3.13", "3.14", "3.15"]
51
51
  steps:
52
52
  - uses: actions/checkout@v7
53
53
  - name: Install uv
@@ -15,3 +15,5 @@ __pycache__
15
15
  /dist/
16
16
  /build/
17
17
  /docs/build
18
+
19
+ /ulid/_version.py
@@ -1,6 +1,6 @@
1
1
  repos:
2
2
  - repo: https://github.com/astral-sh/ruff-pre-commit
3
- rev: v0.15.4
3
+ rev: v0.17.5
4
4
  hooks:
5
5
  - id: ruff-check
6
6
  - id: ruff-format
@@ -13,3 +13,5 @@ python:
13
13
  - requirements: docs/requirements.txt
14
14
  - method: pip
15
15
  path: .
16
+ extra_requirements:
17
+ - sqlalchemy
@@ -8,6 +8,41 @@ Versions follow `Semantic Versioning <http://www.semver.org>`_
8
8
  `Unreleased`_
9
9
  -------------
10
10
 
11
+ `4.2.0`_ - 2026-11-17
12
+ ---------------------
13
+ Added
14
+ ~~~~~
15
+ * Added support for Python 3.15.
16
+ * :class:`~ulid.sqlalchemy.ULIDType`, a SQLAlchemy column type for :class:`.ULID` values that can
17
+ also be used with SQLModel. It stores values as UUID by default, or as binary or string. Install
18
+ it with the new ``sqlalchemy`` extra (``pip install python-ulid[sqlalchemy]``).
19
+
20
+ Fixed
21
+ ~~~~~
22
+ * The :class:`.ULID` constructor now accepts :class:`bytes` and bytes-like values (``bytearray``
23
+ and ``memoryview``), which are stored as immutable :class:`bytes`. A 16-character string or an
24
+ integer was previously accepted and produced an object whose ``str()`` failed or that was
25
+ unhashable, so other types now raise :exc:`TypeError`
26
+ `@KuljeetSinghXDA <https://github.com/KuljeetSinghXDA>`_.
27
+ * Pydantic validation of unsupported values such as ``dict``, ``float`` or an out-of-range
28
+ ``int`` now raises ``pydantic.ValidationError`` instead of leaking :exc:`TypeError` or
29
+ :exc:`OverflowError` `@KuljeetSinghXDA <https://github.com/KuljeetSinghXDA>`_.
30
+ * :meth:`.ULID.parse` now treats any integer in the unsigned 128-bit range as a full ULID
31
+ integer, instead of guessing from the number of decimal digits. Previously only integers with
32
+ exactly 37 digits were accepted, so ``ULID.parse(int(ulid))`` failed for most ULIDs
33
+ `@KuljeetSinghXDA <https://github.com/KuljeetSinghXDA>`_.
34
+ * :meth:`.ULID.from_datetime` and :meth:`.ULID.from_timestamp` no longer land one millisecond early
35
+ when a value on an exact millisecond multiplies to just below that integer as a float
36
+ `@arieleven <https://github.com/arieleven>`_.
37
+ * :meth:`.ULID.from_datetime` and :meth:`.ULID.from_timestamp` raise a :exc:`ValueError` for values
38
+ before the Unix epoch instead of a bare :exc:`OverflowError`.
39
+ * :meth:`.ULID.from_int` raises a :exc:`ValueError` for integers outside the unsigned 128-bit
40
+ range instead of a bare :exc:`OverflowError`.
41
+ * The ``ulid`` command line tool reports invalid input as a short error message with exit status
42
+ 2 instead of a Python traceback.
43
+ * ``import ulid`` no longer fails when the package metadata is missing, e.g. in applications frozen
44
+ with cx_Freeze or PyInstaller. The version is now written into the package at build time.
45
+
11
46
  `4.1.0`_ - 2026-10-27
12
47
  ---------------------
13
48
  Changed
@@ -284,7 +319,8 @@ Changed
284
319
  * The package now has no external dependencies.
285
320
  * The test-coverage has been raised to 100%.
286
321
 
287
- .. _Unreleased: https://github.com/mdomke/python-ulid/compare/4.1.0...HEAD
322
+ .. _Unreleased: https://github.com/mdomke/python-ulid/compare/4.2.0...HEAD
323
+ .. _4.2.0: https://github.com/mdomke/python-ulid/compare/4.1.0...4.2.0
288
324
  .. _4.1.0: https://github.com/mdomke/python-ulid/compare/4.0.1...4.1.0
289
325
  .. _4.0.1: https://github.com/mdomke/python-ulid/compare/4.0.0...4.0.1
290
326
  .. _4.0.0: https://github.com/mdomke/python-ulid/compare/3.2.1...4.0.0
@@ -99,6 +99,16 @@ If you want to run all checks against your staged or unstaged files manually:
99
99
  uv run prek run --all-files
100
100
  ```
101
101
 
102
+ ### Troubleshooting: `cannot import name '_version' from 'ulid'`
103
+
104
+ The package version is written to `ulid/_version.py` when the package is built or installed, and the
105
+ file is not tracked by Git. If it is missing (e.g. after `git clean -X`), `import ulid` fails. Reinstall
106
+ the package into your environment to regenerate it:
107
+
108
+ ```bash
109
+ uv sync --reinstall-package python-ulid
110
+ ```
111
+
102
112
  ---
103
113
 
104
114
  ## 🎨 Coding Standards
@@ -110,8 +120,7 @@ To maintain a clean, readable, and highly maintainable codebase, we enforce the
110
120
  - **Static Analysis**: Our configuration has `disallow_untyped_defs = true` set for Mypy and uses strict `pyrefly` checks. Untyped or partially-typed code will fail the lint pipelines.
111
121
  - **Example**:
112
122
  ```python
113
- def generate_ulid(timestamp: float | None = None) -> ULID:
114
- ...
123
+ def generate_ulid(timestamp: float | None = None) -> ULID: ...
115
124
  ```
116
125
 
117
126
  ### 2. Ruff Formatting & Linting
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: python-ulid
3
- Version: 4.1.0
3
+ Version: 4.2.0
4
4
  Summary: Universally unique lexicographically sortable identifier
5
5
  Project-URL: Homepage, https://github.com/mdomke/python-ulid
6
6
  Project-URL: Documentation, https://python-ulid.readthedocs.io
@@ -22,11 +22,14 @@ Classifier: Programming Language :: Python :: 3.11
22
22
  Classifier: Programming Language :: Python :: 3.12
23
23
  Classifier: Programming Language :: Python :: 3.13
24
24
  Classifier: Programming Language :: Python :: 3.14
25
+ Classifier: Programming Language :: Python :: 3.15
25
26
  Classifier: Topic :: Software Development :: Libraries
26
27
  Requires-Python: >=3.11
27
28
  Requires-Dist: typing-extensions; python_version < '3.12'
28
29
  Provides-Extra: pydantic
29
30
  Requires-Dist: pydantic>=2.0; extra == 'pydantic'
31
+ Provides-Extra: sqlalchemy
32
+ Requires-Dist: sqlalchemy>=2.0; extra == 'sqlalchemy'
30
33
  Description-Content-Type: text/x-rst
31
34
 
32
35
 
@@ -74,6 +77,12 @@ to include Pydantic support install the optional dependency like so
74
77
 
75
78
  $ pip install python-ulid[pydantic]
76
79
 
80
+ and for the SQLAlchemy column type
81
+
82
+ .. code-block:: bash
83
+
84
+ $ pip install python-ulid[sqlalchemy]
85
+
77
86
  .. installation-end
78
87
 
79
88
  .. usage-begin
@@ -149,6 +158,55 @@ The ``ULID`` class can be directly used for the popular data validation library
149
158
 
150
159
  .. pydantic-end
151
160
 
161
+ .. sqlalchemy-begin
162
+
163
+ SQLAlchemy and SQLModel integration
164
+ -----------------------------------
165
+
166
+ The ``ULIDType`` column type stores ``ULID`` values with
167
+ `SQLAlchemy <https://www.sqlalchemy.org/>`_ (version 2.0 or newer). Values are bound from
168
+ ``ULID``, ``UUID``, ``bytes``, ``int`` or any string representation and always loaded as ``ULID``.
169
+ Pass ``default=ULID`` to generate a new identifier for every inserted row
170
+
171
+ .. code-block:: python
172
+
173
+ from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
174
+ from ulid import ULID
175
+ from ulid.sqlalchemy import ULIDType
176
+
177
+
178
+ class Base(DeclarativeBase):
179
+ pass
180
+
181
+
182
+ class Item(Base):
183
+ __tablename__ = "items"
184
+
185
+ id: Mapped[ULID] = mapped_column(ULIDType(), primary_key=True, default=ULID)
186
+ name: Mapped[str]
187
+
188
+ By default the value is stored as a UUID: a native ``UUID`` column where the database has one
189
+ (e.g. PostgreSQL) and ``CHAR(32)`` otherwise. Use ``ULIDType(storage="binary")`` for a
190
+ ``BINARY(16)`` column or ``ULIDType(storage="string")`` for the 26 character ULID string in a
191
+ ``CHAR(26)`` column. All storages keep the database sort order identical to the ULID order, except
192
+ the native ``UNIQUEIDENTIFIER`` type on SQL Server.
193
+
194
+ `SQLModel <https://sqlmodel.tiangolo.com/>`_ models can use ``ULID`` as a field type directly,
195
+ since it is a Pydantic type. Only the column type has to be passed explicitly
196
+
197
+ .. code-block:: python
198
+
199
+ from sqlmodel import Field, SQLModel
200
+ from ulid import ULID
201
+ from ulid.sqlalchemy import ULIDType
202
+
203
+
204
+ class Hero(SQLModel, table=True):
205
+ id: ULID = Field(default_factory=ULID, primary_key=True, sa_type=ULIDType)
206
+ name: str
207
+
208
+ .. sqlalchemy-end
209
+
152
210
  .. monotonic-begin
153
211
 
154
212
  Monotonic Support
@@ -22,7 +22,7 @@
22
22
  <img src="https://img.shields.io/github/actions/workflow/status/mdomke/python-ulid/lint-and-test.yml?style=flat-square&brach=main" />
23
23
  </a>
24
24
  <a href="https://python-ulid.readthedocs.io">
25
- <img src="https://app.readthedocs.org/projects/python-ulid/badge/?version=latest&style=flat-square" />
25
+ <img src="https://readthedocs.org/projects/python-ulid/badge/?version=latest&style=flat-square" />
26
26
  </a>
27
27
  <a href="https://github.com/astral-sh/ruff">
28
28
  <img src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json&style=flat-square" />
@@ -76,6 +76,12 @@ to include Pydantic support install the optional dependency like so
76
76
 
77
77
  $ pip install python-ulid[pydantic]
78
78
 
79
+ and for the SQLAlchemy column type
80
+
81
+ .. code-block:: bash
82
+
83
+ $ pip install python-ulid[sqlalchemy]
84
+
79
85
  .. installation-end
80
86
 
81
87
  .. usage-begin
@@ -151,6 +157,55 @@ The ``ULID`` class can be directly used for the popular data validation library
151
157
 
152
158
  .. pydantic-end
153
159
 
160
+ .. sqlalchemy-begin
161
+
162
+ SQLAlchemy and SQLModel integration
163
+ -----------------------------------
164
+
165
+ The ``ULIDType`` column type stores ``ULID`` values with
166
+ `SQLAlchemy <https://www.sqlalchemy.org/>`_ (version 2.0 or newer). Values are bound from
167
+ ``ULID``, ``UUID``, ``bytes``, ``int`` or any string representation and always loaded as ``ULID``.
168
+ Pass ``default=ULID`` to generate a new identifier for every inserted row
169
+
170
+ .. code-block:: python
171
+
172
+ from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
173
+ from ulid import ULID
174
+ from ulid.sqlalchemy import ULIDType
175
+
176
+
177
+ class Base(DeclarativeBase):
178
+ pass
179
+
180
+
181
+ class Item(Base):
182
+ __tablename__ = "items"
183
+
184
+ id: Mapped[ULID] = mapped_column(ULIDType(), primary_key=True, default=ULID)
185
+ name: Mapped[str]
186
+
187
+ By default the value is stored as a UUID: a native ``UUID`` column where the database has one
188
+ (e.g. PostgreSQL) and ``CHAR(32)`` otherwise. Use ``ULIDType(storage="binary")`` for a
189
+ ``BINARY(16)`` column or ``ULIDType(storage="string")`` for the 26 character ULID string in a
190
+ ``CHAR(26)`` column. All storages keep the database sort order identical to the ULID order, except
191
+ the native ``UNIQUEIDENTIFIER`` type on SQL Server.
192
+
193
+ `SQLModel <https://sqlmodel.tiangolo.com/>`_ models can use ``ULID`` as a field type directly,
194
+ since it is a Pydantic type. Only the column type has to be passed explicitly
195
+
196
+ .. code-block:: python
197
+
198
+ from sqlmodel import Field, SQLModel
199
+ from ulid import ULID
200
+ from ulid.sqlalchemy import ULIDType
201
+
202
+
203
+ class Hero(SQLModel, table=True):
204
+ id: ULID = Field(default_factory=ULID, primary_key=True, sa_type=ULIDType)
205
+ name: str
206
+
207
+ .. sqlalchemy-end
208
+
154
209
  .. monotonic-begin
155
210
 
156
211
  Monotonic Support
@@ -50,3 +50,13 @@ satisfying the :class:`MonotonicityPolicy` protocol can be used; stateful polici
50
50
 
51
51
  .. autoclass:: PureRandomPolicy
52
52
  :members:
53
+
54
+
55
+ SQLAlchemy
56
+ ----------
57
+
58
+ .. module:: ulid.sqlalchemy
59
+
60
+ Requires the optional ``sqlalchemy`` dependency (``pip install python-ulid[sqlalchemy]``).
61
+
62
+ .. autoclass:: ULIDType
@@ -78,4 +78,7 @@ autodoc_member_order = "groupwise"
78
78
  # ----------------------------------------------
79
79
 
80
80
  # Example configuration for intersphinx: refer to the Python standard library.
81
- intersphinx_mapping = {"python": ("https://docs.python.org/3", None)}
81
+ intersphinx_mapping = {
82
+ "python": ("https://docs.python.org/3", None),
83
+ "sqlalchemy": ("https://docs.sqlalchemy.org/en/20/", None),
84
+ }
@@ -20,6 +20,10 @@ Release v\ |release| (:ref:`What's new <changelog>`)
20
20
  :start-after: pydantic-begin
21
21
  :end-before: pydantic-end
22
22
 
23
+ .. include:: ../../README.rst
24
+ :start-after: sqlalchemy-begin
25
+ :end-before: sqlalchemy-end
26
+
23
27
  .. include:: ../../README.rst
24
28
  :start-after: monotonic-begin
25
29
  :end-before: monotonic-end
@@ -23,6 +23,7 @@ classifiers = [
23
23
  "Programming Language :: Python :: 3.12",
24
24
  "Programming Language :: Python :: 3.13",
25
25
  "Programming Language :: Python :: 3.14",
26
+ "Programming Language :: Python :: 3.15",
26
27
  "Topic :: Software Development :: Libraries",
27
28
  ]
28
29
  dependencies = [
@@ -41,6 +42,9 @@ Repository = "https://github.com/mdomke/python-ulid"
41
42
  pydantic = [
42
43
  "pydantic>=2.0"
43
44
  ]
45
+ sqlalchemy = [
46
+ "sqlalchemy>=2.0",
47
+ ]
44
48
 
45
49
  [project.scripts]
46
50
  ulid = "ulid.__main__:entrypoint"
@@ -48,6 +52,9 @@ ulid = "ulid.__main__:entrypoint"
48
52
  [tool.hatch.version]
49
53
  source = "vcs"
50
54
 
55
+ [tool.hatch.build.hooks.vcs]
56
+ version-file = "ulid/_version.py"
57
+
51
58
  [tool.hatch.build.targets.wheel]
52
59
  packages = [
53
60
  "ulid",
@@ -111,10 +118,10 @@ preset = "strict"
111
118
  project-excludes = ["docs"]
112
119
 
113
120
  [tool.poe.tasks]
114
- test = "uv run --extra pydantic pytest --cov --cov-report=term-missing"
121
+ test = "uv run --extra pydantic --extra sqlalchemy pytest --cov --cov-report=term-missing"
115
122
  check-code = "uv run ruff check"
116
123
  check-fmt = "uv run ruff format --check"
117
- check-types = "uv run --extra pydantic pyrefly check"
124
+ check-types = "uv run --extra pydantic --extra sqlalchemy pyrefly check"
118
125
  check-docs = "uv run doc8 docs/source"
119
126
  fmt = "uv run ruff format"
120
127
  fix = "uv run ruff check --fix"
@@ -146,14 +153,15 @@ max-line-length = 100
146
153
 
147
154
  [dependency-groups]
148
155
  dev = [
149
- "coverage==7.17.*",
150
- "freezegun==1.5.*",
151
- "poethepoet==0.49.*",
152
- "prek==0.5.*",
153
- "pyrefly==1.4.*",
154
- "pytest==9.1.*",
155
- "pytest-cov==7.1.*",
156
- "ruff==0.17.*",
156
+ "coverage",
157
+ "freezegun",
158
+ "poethepoet",
159
+ "prek",
160
+ "pyrefly",
161
+ "pytest",
162
+ "pytest-cov",
163
+ "ruff",
164
+ "sqlmodel",
157
165
  ]
158
166
  doc = [
159
167
  "doc8>=2.0.0",
@@ -7,6 +7,10 @@ import ulid.__main__ as cli
7
7
  from ulid import ULID
8
8
 
9
9
 
10
+ # Exit status argparse uses for invalid command-line input.
11
+ USAGE_ERROR = 2
12
+
13
+
10
14
  @pytest.mark.parametrize(
11
15
  "option", ["", "uuid", "uuid4", "uuid7", "hex", "int", "timestamp", "datetime"]
12
16
  )
@@ -106,6 +110,46 @@ def test_module_outputs_result(args: list[str], stdin: str | None, expected: str
106
110
  assert result.stderr == ""
107
111
 
108
112
 
113
+ @pytest.mark.parametrize(
114
+ ("args", "message"),
115
+ [
116
+ (["build", "--from-int", "abc"], "invalid literal for int()"),
117
+ (["build", "--from-int=-1"], "Value is outside the 128-bit range of a ULID"),
118
+ (["build", "--from-str", "not-a-ulid"], "ULID has to be exactly 26 characters long."),
119
+ (["build", "--from-hex", "zz"], "non-hexadecimal number"),
120
+ (["build", "--from-timestamp=-1"], "Value is below minimum possible timestamp"),
121
+ (["build", "--from-datetime", "yesterday"], "Invalid isoformat string"),
122
+ (["build", "--from-uuid", "not-a-uuid"], "badly formed hexadecimal UUID string"),
123
+ (["show", "not-a-ulid"], "ULID has to be exactly 26 characters long."),
124
+ ],
125
+ )
126
+ def test_invalid_input_reports_error_without_traceback(
127
+ capsys: pytest.CaptureFixture[str], args: list[str], message: str
128
+ ) -> None:
129
+ with pytest.raises(SystemExit) as exc_info:
130
+ cli.main(args, prog="ulid")
131
+ assert exc_info.value.code == USAGE_ERROR
132
+ captured = capsys.readouterr()
133
+ assert captured.out == ""
134
+ assert captured.err.startswith("ulid: error: ")
135
+ assert message in captured.err
136
+ assert "Traceback" not in captured.err
137
+
138
+
139
+ def test_module_invalid_input_exits_with_error() -> None:
140
+ result = subprocess.run(
141
+ [sys.executable, "-m", "ulid", "show", "not-a-ulid"],
142
+ capture_output=True,
143
+ text=True,
144
+ check=False,
145
+ timeout=10,
146
+ )
147
+ assert result.returncode == USAGE_ERROR
148
+ assert result.stdout == ""
149
+ assert result.stderr.startswith("python -m ulid: error: ")
150
+ assert "Traceback" not in result.stderr
151
+
152
+
109
153
  @pytest.mark.parametrize("args", [[], ["--help"]])
110
154
  def test_module_help(args: list[str]) -> None:
111
155
  result = subprocess.run(
@@ -0,0 +1,235 @@
1
+ import uuid
2
+ from collections.abc import Callable
3
+ from collections.abc import Iterator
4
+
5
+ import pytest
6
+ from sqlalchemy import Column
7
+ from sqlalchemy import create_engine
8
+ from sqlalchemy import Engine
9
+ from sqlalchemy import insert
10
+ from sqlalchemy import Integer
11
+ from sqlalchemy import literal
12
+ from sqlalchemy import MetaData
13
+ from sqlalchemy import select
14
+ from sqlalchemy import Table
15
+ from sqlalchemy import text
16
+ from sqlalchemy.dialects import mysql
17
+ from sqlalchemy.dialects import postgresql
18
+ from sqlalchemy.dialects import sqlite
19
+ from sqlalchemy.engine import Dialect
20
+ from sqlalchemy.exc import StatementError
21
+ from sqlalchemy.orm import DeclarativeBase
22
+ from sqlalchemy.orm import Mapped
23
+ from sqlalchemy.orm import mapped_column
24
+ from sqlalchemy.orm import Session
25
+ from sqlalchemy.schema import CreateTable
26
+ from sqlmodel import Field
27
+ from sqlmodel import Session as SQLModelSession
28
+ from sqlmodel import SQLModel
29
+
30
+ from ulid import ULID
31
+ from ulid import ULIDGenerator
32
+ from ulid.sqlalchemy import Storage
33
+ from ulid.sqlalchemy import ULIDType
34
+
35
+
36
+ STORAGES: list[Storage] = ["uuid", "binary", "string"]
37
+
38
+
39
+ @pytest.fixture
40
+ def engine() -> Iterator[Engine]:
41
+ engine = create_engine("sqlite://")
42
+ yield engine
43
+ engine.dispose()
44
+
45
+
46
+ def make_table(storage: Storage) -> Table:
47
+ return Table(
48
+ "items",
49
+ MetaData(),
50
+ Column("pk", Integer, primary_key=True),
51
+ Column("id", ULIDType(storage), nullable=True),
52
+ )
53
+
54
+
55
+ @pytest.mark.parametrize("storage", STORAGES)
56
+ def test_round_trip(engine: Engine, storage: Storage) -> None:
57
+ table = make_table(storage)
58
+ table.metadata.create_all(engine)
59
+ value = ULID()
60
+ with engine.begin() as conn:
61
+ conn.execute(insert(table), [{"id": value}, {"id": None}])
62
+ rows = conn.execute(select(table.c.id).order_by(table.c.pk)).scalars().all()
63
+ assert rows == [value, None]
64
+ assert isinstance(rows[0], ULID)
65
+
66
+
67
+ CONVERTERS: dict[str, Callable[[ULID], object]] = {
68
+ "ulid": lambda u: u,
69
+ "str": str,
70
+ "hex": lambda u: u.hex,
71
+ "uuid-str": lambda u: str(u.to_uuid()),
72
+ "uuid": lambda u: u.to_uuid(),
73
+ "bytes": bytes,
74
+ "bytearray": lambda u: bytearray(bytes(u)),
75
+ "int": int,
76
+ }
77
+
78
+
79
+ @pytest.mark.parametrize("storage", STORAGES)
80
+ @pytest.mark.parametrize("convert", CONVERTERS.values(), ids=CONVERTERS.keys())
81
+ def test_bind_accepts_supported_representations(
82
+ engine: Engine, storage: Storage, convert: Callable[[ULID], object]
83
+ ) -> None:
84
+ table = make_table(storage)
85
+ table.metadata.create_all(engine)
86
+ value = ULID()
87
+ with engine.begin() as conn:
88
+ conn.execute(insert(table), {"id": convert(value)})
89
+ stored = conn.execute(select(table.c.id)).scalar_one()
90
+ found = conn.execute(select(table.c.pk).where(table.c.id == convert(value))).scalar()
91
+ assert stored == value
92
+ assert found is not None
93
+
94
+
95
+ @pytest.mark.parametrize("storage", STORAGES)
96
+ def test_database_order_matches_ulid_order(engine: Engine, storage: Storage) -> None:
97
+ table = make_table(storage)
98
+ table.metadata.create_all(engine)
99
+ generator = ULIDGenerator()
100
+ values = [generator.generate(timestamp) for timestamp in (5.0, 1.0, 3.0, 1.0, 2.0)]
101
+ values += [ULID.from_int(0), ULID.from_int(2**128 - 1)]
102
+ with engine.begin() as conn:
103
+ conn.execute(insert(table), [{"id": value} for value in values])
104
+ rows = conn.execute(select(table.c.id).order_by(table.c.id)).scalars().all()
105
+ assert rows == sorted(values)
106
+
107
+
108
+ @pytest.mark.parametrize(
109
+ ("storage", "stored_type"),
110
+ [("uuid", uuid.UUID), ("binary", bytes), ("string", str)],
111
+ )
112
+ def test_raw_storage_format(engine: Engine, storage: Storage, stored_type: type) -> None:
113
+ table = make_table(storage)
114
+ table.metadata.create_all(engine)
115
+ value = ULID()
116
+ with engine.begin() as conn:
117
+ conn.execute(insert(table), {"id": value})
118
+ raw = conn.execute(text("SELECT id FROM items")).scalar_one()
119
+ expected = {"uuid": value.hex, "binary": bytes(value), "string": str(value)}[storage]
120
+ assert raw == expected
121
+ assert isinstance(ULIDType(storage).process_bind_param(value, sqlite.dialect()), stored_type)
122
+
123
+
124
+ @pytest.mark.parametrize(
125
+ ("value", "error"),
126
+ [
127
+ ("not-a-ulid", ValueError),
128
+ (b"too short", ValueError),
129
+ (-1, ValueError),
130
+ (2**128, ValueError),
131
+ (1.5, TypeError),
132
+ (True, TypeError),
133
+ ],
134
+ )
135
+ def test_bind_rejects_invalid_values(engine: Engine, value: object, error: type) -> None:
136
+ table = make_table("uuid")
137
+ table.metadata.create_all(engine)
138
+ with engine.begin() as conn, pytest.raises(StatementError) as exc_info:
139
+ conn.execute(insert(table), {"id": value})
140
+ assert isinstance(exc_info.value.orig, error)
141
+
142
+
143
+ def test_rejects_unknown_storage() -> None:
144
+ with pytest.raises(ValueError, match="Unknown storage 'text'"):
145
+ ULIDType("text") # type: ignore[arg-type]
146
+
147
+
148
+ @pytest.mark.parametrize(
149
+ ("storage", "dialect", "ddl"),
150
+ [
151
+ ("uuid", postgresql.dialect(), "UUID"),
152
+ ("uuid", sqlite.dialect(), "CHAR(32)"),
153
+ ("binary", postgresql.dialect(), "BYTEA"),
154
+ ("binary", mysql.dialect(), "BINARY(16)"),
155
+ ("string", postgresql.dialect(), "CHAR(26)"),
156
+ ],
157
+ )
158
+ def test_column_ddl(storage: Storage, dialect: Dialect, ddl: str) -> None:
159
+ ddl_statement = str(CreateTable(make_table(storage)).compile(dialect=dialect))
160
+ assert f"id {ddl}" in ddl_statement
161
+
162
+
163
+ def test_repr_round_trips_storage() -> None:
164
+ assert repr(ULIDType()) == "ULIDType()"
165
+ assert repr(ULIDType("uuid")) == "ULIDType()"
166
+ assert repr(ULIDType("binary")) == "ULIDType(storage='binary')"
167
+ assert repr(ULIDType("string")) == "ULIDType(storage='string')"
168
+
169
+
170
+ def test_python_type() -> None:
171
+ assert ULIDType().python_type is ULID
172
+
173
+
174
+ @pytest.mark.parametrize(
175
+ ("storage", "dialect", "expected"),
176
+ [
177
+ ("uuid", sqlite.dialect(), "'015f4bffcd735334ada78edc1d4a6f1f'"),
178
+ ("uuid", postgresql.dialect(), "'015f4bff-cd73-5334-ada7-8edc1d4a6f1f'"),
179
+ ("string", sqlite.dialect(), "'01BX5ZZKBKACTAV9WEVGEMMVRZ'"),
180
+ ],
181
+ )
182
+ def test_literal_binds(storage: Storage, dialect: Dialect, expected: str) -> None:
183
+ value = ULID.from_str("01BX5ZZKBKACTAV9WEVGEMMVRZ")
184
+ statement = select(literal(value, ULIDType(storage)))
185
+ compiled = statement.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
186
+ assert str(compiled) == f"SELECT {expected} AS anon_1"
187
+
188
+
189
+ class Base(DeclarativeBase):
190
+ pass
191
+
192
+
193
+ class Item(Base):
194
+ __tablename__ = "orm_items"
195
+
196
+ id: Mapped[ULID] = mapped_column(ULIDType(), primary_key=True, default=ULID)
197
+ name: Mapped[str]
198
+
199
+
200
+ def test_orm_default_and_lookup(engine: Engine) -> None:
201
+ Base.metadata.create_all(engine)
202
+ with Session(engine) as session:
203
+ item = Item(name="first")
204
+ session.add(item)
205
+ session.commit()
206
+ item_id = item.id
207
+ assert isinstance(item_id, ULID)
208
+
209
+ with Session(engine) as session:
210
+ loaded = session.get(Item, item_id)
211
+ assert loaded is not None
212
+ assert loaded.name == "first"
213
+ assert session.scalars(select(Item).where(Item.id == str(item_id))).one() is loaded
214
+
215
+
216
+ class Hero(SQLModel, table=True):
217
+ id: ULID = Field(default_factory=ULID, primary_key=True, sa_type=ULIDType)
218
+ name: str
219
+
220
+
221
+ def test_sqlmodel(engine: Engine) -> None:
222
+ SQLModel.metadata.create_all(engine)
223
+ with SQLModelSession(engine) as session:
224
+ hero = Hero(name="Deadpond")
225
+ session.add(hero)
226
+ session.commit()
227
+ hero_id = hero.id
228
+
229
+ with SQLModelSession(engine) as session:
230
+ loaded = session.get(Hero, hero_id)
231
+ assert loaded is not None
232
+ assert loaded.id == hero_id
233
+ assert isinstance(loaded.id, ULID)
234
+
235
+ assert Hero.model_validate({"id": str(hero_id), "name": "x"}).id == hero_id