python-ulid 4.1.0__py3-none-any.whl → 4.2.0__py3-none-any.whl

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.
@@ -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
@@ -0,0 +1,12 @@
1
+ ulid/__init__.py,sha256=tzODN80NbpnnlmofUnSriOY-_mVP5Nlb2P8BxYgDkFE,22605
2
+ ulid/__main__.py,sha256=If5LwixO0IZd2U5FVDOQLQn3oFdSrdMXrXtT95mHh_M,5861
3
+ ulid/_version.py,sha256=nT-3r7mhc-hueGCIfa_bEdffKxwEZc-wM7Fo2U4hJAo,520
4
+ ulid/base32.py,sha256=40jH4ADBs5ZTpfJmLYvwijiy_rGP1JGum7fFkLmkv7k,6088
5
+ ulid/constants.py,sha256=lbCLRNQXq8qnOdz_w-nJf_j5dC2X7Gjv-8GJUbs5jX8,503
6
+ ulid/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ ulid/sqlalchemy.py,sha256=QNK3oDAXtTceABrGXc0P0U87zxbkCLr2hqjJ1nolRiU,4546
8
+ python_ulid-4.2.0.dist-info/METADATA,sha256=8Al8ld8SVIbtIidwVlD_iEN5wTimJ4ipl-JoEYWnOl4,10583
9
+ python_ulid-4.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ python_ulid-4.2.0.dist-info/entry_points.txt,sha256=9214ghzfSgS8a-TjjlWDF7bI7KSaeewOCBKn5uz7bdU,50
11
+ python_ulid-4.2.0.dist-info/licenses/LICENSE,sha256=DiDPNhW5yUHIqaKowvX0c1c9xWiI0xW4ji8R9N2NJbw,1056
12
+ python_ulid-4.2.0.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: hatchling 1.32.4
2
+ Generator: hatchling 1.33.0
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
ulid/__init__.py CHANGED
@@ -8,7 +8,6 @@ import uuid
8
8
  from collections.abc import Callable
9
9
  from datetime import datetime
10
10
  from datetime import UTC
11
- from importlib.metadata import version
12
11
  from threading import Lock
13
12
  from typing import Any
14
13
  from typing import cast
@@ -21,6 +20,7 @@ try:
21
20
  except ImportError:
22
21
  from typing_extensions import override # type: ignore
23
22
 
23
+ from ulid import _version
24
24
  from ulid import base32
25
25
  from ulid import constants
26
26
 
@@ -33,7 +33,9 @@ if TYPE_CHECKING: # pragma: no cover
33
33
  from pydantic_core import CoreSchema
34
34
 
35
35
 
36
- __version__ = version("python-ulid")
36
+ # Generated at build time so that the version is available even without package metadata,
37
+ # e.g. in applications frozen with cx_Freeze or PyInstaller.
38
+ __version__ = _version.__version__
37
39
 
38
40
 
39
41
  RandomnessSource = Callable[[int], bytes]
@@ -188,13 +190,20 @@ class ULIDGenerator:
188
190
  def _default_randomness(_timestamp: int) -> bytes:
189
191
  return os.urandom(constants.RANDOMNESS_LEN)
190
192
 
193
+ @staticmethod
194
+ def _seconds_to_milliseconds(seconds: float) -> int:
195
+ # Round off the float error first, or x.860 s truncates to x859 ms.
196
+ return int(round(seconds * constants.MILLISECS_IN_SECS, 3))
197
+
191
198
  def _normalize_timestamp(self, value: float | datetime | None = None) -> int:
192
199
  if value is None:
193
200
  value = self.clock()
194
201
  elif isinstance(value, datetime):
195
- value = int(value.timestamp() * constants.MILLISECS_IN_SECS)
202
+ value = self._seconds_to_milliseconds(value.timestamp())
196
203
  elif isinstance(value, float):
197
- value = int(value * constants.MILLISECS_IN_SECS)
204
+ value = self._seconds_to_milliseconds(value)
205
+ if value < constants.MIN_TIMESTAMP:
206
+ raise ValueError("Value is below minimum possible timestamp")
198
207
  if value > constants.MAX_TIMESTAMP:
