nvidia-nat-mysql 1.2.0a20250813__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.
File without changes
@@ -0,0 +1,209 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2024-2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import logging
17
+ import pickle
18
+
19
+ import aiomysql
20
+ from aiomysql.pool import Pool
21
+
22
+ from nat.data_models.object_store import KeyAlreadyExistsError
23
+ from nat.data_models.object_store import NoSuchKeyError
24
+ from nat.object_store.interfaces import ObjectStore
25
+ from nat.object_store.models import ObjectStoreItem
26
+ from nat.plugins.mysql.object_store import MySQLObjectStoreClientConfig
27
+ from nat.utils.type_utils import override
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+
32
+ class MySQLObjectStore(ObjectStore):
33
+ """
34
+ Implementation of ObjectStore that stores objects in a MySQL database.
35
+ """
36
+
37
+ def __init__(self, config: MySQLObjectStoreClientConfig):
38
+
39
+ super().__init__()
40
+
41
+ self._config = config
42
+ self._conn_pool: Pool | None = None
43
+
44
+ self._schema = f"`bucket_{self._config.bucket_name}`"
45
+
46
+ async def __aenter__(self):
47
+
48
+ if self._conn_pool is not None:
49
+ raise RuntimeError("Connection already established")
50
+
51
+ self._conn_pool = await aiomysql.create_pool(
52
+ host=self._config.host,
53
+ port=self._config.port,
54
+ user=self._config.username,
55
+ password=self._config.password,
56
+ autocommit=False, # disable autocommit for transactions
57
+ )
58
+ assert self._conn_pool is not None
59
+
60
+ logger.info(
61
+ f"Created connection pool for {self._config.bucket_name} at {self._config.host}:{self._config.port}")
62
+
63
+ async with self._conn_pool.acquire() as conn:
64
+ async with conn.cursor() as cur:
65
+
66
+ # Create schema (database) if doesn't exist
67
+ await cur.execute(f"CREATE SCHEMA IF NOT EXISTS {self._schema} DEFAULT CHARACTER SET utf8mb4;")
68
+ await cur.execute(f"USE {self._schema};")
69
+
70
+ # Create metadata table_schema
71
+ await cur.execute("""
72
+ CREATE TABLE IF NOT EXISTS object_meta (
73
+ id INT AUTO_INCREMENT PRIMARY KEY,
74
+ path VARCHAR(768) NOT NULL UNIQUE,
75
+ size BIGINT NOT NULL,
76
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
77
+ ) ENGINE=InnoDB;
78
+ """)
79
+
80
+ # Create blob data table
81
+ await cur.execute("""
82
+ CREATE TABLE IF NOT EXISTS object_data (
83
+ id INT PRIMARY KEY,
84
+ data LONGBLOB NOT NULL,
85
+ FOREIGN KEY (id) REFERENCES object_meta(id) ON DELETE CASCADE
86
+ ) ENGINE=InnoDB ROW_FORMAT=DYNAMIC;
87
+ """)
88
+
89
+ await conn.commit()
90
+
91
+ logger.info(
92
+ f"Created schema and tables for {self._config.bucket_name} at {self._config.host}:{self._config.port}")
93
+
94
+ return self
95
+
96
+ async def __aexit__(self, exc_type, exc_value, traceback):
97
+
98
+ if not self._conn_pool:
99
+ raise RuntimeError("Connection not established")
100
+
101
+ # Trigger the non-async close method then wait for the pool to close
102
+ self._conn_pool.close()
103
+
104
+ await self._conn_pool.wait_closed()
105
+
106
+ self._conn_pool = None
107
+
108
+ @override
109
+ async def put_object(self, key: str, item: ObjectStoreItem):
110
+
111
+ if not self._conn_pool:
112
+ raise RuntimeError("Connection not established")
113
+
114
+ async with self._conn_pool.acquire() as conn:
115
+ async with conn.cursor() as cur:
116
+ await cur.execute(f"USE {self._schema};")
117
+ try:
118
+ await cur.execute("START TRANSACTION;")
119
+ await cur.execute("INSERT IGNORE INTO object_meta (path, size) VALUES (%s, %s)",
120
+ (key, len(item.data)))
121
+ if cur.rowcount == 0:
122
+ raise KeyAlreadyExistsError(
123
+ key=key, additional_message=f"MySQL table {self._config.bucket_name} already has key {key}")
124
+ await cur.execute("SELECT id FROM object_meta WHERE path=%s FOR UPDATE;", (key, ))
125
+ (obj_id, ) = await cur.fetchone()
126
+
127
+ blob = pickle.dumps(item)
128
+ await cur.execute("INSERT INTO object_data (id, data) VALUES (%s, %s)", (obj_id, blob))
129
+ await conn.commit()
130
+ except Exception:
131
+ await conn.rollback()
132
+ raise
133
+
134
+ @override
135
+ async def upsert_object(self, key: str, item: ObjectStoreItem):
136
+
137
+ if not self._conn_pool:
138
+ raise RuntimeError("Connection not established")
139
+
140
+ async with self._conn_pool.acquire() as conn:
141
+ async with conn.cursor() as cur:
142
+ await cur.execute(f"USE {self._schema};")
143
+ try:
144
+ await cur.execute("START TRANSACTION;")
145
+ await cur.execute(
146
+ """
147
+ INSERT INTO object_meta (path, size)
148
+ VALUES (%s, %s)
149
+ ON DUPLICATE KEY UPDATE size=VALUES(size), created_at=CURRENT_TIMESTAMP
150
+ """, (key, len(item.data)))
151
+ await cur.execute("SELECT id FROM object_meta WHERE path=%s FOR UPDATE;", (key, ))
152
+ (obj_id, ) = await cur.fetchone()
153
+
154
+ blob = pickle.dumps(item)
155
+ await cur.execute("REPLACE INTO object_data (id, data) VALUES (%s, %s)", (obj_id, blob))
156
+ await conn.commit()
157
+ except Exception:
158
+ await conn.rollback()
159
+ raise
160
+
161
+ @override
162
+ async def get_object(self, key: str) -> ObjectStoreItem:
163
+
164
+ if not self._conn_pool:
165
+ raise RuntimeError("Connection not established")
166
+
167
+ async with self._conn_pool.acquire() as conn:
168
+ async with conn.cursor() as cur:
169
+ await cur.execute(f"USE {self._schema};")
170
+ await cur.execute(
171
+ """
172
+ SELECT d.data
173
+ FROM object_data d
174
+ JOIN object_meta m USING(id)
175
+ WHERE m.path=%s
176
+ """, (key, ))
177
+ row = await cur.fetchone()
178
+ if not row:
179
+ raise NoSuchKeyError(
180
+ key=key, additional_message=f"MySQL table {self._config.bucket_name} does not have key {key}")
181
+ return pickle.loads(row[0])
182
+
183
+ @override
184
+ async def delete_object(self, key: str):
185
+
186
+ if not self._conn_pool:
187
+ raise RuntimeError("Connection not established")
188
+
189
+ async with self._conn_pool.acquire() as conn:
190
+ async with conn.cursor() as cur:
191
+ try:
192
+ await cur.execute(f"USE {self._schema};")
193
+ await cur.execute(
194
+ """
195
+ DELETE m, d
196
+ FROM object_meta m
197
+ JOIN object_data d USING(id)
198
+ WHERE m.path=%s
199
+ """, (key, ))
200
+
201
+ if cur.rowcount == 0:
202
+ raise NoSuchKeyError(
203
+ key=key,
204
+ additional_message=f"MySQL table {self._config.bucket_name} does not have key {key}")
205
+
206
+ await conn.commit()
207
+ except Exception:
208
+ await conn.rollback()
209
+ raise
@@ -0,0 +1,66 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import os
17
+ from typing import ClassVar
18
+
19
+ from pydantic import Field
20
+
21
+ from nat.builder.builder import Builder
22
+ from nat.cli.register_workflow import register_object_store
23
+ from nat.data_models.object_store import ObjectStoreBaseConfig
24
+
25
+
26
+ class MySQLObjectStoreClientConfig(ObjectStoreBaseConfig, name="mysql"):
27
+ """
28
+ Object store that stores objects in a MySQL database.
29
+ """
30
+
31
+ DEFAULT_HOST: ClassVar[str] = "localhost"
32
+ DEFAULT_PORT: ClassVar[int] = 3306
33
+
34
+ HOST_ENV: ClassVar[str] = "AIQ_MYSQL_OBJECT_STORE_HOST"
35
+ PORT_ENV: ClassVar[str] = "AIQ_MYSQL_OBJECT_STORE_PORT"
36
+ USERNAME_ENV: ClassVar[str] = "AIQ_MYSQL_OBJECT_STORE_USERNAME"
37
+ PASSWORD_ENV: ClassVar[str] = "AIQ_MYSQL_OBJECT_STORE_PASSWORD"
38
+
39
+ bucket_name: str = Field(description="The name of the bucket to use for the object store")
40
+ host: str = Field(
41
+ default=os.environ.get(HOST_ENV, DEFAULT_HOST),
42
+ description="The host of the MySQL server"
43
+ " (uses {HOST_ENV} if unspecified; falls back to {DEFAULT_HOST})",
44
+ )
45
+ port: int = Field(
46
+ default=int(os.environ.get(PORT_ENV, DEFAULT_PORT)),
47
+ description="The port of the MySQL server"
48
+ " (uses {PORT_ENV} if unspecified; falls back to {DEFAULT_PORT})",
49
+ )
50
+ username: str | None = Field(
51
+ default=os.environ.get(USERNAME_ENV),
52
+ description=f"The username used to connect to the MySQL server (uses {USERNAME_ENV} if unspecifed)",
53
+ )
54
+ password: str | None = Field(
55
+ default=os.environ.get(PASSWORD_ENV),
56
+ description="The password used to connect to the MySQL server (uses {PASSWORD_ENV} if unspecifed)",
57
+ )
58
+
59
+
60
+ @register_object_store(config_type=MySQLObjectStoreClientConfig)
61
+ async def mysql_object_store_client(config: MySQLObjectStoreClientConfig, builder: Builder):
62
+
63
+ from .mysql_object_store import MySQLObjectStore
64
+
65
+ async with MySQLObjectStore(config) as store:
66
+ yield store
@@ -0,0 +1,22 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ # pylint: disable=unused-import
17
+ # flake8: noqa
18
+ # isort:skip_file
19
+
20
+ # Import any providers which need to be automatically registered here
21
+
22
+ from . import object_store
@@ -0,0 +1,10 @@
1
+ Metadata-Version: 2.4
2
+ Name: nvidia-nat-mysql
3
+ Version: 1.2.0a20250813
4
+ Summary: Subpackage for MySQL integration in NeMo Agent toolkit
5
+ Keywords: ai,agents,memory,data store
6
+ Classifier: Programming Language :: Python
7
+ Requires-Python: >=3.12
8
+ Description-Content-Type: text/markdown
9
+ Requires-Dist: nvidia-nat==v1.2.0a20250813
10
+ Requires-Dist: aiomysql>=0.2.0
@@ -0,0 +1,9 @@
1
+ nat/plugins/mysql/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ nat/plugins/mysql/mysql_object_store.py,sha256=EXHuA6z28__lH6qhSyGuIPWLPZ-5BzH9EHVCkpDYyvE,8042
3
+ nat/plugins/mysql/object_store.py,sha256=_9uPdkXS5C6LMgODizyiyhwObOF5AfNF2vZZr-h6Yc0,2600
4
+ nat/plugins/mysql/register.py,sha256=7gqnwyDrYttIlEaa7lo9AASYt-2GrZJE0YT2jpKjepo,845
5
+ nvidia_nat_mysql-1.2.0a20250813.dist-info/METADATA,sha256=4IC6fs-Bs8S_xAGWl3-wf_uF-fLNi6i4tYNa-i7KN20,352
6
+ nvidia_nat_mysql-1.2.0a20250813.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
7
+ nvidia_nat_mysql-1.2.0a20250813.dist-info/entry_points.txt,sha256=ZI7ielmDX-k_OPXGvpRB5tKFVR5kMCHmHGwLWqxRKh0,56
8
+ nvidia_nat_mysql-1.2.0a20250813.dist-info/top_level.txt,sha256=8-CJ2cP6-f0ZReXe5Hzqp-5pvzzHz-5Ds5H2bGqh1-U,4
9
+ nvidia_nat_mysql-1.2.0a20250813.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [nat.components]
2
+ nat_mysql = nat.plugins.mysql.register