multids 0.1.0__tar.gz → 0.1.1__tar.gz
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.
- {multids-0.1.0 → multids-0.1.1}/PKG-INFO +16 -6
- {multids-0.1.0 → multids-0.1.1}/README.md +7 -4
- {multids-0.1.0 → multids-0.1.1}/pyproject.toml +17 -7
- multids-0.1.1/src/multids/ai.py +41 -0
- {multids-0.1.0 → multids-0.1.1}/src/multids/connectors/s3.py +65 -15
- {multids-0.1.0 → multids-0.1.1}/src/multids/connectors/sql.py +5 -5
- multids-0.1.1/src/multids/connectors/sync/__init__.py +14 -0
- multids-0.1.1/src/multids/connectors/sync/athena.py +142 -0
- multids-0.1.1/src/multids/connectors/sync/local.py +74 -0
- multids-0.1.1/src/multids/connectors/sync/mssql.py +126 -0
- multids-0.1.1/src/multids/connectors/sync/s3.py +199 -0
- multids-0.1.1/src/multids/connectors/sync/sql.py +95 -0
- multids-0.1.1/src/multids/interfaces.py +127 -0
- multids-0.1.0/src/multids/ai.py +0 -18
- multids-0.1.0/src/multids/interfaces.py +0 -67
- {multids-0.1.0 → multids-0.1.1}/LICENSE +0 -0
- {multids-0.1.0 → multids-0.1.1}/src/multids/__init__.py +0 -0
- {multids-0.1.0 → multids-0.1.1}/src/multids/connectors/__init__.py +0 -0
- {multids-0.1.0 → multids-0.1.1}/src/multids/connectors/athena.py +0 -0
- {multids-0.1.0 → multids-0.1.1}/src/multids/connectors/local.py +0 -0
- {multids-0.1.0 → multids-0.1.1}/src/multids/connectors/mssql.py +0 -0
- {multids-0.1.0 → multids-0.1.1}/src/multids/connectors/opensearch.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: multids
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.1
|
|
4
4
|
Summary: Async multi-data-source connectors (S3, OpenSearch, Athena, MySQL, SQL Server, local files) with AI hooks.
|
|
5
5
|
License-File: LICENSE
|
|
6
6
|
Author: Khaldoun Aljasem
|
|
@@ -16,12 +16,19 @@ Classifier: Programming Language :: Python :: 3.13
|
|
|
16
16
|
Classifier: Programming Language :: Python :: 3.14
|
|
17
17
|
Provides-Extra: ai
|
|
18
18
|
Provides-Extra: opensearch
|
|
19
|
+
Provides-Extra: s3
|
|
19
20
|
Provides-Extra: sqlserver
|
|
20
|
-
|
|
21
|
+
Provides-Extra: sync
|
|
22
|
+
Requires-Dist: aioboto3 (>=10.4.0,<11.0.0) ; extra == "s3"
|
|
21
23
|
Requires-Dist: aiofiles (>=23.1,<24.0)
|
|
24
|
+
Requires-Dist: aioodbc ; (python_version < "3.12") and (extra == "sqlserver")
|
|
22
25
|
Requires-Dist: asyncmy (>=0.2,<0.3)
|
|
26
|
+
Requires-Dist: boto3 (>=1.24.59,<1.24.60) ; extra == "s3" or extra == "sync"
|
|
23
27
|
Requires-Dist: httpx[http2] (>=0.24.0,<0.25.0) ; extra == "opensearch"
|
|
24
28
|
Requires-Dist: openai (>=1.0,<2.0) ; extra == "ai"
|
|
29
|
+
Requires-Dist: pymysql (>=1.1,<2.0) ; extra == "sync"
|
|
30
|
+
Requires-Dist: pyodbc (>=4.0,<5.0) ; (python_version < "3.12") and (extra == "sqlserver" or extra == "sync")
|
|
31
|
+
Requires-Dist: requests (>=2.31,<3.0) ; extra == "opensearch" or extra == "sync"
|
|
25
32
|
Requires-Dist: sqlalchemy (>=2.0,<3.0)
|
|
26
33
|
Project-URL: Documentation, https://aljasem-tech.github.io/multids/
|
|
27
34
|
Project-URL: Homepage, https://github.com/aljasem-tech/multids
|
|
@@ -32,6 +39,9 @@ Description-Content-Type: text/markdown
|
|
|
32
39
|
|
|
33
40
|
<!-- Docs status badge: replace OWNER and REPO with your GitHub owner and repository name -->
|
|
34
41
|
[](https://aljasem-tech.github.io/multids/)
|
|
42
|
+
[](https://github.com/aljasem-tech/multids/actions/workflows/ci.yml)
|
|
43
|
+
[](https://pypi.org/project/multids/)
|
|
44
|
+
[](https://github.com/aljasem-tech/multids)
|
|
35
45
|
|
|
36
46
|
Async multi-data-source connectors for S3, OpenSearch, Athena, MySQL, SQL Server and local files. Provides async
|
|
37
47
|
read/write primitives and pluggable AI hooks.
|
|
@@ -43,7 +53,7 @@ Quick start
|
|
|
43
53
|
```powershell
|
|
44
54
|
python -m venv .venv
|
|
45
55
|
.\.venv\Scripts\Activate.ps1
|
|
46
|
-
pip install
|
|
56
|
+
pip install multids[ai]
|
|
47
57
|
```
|
|
48
58
|
|
|
49
59
|
2. See `examples/basic_usage.py` for a quick demonstration.
|
|
@@ -75,7 +85,7 @@ print(result)
|
|
|
75
85
|
```python
|
|
76
86
|
from multids.connectors.s3 import S3Connector
|
|
77
87
|
|
|
78
|
-
s3 = S3Connector(aws_region="
|
|
88
|
+
s3 = S3Connector(aws_region="eu-central-1")
|
|
79
89
|
data = {"status": "ok", "info": "مرحبا"}
|
|
80
90
|
|
|
81
91
|
# Upload JSON object
|
|
@@ -200,7 +210,7 @@ The project includes an async `MSSQLConnector` implemented with `aioodbc` (ODBC)
|
|
|
200
210
|
- Install the optional `sqlserver` extras to get the Python runtime dependency:
|
|
201
211
|
|
|
202
212
|
```powershell
|
|
203
|
-
pip install
|
|
213
|
+
pip install multids[sqlserver]
|
|
204
214
|
```
|
|
205
215
|
|
|
206
216
|
Quick example (using a pool):
|
|
@@ -289,7 +299,7 @@ If you only need the OpenSearch functionality (and want to avoid installing `htt
|
|
|
289
299
|
extra:
|
|
290
300
|
|
|
291
301
|
```powershell
|
|
292
|
-
pip install
|
|
302
|
+
pip install multids[opensearch]
|
|
293
303
|
```
|
|
294
304
|
|
|
295
305
|
Integration tests
|
|
@@ -2,6 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
<!-- Docs status badge: replace OWNER and REPO with your GitHub owner and repository name -->
|
|
4
4
|
[](https://aljasem-tech.github.io/multids/)
|
|
5
|
+
[](https://github.com/aljasem-tech/multids/actions/workflows/ci.yml)
|
|
6
|
+
[](https://pypi.org/project/multids/)
|
|
7
|
+
[](https://github.com/aljasem-tech/multids)
|
|
5
8
|
|
|
6
9
|
Async multi-data-source connectors for S3, OpenSearch, Athena, MySQL, SQL Server and local files. Provides async
|
|
7
10
|
read/write primitives and pluggable AI hooks.
|
|
@@ -13,7 +16,7 @@ Quick start
|
|
|
13
16
|
```powershell
|
|
14
17
|
python -m venv .venv
|
|
15
18
|
.\.venv\Scripts\Activate.ps1
|
|
16
|
-
pip install
|
|
19
|
+
pip install multids[ai]
|
|
17
20
|
```
|
|
18
21
|
|
|
19
22
|
2. See `examples/basic_usage.py` for a quick demonstration.
|
|
@@ -45,7 +48,7 @@ print(result)
|
|
|
45
48
|
```python
|
|
46
49
|
from multids.connectors.s3 import S3Connector
|
|
47
50
|
|
|
48
|
-
s3 = S3Connector(aws_region="
|
|
51
|
+
s3 = S3Connector(aws_region="eu-central-1")
|
|
49
52
|
data = {"status": "ok", "info": "مرحبا"}
|
|
50
53
|
|
|
51
54
|
# Upload JSON object
|
|
@@ -170,7 +173,7 @@ The project includes an async `MSSQLConnector` implemented with `aioodbc` (ODBC)
|
|
|
170
173
|
- Install the optional `sqlserver` extras to get the Python runtime dependency:
|
|
171
174
|
|
|
172
175
|
```powershell
|
|
173
|
-
pip install
|
|
176
|
+
pip install multids[sqlserver]
|
|
174
177
|
```
|
|
175
178
|
|
|
176
179
|
Quick example (using a pool):
|
|
@@ -259,7 +262,7 @@ If you only need the OpenSearch functionality (and want to avoid installing `htt
|
|
|
259
262
|
extra:
|
|
260
263
|
|
|
261
264
|
```powershell
|
|
262
|
-
pip install
|
|
265
|
+
pip install multids[opensearch]
|
|
263
266
|
```
|
|
264
267
|
|
|
265
268
|
Integration tests
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[tool.poetry]
|
|
2
2
|
name = "multids"
|
|
3
|
-
version = "0.1.
|
|
3
|
+
version = "0.1.1"
|
|
4
4
|
description = "Async multi-data-source connectors (S3, OpenSearch, Athena, MySQL, SQL Server, local files) with AI hooks."
|
|
5
5
|
authors = ["Khaldoun Aljasem <khaldoun.aljasem@gmail.com>"]
|
|
6
6
|
readme = "README.md"
|
|
@@ -21,17 +21,27 @@ packages = [
|
|
|
21
21
|
|
|
22
22
|
[tool.poetry.dependencies]
|
|
23
23
|
python = "^3.11"
|
|
24
|
-
aioboto3 = "^10.0"
|
|
24
|
+
aioboto3 = "^10.4.0"
|
|
25
25
|
sqlalchemy = "^2.0"
|
|
26
26
|
asyncmy = "^0.2"
|
|
27
27
|
aiofiles = "^23.1"
|
|
28
|
-
|
|
29
|
-
|
|
28
|
+
|
|
29
|
+
openai = { version = "^1.0", optional = true }
|
|
30
|
+
httpx = { version = "^0.24.0", extras = ["http2"], optional = true }
|
|
31
|
+
boto3 = { version = ">=1.24.59,<1.24.60", optional = true }
|
|
32
|
+
requests = { version = "^2.31", optional = true }
|
|
33
|
+
pymysql = { version = "^1.1", optional = true }
|
|
34
|
+
|
|
35
|
+
# Only allow pyodbc on Python < 3.12 (4.x does not build on 3.12+)
|
|
36
|
+
pyodbc = { version = "^4.0", optional = true, markers = "python_version < '3.12'" }
|
|
37
|
+
aioodbc = { version = "*", optional = true, markers = "python_version < '3.12'" }
|
|
30
38
|
|
|
31
39
|
[tool.poetry.extras]
|
|
32
|
-
ai
|
|
33
|
-
sqlserver = ["aioodbc"]
|
|
34
|
-
opensearch = ["httpx"]
|
|
40
|
+
ai = ["openai"]
|
|
41
|
+
sqlserver = ["aioodbc", "pyodbc"]
|
|
42
|
+
opensearch = ["httpx", "requests"]
|
|
43
|
+
s3 = ["aioboto3", "boto3"]
|
|
44
|
+
sync = ["boto3", "requests", "pymysql", "pyodbc"]
|
|
35
45
|
|
|
36
46
|
[tool.poetry.group.dev.dependencies]
|
|
37
47
|
pytest = "^7.4"
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, Dict, Protocol
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class AIClientInterface(Protocol):
|
|
7
|
+
async def generate(self, prompt: str, **kwargs: Any) -> Dict[str, Any]:
|
|
8
|
+
"""Generate a response for the given prompt."""
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class OpenAIClient:
|
|
12
|
+
def __init__(self, client: Any):
|
|
13
|
+
"""
|
|
14
|
+
Initialize with an async openai client (e.g. AsyncOpenAI).
|
|
15
|
+
|
|
16
|
+
Using Any for client to genericize and avoid hard dependency if openai not installed,
|
|
17
|
+
but runtime it should be `openai.AsyncClient`.
|
|
18
|
+
"""
|
|
19
|
+
self._client = client
|
|
20
|
+
|
|
21
|
+
async def generate(self, prompt: str, **kwargs: Any) -> Dict[str, Any]:
|
|
22
|
+
"""
|
|
23
|
+
Generate text using OpenAI ChatCompletion.
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
prompt: The text prompt.
|
|
27
|
+
**kwargs: Extra arguments to pass to chat.completions.create (model, temperature, etc).
|
|
28
|
+
|
|
29
|
+
Returns:
|
|
30
|
+
Dict containing the raw response or at least 'content'.
|
|
31
|
+
"""
|
|
32
|
+
# Default model if not provided
|
|
33
|
+
model = kwargs.pop("model", "gpt-3.5-turbo")
|
|
34
|
+
|
|
35
|
+
resp = await self._client.chat.completions.create(
|
|
36
|
+
messages=[{"role": "user", "content": prompt}], model=model, **kwargs
|
|
37
|
+
)
|
|
38
|
+
# Simplify return to be dict-like or just the object
|
|
39
|
+
# Returning a simplified dict for easier usage
|
|
40
|
+
content = resp.choices[0].message.content
|
|
41
|
+
return {"content": content, "raw": resp}
|
|
@@ -7,7 +7,7 @@ import tempfile
|
|
|
7
7
|
from pathlib import Path
|
|
8
8
|
from typing import Any, AsyncIterator, Callable, Dict, List, Optional, Tuple
|
|
9
9
|
|
|
10
|
-
from ..interfaces import Connector, Readable, Writable
|
|
10
|
+
from ..interfaces import Connector, ContentHook, Readable, Writable
|
|
11
11
|
|
|
12
12
|
ProgressCallback = Callable[[int, int], Any]
|
|
13
13
|
OverallProgressCallback = Callable[[int, Optional[int]], Any]
|
|
@@ -54,7 +54,12 @@ class S3Connector(Connector, Readable, Writable):
|
|
|
54
54
|
self.min_multipart_upload_size = max(0, int(min_multipart_upload_size))
|
|
55
55
|
|
|
56
56
|
async def read_stream(
|
|
57
|
-
self,
|
|
57
|
+
self,
|
|
58
|
+
bucket: Optional[str] = None,
|
|
59
|
+
key: Optional[str] = None,
|
|
60
|
+
hook: Optional[ContentHook] = None,
|
|
61
|
+
*args: Any,
|
|
62
|
+
**kwargs: Any,
|
|
58
63
|
) -> AsyncIterator[bytes]:
|
|
59
64
|
if not bucket or not key:
|
|
60
65
|
raise ValueError("bucket and key are required for S3Connector")
|
|
@@ -64,38 +69,73 @@ class S3Connector(Connector, Readable, Writable):
|
|
|
64
69
|
obj = await client.get_object(Bucket=bucket, Key=key)
|
|
65
70
|
stream = obj["Body"]
|
|
66
71
|
try:
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
+
if hook:
|
|
73
|
+
# Hook is responsible for yielding chunks.
|
|
74
|
+
# Use 'await' to allow hook to initialize/wrap the stream
|
|
75
|
+
# Then iterate over the result.
|
|
76
|
+
async for chunk in await hook.post_read(stream):
|
|
77
|
+
yield chunk
|
|
78
|
+
else:
|
|
79
|
+
while True:
|
|
80
|
+
chunk = await stream.read(self.part_size)
|
|
81
|
+
if not chunk:
|
|
82
|
+
break
|
|
83
|
+
yield chunk
|
|
72
84
|
finally:
|
|
73
85
|
await stream.close()
|
|
74
86
|
|
|
75
87
|
async def read_bytes(
|
|
76
|
-
self,
|
|
88
|
+
self,
|
|
89
|
+
bucket: Optional[str] = None,
|
|
90
|
+
key: Optional[str] = None,
|
|
91
|
+
hook: Optional[ContentHook] = None,
|
|
92
|
+
*args: Any,
|
|
93
|
+
**kwargs: Any,
|
|
77
94
|
) -> bytes:
|
|
78
95
|
if not bucket or not key:
|
|
79
96
|
raise ValueError("bucket and key are required for S3Connector")
|
|
97
|
+
# Do NOT pass hook to read_stream, we apply it here on the full bytes
|
|
80
98
|
buf = bytearray()
|
|
81
|
-
async for chunk in self.read_stream(bucket, key
|
|
99
|
+
async for chunk in self.read_stream(bucket, key):
|
|
82
100
|
buf.extend(chunk)
|
|
83
|
-
|
|
101
|
+
data = bytes(buf)
|
|
102
|
+
if hook:
|
|
103
|
+
data = await hook.post_read(data)
|
|
104
|
+
return data
|
|
84
105
|
|
|
85
|
-
async def read_json(
|
|
106
|
+
async def read_json(
|
|
107
|
+
self,
|
|
108
|
+
bucket: Optional[str] = None,
|
|
109
|
+
key: Optional[str] = None,
|
|
110
|
+
hook: Optional[ContentHook] = None,
|
|
111
|
+
) -> Any:
|
|
86
112
|
"""Read a JSON object from S3."""
|
|
87
113
|
if not bucket or not key:
|
|
88
114
|
raise ValueError("bucket and key are required for S3Connector")
|
|
115
|
+
# Do NOT pass hook to read_bytes, we apply it here on the object
|
|
89
116
|
data = await self.read_bytes(bucket, key)
|
|
90
|
-
|
|
117
|
+
obj = json.loads(data.decode("utf-8"))
|
|
118
|
+
if hook:
|
|
119
|
+
obj = await hook.post_read(obj)
|
|
120
|
+
return obj
|
|
91
121
|
|
|
92
122
|
async def write_json(
|
|
93
|
-
self,
|
|
123
|
+
self,
|
|
124
|
+
data: Any,
|
|
125
|
+
bucket: Optional[str] = None,
|
|
126
|
+
key: Optional[str] = None,
|
|
127
|
+
indent: int = 2,
|
|
128
|
+
hook: Optional[ContentHook] = None,
|
|
94
129
|
) -> None:
|
|
95
130
|
"""Write a JSON object to S3."""
|
|
96
131
|
if not bucket or not key:
|
|
97
132
|
raise ValueError("bucket and key are required for S3Connector")
|
|
98
|
-
|
|
133
|
+
|
|
134
|
+
if hook:
|
|
135
|
+
data = await hook.pre_write(data)
|
|
136
|
+
|
|
137
|
+
content = json.dumps(data, ensure_ascii=False, indent=indent)
|
|
138
|
+
# Do NOT pass hook to write_bytes
|
|
99
139
|
await self.write_bytes(content.encode("utf-8"), bucket, key)
|
|
100
140
|
|
|
101
141
|
def _save_checkpoint(self, checkpoint_file: Path, data: dict) -> None:
|
|
@@ -187,6 +227,7 @@ class S3Connector(Connector, Readable, Writable):
|
|
|
187
227
|
stream: AsyncIterator[bytes],
|
|
188
228
|
bucket: Optional[str] = None,
|
|
189
229
|
key: Optional[str] = None,
|
|
230
|
+
hook: Optional[ContentHook] = None,
|
|
190
231
|
*args: Any,
|
|
191
232
|
progress_callback: Optional[ProgressCallback] = None,
|
|
192
233
|
overall_progress: Optional[OverallProgressCallback] = None,
|
|
@@ -353,8 +394,17 @@ class S3Connector(Connector, Readable, Writable):
|
|
|
353
394
|
pass
|
|
354
395
|
|
|
355
396
|
async def write_bytes(
|
|
356
|
-
self,
|
|
397
|
+
self,
|
|
398
|
+
data: bytes,
|
|
399
|
+
bucket: Optional[str] = None,
|
|
400
|
+
key: Optional[str] = None,
|
|
401
|
+
hook: Optional[ContentHook] = None,
|
|
402
|
+
*args: Any,
|
|
403
|
+
**kwargs: Any,
|
|
357
404
|
) -> None:
|
|
405
|
+
if hook:
|
|
406
|
+
data = await hook.pre_write(data)
|
|
407
|
+
|
|
358
408
|
async def gen() -> AsyncIterator[bytes]:
|
|
359
409
|
yield data
|
|
360
410
|
|
|
@@ -21,14 +21,14 @@ class SQLConnectorBase(Connector):
|
|
|
21
21
|
|
|
22
22
|
async def fetch_rows(self, query: str, /, **params: Any) -> AsyncIterator[dict]:
|
|
23
23
|
"""Stream rows from a query as dictionaries (uses SQLAlchemy streaming API)."""
|
|
24
|
-
async with self._engine.connect() as conn:
|
|
24
|
+
async with self._engine.connect() as conn: # type: ignore
|
|
25
25
|
result = await conn.stream(text(query), params)
|
|
26
26
|
async for row in result.mappings():
|
|
27
27
|
yield dict(row)
|
|
28
28
|
|
|
29
29
|
async def execute(self, statement: str, /, **params: Any) -> None:
|
|
30
30
|
"""Execute a statement (INSERT/UPDATE/DELETE)."""
|
|
31
|
-
async with self._engine.begin() as conn:
|
|
31
|
+
async with self._engine.begin() as conn: # type: ignore
|
|
32
32
|
await conn.execute(text(statement), params)
|
|
33
33
|
|
|
34
34
|
async def execute_many(self, statement: str, params_iter: Iterable[dict]) -> None:
|
|
@@ -38,7 +38,7 @@ class SQLConnectorBase(Connector):
|
|
|
38
38
|
This implementation iterates and executes repeatedly inside a transaction.
|
|
39
39
|
Drivers or more advanced techniques (COPY, bulk insert) may be added for performance.
|
|
40
40
|
"""
|
|
41
|
-
async with self._engine.begin() as conn:
|
|
41
|
+
async with self._engine.begin() as conn: # type: ignore
|
|
42
42
|
for params in params_iter:
|
|
43
43
|
await conn.execute(text(statement), params)
|
|
44
44
|
|
|
@@ -48,7 +48,7 @@ class SQLConnectorBase(Connector):
|
|
|
48
48
|
async def ping(self) -> bool:
|
|
49
49
|
"""Check connection by running a simple query."""
|
|
50
50
|
try:
|
|
51
|
-
async with self._engine.connect() as conn:
|
|
51
|
+
async with self._engine.connect() as conn: # type: ignore
|
|
52
52
|
await conn.execute(text("SELECT 1"))
|
|
53
53
|
return True
|
|
54
54
|
except Exception:
|
|
@@ -99,7 +99,7 @@ class MySQLConnector(SQLConnectorBase):
|
|
|
99
99
|
placeholders = ", ".join([f":{c}" for c in cols])
|
|
100
100
|
stmt = text(f"INSERT INTO {table} ({col_list}) VALUES ({placeholders})")
|
|
101
101
|
|
|
102
|
-
async with self._engine.begin() as conn:
|
|
102
|
+
async with self._engine.begin() as conn: # type: ignore
|
|
103
103
|
while True:
|
|
104
104
|
chunk = list(islice(rows_iter, chunk_size))
|
|
105
105
|
if not chunk:
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from .athena import SyncAthenaConnector
|
|
2
|
+
from .local import SyncLocalConnector
|
|
3
|
+
from .mssql import SyncMSSQLConnector
|
|
4
|
+
from .s3 import SyncS3Connector
|
|
5
|
+
from .sql import SyncMySQLConnector, SyncSQLConnectorBase
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"SyncLocalConnector",
|
|
9
|
+
"SyncS3Connector",
|
|
10
|
+
"SyncAthenaConnector",
|
|
11
|
+
"SyncSQLConnectorBase",
|
|
12
|
+
"SyncMySQLConnector",
|
|
13
|
+
"SyncMSSQLConnector",
|
|
14
|
+
]
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import time
|
|
2
|
+
from typing import Any, Dict, Iterator, List, Optional
|
|
3
|
+
|
|
4
|
+
try:
|
|
5
|
+
import boto3
|
|
6
|
+
except ImportError:
|
|
7
|
+
boto3 = None
|
|
8
|
+
|
|
9
|
+
from ...interfaces import SyncConnector
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class SyncAthenaConnector(SyncConnector):
|
|
13
|
+
"""
|
|
14
|
+
Synchronous Athena connector using boto3.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
def __init__(
|
|
18
|
+
self,
|
|
19
|
+
region_name: Optional[str] = None,
|
|
20
|
+
workgroup: Optional[str] = None,
|
|
21
|
+
poll_interval: float = 1.0,
|
|
22
|
+
max_wait: float = 300.0,
|
|
23
|
+
):
|
|
24
|
+
if boto3 is None:
|
|
25
|
+
raise ImportError("boto3 is required for SyncAthenaConnector. Install with `pip install multids[sync]`")
|
|
26
|
+
|
|
27
|
+
self.region_name = region_name
|
|
28
|
+
self.workgroup = workgroup
|
|
29
|
+
self.poll_interval = poll_interval
|
|
30
|
+
self.max_wait = max_wait
|
|
31
|
+
self._session = boto3.Session(region_name=region_name)
|
|
32
|
+
self._client = self._session.client("athena")
|
|
33
|
+
|
|
34
|
+
def close(self) -> None:
|
|
35
|
+
if self._client:
|
|
36
|
+
self._client.close()
|
|
37
|
+
|
|
38
|
+
def ping(self) -> bool:
|
|
39
|
+
try:
|
|
40
|
+
self._client.list_work_groups(MaxResults=1)
|
|
41
|
+
return True
|
|
42
|
+
except Exception:
|
|
43
|
+
return False
|
|
44
|
+
|
|
45
|
+
def start_query(
|
|
46
|
+
self,
|
|
47
|
+
sql: str,
|
|
48
|
+
database: Optional[str] = None,
|
|
49
|
+
output_location: Optional[str] = None,
|
|
50
|
+
encryption_configuration: Optional[Dict] = None,
|
|
51
|
+
) -> str:
|
|
52
|
+
"""Start an Athena query execution and return the execution id."""
|
|
53
|
+
params: Dict[str, Any] = {"QueryString": sql}
|
|
54
|
+
if database:
|
|
55
|
+
params["QueryExecutionContext"] = {"Database": database}
|
|
56
|
+
cfg = {}
|
|
57
|
+
if output_location:
|
|
58
|
+
cfg["OutputLocation"] = output_location
|
|
59
|
+
if encryption_configuration:
|
|
60
|
+
cfg["EncryptionConfiguration"] = encryption_configuration
|
|
61
|
+
if cfg:
|
|
62
|
+
params["ResultConfiguration"] = cfg
|
|
63
|
+
if self.workgroup:
|
|
64
|
+
params["WorkGroup"] = self.workgroup
|
|
65
|
+
|
|
66
|
+
resp = self._client.start_query_execution(**params)
|
|
67
|
+
return resp["QueryExecutionId"]
|
|
68
|
+
|
|
69
|
+
def wait_query(self, query_execution_id: str, timeout: Optional[float] = None) -> Dict[str, Any]:
|
|
70
|
+
"""Poll Athena until the query reaches a terminal state."""
|
|
71
|
+
timeout = timeout if timeout is not None else self.max_wait
|
|
72
|
+
elapsed = 0.0
|
|
73
|
+
while True:
|
|
74
|
+
resp = self._client.get_query_execution(QueryExecutionId=query_execution_id)
|
|
75
|
+
state = resp.get("QueryExecution", {}).get("Status", {}).get("State")
|
|
76
|
+
if state in ("SUCCEEDED", "FAILED", "CANCELLED"):
|
|
77
|
+
return resp
|
|
78
|
+
|
|
79
|
+
if elapsed >= timeout:
|
|
80
|
+
try:
|
|
81
|
+
self._client.stop_query_execution(QueryExecutionId=query_execution_id)
|
|
82
|
+
except Exception:
|
|
83
|
+
pass
|
|
84
|
+
raise TimeoutError(f"Query {query_execution_id} timed out after {timeout}s")
|
|
85
|
+
|
|
86
|
+
time.sleep(self.poll_interval)
|
|
87
|
+
elapsed += self.poll_interval
|
|
88
|
+
|
|
89
|
+
def get_results(self, query_execution_id: str) -> Iterator[Dict[str, Any]]:
|
|
90
|
+
"""Yield rows from `get_query_results` as dictionaries keyed by column name."""
|
|
91
|
+
paginator = self._client.get_paginator("get_query_results")
|
|
92
|
+
|
|
93
|
+
columns: List[str] = []
|
|
94
|
+
|
|
95
|
+
# We need to handle the header row carefully across pages
|
|
96
|
+
# Actually, get_query_results paginator usually returns header in first page only?
|
|
97
|
+
# boto3 docs vary, but let's assume standard behavior.
|
|
98
|
+
|
|
99
|
+
for page in paginator.paginate(QueryExecutionId=query_execution_id):
|
|
100
|
+
result_set = page.get("ResultSet", {})
|
|
101
|
+
metadata = result_set.get("ResultSetMetadata", {})
|
|
102
|
+
col_info = metadata.get("ColumnInfo", [])
|
|
103
|
+
|
|
104
|
+
if not columns and col_info:
|
|
105
|
+
columns = [cinfo.get("Name") for cinfo in col_info]
|
|
106
|
+
|
|
107
|
+
rows = result_set.get("Rows", [])
|
|
108
|
+
if not rows:
|
|
109
|
+
continue
|
|
110
|
+
|
|
111
|
+
# Standard Athena API returns header as the first row of the first page
|
|
112
|
+
first_row_data = rows[0].get("Data", [])
|
|
113
|
+
header_detected = (
|
|
114
|
+
bool(columns)
|
|
115
|
+
and bool(first_row_data)
|
|
116
|
+
and all("VarCharValue" in cell for cell in first_row_data)
|
|
117
|
+
# Safeguard: if first row matches column names
|
|
118
|
+
and first_row_data[0].get("VarCharValue") == columns[0]
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
start = 1 if header_detected else 0
|
|
122
|
+
for r in rows[start:]:
|
|
123
|
+
data = r.get("Data", [])
|
|
124
|
+
values = [d.get("VarCharValue") for d in data]
|
|
125
|
+
if columns:
|
|
126
|
+
yield dict(zip(columns, values))
|
|
127
|
+
else:
|
|
128
|
+
yield {str(i): v for i, v in enumerate(values)}
|
|
129
|
+
|
|
130
|
+
def query_stream(self, sql: str, database: Optional[str] = None) -> Iterator[Dict[str, Any]]:
|
|
131
|
+
"""Convenience: run SQL and stream results."""
|
|
132
|
+
qid = self.start_query(sql, database=database)
|
|
133
|
+
exec_resp = self.wait_query(qid)
|
|
134
|
+
state = exec_resp.get("QueryExecution", {}).get("Status", {}).get("State")
|
|
135
|
+
if state != "SUCCEEDED":
|
|
136
|
+
reason = exec_resp.get("QueryExecution", {}).get("Status", {}).get("StateChangeReason")
|
|
137
|
+
raise RuntimeError(f"Query failed: {reason}")
|
|
138
|
+
|
|
139
|
+
yield from self.get_results(qid)
|
|
140
|
+
|
|
141
|
+
def fetch_all(self, sql: str, database: Optional[str] = None) -> List[Dict[str, Any]]:
|
|
142
|
+
return list(self.query_stream(sql, database=database))
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import Any, Iterator, Optional
|
|
4
|
+
|
|
5
|
+
from ...interfaces import SyncConnector, SyncReadable, SyncWritable
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class SyncLocalConnector(SyncConnector, SyncReadable, SyncWritable):
|
|
9
|
+
"""
|
|
10
|
+
Synchronous connector to read/write files from the local filesystem.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
def __init__(self, base_path: Optional[str] = None):
|
|
14
|
+
self._base_path = Path(base_path) if base_path else Path.cwd()
|
|
15
|
+
|
|
16
|
+
def close(self) -> None:
|
|
17
|
+
pass
|
|
18
|
+
|
|
19
|
+
def ping(self) -> bool:
|
|
20
|
+
return True
|
|
21
|
+
|
|
22
|
+
def _resolve_path(self, path: str) -> Path:
|
|
23
|
+
p = Path(path)
|
|
24
|
+
if not p.is_absolute():
|
|
25
|
+
p = self._base_path / p
|
|
26
|
+
return p
|
|
27
|
+
|
|
28
|
+
def read_stream(self, path: str = "", chunk_size: int = 65536, *args: Any, **kwargs: Any) -> Iterator[bytes]:
|
|
29
|
+
"""Yield chunks of bytes from a local file."""
|
|
30
|
+
if not path:
|
|
31
|
+
raise ValueError("path is required")
|
|
32
|
+
full_path = self._resolve_path(path)
|
|
33
|
+
if not full_path.exists():
|
|
34
|
+
raise FileNotFoundError(f"File not found: {full_path}")
|
|
35
|
+
|
|
36
|
+
with open(full_path, "rb") as f:
|
|
37
|
+
while True:
|
|
38
|
+
chunk = f.read(chunk_size)
|
|
39
|
+
if not chunk:
|
|
40
|
+
break
|
|
41
|
+
yield chunk
|
|
42
|
+
|
|
43
|
+
def read_bytes(self, path: str = "", *args: Any, **kwargs: Any) -> bytes:
|
|
44
|
+
"""Read whole file as bytes."""
|
|
45
|
+
if not path:
|
|
46
|
+
raise ValueError("path is required")
|
|
47
|
+
full_path = self._resolve_path(path)
|
|
48
|
+
return full_path.read_bytes()
|
|
49
|
+
|
|
50
|
+
def read_json(self, path: str) -> Any:
|
|
51
|
+
content = self.read_bytes(path)
|
|
52
|
+
return json.loads(content.decode("utf-8"))
|
|
53
|
+
|
|
54
|
+
def write_stream(self, stream: Iterator[bytes], path: str = "", *args: Any, **kwargs: Any) -> None:
|
|
55
|
+
"""Write stream of bytes to a local file."""
|
|
56
|
+
if not path:
|
|
57
|
+
raise ValueError("path is required")
|
|
58
|
+
full_path = self._resolve_path(path)
|
|
59
|
+
full_path.parent.mkdir(parents=True, exist_ok=True)
|
|
60
|
+
with open(full_path, "wb") as f:
|
|
61
|
+
for chunk in stream:
|
|
62
|
+
f.write(chunk)
|
|
63
|
+
|
|
64
|
+
def write_bytes(self, data: bytes, path: str = "", *args: Any, **kwargs: Any) -> None:
|
|
65
|
+
"""Write bytes to a local file."""
|
|
66
|
+
if not path:
|
|
67
|
+
raise ValueError("path is required")
|
|
68
|
+
full_path = self._resolve_path(path)
|
|
69
|
+
full_path.parent.mkdir(parents=True, exist_ok=True)
|
|
70
|
+
full_path.write_bytes(data)
|
|
71
|
+
|
|
72
|
+
def write_json(self, data: Any, path: str, indent: int = 2) -> None:
|
|
73
|
+
content = json.dumps(data, ensure_ascii=False, indent=indent)
|
|
74
|
+
self.write_bytes(content.encode("utf-8"), path)
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
from typing import Any, Dict, Iterator, List, Optional, Sequence
|
|
2
|
+
|
|
3
|
+
from ...interfaces import SyncConnector
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
import pyodbc
|
|
7
|
+
except ImportError:
|
|
8
|
+
pyodbc = None
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class SyncMSSQLConnector(SyncConnector):
|
|
12
|
+
"""
|
|
13
|
+
Synchronous SQL Server connector using pyodbc.
|
|
14
|
+
|
|
15
|
+
Requires an ODBC driver for SQL Server installed on the system.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
def __init__(
|
|
19
|
+
self,
|
|
20
|
+
dsn: Optional[str] = None,
|
|
21
|
+
user: Optional[str] = None,
|
|
22
|
+
password: Optional[str] = None,
|
|
23
|
+
host: Optional[str] = None,
|
|
24
|
+
port: Optional[int] = None,
|
|
25
|
+
database: Optional[str] = None,
|
|
26
|
+
):
|
|
27
|
+
self._dsn = dsn
|
|
28
|
+
self._user = user
|
|
29
|
+
self._password = password
|
|
30
|
+
self._host = host
|
|
31
|
+
self._port = port
|
|
32
|
+
self._database = database
|
|
33
|
+
self._conn = None
|
|
34
|
+
|
|
35
|
+
if pyodbc is None:
|
|
36
|
+
raise ImportError("pyodbc is required for SyncMSSQLConnector. Install with `pip install multids[sync]`")
|
|
37
|
+
|
|
38
|
+
def connect(self) -> None:
|
|
39
|
+
if self._conn is not None:
|
|
40
|
+
return
|
|
41
|
+
|
|
42
|
+
conn_str = self._dsn
|
|
43
|
+
if conn_str is None:
|
|
44
|
+
parts = []
|
|
45
|
+
if self._host:
|
|
46
|
+
parts.append(f"Server={self._host}")
|
|
47
|
+
if self._port:
|
|
48
|
+
parts.append(f"Port={self._port}")
|
|
49
|
+
if self._database:
|
|
50
|
+
parts.append(f"Database={self._database}")
|
|
51
|
+
if self._user:
|
|
52
|
+
parts.append(f"UID={self._user}")
|
|
53
|
+
if self._password:
|
|
54
|
+
parts.append(f"PWD={self._password}")
|
|
55
|
+
|
|
56
|
+
# Usually pyodbc needs a Driver spec too unless DSN is configured
|
|
57
|
+
# Assume user knows what they are doing or DSN is provided
|
|
58
|
+
# If not, let's default to a common driver if none provided?
|
|
59
|
+
# Better to let user provide full string or set parts.
|
|
60
|
+
conn_str = ";".join(parts)
|
|
61
|
+
|
|
62
|
+
# Basic retries or connection logic could go here
|
|
63
|
+
self._conn = pyodbc.connect(conn_str)
|
|
64
|
+
|
|
65
|
+
def close(self) -> None:
|
|
66
|
+
if self._conn:
|
|
67
|
+
self._conn.close()
|
|
68
|
+
self._conn = None
|
|
69
|
+
|
|
70
|
+
def ping(self) -> bool:
|
|
71
|
+
try:
|
|
72
|
+
if self._conn is None:
|
|
73
|
+
self.connect()
|
|
74
|
+
cursor = self._conn.cursor()
|
|
75
|
+
cursor.execute("SELECT 1")
|
|
76
|
+
cursor.fetchone()
|
|
77
|
+
return True
|
|
78
|
+
except Exception:
|
|
79
|
+
return False
|
|
80
|
+
|
|
81
|
+
def execute(self, sql: str, params: Optional[Sequence[Any]] = None) -> None:
|
|
82
|
+
if self._conn is None:
|
|
83
|
+
self.connect()
|
|
84
|
+
cursor = self._conn.cursor()
|
|
85
|
+
cursor.execute(sql, params or [])
|
|
86
|
+
self._conn.commit()
|
|
87
|
+
|
|
88
|
+
def fetch_rows(self, sql: str, params: Optional[Sequence[Any]] = None) -> List[Dict[str, Any]]:
|
|
89
|
+
return list(self.fetch_iter(sql, params))
|
|
90
|
+
|
|
91
|
+
def fetch_iter(self, sql: str, params: Optional[Sequence[Any]] = None) -> Iterator[Dict[str, Any]]:
|
|
92
|
+
if self._conn is None:
|
|
93
|
+
self.connect()
|
|
94
|
+
cursor = self._conn.cursor()
|
|
95
|
+
cursor.execute(sql, params or [])
|
|
96
|
+
|
|
97
|
+
cols = [c[0] for c in cursor.description]
|
|
98
|
+
for row in cursor:
|
|
99
|
+
yield {k: v for k, v in zip(cols, row)}
|
|
100
|
+
|
|
101
|
+
def bulk_insert(
|
|
102
|
+
self, table: str, columns: Sequence[str], rows: Sequence[Sequence[Any]], batch_size: int = 1000
|
|
103
|
+
) -> None:
|
|
104
|
+
"""
|
|
105
|
+
Bulk insert rows using executemany.
|
|
106
|
+
"""
|
|
107
|
+
if self._conn is None:
|
|
108
|
+
self.connect()
|
|
109
|
+
|
|
110
|
+
placeholders = ",".join(["?" for _ in columns])
|
|
111
|
+
cols = ",".join(columns)
|
|
112
|
+
sql = f"INSERT INTO {table} ({cols}) VALUES ({placeholders})"
|
|
113
|
+
|
|
114
|
+
cursor = self._conn.cursor()
|
|
115
|
+
|
|
116
|
+
# pyodbc's executemany is reasonably fast if fast_executemany is enabled
|
|
117
|
+
# which depends on the driver, but typically used.
|
|
118
|
+
try:
|
|
119
|
+
cursor.fast_executemany = True
|
|
120
|
+
except Exception:
|
|
121
|
+
pass
|
|
122
|
+
|
|
123
|
+
for i in range(0, len(rows), batch_size):
|
|
124
|
+
batch = rows[i : i + batch_size]
|
|
125
|
+
cursor.executemany(sql, batch)
|
|
126
|
+
self._conn.commit()
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from typing import Any, Iterator, Optional
|
|
3
|
+
|
|
4
|
+
try:
|
|
5
|
+
import boto3
|
|
6
|
+
except ImportError:
|
|
7
|
+
boto3 = None
|
|
8
|
+
|
|
9
|
+
from ...interfaces import SyncConnector, SyncContentHook, SyncReadable, SyncWritable
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class IteratorFile:
|
|
13
|
+
"""Helper to convert an iterator of bytes into a file-like object for boto3."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, iterator):
|
|
16
|
+
self._iterator = iterator
|
|
17
|
+
self._buffer = b""
|
|
18
|
+
|
|
19
|
+
def read(self, size: int = -1) -> bytes:
|
|
20
|
+
if size == 0:
|
|
21
|
+
return b""
|
|
22
|
+
|
|
23
|
+
# If we have enough in buffer, return it
|
|
24
|
+
if 0 < size <= len(self._buffer):
|
|
25
|
+
ret = self._buffer[:size]
|
|
26
|
+
self._buffer = self._buffer[size:]
|
|
27
|
+
return ret
|
|
28
|
+
|
|
29
|
+
# Consume iterator
|
|
30
|
+
try:
|
|
31
|
+
while size < 0 or len(self._buffer) < size:
|
|
32
|
+
chunk = next(self._iterator)
|
|
33
|
+
self._buffer += chunk
|
|
34
|
+
except StopIteration:
|
|
35
|
+
pass
|
|
36
|
+
|
|
37
|
+
if size < 0:
|
|
38
|
+
ret = self._buffer
|
|
39
|
+
self._buffer = b""
|
|
40
|
+
return ret
|
|
41
|
+
else:
|
|
42
|
+
ret = self._buffer[:size]
|
|
43
|
+
self._buffer = self._buffer[size:]
|
|
44
|
+
return ret
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class SyncS3Connector(SyncConnector, SyncReadable, SyncWritable):
|
|
48
|
+
"""
|
|
49
|
+
Synchronous S3 Connector using boto3.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
def __init__(
|
|
53
|
+
self,
|
|
54
|
+
region_name: str = "eu-central-1",
|
|
55
|
+
aws_access_key_id: Optional[str] = None,
|
|
56
|
+
aws_secret_access_key: Optional[str] = None,
|
|
57
|
+
session_token: Optional[str] = None,
|
|
58
|
+
profile_name: Optional[str] = None,
|
|
59
|
+
):
|
|
60
|
+
if boto3 is None:
|
|
61
|
+
raise ImportError("boto3 is required for SyncS3Connector. Install with `pip install multids[sync]`")
|
|
62
|
+
|
|
63
|
+
self._session = boto3.Session(
|
|
64
|
+
aws_access_key_id=aws_access_key_id,
|
|
65
|
+
aws_secret_access_key=aws_secret_access_key,
|
|
66
|
+
aws_session_token=session_token,
|
|
67
|
+
profile_name=profile_name,
|
|
68
|
+
region_name=region_name,
|
|
69
|
+
)
|
|
70
|
+
self._client = self._session.client("s3")
|
|
71
|
+
|
|
72
|
+
def close(self) -> None:
|
|
73
|
+
if self._client:
|
|
74
|
+
self._client.close()
|
|
75
|
+
|
|
76
|
+
def ping(self) -> bool:
|
|
77
|
+
try:
|
|
78
|
+
# Simple list buckets as a connectivity check
|
|
79
|
+
self._client.list_buckets()
|
|
80
|
+
return True
|
|
81
|
+
except Exception:
|
|
82
|
+
return False
|
|
83
|
+
|
|
84
|
+
def read_stream(
|
|
85
|
+
self,
|
|
86
|
+
bucket: str = "",
|
|
87
|
+
key: str = "",
|
|
88
|
+
chunk_size: int = 65536,
|
|
89
|
+
hook: Optional[SyncContentHook] = None,
|
|
90
|
+
*args: Any,
|
|
91
|
+
**kwargs: Any,
|
|
92
|
+
) -> Iterator[bytes]:
|
|
93
|
+
if not bucket or not key:
|
|
94
|
+
raise ValueError("bucket and key are required")
|
|
95
|
+
|
|
96
|
+
response = self._client.get_object(Bucket=bucket, Key=key)
|
|
97
|
+
stream = response["Body"]
|
|
98
|
+
|
|
99
|
+
# If hook exists, it wraps the stream logic
|
|
100
|
+
if hook:
|
|
101
|
+
# hook.post_read should return an iterator if it wraps the stream
|
|
102
|
+
# or we might need to apply it differently.
|
|
103
|
+
# Protocol says: post_read(data). If data is stream, it transforms stream.
|
|
104
|
+
yield from hook.post_read(stream)
|
|
105
|
+
else:
|
|
106
|
+
for chunk in stream.iter_chunks(chunk_size):
|
|
107
|
+
yield chunk
|
|
108
|
+
|
|
109
|
+
def read_bytes(
|
|
110
|
+
self,
|
|
111
|
+
bucket: str = "",
|
|
112
|
+
key: str = "",
|
|
113
|
+
hook: Optional[SyncContentHook] = None,
|
|
114
|
+
*args: Any,
|
|
115
|
+
**kwargs: Any,
|
|
116
|
+
) -> bytes:
|
|
117
|
+
if not bucket or not key:
|
|
118
|
+
raise ValueError("bucket and key are required")
|
|
119
|
+
|
|
120
|
+
# Optimization: use read_stream to aggregate or direct get if small?
|
|
121
|
+
# Let's use read_stream to be consistent
|
|
122
|
+
buf = bytearray()
|
|
123
|
+
for chunk in self.read_stream(bucket, key):
|
|
124
|
+
buf.extend(chunk)
|
|
125
|
+
data = bytes(buf)
|
|
126
|
+
|
|
127
|
+
if hook:
|
|
128
|
+
data = hook.post_read(data)
|
|
129
|
+
return data
|
|
130
|
+
|
|
131
|
+
def read_json(
|
|
132
|
+
self,
|
|
133
|
+
bucket: str,
|
|
134
|
+
key: str,
|
|
135
|
+
hook: Optional[SyncContentHook] = None,
|
|
136
|
+
) -> Any:
|
|
137
|
+
# Do not use read_bytes hook logic, we apply hook to the object
|
|
138
|
+
buf = bytearray()
|
|
139
|
+
# Call internal read_stream without hook to get raw bytes
|
|
140
|
+
response = self._client.get_object(Bucket=bucket, Key=key)
|
|
141
|
+
for chunk in response["Body"].iter_chunks():
|
|
142
|
+
buf.extend(chunk)
|
|
143
|
+
|
|
144
|
+
data = bytes(buf)
|
|
145
|
+
obj = json.loads(data.decode("utf-8"))
|
|
146
|
+
|
|
147
|
+
if hook:
|
|
148
|
+
obj = hook.post_read(obj)
|
|
149
|
+
return obj
|
|
150
|
+
|
|
151
|
+
def write_stream(
|
|
152
|
+
self,
|
|
153
|
+
stream: Iterator[bytes],
|
|
154
|
+
bucket: str = "",
|
|
155
|
+
key: str = "",
|
|
156
|
+
hook: Optional[SyncContentHook] = None,
|
|
157
|
+
*args: Any,
|
|
158
|
+
**kwargs: Any,
|
|
159
|
+
) -> None:
|
|
160
|
+
if not bucket or not key:
|
|
161
|
+
raise ValueError("bucket and key are required")
|
|
162
|
+
|
|
163
|
+
if hook:
|
|
164
|
+
stream = hook.pre_write(stream)
|
|
165
|
+
|
|
166
|
+
fileobj = IteratorFile(stream)
|
|
167
|
+
self._client.upload_fileobj(fileobj, bucket, key)
|
|
168
|
+
|
|
169
|
+
def write_bytes(
|
|
170
|
+
self,
|
|
171
|
+
data: bytes,
|
|
172
|
+
bucket: str = "",
|
|
173
|
+
key: str = "",
|
|
174
|
+
hook: Optional[SyncContentHook] = None,
|
|
175
|
+
*args: Any,
|
|
176
|
+
**kwargs: Any,
|
|
177
|
+
) -> None:
|
|
178
|
+
if not bucket or not key:
|
|
179
|
+
raise ValueError("bucket and key are required")
|
|
180
|
+
|
|
181
|
+
if hook:
|
|
182
|
+
data = hook.pre_write(data)
|
|
183
|
+
|
|
184
|
+
# Direct put for bytes
|
|
185
|
+
self._client.put_object(Bucket=bucket, Key=key, Body=data)
|
|
186
|
+
|
|
187
|
+
def write_json(
|
|
188
|
+
self,
|
|
189
|
+
data: Any,
|
|
190
|
+
bucket: str,
|
|
191
|
+
key: str,
|
|
192
|
+
indent: int = 2,
|
|
193
|
+
hook: Optional[SyncContentHook] = None,
|
|
194
|
+
) -> None:
|
|
195
|
+
if hook:
|
|
196
|
+
data = hook.pre_write(data)
|
|
197
|
+
|
|
198
|
+
content = json.dumps(data, ensure_ascii=False, indent=indent)
|
|
199
|
+
self.write_bytes(content.encode("utf-8"), bucket, key)
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
from itertools import islice
|
|
2
|
+
from typing import Any, Iterable, Iterator
|
|
3
|
+
|
|
4
|
+
from sqlalchemy import create_engine, text
|
|
5
|
+
from sqlalchemy.engine import Engine
|
|
6
|
+
|
|
7
|
+
from ...interfaces import SyncConnector
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class SyncSQLConnectorBase(SyncConnector):
|
|
11
|
+
"""
|
|
12
|
+
Base synchronous SQL connector using SQLAlchemy engine.
|
|
13
|
+
|
|
14
|
+
The `url` should be a standard SQLAlchemy URL (e.g. `mysql+pymysql://...`).
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
def __init__(self, url: str):
|
|
18
|
+
self._url = url
|
|
19
|
+
self._engine: Engine = create_engine(self._url, future=True)
|
|
20
|
+
|
|
21
|
+
def fetch_rows(self, query: str, **params: Any) -> Iterator[dict]:
|
|
22
|
+
"""Stream rows from a query as dictionaries."""
|
|
23
|
+
with self._engine.connect() as conn: # type: ignore
|
|
24
|
+
# stream_results=True might be needed for server-side cursors depending on driver
|
|
25
|
+
# For strict streaming, execution options might be needed.
|
|
26
|
+
# Here we follow basic SQLAlchemy usage.
|
|
27
|
+
result = conn.execution_options(stream_results=True).execute(text(query), params)
|
|
28
|
+
for row in result.mappings():
|
|
29
|
+
yield dict(row)
|
|
30
|
+
|
|
31
|
+
def execute(self, statement: str, **params: Any) -> None:
|
|
32
|
+
"""Execute a statement (INSERT/UPDATE/DELETE)."""
|
|
33
|
+
with self._engine.begin() as conn: # type: ignore
|
|
34
|
+
conn.execute(text(statement), params)
|
|
35
|
+
|
|
36
|
+
def execute_many(self, statement: str, params_iter: Iterable[dict]) -> None:
|
|
37
|
+
"""
|
|
38
|
+
Execute the same statement multiple times.
|
|
39
|
+
"""
|
|
40
|
+
with self._engine.begin() as conn: # type: ignore
|
|
41
|
+
for params in params_iter:
|
|
42
|
+
conn.execute(text(statement), params)
|
|
43
|
+
|
|
44
|
+
def close(self) -> None:
|
|
45
|
+
self._engine.dispose()
|
|
46
|
+
|
|
47
|
+
def ping(self) -> bool:
|
|
48
|
+
"""Check connection by running a simple query."""
|
|
49
|
+
try:
|
|
50
|
+
with self._engine.connect() as conn: # type: ignore
|
|
51
|
+
conn.execute(text("SELECT 1"))
|
|
52
|
+
return True
|
|
53
|
+
except Exception:
|
|
54
|
+
return False
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class SyncMySQLConnector(SyncSQLConnectorBase):
|
|
58
|
+
"""
|
|
59
|
+
Synchronous MySQL connector.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
def __init__(self, url: str):
|
|
63
|
+
super().__init__(url)
|
|
64
|
+
|
|
65
|
+
def bulk_insert(
|
|
66
|
+
self,
|
|
67
|
+
table: str,
|
|
68
|
+
rows: Iterable[dict],
|
|
69
|
+
chunk_size: int = 1000,
|
|
70
|
+
) -> None:
|
|
71
|
+
"""
|
|
72
|
+
Optimized bulk insert using SQLAlchemy's batch execution.
|
|
73
|
+
"""
|
|
74
|
+
rows_iter = iter(rows)
|
|
75
|
+
|
|
76
|
+
try:
|
|
77
|
+
first_row = next(rows_iter)
|
|
78
|
+
except StopIteration:
|
|
79
|
+
return
|
|
80
|
+
|
|
81
|
+
cols = list(first_row.keys())
|
|
82
|
+
from itertools import chain
|
|
83
|
+
|
|
84
|
+
rows_iter = chain([first_row], rows_iter)
|
|
85
|
+
|
|
86
|
+
col_list = ", ".join([f"`{c}`" for c in cols])
|
|
87
|
+
placeholders = ", ".join([f":{c}" for c in cols])
|
|
88
|
+
stmt = text(f"INSERT INTO {table} ({col_list}) VALUES ({placeholders})")
|
|
89
|
+
|
|
90
|
+
with self._engine.begin() as conn: # type: ignore
|
|
91
|
+
while True:
|
|
92
|
+
chunk = list(islice(rows_iter, chunk_size))
|
|
93
|
+
if not chunk:
|
|
94
|
+
break
|
|
95
|
+
conn.execute(stmt, chunk)
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from abc import abstractmethod
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import Any, AsyncIterator, Iterator, Optional, Protocol, TypedDict, runtime_checkable
|
|
6
|
+
|
|
7
|
+
DataChunk = bytes
|
|
8
|
+
AsyncByteIterator = AsyncIterator[DataChunk]
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Readable(Protocol):
|
|
12
|
+
"""Protocol for objects that can stream bytes out of a data source."""
|
|
13
|
+
|
|
14
|
+
def read_stream(self, *args: Any, **kwargs: Any) -> AsyncByteIterator:
|
|
15
|
+
"""Yield chunks of bytes from the source."""
|
|
16
|
+
...
|
|
17
|
+
|
|
18
|
+
async def read_bytes(self, *args: Any, **kwargs: Any) -> bytes:
|
|
19
|
+
"""Convenience: read the entire payload into memory."""
|
|
20
|
+
...
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Writable(Protocol):
|
|
24
|
+
"""Protocol for objects that can consume async byte streams to write to a destination."""
|
|
25
|
+
|
|
26
|
+
async def write_stream(self, stream: AsyncByteIterator, *args: Any, **kwargs: Any) -> None:
|
|
27
|
+
"""Consume the stream and store the content."""
|
|
28
|
+
...
|
|
29
|
+
|
|
30
|
+
async def write_bytes(self, data: bytes, *args: Any, **kwargs: Any) -> None:
|
|
31
|
+
"""Convenience: write a single bytes object."""
|
|
32
|
+
...
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@runtime_checkable
|
|
36
|
+
class Connector(Protocol):
|
|
37
|
+
"""
|
|
38
|
+
Base connector interface.
|
|
39
|
+
|
|
40
|
+
Connectors SHOULD implement `close()` and may provide any combination of
|
|
41
|
+
the read/write convenience methods above.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
@abstractmethod
|
|
45
|
+
async def close(self) -> None: # pragma: no cover - interface only
|
|
46
|
+
"""Release any held resources (sessions, clients)."""
|
|
47
|
+
...
|
|
48
|
+
|
|
49
|
+
async def ping(self) -> bool:
|
|
50
|
+
"""Optional quick health check; return True if the connector is responsive."""
|
|
51
|
+
...
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class S3Location(TypedDict):
|
|
55
|
+
bucket: str
|
|
56
|
+
key: str
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class SQLLocation(TypedDict, total=False):
|
|
60
|
+
table: str
|
|
61
|
+
schema: Optional[str]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass
|
|
65
|
+
class RangeSpec:
|
|
66
|
+
offset: Optional[int] = None
|
|
67
|
+
length: Optional[int] = None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@runtime_checkable
|
|
71
|
+
class ContentHook(Protocol):
|
|
72
|
+
"""Protocol for hooks that can intercept and transform data."""
|
|
73
|
+
|
|
74
|
+
async def pre_write(self, data: Any, **kwargs: Any) -> Any:
|
|
75
|
+
"""Called before writing data to storage. Return transformed data."""
|
|
76
|
+
...
|
|
77
|
+
|
|
78
|
+
async def post_read(self, data: Any, **kwargs: Any) -> Any:
|
|
79
|
+
"""Called after reading data from storage. Return transformed data."""
|
|
80
|
+
...
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class SyncReadable(Protocol):
|
|
84
|
+
"""Protocol for objects that can stream bytes synchronously."""
|
|
85
|
+
|
|
86
|
+
def read_stream(self, *args: Any, **kwargs: Any) -> Iterator[bytes]:
|
|
87
|
+
"""Yield chunks of bytes from the source."""
|
|
88
|
+
...
|
|
89
|
+
|
|
90
|
+
def read_bytes(self, *args: Any, **kwargs: Any) -> bytes:
|
|
91
|
+
"""Convenience: read the entire payload into memory."""
|
|
92
|
+
...
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class SyncWritable(Protocol):
|
|
96
|
+
"""Protocol for objects that can consume synchronous byte streams."""
|
|
97
|
+
|
|
98
|
+
def write_stream(self, stream: Iterator[bytes], *args: Any, **kwargs: Any) -> None:
|
|
99
|
+
"""Consume the stream and store the content."""
|
|
100
|
+
...
|
|
101
|
+
|
|
102
|
+
def write_bytes(self, data: bytes, *args: Any, **kwargs: Any) -> None:
|
|
103
|
+
"""Convenience: write a single bytes object."""
|
|
104
|
+
...
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@runtime_checkable
|
|
108
|
+
class SyncConnector(Protocol):
|
|
109
|
+
"""Base synchronous connector interface."""
|
|
110
|
+
|
|
111
|
+
@abstractmethod
|
|
112
|
+
def close(self) -> None:
|
|
113
|
+
"""Release any held resources."""
|
|
114
|
+
...
|
|
115
|
+
|
|
116
|
+
def ping(self) -> bool:
|
|
117
|
+
"""Optional quick health check."""
|
|
118
|
+
...
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
@runtime_checkable
|
|
122
|
+
class SyncContentHook(Protocol):
|
|
123
|
+
"""Protocol for synchronous hooks."""
|
|
124
|
+
|
|
125
|
+
def pre_write(self, data: Any, **kwargs: Any) -> Any: ...
|
|
126
|
+
|
|
127
|
+
def post_read(self, data: Any, **kwargs: Any) -> Any: ...
|
multids-0.1.0/src/multids/ai.py
DELETED
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
from __future__ import annotations
|
|
2
|
-
|
|
3
|
-
from typing import Any, Dict, Protocol
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
class AIClientInterface(Protocol):
|
|
7
|
-
async def generate(self, prompt: str, **kwargs: Any) -> Dict[str, Any]:
|
|
8
|
-
"""Generate a response for the given prompt."""
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
class OpenAIClient:
|
|
12
|
-
def __init__(self, client):
|
|
13
|
-
# client: an `openai` async-compatible client or wrapper
|
|
14
|
-
self._client = client
|
|
15
|
-
|
|
16
|
-
async def generate(self, prompt: str, **kwargs: Any) -> Dict[str, Any]:
|
|
17
|
-
# Implementation will depend on the chosen AI provider.
|
|
18
|
-
return await self._client.create(prompt=prompt, **kwargs)
|
|
@@ -1,67 +0,0 @@
|
|
|
1
|
-
from __future__ import annotations
|
|
2
|
-
|
|
3
|
-
from abc import abstractmethod
|
|
4
|
-
from dataclasses import dataclass
|
|
5
|
-
from typing import Any, AsyncIterator, Optional, Protocol, TypedDict, runtime_checkable
|
|
6
|
-
|
|
7
|
-
DataChunk = bytes
|
|
8
|
-
AsyncByteIterator = AsyncIterator[DataChunk]
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
class Readable(Protocol):
|
|
12
|
-
"""Protocol for objects that can stream bytes out of a data source."""
|
|
13
|
-
|
|
14
|
-
def read_stream(self, *args: Any, **kwargs: Any) -> AsyncByteIterator:
|
|
15
|
-
"""Yield chunks of bytes from the source."""
|
|
16
|
-
...
|
|
17
|
-
|
|
18
|
-
async def read_bytes(self, *args: Any, **kwargs: Any) -> bytes:
|
|
19
|
-
"""Convenience: read the entire payload into memory."""
|
|
20
|
-
...
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
class Writable(Protocol):
|
|
24
|
-
"""Protocol for objects that can consume async byte streams to write to a destination."""
|
|
25
|
-
|
|
26
|
-
async def write_stream(self, stream: AsyncByteIterator, *args: Any, **kwargs: Any) -> None:
|
|
27
|
-
"""Consume the stream and store the content."""
|
|
28
|
-
...
|
|
29
|
-
|
|
30
|
-
async def write_bytes(self, data: bytes, *args: Any, **kwargs: Any) -> None:
|
|
31
|
-
"""Convenience: write a single bytes object."""
|
|
32
|
-
...
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
@runtime_checkable
|
|
36
|
-
class Connector(Protocol):
|
|
37
|
-
"""
|
|
38
|
-
Base connector interface.
|
|
39
|
-
|
|
40
|
-
Connectors SHOULD implement `close()` and may provide any combination of
|
|
41
|
-
the read/write convenience methods above.
|
|
42
|
-
"""
|
|
43
|
-
|
|
44
|
-
@abstractmethod
|
|
45
|
-
async def close(self) -> None: # pragma: no cover - interface only
|
|
46
|
-
"""Release any held resources (sessions, clients)."""
|
|
47
|
-
...
|
|
48
|
-
|
|
49
|
-
async def ping(self) -> bool:
|
|
50
|
-
"""Optional quick health check; return True if the connector is responsive."""
|
|
51
|
-
...
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
class S3Location(TypedDict):
|
|
55
|
-
bucket: str
|
|
56
|
-
key: str
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
class SQLLocation(TypedDict, total=False):
|
|
60
|
-
table: str
|
|
61
|
-
schema: Optional[str]
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
@dataclass
|
|
65
|
-
class RangeSpec:
|
|
66
|
-
offset: Optional[int] = None
|
|
67
|
-
length: Optional[int] = None
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|