199
208
  raise ValueError("Value exceeds maximum possible timestamp")
200
209
  return value
@@ -249,9 +258,11 @@ class ULID:
249
258
  '01E75PVKXA3GFABX1M1J9NZZNF'
250
259
 
251
260
  Args:
252
- value (bytes, None): A sequence of 16 bytes representing an encoded ULID.
261
+ value (bytes, None): A sequence of 16 bytes representing an encoded ULID. Bytes-like
262
+ values (:class:`bytearray` and :class:`memoryview`) are converted to :class:`bytes`.
253
263
 
254
264
  Raises:
265
+ TypeError: If the provided value is not :class:`bytes` or a bytes-like object.
255
266
  ValueError: If the provided value is not a valid encoded ULID.
256
267
  """
257
268
 
@@ -259,8 +270,13 @@ class ULID:
259
270
  self,
260
271
  value: bytes | None = None,
261
272
  ) -> None:
262
- if value is not None and len(value) != constants.BYTES_LEN:
263
- raise ValueError("ULID has to be exactly 16 bytes long.")
273
+ if value is not None:
274
+ if isinstance(value, (bytearray, memoryview)):
275
+ value = bytes(value)
276
+ elif not isinstance(value, bytes):
277
+ raise TypeError("Value has to be of type bytes")
278
+ if len(value) != constants.BYTES_LEN:
279
+ raise ValueError("ULID has to be exactly 16 bytes long.")
264
280
  if value is None:
265
281
  self.bytes: bytes = default_generator.generate().bytes
266
282
  else:
@@ -335,9 +351,17 @@ class ULID:
335
351
 
336
352
  @classmethod
337
353
  def from_int(cls, value: int) -> Self:
338
- """Create a new :class:`ULID`-object from an `int`."""
354
+ """Create a new :class:`ULID`-object from an `int`.
355
+
356
+ Raises:
357
+ TypeError: If the value is not an `int`.
358
+ ValueError: If the value is outside the unsigned 128-bit range (``0`` to
359
+ ``2**128 - 1``).
360
+ """
339
361
  if not isinstance(value, int):
340
362
  raise TypeError("Value has to be of type int")
363
+ if not 0 <= value < 1 << (constants.BYTES_LEN * 8):
364
+ raise ValueError("Value is outside the 128-bit range of a ULID")
341
365
  return cls(int.to_bytes(value, constants.BYTES_LEN, "big"))
342
366
 
343
367
  @classmethod
@@ -347,6 +371,10 @@ class ULID:
347
371
  .. note::
348
372
  This method should only be used when the caller is trying to parse a ULID from
349
373
  a value when they're unsure what format/primitive type it will be given in.
374
+
375
+ Integer values up to ``MAX_TIMESTAMP`` are interpreted as millisecond timestamps,
376
+ while larger integers up to ``2**128 - 1`` are interpreted as the 128-bit integer
377
+ representation of a ULID.
350
378
  """
351
379
  if isinstance(value, ULID):
352
380
  return cast("Self", value)
@@ -362,9 +390,11 @@ class ULID:
362
390
  return cls.from_str(value)
363
391
  raise ValueError(f"Cannot parse ULID from string of length {len_value}")
364
392
  if isinstance(value, int):
365
- if len(str(value)) == constants.INT_REPR_LEN:
366
- return cls.from_int(value)
367
- return cls.from_timestamp(value)
393
+ if not 0 <= value < 1 << (constants.BYTES_LEN * 8):
394
+ raise ValueError("Cannot parse ULID from an integer outside the 128-bit range")
395
+ if value <= constants.MAX_TIMESTAMP:
396
+ return cls.from_timestamp(value)
397
+ return cls.from_int(value)
368
398
  if isinstance(value, float):
369
399
  return cls.from_timestamp(value)
370
400
  if isinstance(value, datetime):
@@ -585,6 +615,6 @@ class ULID:
585
615
  ulid = value
586
616
  else:
587
617
  ulid = cls.from_bytes(value)
