Created
August 24, 2024 20:18
-
-
Save scottjmaddox/77ad39531600556aedb89de58c396511 to your computer and use it in GitHub Desktop.
Dependency-free python `ulid()` function and use in an sqlite3 connection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import os | |
# Base32 encoding alphabet without 'I', 'L', 'O', 'U' | |
CROCKFORD_BASE32_ALPHABET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ' | |
def ulid(): | |
# Generate 48-bit timestamp (time in milliseconds since Unix epoch) | |
timestamp = time.time_ns() // 1_000_000 | |
encoded_time = '' | |
for _ in range(10): | |
encoded_time = CROCKFORD_BASE32_ALPHABET[timestamp % 32] + encoded_time | |
timestamp //= 32 | |
# Generate 80 bits of randomness | |
randomness = int.from_bytes(os.urandom(10)) | |
encoded_randomness = '' | |
for _ in range(16): | |
encoded_randomness = CROCKFORD_BASE32_ALPHABET[randomness % 32] + encoded_randomness | |
randomness //= 32 | |
# Combine the timestamp and randomness into a ULID | |
return encoded_time + encoded_randomness | |
# Example usage: | |
import sqlite3 | |
db = sqlite3.connect("db.sqlite", autocommit=True) | |
db.create_function("ulid", 0, ulid) | |
db.executescript(""" | |
CREATE TABLE IF NOT EXISTS ids ( | |
id TEXT PRIMARY KEY DEFAULT(ulid()) | |
) STRICT; | |
""") | |
db.execute("insert into ids default values;") | |
print(db.execute("select * from ids").fetchone()[0]) | |
# Output: 01J630F55ZPS7S4WC4S8EBRD6C |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment