python-ulid 4.0.1__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.
- {python_ulid-4.0.1.dist-info → python_ulid-4.2.0.dist-info}/METADATA +62 -5
- python_ulid-4.2.0.dist-info/RECORD +12 -0
- {python_ulid-4.0.1.dist-info → python_ulid-4.2.0.dist-info}/WHEEL +1 -1
- ulid/__init__.py +45 -24
- ulid/__main__.py +15 -6
- ulid/_version.py +24 -0
- ulid/base32.py +3 -1
- ulid/sqlalchemy.py +132 -0
- python_ulid-4.0.1.dist-info/RECORD +0 -10
- {python_ulid-4.0.1.dist-info → python_ulid-4.2.0.dist-info}/entry_points.txt +0 -0
- {python_ulid-4.0.1.dist-info → python_ulid-4.2.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
2
|
Name: python-ulid
|
|
3
|
-
Version: 4.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
|
|
@@ -18,16 +18,18 @@ Classifier: License :: OSI Approved :: MIT License
|
|
|
18
18
|
Classifier: Operating System :: MacOS :: MacOS X
|
|
19
19
|
Classifier: Operating System :: POSIX :: Linux
|
|
20
20
|
Classifier: Programming Language :: Python
|
|
21
|
-
Classifier: Programming Language :: Python :: 3.10
|
|
22
21
|
Classifier: Programming Language :: Python :: 3.11
|
|
23
22
|
Classifier: Programming Language :: Python :: 3.12
|
|
24
23
|
Classifier: Programming Language :: Python :: 3.13
|
|
25
24
|
Classifier: Programming Language :: Python :: 3.14
|
|
25
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
26
26
|
Classifier: Topic :: Software Development :: Libraries
|
|
27
|
-
Requires-Python: >=3.
|
|
28
|
-
Requires-Dist: typing-extensions; python_version < '3.
|
|
27
|
+
Requires-Python: >=3.11
|
|
28
|
+
Requires-Dist: typing-extensions; python_version < '3.12'
|
|
29
29
|
Provides-Extra: pydantic
|
|
30
30
|
Requires-Dist: pydantic>=2.0; extra == 'pydantic'
|
|
31
|
+
Provides-Extra: sqlalchemy
|
|
32
|
+
Requires-Dist: sqlalchemy>=2.0; extra == 'sqlalchemy'
|
|
31
33
|
Description-Content-Type: text/x-rst
|
|
32
34
|
|
|
33
35
|
|
|
@@ -75,6 +77,12 @@ to include Pydantic support install the optional dependency like so
|
|
|
75
77
|
|
|
76
78
|
$ pip install python-ulid[pydantic]
|
|
77
79
|
|
|
80
|
+
and for the SQLAlchemy column type
|
|
81
|
+
|
|
82
|
+
.. code-block:: bash
|
|
83
|
+
|
|
84
|
+
$ pip install python-ulid[sqlalchemy]
|
|
85
|
+
|
|
78
86
|
.. installation-end
|
|
79
87
|
|
|
80
88
|
.. usage-begin
|
|
@@ -150,6 +158,55 @@ The ``ULID`` class can be directly used for the popular data validation library
|
|
|
150
158
|
|
|
151
159
|
.. pydantic-end
|
|
152
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
|
+
|
|
153
210
|
.. monotonic-begin
|
|
154
211
|
|
|
155
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,,
|
ulid/__init__.py
CHANGED
|
@@ -7,7 +7,7 @@ import time
|
|
|
7
7
|
import uuid
|
|
8
8
|
from collections.abc import Callable
|
|
9
9
|
from datetime import datetime
|
|
10
|
-
from datetime import
|
|
10
|
+
from datetime import UTC
|
|
11
11
|
from threading import Lock
|
|
12
12
|
from typing import Any
|
|
13
13
|
from typing import cast
|
|
@@ -20,29 +20,22 @@ try:
|
|
|
20
20
|
except ImportError:
|
|
21
21
|
from typing_extensions import override # type: ignore
|
|
22
22
|
|
|
23
|
+
from ulid import _version
|
|
23
24
|
from ulid import base32
|
|
24
25
|
from ulid import constants
|
|
25
26
|
|
|
26
27
|
|
|
27
28
|
if TYPE_CHECKING: # pragma: no cover
|
|
28
|
-
import
|
|
29
|
+
from typing import Self
|
|
29
30
|
|
|
30
31
|
from pydantic import GetCoreSchemaHandler
|
|
31
32
|
from pydantic import ValidatorFunctionWrapHandler
|
|
32
33
|
from pydantic_core import CoreSchema
|
|
33
34
|
|
|
34
|
-
if sys.version_info >= (3, 11):
|
|
35
|
-
from typing import Self
|
|
36
|
-
else:
|
|
37
|
-
from typing_extensions import Self
|
|
38
35
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
from importlib_metadata import version # type: ignore
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
__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__
|
|
46
39
|
|
|
47
40
|
|
|
48
41
|
RandomnessSource = Callable[[int], bytes]
|
|
@@ -197,13 +190,20 @@ class ULIDGenerator:
|
|
|
197
190
|
def _default_randomness(_timestamp: int) -> bytes:
|
|
198
191
|
return os.urandom(constants.RANDOMNESS_LEN)
|
|
199
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
|
+
|
|
200
198
|
def _normalize_timestamp(self, value: float | datetime | None = None) -> int:
|
|
201
199
|
if value is None:
|
|
202
200
|
value = self.clock()
|
|
203
201
|
elif isinstance(value, datetime):
|
|
204
|
-
value =
|
|
202
|
+
value = self._seconds_to_milliseconds(value.timestamp())
|
|
205
203
|
elif isinstance(value, float):
|
|
206
|
-
value =
|
|
204
|
+
value = self._seconds_to_milliseconds(value)
|
|
205
|
+
if value < constants.MIN_TIMESTAMP:
|
|
206
|
+
raise ValueError("Value is below minimum possible timestamp")
|
|
207
207
|
if value > constants.MAX_TIMESTAMP:
|
|
208
208
|
raise ValueError("Value exceeds maximum possible timestamp")
|
|
209
209
|
return value
|
|
@@ -258,9 +258,11 @@ class ULID:
|
|
|
258
258
|
'01E75PVKXA3GFABX1M1J9NZZNF'
|
|
259
259
|
|
|
260
260
|
Args:
|
|
261
|
-
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`.
|
|
262
263
|
|
|
263
264
|
Raises:
|
|
265
|
+
TypeError: If the provided value is not :class:`bytes` or a bytes-like object.
|
|
264
266
|
ValueError: If the provided value is not a valid encoded ULID.
|
|
265
267
|
"""
|
|
266
268
|
|
|
@@ -268,8 +270,13 @@ class ULID:
|
|
|
268
270
|
self,
|
|
269
271
|
value: bytes | None = None,
|
|
270
272
|
) -> None:
|
|
271
|
-
if value is not None
|
|
272
|
-
|
|
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.")
|
|
273
280
|
if value is None:
|
|
274
281
|
self.bytes: bytes = default_generator.generate().bytes
|
|
275
282
|
else:
|
|
@@ -344,9 +351,17 @@ class ULID:
|
|
|
344
351
|
|
|
345
352
|
@classmethod
|
|
346
353
|
def from_int(cls, value: int) -> Self:
|
|
347
|
-
"""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
|
+
"""
|
|
348
361
|
if not isinstance(value, int):
|
|
349
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")
|
|
350
365
|
return cls(int.to_bytes(value, constants.BYTES_LEN, "big"))
|
|
351
366
|
|
|
352
367
|
@classmethod
|
|
@@ -356,6 +371,10 @@ class ULID:
|
|
|
356
371
|
.. note::
|
|
357
372
|
This method should only be used when the caller is trying to parse a ULID from
|
|
358
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.
|
|
359
378
|
"""
|
|
360
379
|
if isinstance(value, ULID):
|
|
361
380
|
return cast("Self", value)
|
|
@@ -371,9 +390,11 @@ class ULID:
|
|
|
371
390
|
return cls.from_str(value)
|
|
372
391
|
raise ValueError(f"Cannot parse ULID from string of length {len_value}")
|
|
373
392
|
if isinstance(value, int):
|
|
374
|
-
if
|
|
375
|
-
|
|
376
|
-
|
|
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)
|
|
377
398
|
if isinstance(value, float):
|
|
378
399
|
return cls.from_timestamp(value)
|
|
379
400
|
if isinstance(value, datetime):
|
|
@@ -413,7 +434,7 @@ class ULID:
|
|
|
413
434
|
>>> ulid.datetime
|
|
414
435
|
datetime.datetime(2020, 4, 30, 14, 33, 27, 560000, tzinfo=datetime.timezone.utc)
|
|
415
436
|
"""
|
|
416
|
-
return datetime.fromtimestamp(self.timestamp,
|
|
437
|
+
return datetime.fromtimestamp(self.timestamp, UTC)
|
|
417
438
|
|
|
418
439
|
@functools.cached_property
|
|
419
440
|
def hex(self) -> str:
|
|
@@ -594,6 +615,6 @@ class ULID:
|
|
|
594
615
|
ulid = value
|
|
595
616
|
else:
|
|
596
617
|
ulid = cls.from_bytes(value)
|
|
597
|
-
except ValueError as err:
|
|
618
|
+
except (TypeError, ValueError) as err:
|
|
598
619
|
raise PydanticCustomError("ulid_format", "Unrecognized format") from err
|
|
599
620
|
return handler(ulid)
|
ulid/__main__.py
CHANGED
|
@@ -45,7 +45,11 @@ def make_parser(prog: str | None = None) -> argparse.ArgumentParser:
|
|
|
45
45
|
width=min(shutil.get_terminal_size().columns - 2, 127),
|
|
46
46
|
),
|
|
47
47
|
)
|
|
48
|
-
|
|
48
|
+
|
|
49
|
+
def help(*_args: Any) -> None:
|
|
50
|
+
parser.print_help()
|
|
51
|
+
|
|
52
|
+
parser.set_defaults(func=help)
|
|
49
53
|
parser.add_argument("--version", "-V", action="version", version=ulid.__version__)
|
|
50
54
|
|
|
51
55
|
subparsers = parser.add_subparsers(title="subcommands")
|
|
@@ -99,8 +103,13 @@ def make_parser(prog: str | None = None) -> argparse.ArgumentParser:
|
|
|
99
103
|
|
|
100
104
|
|
|
101
105
|
def main(argv: Sequence[str], prog: str | None = None) -> str:
|
|
102
|
-
|
|
103
|
-
|
|
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")
|
|
104
113
|
|
|
105
114
|
|
|
106
115
|
def from_value_or_stdin(value: str, convert: Callable[[str], Any] | None = None) -> Any:
|
|
@@ -163,10 +172,10 @@ def show(args: argparse.Namespace) -> str:
|
|
|
163
172
|
).strip()
|
|
164
173
|
|
|
165
174
|
|
|
166
|
-
def entrypoint() -> None: # pragma: no cover
|
|
167
|
-
if (value := main(sys.argv[1:])) is not None:
|
|
175
|
+
def entrypoint(prog: str | None = None) -> None: # pragma: no cover
|
|
176
|
+
if (value := main(sys.argv[1:], prog)) is not None:
|
|
168
177
|
print(value) # noqa: T201
|
|
169
178
|
|
|
170
179
|
|
|
171
180
|
if __name__ == "__main__": # pragma: no cover
|
|
172
|
-
|
|
181
|
+
entrypoint("python -m ulid")
|
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/base32.py
CHANGED
|
@@ -7,6 +7,8 @@ from ulid import constants
|
|
|
7
7
|
# https://github.com/RobThree/NUlid/blob/89f5a9fc827d191ae5adafe42547575ed3a47723/NUlid/Ulid.cs#L168
|
|
8
8
|
|
|
9
9
|
ENCODE: str = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
|
|
10
|
+
# The ULID spec defines the string representation as case insensitive.
|
|
11
|
+
DECODE_ALPHABET: str = ENCODE + ENCODE.lower()
|
|
10
12
|
DECODE: Sequence[int] = [
|
|
11
13
|
0xFF,
|
|
12
14
|
0xFF,
|
|
@@ -194,7 +196,7 @@ def encode_randomness(binary: bytes) -> str:
|
|
|
194
196
|
def decode(encoded: str) -> bytes:
|
|
195
197
|
if len(encoded) != constants.REPR_LEN:
|
|
196
198
|
raise ValueError("Encoded ULID has to be exactly 26 characters long.")
|
|
197
|
-
if any((c not in
|
|
199
|
+
if any((c not in DECODE_ALPHABET) for c in encoded):
|
|
198
200
|
raise ValueError(f"Encoded ULID can only consist of letters in {ENCODE}.")
|
|
199
201
|
return decode_timestamp(encoded[: constants.TIMESTAMP_REPR_LEN]) + decode_randomness(
|
|
200
202
|
encoded[constants.TIMESTAMP_REPR_LEN :]
|
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=RUAerfe39tcNib2oAREKB7U9DfF-rdXueNg3kF76zV8,21227
|
|
2
|
-
ulid/__main__.py,sha256=ZP8ZbhQ_o-O4Ckbba87bZ4NkwzrSFhAkrRLmUnzkW0Y,5586
|
|
3
|
-
ulid/base32.py,sha256=iUE5BGPW5Dul-Eu3ITvcymk8acNkIFAVTlrL12YIPKI,5961
|
|
4
|
-
ulid/constants.py,sha256=lbCLRNQXq8qnOdz_w-nJf_j5dC2X7Gjv-8GJUbs5jX8,503
|
|
5
|
-
ulid/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
-
python_ulid-4.0.1.dist-info/METADATA,sha256=LuILMUf_zi1x8OonhM9KEuPdygFqPs9R4ubHAMxn6fQ,8758
|
|
7
|
-
python_ulid-4.0.1.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
|
|
8
|
-
python_ulid-4.0.1.dist-info/entry_points.txt,sha256=9214ghzfSgS8a-TjjlWDF7bI7KSaeewOCBKn5uz7bdU,50
|
|
9
|
-
python_ulid-4.0.1.dist-info/licenses/LICENSE,sha256=DiDPNhW5yUHIqaKowvX0c1c9xWiI0xW4ji8R9N2NJbw,1056
|
|
10
|
-
python_ulid-4.0.1.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|