This repository was archived by the owner on Sep 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdatabase.py
76 lines (61 loc) · 2.41 KB
/
database.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
"""Database as a Service."""
from typing import Any, Dict, List
from httpx import Client
from pydantic import BaseModel
from .base import Base
from .errors import RecordNotFoundError
class DocumentResults(BaseModel):
page: int
size: int
total: int
results: List[Dict[str, Any]]
class Database(Base):
"""Database as a Service API."""
def __init__(self, client: Client, token: str) -> None:
"""Initialize the Database object."""
super().__init__(client, token)
def create_document(self, repo: str, data: Dict[str, Any]) -> Dict[str, Any]:
"""Create a document."""
resp: Any = self._request(f"/db/{repo}", body=data)
return resp # type: ignore
def bulk_create_documents(
self, repo: str, data: List[Dict[str, Any]]
) -> Dict[str, Any]:
"""Create documents in bulk."""
resp: Any = self._request(f"/db/{repo}?bulk=1", body=data)
return resp # type: ignore
def list_documents(
self, repo: str, page: int = 1, size: int = 25, desc: bool = False
) -> DocumentResults:
"""List all documents."""
resp: Any = self._request(f"/db/{repo}", method="get")
return DocumentResults(**resp)
def get_document(self, repo: str, doc_id: str) -> Dict[str, Any]:
resp: Any = self._request(f"/db/{repo}/{doc_id}", method="get")
if isinstance(resp, str):
raise RecordNotFoundError(doc_id)
return resp # type: ignore
def query(
self,
repo: str,
filters: List[Dict[str, Any]],
page: int = 1,
size: int = 25,
desc: bool = False,
) -> Dict[str, Any]:
resp: Any = self._request(f"/db/{repo}", body=filters)
return resp # type: ignore
def update_document(
self, repo: str, doc_id: str, doc: Dict[str, Any]
) -> Dict[str, Any]:
resp: Any = self._request(f"/db/{repo}/{doc_id}", body=doc, method="put")
if isinstance(resp, str):
raise RecordNotFoundError(doc_id)
return resp # type: ignore
def delete_document(self, repo: str, doc_id: str) -> int:
resp: Any = self._request(f"/db/{repo}/{doc_id}", method="delete")
return int(resp)
def increment(self, repo: str, doc_id: str, field: str, range: int) -> Any:
data = {"field": field, "range": range}
resp: Any = self._request(f"/inc/{repo}/{doc_id}", body=data)
return resp