4 Commits
Author SHA1 Message Date
dsql 262636d49f release: 1.0.0
first stable release. pre-1.0.0 verification complete: all surviving MED regressions and
gaps resolved and independently re-fired, tree audited clean across the suite.

Signed-off-by: disqualifier <dev@disqualifier.me>
2026-07-06 21:21:00 -04:00
dsql d89a91e2d9 refactor: derive __version__ from package metadata (single source)
Signed-off-by: disqualifier <dev@disqualifier.me>
2026-07-03 17:00:03 -04:00
dsql fbd94d6c81 docs: add missing trailing newline to README
Signed-off-by: disqualifier <dev@disqualifier.me>
2026-07-03 16:23:37 -04:00
dsql aedc8f3b84 docs: compress prose/module docstrings, em-dash->hyphen (de-bloat wave 1)
Signed-off-by: disqualifier <dev@disqualifier.me>
2026-07-03 00:14:55 -04:00
4 changed files with 35 additions and 65 deletions
+3 -3
View File
@@ -8,18 +8,18 @@ helpers for the common paths, with a raw escape hatch for everything else.
`requirements.txt`: `requirements.txt`:
``` ```
mongo @ git+ssh://git@git.rethinkstudios.io/rethink-public/mongo.git@v0.1.8 mongo @ git+ssh://git@git.rethinkstudios.io/rethink-public/mongo.git@v0.1.9
``` ```
Direct: Direct:
```bash ```bash
pip install "mongo @ git+ssh://git@git.rethinkstudios.io/rethink-public/mongo.git@v0.1.8" pip install "mongo @ git+ssh://git@git.rethinkstudios.io/rethink-public/mongo.git@v0.1.9"
``` ```
Requires `motor` and `pymongo` (pulled transitively). Requires `motor` and `pymongo` (pulled transitively).
Drop the `@v0.1.8` suffix from the line above to install the latest unpinned. Drop the `@v0.1.9` suffix from the line above to install the latest unpinned.
## Usage ## Usage
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project] [project]
name = "mongo" name = "mongo"
version = "0.1.8" version = "1.0.0"
description = "async mongodb wrapper over motor with a raw escape hatch" description = "async mongodb wrapper over motor with a raw escape hatch"
requires-python = ">=3.10" requires-python = ">=3.10"
dependencies = [ dependencies = [
+9 -8
View File
@@ -1,17 +1,18 @@
from importlib.metadata import PackageNotFoundError, version
from .mongo import MongoDB, Mongo, init, instance from .mongo import MongoDB, Mongo, init, instance
__all__ = ["MongoDB", "Mongo", "init", "instance"] __all__ = ["MongoDB", "Mongo", "init", "instance"]
try:
__version__ = version("mongo")
except PackageNotFoundError:
__version__ = "0.0.0+unknown"
def __getattr__(name: str): def __getattr__(name: str):
"""proxy bare package attribute access to the default instance (PEP 562) """proxy bare attribute access to the default instance (PEP 562); needs
`import mongo`, not `from mongo import func` (resolved before init)"""
lets `import mongo; await mongo.get_documents(...)` work after init().
`from mongo import func` still won't see this (resolved before init). the
bare-proxy raw escape hatch is `mongo.collection(name)`, not `mongo[name]` —
module-level subscripting isn't a thing in python, so the proxy only forwards
named attributes (an instance's `db[name]` still works fine).
"""
if not name.startswith("_") and hasattr(MongoDB, name): if not name.startswith("_") and hasattr(MongoDB, name):
return getattr(instance(), name) return getattr(instance(), name)
raise AttributeError(f"module {__name__!r} has no attribute {name!r}") raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+21 -52
View File
@@ -1,41 +1,17 @@
""" """
async mongodb wrapper over motor async mongodb wrapper over motor, with a raw escape hatch for anything not wrapped
object (preferred), one client per process:
from mongo import MongoDB from mongo import MongoDB
bot.db = MongoDB(conn_string, database) db = MongoDB(conn_string, database)
await bot.db.connect() # optional: ping to fail-early await db.get_documents("users", {"active": True})
await bot.db.get_documents("users", {"active": True})
bot.db.close() # on shutdown (sync)
# async with (guaranteed cleanup): `Mongo` is a back-compat alias of `MongoDB`. A module-proxy path also exists
async with MongoDB(conn_string, database) as db: (`mongo.init(...)` then bare `mongo.func(...)`) - see README for both usage patterns.
await db.get_documents("users", {})
`Mongo` is a back-compat alias of `MongoDB`; old `Mongo(...)` call sites still work. errors: wrapped methods log and swallow, returning a safe default (False / [] / {} / 0 /
None). .collection(name) / db[name] return the raw motor collection: full driver surface,
module proxy (back-compat), arm once then call bare: raises, nothing swallowed. mongo SWALLOWS by design, unlike the fail-loud redis/psql/mysql
import mongo # not `from mongo import ...` trio - kept so existing consumers' branch-on-result control flow doesn't break.
mongo.init(conn_string, database)
await mongo.get_documents("users", {"active": True})
errors:
wrapped methods log and swallow, returning a safe default (False / [] / {} / 0 /
None). .collection(name) / db[name] return the raw motor collection: full driver
surface, raises, nothing swallowed. mongo SWALLOWS by design — the one deliberate
difference from the fail-loud redis/psql/mysql trio, kept so existing consumers'
branch-on-result control flow doesn't break.
naming consistency with the trio (all additive — old names still work):
- class is `MongoDB` (was `Mongo`, kept as alias)
- `connect()` / `async with` like the trio (motor connects lazily, so connect()
just pings to validate early)
- `exists()` aliases `check_document_exists()`; `delete()` aliases `delete_document()`
notes:
- the proxy needs `import mongo`; `from mongo import func` resolves before init
- find_one_and_update returns the after-image by default
- bulk_write takes caller-built pymongo ops (UpdateOne/DeleteOne/...)
""" """
import logging import logging
@@ -52,9 +28,6 @@ class MongoDB:
"""async mongodb wrapper; one client per process, attach to bot as bot.db""" """async mongodb wrapper; one client per process, attach to bot as bot.db"""
def __init__(self, connection_string: str, database: str): def __init__(self, connection_string: str, database: str):
# motor builds the client eagerly (no I/O yet); a bad URI raises InvalidURI
# here with nothing built. an invalid db name raises below, after the client
# exists — close it before propagating so it doesn't outlive the raise.
self._client = AsyncIOMotorClient(connection_string) self._client = AsyncIOMotorClient(connection_string)
try: try:
self._db = self._client[database] self._db = self._client[database]
@@ -63,11 +36,8 @@ class MongoDB:
raise raise
async def connect(self) -> "MongoDB": async def connect(self) -> "MongoDB":
"""validate the connection with a ping and return self """validate the connection with a ping and return self; raises, unlike the
swallowing wrapped methods
optional — motor connects lazily, so this just fails early on a bad
URI/credentials (parallel to the trio's connect()). raises, unlike the
swallowing wrapped methods.
an instance is single-use: pymongo 4.x `close()` is irreversible and an instance is single-use: pymongo 4.x `close()` is irreversible and
connect() doesn't rebuild the client. construct a fresh MongoDB instead of connect() doesn't rebuild the client. construct a fresh MongoDB instead of
@@ -80,9 +50,8 @@ class MongoDB:
try: try:
return await self.connect() return await self.connect()
except BaseException: except BaseException:
# __aexit__ is not called when __aenter__ raises, so a failed ping here # __aexit__ isn't called when __aenter__ raises; close here so the
# would otherwise leak the motor client built in __init__. close it # client built in __init__ doesn't leak
# before propagating.
self.close() self.close()
raise raise
@@ -112,7 +81,7 @@ class MongoDB:
return False return False
def close(self) -> None: def close(self) -> None:
"""close the client pool on shutdown (sync motor's close() is synchronous)""" """close the client pool on shutdown (sync - motor's close() is synchronous)"""
self._client.close() self._client.close()
# ------------------------------------------------------------------------- # -------------------------------------------------------------------------
@@ -121,8 +90,8 @@ class MongoDB:
async def create_collection(self, collection: str, index=None) -> bool: async def create_collection(self, collection: str, index=None) -> bool:
"""create a collection, optionally seeding ONE index """create a collection, optionally seeding ONE index
`index` is a single index key-spec (e.g. `[("a", 1), ("b", 1)]` builds one `index` is a single key-spec (e.g. `[("a", 1), ("b", 1)]` builds one compound
compound index, NOT two); call `create_index` per index for multiples. index, not two) - call create_index per index for multiples
""" """
try: try:
await self._db.create_collection(collection) await self._db.create_collection(collection)
@@ -377,7 +346,7 @@ class MongoDB:
"""$set one or more fields on a single document """$set one or more fields on a single document
returns True when a document matched, even if `$set` to an identical value returns True when a document matched, even if `$set` to an identical value
leaves `modified_count=0` uses `matched_count` so an idempotent no-op isn't leaves `modified_count=0` - uses `matched_count` so an idempotent no-op isn't
misread as a failure. misread as a failure.
""" """
try: try:
@@ -392,7 +361,7 @@ class MongoDB:
) -> bool: ) -> bool:
"""apply raw update operators ($set/$inc/$unset/...) to a single document """apply raw update operators ($set/$inc/$unset/...) to a single document
returns True when a document matched, even if the operators changed nothing returns True when a document matched, even if the operators changed nothing -
uses `matched_count` so an idempotent write isn't misread as a failure. uses `matched_count` so an idempotent write isn't misread as a failure.
""" """
try: try:
@@ -406,7 +375,7 @@ class MongoDB:
"""$set fields on a single document, creating it if absent """$set fields on a single document, creating it if absent
returns True when a document matched or was upserted, even if `$set` to an returns True when a document matched or was upserted, even if `$set` to an
identical value leaves `modified_count=0` mirrors update_document_field's identical value leaves `modified_count=0` - mirrors update_document_field's
matched_count-over-modified_count contract. matched_count-over-modified_count contract.
""" """
try: try:
@@ -468,7 +437,7 @@ class MongoDB:
"""$pull a value from an array field """$pull a value from an array field
returns True when a document matched, even if the value was absent and returns True when a document matched, even if the value was absent and
nothing was pulled uses `matched_count`, not `modified_count`. nothing was pulled - uses `matched_count`, not `modified_count`.
""" """
try: try:
response = await self._db[collection].update_one(target, {"$pull": {array: value}}) response = await self._db[collection].update_one(target, {"$pull": {array: value}})
@@ -593,7 +562,7 @@ Mongo = MongoDB
# ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------
# backwards-compat module proxy: `import mongo; mongo.init(conn, db)` then # backwards-compat module proxy: `import mongo; mongo.init(conn, db)` then
# bare `await mongo.func(...)`. needs `import mongo` `from mongo import func` # bare `await mongo.func(...)`. needs `import mongo` - `from mongo import func`
# resolves at import time, before init() runs. # resolves at import time, before init() runs.
_default: Optional[MongoDB] = None _default: Optional[MongoDB] = None