588
- except ValueError as err:
618
+ except (TypeError, ValueError) as err:
589
619
  raise PydanticCustomError("ulid_format", "Unrecognized format") from err
590
620
  return handler(ulid)
ulid/__main__.py CHANGED
@@ -103,8 +103,13 @@ def make_parser(prog: str | None = None) -> argparse.ArgumentParser:
103
103
 
104
104
 
105
105
  def main(argv: Sequence[str], prog: str | None = None) -> str:
106
- args = make_parser(prog).parse_args(argv)
107
- return args.func(args)
106
+ parser = make_parser(prog)
107
+ args = parser.parse_args(argv)
108
+ try:
109
+ return args.func(args)
110
+ except ValueError as err:
111
+ # Report invalid input like argparse does for invalid arguments, without a traceback.
112
+ parser.exit(2, f"{parser.prog}: error: {err}\n")
108
113
 
109
114
 
110
115
  def from_value_or_stdin(value: str, convert: Callable[[str], Any] | None = None) -> Any:
ulid/_version.py ADDED
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '4.2.0'
22
+ __version_tuple__ = version_tuple = (4, 2, 0)
23
+
24
+ __commit_id__ = commit_id = None
ulid/sqlalchemy.py ADDED
@@ -0,0 +1,132 @@
1
+ """SQLAlchemy column type for :class:`~ulid.ULID` values.
2
+
3
+ Requires the optional ``sqlalchemy`` dependency (``pip install python-ulid[sqlalchemy]``).
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import uuid
9
+ from typing import Any
10
+ from typing import Literal
11
+ from typing import TYPE_CHECKING
12
+
13
+
14
+ try:
15
+ from typing import override
16
+ except ImportError:
17
+ from typing_extensions import override # type: ignore
18
+
19
+ from sqlalchemy import types
20
+ from sqlalchemy.dialects import postgresql
21
+
22
+ from ulid import constants
23
+ from ulid import ULID
24
+
25
+
26
+ if TYPE_CHECKING: # pragma: no cover
27
+ from sqlalchemy.engine import Dialect
28
+
29
+
30
+ __all__ = ["Storage", "ULIDType"]
31
+
32
+
33
+ Storage = Literal["uuid", "binary", "string"]
34
+
35
+ _STORAGES: tuple[Storage, ...] = ("uuid", "binary", "string")
36
+
37
+
38
+ class ULIDType(types.TypeDecorator[ULID]):
39
+ """Store :class:`~ulid.ULID` values in a database column.
40
+
41
+ Bound parameters may be given as :class:`~ulid.ULID`, :class:`uuid.UUID`, 16 :class:`bytes`,
42
+ :class:`int` (see :meth:`.ULID.from_int`) or :class:`str` (base32, hex or UUID
43
+ representation). Values loaded from the database are always returned as :class:`~ulid.ULID`.
44
+
45
+ Args:
46
+ storage: How the value is stored in the database.
47
+
48
+ * ``"uuid"`` (default): SQLAlchemy's :class:`~sqlalchemy.types.Uuid` type, i.e. a native
49
+ ``UUID`` column where available (e.g. PostgreSQL) and ``CHAR(32)`` hex otherwise.
50
+ * ``"binary"``: the raw 16 bytes in a ``BINARY(16)`` column (``BYTEA`` on
51
+ PostgreSQL).
52
+ * ``"string"``: the 26 character Crockford base32 representation in a ``CHAR(26)``
53
+ column.
54
+
55
+ All storages preserve the sort order of ULIDs in the database, with one exception: SQL
56
+ Server orders its native ``UNIQUEIDENTIFIER`` type by a different byte order, so use
57
+ ``"binary"`` or ``"string"`` there if ordering by the column matters.
58
+
59
+ Raises:
60
+ ValueError: If ``storage`` is not one of ``"uuid"``, ``"binary"`` or ``"string"``, or if a
61
+ bound value cannot be converted to a :class:`~ulid.ULID`.
62
+ TypeError: If a bound value has an unsupported type.
63
+ """
64
+
65
+ impl = types.Uuid
66
+ cache_ok = True
67
+
68
+ def __init__(self, storage: Storage = "uuid") -> None:
69
+ if storage not in _STORAGES:
70
+ raise ValueError(f"Unknown storage {storage!r}, expected one of {_STORAGES}")
71
+ super().__init__()
72
+ self.storage: Storage = storage
73
+
74
+ @override
75
+ def __repr__(self) -> str:
76
+ if self.storage == "uuid":
77
+ return f"{type(self).__name__}()"
78
+ return f"{type(self).__name__}(storage={self.storage!r})"
79
+
80
+ @override
81
+ @property
82
+ def python_type(self) -> type[ULID]:
83
+ return ULID
84
+
85
+ @override
86
+ def load_dialect_impl(self, dialect: Dialect) -> types.TypeEngine[Any]:
87
+ if self.storage == "binary":
88
+ impl: types.TypeEngine[Any] = (
89
+ postgresql.BYTEA() if dialect.name == "postgresql" else types.BINARY(16)
90
+ )
91
+ elif self.storage == "string":
92
+ impl = types.CHAR(constants.REPR_LEN)
93
+ else:
94
+ impl = types.Uuid(as_uuid=True)
95
+ return impl
96
+
97
+ @override
98
+ def process_bind_param(self, value: Any, dialect: Dialect) -> uuid.UUID | bytes | str | None:
99
+ if value is None:
100
+ return None
101
+ ulid = _to_ulid(value)
102
+ if self.storage == "binary":
103
+ return ulid.bytes
104
+ if self.storage == "string":
105
+ return str(ulid)
106
+ return ulid.to_uuid()
107
+
108
+ @override
109
+ def process_result_value(self, value: Any, dialect: Dialect) -> ULID | None:
110
+ if value is None:
111
+ return None
112
+ if isinstance(value, uuid.UUID):
113
+ return ULID.from_uuid(value)
114
+ if isinstance(value, str):
115
+ return ULID.from_str(value)
116
+ return ULID.from_bytes(bytes(value))
117
+
118
+
119
+ def _to_ulid(value: object) -> ULID:
120
+ # ULID.parse is deliberately not used for every type: it treats int and float values as
121
+ # timestamps and would silently bind a freshly generated ULID.
122
+ if isinstance(value, ULID):
123
+ return value
124
+ if isinstance(value, uuid.UUID):
125
+ return ULID.from_uuid(value)
126
+ if isinstance(value, str):
127
+ return ULID.parse(value)
128
+ if isinstance(value, (bytes, bytearray, memoryview)):
129
+ return ULID.from_bytes(bytes(value))
130
+ if isinstance(value, int) and not isinstance(value, bool):
131
+ return ULID.from_int(value)
132
+ raise TypeError(f"Cannot convert value of type {type(value).__name__} to ULID")
@@ -1,10 +0,0 @@
1
- ulid/__init__.py,sha256=vD10dtMt6iV4_iLJTBkiNwlcBzy1ID0uJg_Dw21iXxY,20995
2
- ulid/__main__.py,sha256=nyRtUgdkXbxxvCRz4XtvnrYWqY6NhHFG2Uf7HtUS18Q,5647
3
- ulid/base32.py,sha256=40jH4ADBs5ZTpfJmLYvwijiy_rGP1JGum7fFkLmkv7k,6088
4
- ulid/constants.py,sha256=lbCLRNQXq8qnOdz_w-nJf_j5dC2X7Gjv-8GJUbs5jX8,503
5
- ulid/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
- python_ulid-4.1.0.dist-info/METADATA,sha256=Zmlduve0O4R_HHJjgnc_TFop8CrLeDZVNmLTGX-W0Ck,8707
7
- python_ulid-4.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
8
- python_ulid-4.1.0.dist-info/entry_points.txt,sha256=9214ghzfSgS8a-TjjlWDF7bI7KSaeewOCBKn5uz7bdU,50
9
- python_ulid-4.1.0.dist-info/licenses/LICENSE,sha256=DiDPNhW5yUHIqaKowvX0c1c9xWiI0xW4ji8R9N2NJbw,1056
10
- python_ulid-4.1.0.dist-info/RECORD,,