Skip to content

Commit 791e0fe

Browse files
committed
add exists() method
1 parent aeaba6f commit 791e0fe

2 files changed

Lines changed: 44 additions & 0 deletions

File tree

src/bubble_data_api_client/client/orm.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,3 +95,14 @@ async def count(cls, *, constraints: list[Constraint] | None = None) -> int:
9595
"""Return total count of objects matching constraints."""
9696
async with _get_client() as client:
9797
return await client.count(cls._typename, constraints=constraints)
98+
99+
@classmethod
100+
async def exists(
101+
cls,
102+
uid: str | None = None,
103+
*,
104+
constraints: list[Constraint] | None = None,
105+
) -> bool:
106+
"""Check if record(s) exist by ID or constraints."""
107+
async with _get_client() as client:
108+
return await client.exists(cls._typename, uid=uid, constraints=constraints)

src/bubble_data_api_client/client/raw_client.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import http
12
import json
23
import types
34
import typing
@@ -105,3 +106,35 @@ async def count(
105106
response = await self.find(typename, constraints=constraints, limit=1)
106107
body = response.json()["response"]
107108
return body["count"] + body["remaining"]
109+
110+
async def exists(
111+
self,
112+
typename: str,
113+
uid: str | None = None,
114+
*,
115+
constraints: list[Constraint] | None = None,
116+
) -> bool:
117+
"""Check if record(s) exist by ID or constraints."""
118+
if uid is not None and constraints is not None:
119+
msg = "Cannot specify both uid and constraints"
120+
raise ValueError(msg)
121+
122+
if uid is not None:
123+
# ID lookup: retrieve + 404 is optimal (no JSON parsing needed)
124+
try:
125+
await self.retrieve(typename, uid)
126+
except httpx.HTTPStatusError as e:
127+
if e.response.status_code == http.HTTPStatus.NOT_FOUND:
128+
return False
129+
raise
130+
else:
131+
return True
132+
133+
# constraint-based: find with exclude_remaining for DB short-circuit
134+
response = await self.find(
135+
typename,
136+
constraints=constraints,
137+
limit=1,
138+
exclude_remaining=True,
139+
)
140+
return response.json()["response"]["count"] >= 1

0 commit comments

Comments
 (0)