rushdb 0.1.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.
rushdb/__init__.py ADDED
@@ -0,0 +1,21 @@
1
+ """RushDB Client Package
2
+
3
+ Exposes the RushDBClient class.
4
+ """
5
+
6
+ from .client import RushDBClient
7
+ from .common import RushDBError
8
+ from .models.property import Property
9
+ from .models.record import Record
10
+ from .models.relationship import RelationshipDetachOptions, RelationshipOptions
11
+ from .models.transaction import Transaction
12
+
13
+ __all__ = [
14
+ "RushDBClient",
15
+ "RushDBError",
16
+ "Record",
17
+ "Transaction",
18
+ "Property",
19
+ "RelationshipOptions",
20
+ "RelationshipDetachOptions",
21
+ ]
rushdb/api/__init__.py ADDED
File without changes
rushdb/api/base.py ADDED
@@ -0,0 +1,11 @@
1
+ from typing import TYPE_CHECKING
2
+
3
+ if TYPE_CHECKING:
4
+ from ..client import RushDBClient
5
+
6
+
7
+ class BaseAPI:
8
+ """Base class for all API endpoints."""
9
+
10
+ def __init__(self, client: "RushDBClient"):
11
+ self.client = client
rushdb/api/labels.py ADDED
@@ -0,0 +1,25 @@
1
+ import typing
2
+ from typing import List, Optional
3
+
4
+ from ..models.search_query import SearchQuery
5
+ from ..models.transaction import Transaction
6
+ from .base import BaseAPI
7
+
8
+
9
+ class LabelsAPI(BaseAPI):
10
+ """API for managing labels in RushDB."""
11
+
12
+ def list(
13
+ self,
14
+ query: Optional[SearchQuery] = None,
15
+ transaction: Optional[Transaction] = None,
16
+ ) -> List[str]:
17
+ """List all labels."""
18
+ headers = Transaction._build_transaction_header(transaction)
19
+
20
+ return self.client._make_request(
21
+ "POST",
22
+ "/api/v1/labels",
23
+ data=typing.cast(typing.Dict[str, typing.Any], query or {}),
24
+ headers=headers,
25
+ )
@@ -0,0 +1,64 @@
1
+ import typing
2
+ from typing import List, Literal, Optional
3
+
4
+ from ..models.property import Property, PropertyValuesData
5
+ from ..models.search_query import SearchQuery
6
+ from ..models.transaction import Transaction
7
+ from .base import BaseAPI
8
+
9
+
10
+ class PropertiesAPI(BaseAPI):
11
+ """API for managing properties in RushDB."""
12
+
13
+ def find(
14
+ self,
15
+ query: Optional[SearchQuery] = None,
16
+ transaction: Optional[Transaction] = None,
17
+ ) -> List[Property]:
18
+ """List all properties."""
19
+ headers = Transaction._build_transaction_header(transaction)
20
+
21
+ return self.client._make_request(
22
+ "POST",
23
+ "/api/v1/properties",
24
+ typing.cast(typing.Dict[str, typing.Any], query or {}),
25
+ headers,
26
+ )
27
+
28
+ def find_by_id(
29
+ self, property_id: str, transaction: Optional[Transaction] = None
30
+ ) -> Property:
31
+ """Get a property by ID."""
32
+ headers = Transaction._build_transaction_header(transaction)
33
+
34
+ return self.client._make_request(
35
+ "GET", f"/api/v1/properties/{property_id}", headers=headers
36
+ )
37
+
38
+ def delete(
39
+ self, property_id: str, transaction: Optional[Transaction] = None
40
+ ) -> None:
41
+ """Delete a property."""
42
+ headers = Transaction._build_transaction_header(transaction)
43
+
44
+ return self.client._make_request(
45
+ "DELETE", f"/api/v1/properties/{property_id}", headers=headers
46
+ )
47
+
48
+ def values(
49
+ self,
50
+ property_id: str,
51
+ sort: Optional[Literal["asc", "desc"]],
52
+ skip: Optional[int],
53
+ limit: Optional[int],
54
+ transaction: Optional[Transaction] = None,
55
+ ) -> PropertyValuesData:
56
+ """Get values data for a property."""
57
+ headers = Transaction._build_transaction_header(transaction)
58
+
59
+ return self.client._make_request(
60
+ "GET",
61
+ f"/api/v1/properties/{property_id}/values",
62
+ headers=headers,
63
+ params={"sort": sort, "skip": skip, "limit": limit},
64
+ )
rushdb/api/records.py ADDED
@@ -0,0 +1,250 @@
1
+ import typing
2
+ from typing import Any, Dict, List, Optional, Union
3
+
4
+ from ..models.record import Record
5
+ from ..models.relationship import RelationshipDetachOptions, RelationshipOptions
6
+ from ..models.search_query import SearchQuery
7
+ from ..models.transaction import Transaction
8
+ from .base import BaseAPI
9
+
10
+
11
+ class RecordsAPI(BaseAPI):
12
+ """API for managing records in RushDB."""
13
+
14
+ def set(
15
+ self,
16
+ record_id: str,
17
+ data: Dict[str, Any],
18
+ transaction: Optional[Transaction] = None,
19
+ ) -> Dict[str, str]:
20
+ """Update a record by ID."""
21
+ headers = Transaction._build_transaction_header(transaction)
22
+ return self.client._make_request(
23
+ "PUT", f"/api/v1/records/{record_id}", data, headers
24
+ )
25
+
26
+ def update(
27
+ self,
28
+ record_id: str,
29
+ data: Dict[str, Any],
30
+ transaction: Optional[Transaction] = None,
31
+ ) -> Dict[str, str]:
32
+ """Update a record by ID."""
33
+ headers = Transaction._build_transaction_header(transaction)
34
+
35
+ return self.client._make_request(
36
+ "PATCH", f"/api/v1/records/{record_id}", data, headers
37
+ )
38
+
39
+ def create(
40
+ self,
41
+ label: str,
42
+ data: Dict[str, Any],
43
+ options: Optional[Dict[str, bool]] = None,
44
+ transaction: Optional[Transaction] = None,
45
+ ) -> Record:
46
+ """Create a new record.
47
+
48
+ Args:
49
+ label: Label for the record
50
+ data: Record data
51
+ options: Optional parsing and response options (returnResult, suggestTypes)
52
+ transaction: Optional transaction object
53
+
54
+ Returns:
55
+ Record object
56
+ :param
57
+ """
58
+ headers = Transaction._build_transaction_header(transaction)
59
+
60
+ payload = {
61
+ "label": label,
62
+ "payload": data,
63
+ "options": options or {"returnResult": True, "suggestTypes": True},
64
+ }
65
+ response = self.client._make_request(
66
+ "POST", "/api/v1/records", payload, headers
67
+ )
68
+ return Record(self.client, response.get("data"))
69
+
70
+ def create_many(
71
+ self,
72
+ label: str,
73
+ data: Union[Dict[str, Any], List[Dict[str, Any]]],
74
+ options: Optional[Dict[str, bool]] = None,
75
+ transaction: Optional[Transaction] = None,
76
+ ) -> List[Record]:
77
+ """Create multiple records.
78
+
79
+ Args:
80
+ label: Label for all records
81
+ data: List or Dict of record data
82
+ options: Optional parsing and response options (returnResult, suggestTypes)
83
+ transaction: Optional transaction object
84
+
85
+ Returns:
86
+ List of Record objects
87
+ """
88
+ headers = Transaction._build_transaction_header(transaction)
89
+
90
+ payload = {
91
+ "label": label,
92
+ "payload": data,
93
+ "options": options or {"returnResult": True, "suggestTypes": True},
94
+ }
95
+ response = self.client._make_request(
96
+ "POST", "/api/v1/records/import/json", payload, headers
97
+ )
98
+ return [Record(self.client, record) for record in response.get("data")]
99
+
100
+ def attach(
101
+ self,
102
+ source: Union[str, Dict[str, Any]],
103
+ target: Union[
104
+ str,
105
+ List[str],
106
+ Dict[str, Any],
107
+ List[Dict[str, Any]],
108
+ "Record",
109
+ List["Record"],
110
+ ],
111
+ options: Optional[RelationshipOptions] = None,
112
+ transaction: Optional[Transaction] = None,
113
+ ) -> Dict[str, str]:
114
+ """Attach records to a source record."""
115
+ headers = Transaction._build_transaction_header(transaction)
116
+
117
+ source_id = self._extract_target_ids(source)[0]
118
+ target_ids = self._extract_target_ids(target)
119
+ payload = {"targetIds": target_ids}
120
+ if options:
121
+ payload.update(typing.cast(typing.Dict[str, typing.Any], options))
122
+ return self.client._make_request(
123
+ "POST", f"/api/v1/records/{source_id}/relations", payload, headers
124
+ )
125
+
126
+ def detach(
127
+ self,
128
+ source: Union[str, Dict[str, Any]],
129
+ target: Union[
130
+ str,
131
+ List[str],
132
+ Dict[str, Any],
133
+ List[Dict[str, Any]],
134
+ "Record",
135
+ List["Record"],
136
+ ],
137
+ options: Optional[RelationshipDetachOptions] = None,
138
+ transaction: Optional[Transaction] = None,
139
+ ) -> Dict[str, str]:
140
+ """Detach records from a source record."""
141
+ headers = Transaction._build_transaction_header(transaction)
142
+
143
+ source_id = self._extract_target_ids(source)[0]
144
+ target_ids = self._extract_target_ids(target)
145
+ payload = {"targetIds": target_ids}
146
+ if options:
147
+ payload.update(typing.cast(typing.Dict[str, typing.Any], options))
148
+ return self.client._make_request(
149
+ "PUT", f"/api/v1/records/{source_id}/relations", payload, headers
150
+ )
151
+
152
+ def delete(
153
+ self, query: SearchQuery, transaction: Optional[Transaction] = None
154
+ ) -> Dict[str, str]:
155
+ """Delete records matching the query."""
156
+ headers = Transaction._build_transaction_header(transaction)
157
+
158
+ return self.client._make_request(
159
+ "PUT",
160
+ "/api/v1/records/delete",
161
+ typing.cast(typing.Dict[str, typing.Any], query or {}),
162
+ headers,
163
+ )
164
+
165
+ def delete_by_id(
166
+ self,
167
+ id_or_ids: Union[str, List[str]],
168
+ transaction: Optional[Transaction] = None,
169
+ ) -> Dict[str, str]:
170
+ """Delete records by ID(s)."""
171
+ headers = Transaction._build_transaction_header(transaction)
172
+
173
+ if isinstance(id_or_ids, list):
174
+ return self.client._make_request(
175
+ "PUT",
176
+ "/api/v1/records/delete",
177
+ {"limit": 1000, "where": {"$id": {"$in": id_or_ids}}},
178
+ headers,
179
+ )
180
+ return self.client._make_request(
181
+ "DELETE", f"/api/v1/records/{id_or_ids}", None, headers
182
+ )
183
+
184
+ def find(
185
+ self,
186
+ query: Optional[SearchQuery] = None,
187
+ record_id: Optional[str] = None,
188
+ transaction: Optional[Transaction] = None,
189
+ ) -> List[Record]:
190
+ """Find records matching the query."""
191
+
192
+ try:
193
+ headers = Transaction._build_transaction_header(transaction)
194
+
195
+ path = (
196
+ f"/api/v1/records/{record_id}/search"
197
+ if record_id
198
+ else "/api/v1/records/search"
199
+ )
200
+ response = self.client._make_request(
201
+ "POST",
202
+ path,
203
+ data=typing.cast(typing.Dict[str, typing.Any], query or {}),
204
+ headers=headers,
205
+ )
206
+ return [Record(self.client, record) for record in response.get("data")]
207
+ except Exception:
208
+ return []
209
+
210
+ def import_csv(
211
+ self,
212
+ label: str,
213
+ csv_data: Union[str, bytes],
214
+ options: Optional[Dict[str, bool]] = None,
215
+ transaction: Optional[Transaction] = None,
216
+ ) -> List[Dict[str, Any]]:
217
+ """Import data from CSV."""
218
+ headers = Transaction._build_transaction_header(transaction)
219
+
220
+ payload = {
221
+ "label": label,
222
+ "payload": csv_data,
223
+ "options": options or {"returnResult": True, "suggestTypes": True},
224
+ }
225
+
226
+ return self.client._make_request(
227
+ "POST", "/api/v1/records/import/csv", payload, headers
228
+ )
229
+
230
+ @staticmethod
231
+ def _extract_target_ids(
232
+ target: Union[
233
+ str,
234
+ List[str],
235
+ Dict[str, Any],
236
+ List[Dict[str, Any]],
237
+ "Record",
238
+ List["Record"],
239
+ ]
240
+ ) -> List[str]:
241
+ """Extract target IDs from various input types."""
242
+ if isinstance(target, str):
243
+ return [target]
244
+ elif isinstance(target, list):
245
+ return [t.get("__id", "") if isinstance(t, dict) else "" for t in target]
246
+ elif isinstance(target, Record) and "__id" in target.data:
247
+ return [target.data["__id"]]
248
+ elif isinstance(target, dict) and "__id" in target:
249
+ return [target["__id"]]
250
+ raise ValueError("Invalid target format")
@@ -0,0 +1,60 @@
1
+ import typing
2
+ from typing import List, Optional, TypedDict, Union
3
+ from urllib.parse import urlencode
4
+
5
+ from ..models.relationship import Relationship
6
+ from ..models.search_query import SearchQuery
7
+ from ..models.transaction import Transaction
8
+ from .base import BaseAPI
9
+
10
+
11
+ class PaginationParams(TypedDict, total=False):
12
+ """TypedDict for pagination parameters."""
13
+
14
+ limit: int
15
+ skip: int
16
+
17
+
18
+ class RelationsAPI(BaseAPI):
19
+ """API for managing relationships in RushDB."""
20
+
21
+ async def find(
22
+ self,
23
+ query: Optional[SearchQuery] = None,
24
+ pagination: Optional[PaginationParams] = None,
25
+ transaction: Optional[Union[Transaction, str]] = None,
26
+ ) -> List[Relationship]:
27
+ """Find relations matching the search parameters.
28
+
29
+ Args:
30
+ query: Search query parameters
31
+ pagination: Optional pagination parameters (limit and skip)
32
+ transaction: Optional transaction context or transaction ID
33
+
34
+ Returns:
35
+ List of matching relations
36
+ """
37
+ # Build query string for pagination
38
+ query_params = {}
39
+ if pagination:
40
+ if pagination.get("limit") is not None:
41
+ query_params["limit"] = str(pagination["limit"])
42
+ if pagination.get("skip") is not None:
43
+ query_params["skip"] = str(pagination["skip"])
44
+
45
+ # Construct path with query string
46
+ query_string = f"?{urlencode(query_params)}" if query_params else ""
47
+ path = f"/records/relations/search{query_string}"
48
+
49
+ # Build headers with transaction if present
50
+ headers = Transaction._build_transaction_header(transaction)
51
+
52
+ # Make request
53
+ response = self.client._make_request(
54
+ method="POST",
55
+ path=path,
56
+ data=typing.cast(typing.Dict[str, typing.Any], query or {}),
57
+ headers=headers,
58
+ )
59
+
60
+ return response.data
@@ -0,0 +1,29 @@
1
+ from typing import Optional
2
+
3
+ from ..models.transaction import Transaction
4
+ from .base import BaseAPI
5
+
6
+
7
+ class TransactionsAPI(BaseAPI):
8
+ """API for managing transactions in RushDB."""
9
+
10
+ def begin(self, ttl: Optional[int] = None) -> Transaction:
11
+ """Begin a new transaction.
12
+
13
+ Returns:
14
+ Transaction object
15
+ """
16
+ response = self.client._make_request("POST", "/api/v1/tx", {"ttl": ttl or 5000})
17
+ return Transaction(self.client, response.get("data")["id"])
18
+
19
+ def _commit(self, transaction_id: str) -> None:
20
+ """Internal method to commit a transaction."""
21
+ return self.client._make_request(
22
+ "POST", f"/api/v1/tx/{transaction_id}/commit", {}
23
+ )
24
+
25
+ def _rollback(self, transaction_id: str) -> None:
26
+ """Internal method to rollback a transaction."""
27
+ return self.client._make_request(
28
+ "POST", f"/api/v1/tx/{transaction_id}/rollback", {}
29
+ )
rushdb/client.py ADDED
@@ -0,0 +1,106 @@
1
+ """RushDB Client"""
2
+
3
+ import json
4
+ import urllib.error
5
+ import urllib.parse
6
+ import urllib.request
7
+ from typing import Any, Dict, Optional
8
+
9
+ from .api.labels import LabelsAPI
10
+ from .api.properties import PropertiesAPI
11
+ from .api.records import RecordsAPI
12
+ from .api.transactions import TransactionsAPI
13
+ from .common import RushDBError
14
+
15
+
16
+ class RushDBClient:
17
+ """Main client for interacting with RushDB."""
18
+
19
+ DEFAULT_BASE_URL = "https://api.rushdb.com"
20
+
21
+ def __init__(self, api_key: str, base_url: Optional[str] = None):
22
+ """Initialize the RushDB client.
23
+
24
+ Args:
25
+ api_key: The API key for authentication
26
+ base_url: Optional base URL for the RushDB server (default: https://api.rushdb.com)
27
+ """
28
+ self.base_url = (base_url or self.DEFAULT_BASE_URL).rstrip("/")
29
+ self.api_key = api_key
30
+ self.records = RecordsAPI(self)
31
+ self.properties = PropertiesAPI(self)
32
+ self.labels = LabelsAPI(self)
33
+ self.transactions = TransactionsAPI(self)
34
+
35
+ def _make_request(
36
+ self,
37
+ method: str,
38
+ path: str,
39
+ data: Optional[Dict] = None,
40
+ headers: Optional[Dict[str, str]] = None,
41
+ params: Optional[Dict[str, Any]] = None,
42
+ ) -> Any:
43
+ """Make an HTTP request to the RushDB server.
44
+
45
+ Args:
46
+ method: HTTP method (GET, POST, PUT, DELETE)
47
+ path: API endpoint path
48
+ data: Request body data
49
+ headers: Optional request headers
50
+ params: Optional URL query parameters
51
+
52
+ Returns:
53
+ The parsed JSON response
54
+ """
55
+ # Ensure path starts with /
56
+ if not path.startswith("/"):
57
+ path = "/" + path
58
+
59
+ # Clean and encode path components
60
+ path = path.strip()
61
+ path_parts = [
62
+ urllib.parse.quote(part, safe="") for part in path.split("/") if part
63
+ ]
64
+ clean_path = "/" + "/".join(path_parts)
65
+
66
+ # Build URL with query parameters
67
+ url = f"{self.base_url}{clean_path}"
68
+ if params:
69
+ query_string = urllib.parse.urlencode(params)
70
+ url = f"{url}?{query_string}"
71
+
72
+ # Prepare headers
73
+ request_headers = {
74
+ "token": self.api_key,
75
+ "Content-Type": "application/json",
76
+ **(headers or {}),
77
+ }
78
+
79
+ try:
80
+ # Prepare request body
81
+ body = None
82
+ if data is not None:
83
+ body = json.dumps(data).encode("utf-8")
84
+
85
+ # Create and send request
86
+ request = urllib.request.Request(
87
+ url, data=body, headers=request_headers, method=method
88
+ )
89
+
90
+ with urllib.request.urlopen(request) as response:
91
+ return json.loads(response.read().decode("utf-8"))
92
+ except urllib.error.HTTPError as e:
93
+ error_body = json.loads(e.read().decode("utf-8"))
94
+ raise RushDBError(error_body.get("message", str(e)), error_body)
95
+ except urllib.error.URLError as e:
96
+ raise RushDBError(f"Connection error: {str(e)}")
97
+ except json.JSONDecodeError as e:
98
+ raise RushDBError(f"Invalid JSON response: {str(e)}")
99
+
100
+ def ping(self) -> bool:
101
+ """Check if the server is reachable."""
102
+ try:
103
+ self._make_request("GET", "/")
104
+ return True
105
+ except RushDBError:
106
+ return False
rushdb/common.py ADDED
@@ -0,0 +1,9 @@
1
+ from typing import Dict, Optional
2
+
3
+
4
+ class RushDBError(Exception):
5
+ """Custom exception for RushDB client errors."""
6
+
7
+ def __init__(self, message: str, details: Optional[Dict] = None):
8
+ super().__init__(message)
9
+ self.details = details or {}
File without changes
@@ -0,0 +1,55 @@
1
+ from typing import Any, List, Literal, Optional, TypedDict, Union
2
+
3
+
4
+ # Value types
5
+ class DatetimeObject(TypedDict, total=False):
6
+ """Datetime object structure"""
7
+
8
+ year: int
9
+ month: Optional[int]
10
+ day: Optional[int]
11
+ hour: Optional[int]
12
+ minute: Optional[int]
13
+ second: Optional[int]
14
+ millisecond: Optional[int]
15
+ microsecond: Optional[int]
16
+ nanosecond: Optional[int]
17
+
18
+
19
+ DatetimeValue = Union[DatetimeObject, str]
20
+ BooleanValue = bool
21
+ NumberValue = float
22
+ StringValue = str
23
+
24
+ # Property types
25
+ PropertyType = Literal["boolean", "datetime", "null", "number", "string"]
26
+
27
+
28
+ class Property(TypedDict):
29
+ """Base property structure"""
30
+
31
+ id: str
32
+ name: str
33
+ type: PropertyType
34
+ metadata: Optional[str]
35
+
36
+
37
+ class PropertyWithValue(Property):
38
+ """Property with a value"""
39
+
40
+ value: Union[
41
+ DatetimeValue,
42
+ BooleanValue,
43
+ None,
44
+ NumberValue,
45
+ StringValue,
46
+ List[Union[DatetimeValue, BooleanValue, None, NumberValue, StringValue]],
47
+ ]
48
+
49
+
50
+ class PropertyValuesData(TypedDict, total=False):
51
+ """Property values data structure"""
52
+
53
+ max: Optional[float]
54
+ min: Optional[float]
55
+ values: List[Any]
@@ -0,0 +1,112 @@
1
+ from datetime import datetime
2
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
3
+
4
+ from .relationship import RelationshipDetachOptions, RelationshipOptions
5
+ from .transaction import Transaction
6
+
7
+ if TYPE_CHECKING:
8
+ from ..client import RushDBClient
9
+
10
+
11
+ class Record:
12
+ """Represents a record in RushDB with methods for manipulation."""
13
+
14
+ def __init__(
15
+ self, client: "RushDBClient", data: Union[Dict[str, Any], None] = None
16
+ ):
17
+ self._client = client
18
+ # Handle different data formats
19
+ if isinstance(data, dict):
20
+ self.data = data
21
+ elif isinstance(data, str):
22
+ # If just a string is passed, assume it's an ID
23
+ self.data = {}
24
+ else:
25
+ raise ValueError(f"Invalid data format for Record: {type(data)}")
26
+
27
+ @property
28
+ def id(self) -> str:
29
+ """Get record ID."""
30
+ record_id = self.data.get("__id")
31
+ if record_id is None:
32
+ raise ValueError("Record ID is missing or None")
33
+
34
+ return record_id
35
+
36
+ @property
37
+ def proptypes(self) -> str:
38
+ """Get record ID."""
39
+ return self.data["__proptypes"]
40
+
41
+ @property
42
+ def label(self) -> str:
43
+ """Get record ID."""
44
+ return self.data["__label"]
45
+
46
+ @property
47
+ def timestamp(self) -> int:
48
+ """Get record timestamp from ID."""
49
+ record_id = self.data.get("__id")
50
+ if record_id is None:
51
+ raise ValueError("Record ID is missing or None")
52
+
53
+ parts = record_id.split("-")
54
+ high_bits_hex = parts[0] + parts[1][:4]
55
+ return int(high_bits_hex, 16)
56
+
57
+ @property
58
+ def date(self) -> datetime:
59
+ """Get record creation date from ID."""
60
+ return datetime.fromtimestamp(self.timestamp / 1000)
61
+
62
+ def set(
63
+ self, data: Dict[str, Any], transaction: Optional[Transaction] = None
64
+ ) -> Dict[str, str]:
65
+ """Set record data through API request."""
66
+ return self._client.records.set(self.id, data, transaction)
67
+
68
+ def update(
69
+ self, data: Dict[str, Any], transaction: Optional[Transaction] = None
70
+ ) -> Dict[str, str]:
71
+ """Update record data through API request."""
72
+ return self._client.records.update(self.id, data, transaction)
73
+
74
+ def attach(
75
+ self,
76
+ target: Union[
77
+ str,
78
+ List[str],
79
+ Dict[str, Any],
80
+ List[Dict[str, Any]],
81
+ "Record",
82
+ List["Record"],
83
+ ],
84
+ options: Optional[RelationshipOptions] = None,
85
+ transaction: Optional[Transaction] = None,
86
+ ) -> Dict[str, str]:
87
+ """Attach other records to this record."""
88
+ return self._client.records.attach(self.id, target, options, transaction)
89
+
90
+ def detach(
91
+ self,
92
+ target: Union[
93
+ str,
94
+ List[str],
95
+ Dict[str, Any],
96
+ List[Dict[str, Any]],
97
+ "Record",
98
+ List["Record"],
99
+ ],
100
+ options: Optional[RelationshipDetachOptions] = None,
101
+ transaction: Optional[Transaction] = None,
102
+ ) -> Dict[str, str]:
103
+ """Detach records from this record."""
104
+ return self._client.records.detach(self.id, target, options, transaction)
105
+
106
+ def delete(self, transaction: Optional[Transaction] = None) -> Dict[str, str]:
107
+ """Delete this record."""
108
+ return self._client.records.delete_by_id(self.id, transaction)
109
+
110
+ def __repr__(self) -> str:
111
+ """String representation of record."""
112
+ return f"Record(id='{self.id}')"
@@ -0,0 +1,25 @@
1
+ from typing import List, Literal, Optional, TypedDict, Union
2
+
3
+ RelationshipDirection = Literal["in", "out"]
4
+
5
+
6
+ class Relationship(TypedDict, total=False):
7
+ targetLabel: str
8
+ targetId: str
9
+ type: str
10
+ sourceId: str
11
+ sourceLabel: str
12
+
13
+
14
+ class RelationshipOptions(TypedDict, total=False):
15
+ """Options for creating relations."""
16
+
17
+ direction: Optional[RelationshipDirection]
18
+ type: Optional[str]
19
+
20
+
21
+ class RelationshipDetachOptions(TypedDict, total=False):
22
+ """Options for detaching relations."""
23
+
24
+ direction: Optional[RelationshipDirection]
25
+ typeOrTypes: Optional[Union[str, List[str]]]
@@ -0,0 +1,18 @@
1
+ from enum import Enum
2
+ from typing import Any, Dict, List, Optional, TypedDict, Union
3
+
4
+
5
+ class OrderDirection(str, Enum):
6
+ ASC = "asc"
7
+ DESC = "desc"
8
+
9
+
10
+ class SearchQuery(TypedDict, total=False):
11
+ """TypedDict representing the query structure for finding records."""
12
+
13
+ where: Optional[Dict[str, Any]]
14
+ labels: Optional[List[str]]
15
+ skip: Optional[int]
16
+ limit: Optional[int]
17
+ orderBy: Optional[Union[Dict[str, OrderDirection], OrderDirection]]
18
+ aggregate: Optional[Dict[str, Any]]
@@ -0,0 +1,54 @@
1
+ from typing import TYPE_CHECKING, Dict, Optional, Union
2
+
3
+ from ..common import RushDBError
4
+
5
+ if TYPE_CHECKING:
6
+ from ..client import RushDBClient
7
+
8
+
9
+ class Transaction:
10
+ """Represents a RushDB transaction."""
11
+
12
+ def __init__(self, client: "RushDBClient", transaction_id: str):
13
+ self.client = client
14
+ self.id = transaction_id
15
+ self._committed = False
16
+ self._rolled_back = False
17
+
18
+ def commit(self) -> None:
19
+ """Commit the transaction."""
20
+ if self._committed or self._rolled_back:
21
+ raise RushDBError("Transaction already completed")
22
+ self.client.transactions._commit(self.id)
23
+ self._committed = True
24
+
25
+ def rollback(self) -> None:
26
+ """Rollback the transaction."""
27
+ if self._committed or self._rolled_back:
28
+ raise RushDBError("Transaction already completed")
29
+ self.client.transactions._rollback(self.id)
30
+ self._rolled_back = True
31
+
32
+ @staticmethod
33
+ def _build_transaction_header(
34
+ transaction: Optional[Union[str, "Transaction"]] = None,
35
+ ) -> Optional[Dict[str, str]]:
36
+ """Build transaction header if transaction_id is provided."""
37
+ transaction_id = None
38
+
39
+ if isinstance(transaction, Transaction):
40
+ transaction_id = transaction.id
41
+ else:
42
+ transaction_id = transaction
43
+
44
+ return {"X-Transaction-Id": transaction_id} if transaction_id else None
45
+
46
+ def __enter__(self) -> "Transaction":
47
+ return self
48
+
49
+ def __exit__(self, exc_type, exc_val, exc_tb):
50
+ if exc_type is not None:
51
+ if not self._rolled_back:
52
+ self.rollback()
53
+ elif not self._committed and not self._rolled_back:
54
+ self.commit()
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 Collect Software Inc.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,174 @@
1
+ Metadata-Version: 2.1
2
+ Name: rushdb
3
+ Version: 0.1.0
4
+ Summary: RushDB Python SDK
5
+ Home-page: https://github.com/rushdb/rushdb-python
6
+ License: Apache-2.0
7
+ Keywords: database,graph database,instant database,instant-database,instantdatabase,instant db,instant-db,instantdb,neo4j,cypher,ai,ai database,etl,data-pipeline,data science,data-science,data management,data-management,machine learning,machine-learning,persistence,db,graph,graphs,graph-database,self-hosted,rush-db,rush db,rushdb
8
+ Author: RushDB Team
9
+ Author-email: hi@rushdb.com
10
+ Requires-Python: >=3.8,<4.0
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.8
14
+ Classifier: Programming Language :: Python :: 3.9
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Requires-Dist: python-dotenv (>=1.0.0,<2.0.0)
19
+ Requires-Dist: requests (>=2.31.0,<3.0.0)
20
+ Project-URL: Documentation, https://docs.rushdb.com
21
+ Project-URL: Repository, https://github.com/rushdb/rushdb-python
22
+ Description-Content-Type: text/markdown
23
+
24
+ <div align="center">
25
+
26
+ ![RushDB Logo](https://raw.githubusercontent.com/rush-db/rushdb/main/rushdb-logo.svg)
27
+
28
+ # RushDB Python SDK
29
+ ### The Instant Database for Modern Apps and DS/ML Ops
30
+
31
+ RushDB is an open-source database built on Neo4j, designed to simplify application development.
32
+
33
+ It automates data normalization, manages relationships, and infers data types, enabling developers to focus on building features rather than wrestling with data.
34
+
35
+ [🌐 Homepage](https://rushdb.com) — [📢 Blog](https://rushdb.com/blog) — [☁️ Platform ](https://app.rushdb.com) — [📚 Docs](https://docs.rushdb.com) — [🧑‍💻 Examples](https://github.com/rush-db/rushdb/examples)
36
+ </div>
37
+
38
+ ## 🚀 Feature Highlights
39
+
40
+ ### 1. **Data modeling is optional**
41
+ Push data of any shape—RushDB handles relationships, data types, and more automatically.
42
+
43
+ ### 2. **Automatic type inference**
44
+ Minimizes overhead while optimizing performance for high-speed searches.
45
+
46
+ ### 3. **Powerful search API**
47
+ Query data with accuracy using the graph-powered search API.
48
+
49
+ ### 4. **Flexible data import**
50
+ Easily import data in `JSON`, `CSV`, or `JSONB`, creating data-rich applications fast.
51
+
52
+ ### 5. **Developer-Centric Design**
53
+ RushDB prioritizes DX with an intuitive and consistent API.
54
+
55
+ ### 6. **REST API Readiness**
56
+ A REST API with SDK-like DX for every operation: manage relationships, create, delete, and search effortlessly. Same DTO everywhere.
57
+
58
+ ---
59
+
60
+ ## Installation
61
+
62
+ Install the RushDB Python SDK via pip:
63
+
64
+ ```sh
65
+ pip install rushdb
66
+ ```
67
+
68
+ ---
69
+
70
+ ## Usage
71
+
72
+ ### **1. Setup SDK**
73
+
74
+ ```python
75
+ from rushdb import RushDB
76
+
77
+ db = RushDB("API_TOKEN", url="https://api.rushdb.com")
78
+ ```
79
+
80
+ ---
81
+
82
+ ### **2. Push any JSON data**
83
+
84
+ ```python
85
+ company_data = {
86
+ "label": "COMPANY",
87
+ "payload": {
88
+ "name": "Google LLC",
89
+ "address": "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA",
90
+ "foundedAt": "1998-09-04T00:00:00.000Z",
91
+ "rating": 4.9,
92
+ "DEPARTMENT": [{
93
+ "name": "Research & Development",
94
+ "description": "Innovating and creating advanced technologies for AI, cloud computing, and consumer devices.",
95
+ "PROJECT": [{
96
+ "name": "Bard AI",
97
+ "description": "A state-of-the-art generative AI model for natural language understanding and creation.",
98
+ "active": True,
99
+ "budget": 1200000000,
100
+ "EMPLOYEE": [{
101
+ "name": "Jeff Dean",
102
+ "position": "Head of AI Research",
103
+ "email": "jeff@google.com",
104
+ "dob": "1968-07-16T00:00:00.000Z",
105
+ "salary": 3000000
106
+ }]
107
+ }]
108
+ }]
109
+ }
110
+ }
111
+
112
+ db.records.create_many(company_data)
113
+ ```
114
+
115
+ ---
116
+
117
+ ### **3. Find Records by specific criteria**
118
+
119
+ ```python
120
+ query = {
121
+ "labels": ["EMPLOYEE"],
122
+ "where": {
123
+ "position": {"$contains": "AI"},
124
+ "PROJECT": {
125
+ "DEPARTMENT": {
126
+ "COMPANY": {
127
+ "rating": {"$gte": 4}
128
+ }
129
+ }
130
+ }
131
+ }
132
+ }
133
+
134
+ matched_employees = db.records.find(query)
135
+
136
+ company = db.records.find_uniq("COMPANY", {"where": {"name": "Google LLC"}})
137
+ ```
138
+
139
+ ---
140
+
141
+ ### **4. Use REST API with cURL**
142
+
143
+ ```sh
144
+ curl -X POST https://api.rushdb.com/api/v1/records/search \
145
+ -H "Authorization: Bearer API_TOKEN" \
146
+ -H "Content-Type: application/json" \
147
+ -d '{
148
+ "labels": ["EMPLOYEE"],
149
+ "where": {
150
+ "position": { "$contains": "AI" },
151
+ "PROJECT": {
152
+ "DEPARTMENT": {
153
+ "COMPANY": {
154
+ "rating": { "$gte": 4 }
155
+ }
156
+ }
157
+ }
158
+ }
159
+ }'
160
+ ```
161
+
162
+ <div align="center">
163
+ <b>You Rock</b> 🚀
164
+ </div>
165
+
166
+ ---
167
+
168
+ <div align="center" style="margin-top: 20px">
169
+
170
+ > Check the [Documentation](https://docs.rushdb.com) and [Examples](https://github.com/rush-db/rushdb/examples) to learn more 🧐
171
+
172
+ </div>
173
+
174
+
@@ -0,0 +1,20 @@
1
+ rushdb/__init__.py,sha256=JaMZR74Rgs8oSEGzS-86xApSm6eAm3aitfAVzZYr8yw,487
2
+ rushdb/api/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ rushdb/api/base.py,sha256=nWe3mQiIqVpY153pZkCrqR1bn3FAokr7OLpgvnbs91E,229
4
+ rushdb/api/labels.py,sha256=xKFH4xRIORnrBi0U_KL2x38f4YdliovpSnkaO4xuWqE,689
5
+ rushdb/api/properties.py,sha256=Zb9TJ9Eivd37LtY9WQ0p9T7GpGwSjqxOAFwtz28vE_E,2026
6
+ rushdb/api/records.py,sha256=U7Addgmnl6jSI7aeJYA6M-E0eYWheEG0LMh-26ZjZnI,8201
7
+ rushdb/api/relationships.py,sha256=maHXFoWjwBtHxgcc_FUUbXlniXb7yfv8Lny4yzUCwRQ,1919
8
+ rushdb/api/transactions.py,sha256=rAuGZ4tLlMBvE9BKezJYk9t4LcJ19fvWgQrrylUnFH0,953
9
+ rushdb/client.py,sha256=vB3tW4U1gFL_cMNP7N5G6A4jwamuVeYKnTs0TjPn--A,3391
10
+ rushdb/common.py,sha256=xsRDTB-uTqIvWiNglwwcxefau87GzrQ4-klNsox7oF0,261
11
+ rushdb/models/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
+ rushdb/models/property.py,sha256=Y_al7GaRwWdrIbz3Tkru3yaP75MA9v_RAF1UDNOUVf0,1174
13
+ rushdb/models/record.py,sha256=NQ6qBRqMXhUWcj1jd2waxI8oyUun2FqCNiWxT7a-C0k,3516
14
+ rushdb/models/relationship.py,sha256=BlUW_LOEYDzoLe8-pTthDQ4_u7xkxaAiZIKsuIHuRtc,611
15
+ rushdb/models/search_query.py,sha256=rn2NhEqkFp3DEYf4sQQfF0PTyqihwPvQFiZ0wRQ3Df4,503
16
+ rushdb/models/transaction.py,sha256=N3CCqVnxDirJsx6zxaGfiVYl4LlgBqns32jJ-xzDtMI,1729
17
+ rushdb-0.1.0.dist-info/LICENSE,sha256=vEvRdblNE1bLDiGpey4LYTqMtY7R4IaOHIYRMxifYtM,11350
18
+ rushdb-0.1.0.dist-info/METADATA,sha256=Aqar0ZY2QclcLv49kTpKKWFVCVav4rPgNbZZg2SMljc,5010
19
+ rushdb-0.1.0.dist-info/WHEEL,sha256=FMvqSimYX_P7y0a7UY-_Mc83r5zkBZsCYPm7Lr0Bsq4,88
20
+ rushdb-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 1.8.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any