sqlalchemy-foundation-kit 0.0.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.
Files changed (49) hide show
  1. sqlalchemy_foundation_kit/__init__.py +119 -0
  2. sqlalchemy_foundation_kit/__version__.py +1 -0
  3. sqlalchemy_foundation_kit/_typing.py +28 -0
  4. sqlalchemy_foundation_kit/base/__init__.py +46 -0
  5. sqlalchemy_foundation_kit/base/_optional.py +37 -0
  6. sqlalchemy_foundation_kit/base/engine.py +256 -0
  7. sqlalchemy_foundation_kit/base/metadata.py +57 -0
  8. sqlalchemy_foundation_kit/base/models.py +101 -0
  9. sqlalchemy_foundation_kit/base/serialization.py +98 -0
  10. sqlalchemy_foundation_kit/base/types.py +72 -0
  11. sqlalchemy_foundation_kit/config/__init__.py +17 -0
  12. sqlalchemy_foundation_kit/config/postgres.py +177 -0
  13. sqlalchemy_foundation_kit/contrib/__init__.py +5 -0
  14. sqlalchemy_foundation_kit/contrib/_metrics_utils.py +19 -0
  15. sqlalchemy_foundation_kit/contrib/dependency_injector/__init__.py +27 -0
  16. sqlalchemy_foundation_kit/contrib/dependency_injector/_base.py +27 -0
  17. sqlalchemy_foundation_kit/contrib/dependency_injector/_deps.py +37 -0
  18. sqlalchemy_foundation_kit/contrib/dependency_injector/database.py +196 -0
  19. sqlalchemy_foundation_kit/contrib/dependency_injector/metrics.py +85 -0
  20. sqlalchemy_foundation_kit/contrib/di/__init__.py +21 -0
  21. sqlalchemy_foundation_kit/contrib/di/_base.py +27 -0
  22. sqlalchemy_foundation_kit/contrib/di/_deps.py +32 -0
  23. sqlalchemy_foundation_kit/contrib/di/database.py +169 -0
  24. sqlalchemy_foundation_kit/contrib/di/metrics.py +71 -0
  25. sqlalchemy_foundation_kit/contrib/metrics/__init__.py +7 -0
  26. sqlalchemy_foundation_kit/contrib/metrics/postgres.py +149 -0
  27. sqlalchemy_foundation_kit/contrib/settings/__init__.py +19 -0
  28. sqlalchemy_foundation_kit/contrib/settings/postgres.py +183 -0
  29. sqlalchemy_foundation_kit/contrib/telemetry/__init__.py +17 -0
  30. sqlalchemy_foundation_kit/contrib/telemetry/instrumentations.py +101 -0
  31. sqlalchemy_foundation_kit/contrib/telemetry/uow.py +227 -0
  32. sqlalchemy_foundation_kit/protocols/__init__.py +21 -0
  33. sqlalchemy_foundation_kit/protocols/metrics.py +77 -0
  34. sqlalchemy_foundation_kit/py.typed +0 -0
  35. sqlalchemy_foundation_kit/session/__init__.py +27 -0
  36. sqlalchemy_foundation_kit/session/builder.py +293 -0
  37. sqlalchemy_foundation_kit/session/connection.py +33 -0
  38. sqlalchemy_foundation_kit/session/factories.py +104 -0
  39. sqlalchemy_foundation_kit/session/locks.py +68 -0
  40. sqlalchemy_foundation_kit/session/manager.py +252 -0
  41. sqlalchemy_foundation_kit/session/retry.py +82 -0
  42. sqlalchemy_foundation_kit/uow/__init__.py +21 -0
  43. sqlalchemy_foundation_kit/uow/enums.py +18 -0
  44. sqlalchemy_foundation_kit/uow/protocols.py +80 -0
  45. sqlalchemy_foundation_kit/uow/sqlalchemy.py +406 -0
  46. sqlalchemy_foundation_kit-0.0.0.dist-info/METADATA +624 -0
  47. sqlalchemy_foundation_kit-0.0.0.dist-info/RECORD +49 -0
  48. sqlalchemy_foundation_kit-0.0.0.dist-info/WHEEL +4 -0
  49. sqlalchemy_foundation_kit-0.0.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,624 @@
1
+ Metadata-Version: 2.4
2
+ Name: sqlalchemy-foundation-kit
3
+ Version: 0.0.0
4
+ Summary: Foundation layer for SQLAlchemy-based services with UoW, session management, and observability
5
+ Project-URL: Repository, https://github.com/bedrock-python/sqlalchemy-foundation-kit
6
+ Project-URL: Documentation, https://bedrock-python.github.io/sqlalchemy-foundation-kit/
7
+ Project-URL: Changelog, https://github.com/bedrock-python/sqlalchemy-foundation-kit/blob/master/CHANGELOG.md
8
+ Project-URL: Bug Tracker, https://github.com/bedrock-python/sqlalchemy-foundation-kit/issues
9
+ Author-email: Alex Shalaev <shalaevad.alexey@yandex.ru>
10
+ License: Apache License
11
+ Version 2.0, January 2004
12
+ http://www.apache.org/licenses/
13
+
14
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
15
+
16
+ 1. Definitions.
17
+
18
+ "License" shall mean the terms and conditions for use, reproduction,
19
+ and distribution as defined by Sections 1 through 9 of this document.
20
+
21
+ "Licensor" shall mean the copyright owner or entity authorized by
22
+ the copyright owner that is granting the License.
23
+
24
+ "Legal Entity" shall mean the union of the acting entity and all
25
+ other entities that control, are controlled by, or are under common
26
+ control with that entity. For the purposes of this definition,
27
+ "control" means (i) the power, direct or indirect, to cause the
28
+ direction or management of such entity, whether by contract or
29
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
30
+ outstanding shares, or (iii) beneficial ownership of such entity.
31
+
32
+ "You" (or "Your") shall mean an individual or Legal Entity
33
+ exercising permissions granted by this License.
34
+
35
+ "Source" form shall mean the preferred form for making modifications,
36
+ including but not limited to software source code, documentation
37
+ source, and configuration files.
38
+
39
+ "Object" form shall mean any form resulting from mechanical
40
+ transformation or translation of a Source form, including but
41
+ not limited to compiled object code, generated documentation,
42
+ and conversions to other media types.
43
+
44
+ "Work" shall mean the work of authorship, whether in Source or
45
+ Object form, made available under the License, as indicated by a
46
+ copyright notice that is included in or attached to the work
47
+ (an example is provided in the Appendix below).
48
+
49
+ "Derivative Works" shall mean any work, whether in Source or Object
50
+ form, that is based on (or derived from) the Work and for which the
51
+ editorial revisions, annotations, elaborations, or other modifications
52
+ represent, as a whole, an original work of authorship. For the purposes
53
+ of this License, Derivative Works shall not include works that remain
54
+ separable from, or merely link (or bind by name) to the interfaces of,
55
+ the Work and Derivative Works thereof.
56
+
57
+ "Contribution" shall mean any work of authorship, including
58
+ the original version of the Work and any modifications or additions
59
+ to that Work or Derivative Works thereof, that is intentionally
60
+ submitted to Licensor for inclusion in the Work by the copyright owner
61
+ or by an individual or Legal Entity authorized to submit on behalf of
62
+ the copyright owner. For the purposes of this definition, "submitted"
63
+ means any form of electronic, verbal, or written communication sent
64
+ to the Licensor or its representatives, including but not limited to
65
+ communication on electronic mailing lists, source code control systems,
66
+ and issue tracking systems that are managed by, or on behalf of, the
67
+ Licensor for the purpose of discussing and improving the Work, but
68
+ excluding communication that is conspicuously marked or otherwise
69
+ designated in writing by the copyright owner as "Not a Contribution."
70
+
71
+ "Contributor" shall mean Licensor and any individual or Legal Entity
72
+ on behalf of whom a Contribution has been received by Licensor and
73
+ subsequently incorporated within the Work.
74
+
75
+ 2. Grant of Copyright License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ copyright license to reproduce, prepare Derivative Works of,
79
+ publicly display, publicly perform, sublicense, and distribute the
80
+ Work and such Derivative Works in Source or Object form.
81
+
82
+ 3. Grant of Patent License. Subject to the terms and conditions of
83
+ this License, each Contributor hereby grants to You a perpetual,
84
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
85
+ (except as stated in this section) patent license to make, have made,
86
+ use, offer to sell, sell, import, and otherwise transfer the Work,
87
+ where such license applies only to those patent claims licensable
88
+ by such Contributor that are necessarily infringed by their
89
+ Contribution(s) alone or by combination of their Contribution(s)
90
+ with the Work to which such Contribution(s) was submitted. If You
91
+ institute patent litigation against any entity (including a
92
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
93
+ or a Contribution incorporated within the Work constitutes direct
94
+ or contributory patent infringement, then any patent licenses
95
+ granted to You under this License for that Work shall terminate
96
+ as of the date such litigation is filed.
97
+
98
+ 4. Redistribution. You may reproduce and distribute copies of the
99
+ Work or Derivative Works thereof in any medium, with or without
100
+ modifications, and in Source or Object form, provided that You
101
+ meet the following conditions:
102
+
103
+ (a) You must give any other recipients of the Work or
104
+ Derivative Works a copy of this License; and
105
+
106
+ (b) You must cause any modified files to carry prominent notices
107
+ stating that You changed the files; and
108
+
109
+ (c) You must retain, in the Source form of any Derivative Works
110
+ that You distribute, all copyright, patent, trademark, and
111
+ attribution notices from the Source form of the Work,
112
+ excluding those notices that do not pertain to any part of
113
+ the Derivative Works; and
114
+
115
+ (d) If the Work includes a "NOTICE" text file as part of its
116
+ distribution, then any Derivative Works that You distribute must
117
+ include a readable copy of the attribution notices contained
118
+ within such NOTICE file, excluding those notices that do not
119
+ pertain to any part of the Derivative Works, in at least one
120
+ of the following places: within a NOTICE text file distributed
121
+ as part of the Derivative Works; within the Source form or
122
+ documentation, if provided along with the Derivative Works; or,
123
+ within a display generated by the Derivative Works, if and
124
+ wherever such third-party notices normally appear. The contents
125
+ of the NOTICE file are for informational purposes only and
126
+ do not modify the License. You may add Your own attribution
127
+ notices within Derivative Works that You distribute, alongside
128
+ or as an addendum to the NOTICE text from the Work, provided
129
+ that such additional attribution notices cannot be construed
130
+ as modifying the License.
131
+
132
+ You may add Your own copyright statement to Your modifications and
133
+ may provide additional or different license terms and conditions
134
+ for use, reproduction, or distribution of Your modifications, or
135
+ for any such Derivative Works as a whole, provided Your use,
136
+ reproduction, and distribution of the Work otherwise complies with
137
+ the conditions stated in this License.
138
+
139
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
140
+ any Contribution intentionally submitted for inclusion in the Work
141
+ by You to the Licensor shall be under the terms and conditions of
142
+ this License, without any additional terms or conditions.
143
+ Notwithstanding the above, nothing herein shall supersede or modify
144
+ the terms of any separate license agreement you may have executed
145
+ with Licensor regarding such Contributions.
146
+
147
+ 6. Trademarks. This License does not grant permission to use the trade
148
+ names, trademarks, service marks, or product names of the Licensor,
149
+ except as required for reasonable and customary use in describing the
150
+ origin of the Work and reproducing the content of the NOTICE file.
151
+
152
+ 7. Disclaimer of Warranty. Unless required by applicable law or
153
+ agreed to in writing, Licensor provides the Work (and each
154
+ Contributor provides its Contributions) on an "AS IS" BASIS,
155
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
156
+ implied, including, without limitation, any warranties or conditions
157
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
158
+ PARTICULAR PURPOSE. You are solely responsible for determining the
159
+ appropriateness of using or redistributing the Work and assume any
160
+ risks associated with Your exercise of permissions under this License.
161
+
162
+ 8. Limitation of Liability. In no event and under no legal theory,
163
+ whether in tort (including negligence), contract, or otherwise,
164
+ unless required by applicable law (such as deliberate and grossly
165
+ negligent acts) or agreed to in writing, shall any Contributor be
166
+ liable to You for damages, including any direct, indirect, special,
167
+ incidental, or consequential damages of any character arising as a
168
+ result of this License or out of the use or inability to use the
169
+ Work (including but not limited to damages for loss of goodwill,
170
+ work stoppage, computer failure or malfunction, or any and all
171
+ other commercial damages or losses), even if such Contributor
172
+ has been advised of the possibility of such damages.
173
+
174
+ 9. Accepting Warranty or Additional Liability. While redistributing
175
+ the Work or Derivative Works thereof, You may choose to offer,
176
+ and charge a fee for, acceptance of support, warranty, indemnity,
177
+ or other liability obligations and/or rights consistent with this
178
+ License. However, in accepting such obligations, You may act only
179
+ on Your own behalf and on Your sole responsibility, not on behalf
180
+ of any other Contributor, and only if You agree to indemnify,
181
+ defend, and hold each Contributor harmless for any liability
182
+ incurred by, or claims asserted against, such Contributor by reason
183
+ of your accepting any such warranty or additional liability.
184
+
185
+ END OF TERMS AND CONDITIONS
186
+
187
+ APPENDIX: How to apply the Apache License to your work.
188
+
189
+ To apply the Apache License to your work, attach the following
190
+ boilerplate notice, with the fields enclosed by brackets "[]"
191
+ replaced with your own identifying information. (Don't include
192
+ the brackets!) The text should be enclosed in the appropriate
193
+ comment syntax for the file format. We also recommend that a
194
+ file or class name and description of purpose be included on the
195
+ same "printed page" as the copyright notice for easier
196
+ identification within third-party archives.
197
+
198
+ Copyright 2026 Alex Shalaev
199
+
200
+ Licensed under the Apache License, Version 2.0 (the "License");
201
+ you may not use this file except in compliance with the License.
202
+ You may obtain a copy of the License at
203
+
204
+ http://www.apache.org/licenses/LICENSE-2.0
205
+
206
+ Unless required by applicable law or agreed to in writing, software
207
+ distributed under the License is distributed on an "AS IS" BASIS,
208
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
209
+ See the License for the specific language governing permissions and
210
+ limitations under the License.
211
+ License-File: LICENSE
212
+ Keywords: foundation,microservices,observability,opentelemetry,postgres,postgresql,sqlalchemy,tracing,unit-of-work,uow
213
+ Classifier: Development Status :: 4 - Beta
214
+ Classifier: Intended Audience :: Developers
215
+ Classifier: License :: OSI Approved :: Apache Software License
216
+ Classifier: Programming Language :: Python :: 3
217
+ Classifier: Programming Language :: Python :: 3.11
218
+ Classifier: Programming Language :: Python :: 3.12
219
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
220
+ Classifier: Typing :: Typed
221
+ Requires-Python: >=3.11
222
+ Requires-Dist: pydantic<3.0.0,>=2.5.0
223
+ Requires-Dist: sqlalchemy[asyncio]<3.0.0,>=2.0.35
224
+ Provides-Extra: all
225
+ Requires-Dist: dependency-injector<5.0.0,>=4.41.0; extra == 'all'
226
+ Requires-Dist: dishka<2.0.0,>=1.3.0; extra == 'all'
227
+ Requires-Dist: opentelemetry-api<2.0.0,>=1.20.0; extra == 'all'
228
+ Requires-Dist: opentelemetry-instrumentation-asyncpg<1.0.0,>=0.41b0; extra == 'all'
229
+ Requires-Dist: opentelemetry-instrumentation-sqlalchemy<1.0.0,>=0.41b0; extra == 'all'
230
+ Requires-Dist: opentelemetry-sdk<2.0.0,>=1.20.0; extra == 'all'
231
+ Requires-Dist: orjson<4.0.0,>=3.9.0; extra == 'all'
232
+ Requires-Dist: prometheus-client<1.0.0,>=0.19.0; extra == 'all'
233
+ Requires-Dist: pydantic-settings<3.0.0,>=2.3.0; extra == 'all'
234
+ Provides-Extra: dependency-injector
235
+ Requires-Dist: dependency-injector<5.0.0,>=4.41.0; extra == 'dependency-injector'
236
+ Provides-Extra: dishka
237
+ Requires-Dist: dishka<2.0.0,>=1.3.0; extra == 'dishka'
238
+ Provides-Extra: metrics
239
+ Requires-Dist: prometheus-client<1.0.0,>=0.19.0; extra == 'metrics'
240
+ Provides-Extra: orjson
241
+ Requires-Dist: orjson<4.0.0,>=3.9.0; extra == 'orjson'
242
+ Provides-Extra: settings
243
+ Requires-Dist: pydantic-settings<3.0.0,>=2.3.0; extra == 'settings'
244
+ Provides-Extra: telemetry
245
+ Requires-Dist: opentelemetry-api<2.0.0,>=1.20.0; extra == 'telemetry'
246
+ Requires-Dist: opentelemetry-instrumentation-asyncpg<1.0.0,>=0.41b0; extra == 'telemetry'
247
+ Requires-Dist: opentelemetry-instrumentation-sqlalchemy<1.0.0,>=0.41b0; extra == 'telemetry'
248
+ Requires-Dist: opentelemetry-sdk<2.0.0,>=1.20.0; extra == 'telemetry'
249
+ Description-Content-Type: text/markdown
250
+
251
+ # sqlalchemy-foundation-kit
252
+
253
+ <div align="center">
254
+
255
+ [![PyPI - Version](https://img.shields.io/pypi/v/sqlalchemy-foundation-kit?style=flat-square&logo=pypi&logoColor=white)](https://pypi.org/project/sqlalchemy-foundation-kit/)
256
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/sqlalchemy-foundation-kit?style=flat-square&logo=python&logoColor=white)](https://pypi.org/project/sqlalchemy-foundation-kit/)
257
+ [![License](https://img.shields.io/github/license/bedrock-python/sqlalchemy-foundation-kit?style=flat-square)](https://github.com/bedrock-python/sqlalchemy-foundation-kit/blob/master/LICENSE)
258
+
259
+ [![CI](https://img.shields.io/github/actions/workflow/status/bedrock-python/sqlalchemy-foundation-kit/ci.yml?branch=master&style=flat-square&logo=github&label=CI)](https://github.com/bedrock-python/sqlalchemy-foundation-kit/actions/workflows/ci.yml)
260
+ [![codecov](https://img.shields.io/codecov/c/github/bedrock-python/sqlalchemy-foundation-kit?style=flat-square&logo=codecov&logoColor=white)](https://codecov.io/gh/bedrock-python/sqlalchemy-foundation-kit)
261
+ [![Documentation](https://img.shields.io/badge/docs-github_pages-blue?style=flat-square&logo=materialformkdocs&logoColor=white)](https://bedrock-python.github.io/sqlalchemy-foundation-kit/)
262
+
263
+ [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json&style=flat-square)](https://github.com/astral-sh/ruff)
264
+ [![Type checked: mypy](https://img.shields.io/badge/type_checker-mypy-blue?style=flat-square&logo=python)](http://mypy-lang.org/)
265
+ [![uv](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/uv/main/assets/badge/v0.json&style=flat-square)](https://github.com/astral-sh/uv)
266
+
267
+ </div>
268
+
269
+ ---
270
+
271
+ **Production-ready foundation for SQLAlchemy-based async services with Unit of Work, session management, and observability**
272
+
273
+ `sqlalchemy-foundation-kit` is a standalone, batteries-included foundation for building async SQLAlchemy microservices. It bundles everything you commonly re-implement for every service into a single library:
274
+
275
+ - **PostgreSQL configuration** — Pydantic-based settings with grouped connection / pool / query options
276
+ - **Session management** — `AsyncSessionManager` with pgbouncer transaction-mode compatibility
277
+ - **Unit of Work pattern** — `AsyncSQLAlchemyUnitOfWork` with automatic commit/rollback
278
+ - **Base ORM models** — Pre-configured `Base`, mixins, custom types (`PydanticJSONB`, `UnConstrainedEnum`)
279
+ - **Observability** — Prometheus connection-pool metrics and OpenTelemetry tracing
280
+ - **DI integration** — Ready-to-use providers for [`dishka`](https://github.com/reagento/dishka) and `dependency-injector`
281
+
282
+ Only `sqlalchemy[asyncio]` and `pydantic` are required by default — everything else is an opt-in extra.
283
+
284
+ ## Key Features
285
+
286
+ ✅ **Single dependency** — All foundation pieces in one place
287
+ ✅ **Unit of Work pattern** — Transactional consistency with automatic commit/rollback
288
+ ✅ **Connection pool management** — `AsyncSessionManager` with metrics and health checks
289
+ ✅ **pgbouncer compatible** — Custom connection class for transaction mode
290
+ ✅ **Observability built-in** — Prometheus metrics + OpenTelemetry tracing
291
+ ✅ **Type-safe configuration** — Pydantic settings with validation
292
+ ✅ **Base ORM models** — Pre-configured `Base` with naming conventions and mixins
293
+
294
+ ## Installation
295
+
296
+ ```bash
297
+ # Basic installation (core functionality)
298
+ pip install sqlalchemy-foundation-kit
299
+
300
+ # With pydantic-settings support
301
+ pip install sqlalchemy-foundation-kit[settings]
302
+
303
+ # With Prometheus metrics
304
+ pip install sqlalchemy-foundation-kit[metrics]
305
+
306
+ # With OpenTelemetry tracing
307
+ pip install sqlalchemy-foundation-kit[telemetry]
308
+
309
+ # With dishka dependency injection
310
+ pip install sqlalchemy-foundation-kit[dishka]
311
+
312
+ # With dependency-injector containers
313
+ pip install sqlalchemy-foundation-kit[dependency-injector]
314
+
315
+ # With orjson serialization
316
+ pip install sqlalchemy-foundation-kit[orjson]
317
+
318
+ # All features
319
+ pip install sqlalchemy-foundation-kit[all]
320
+ ```
321
+
322
+ ## Quick Start
323
+
324
+ ### 1. Configuration (with pydantic-settings)
325
+
326
+ ```python
327
+ from pydantic import SecretStr
328
+ from pydantic_settings import BaseSettings
329
+ from sqlalchemy_foundation_kit.contrib.settings import (
330
+ BasePostgresConfig,
331
+ ConnectionSettings,
332
+ PoolSettings,
333
+ QuerySettings,
334
+ )
335
+
336
+ class Settings(BaseSettings):
337
+ postgres: BasePostgresConfig = BasePostgresConfig(
338
+ connection=ConnectionSettings(
339
+ host="localhost",
340
+ port=5432,
341
+ user="postgres",
342
+ password=SecretStr("secret"),
343
+ database="mydb",
344
+ ),
345
+ pool=PoolSettings(), # Uses defaults
346
+ query=QuerySettings(), # Uses defaults
347
+ application_name="my-service",
348
+ )
349
+ ```
350
+
351
+ Or implement `PostgresSettingsProtocol` directly:
352
+
353
+ ```python
354
+ from dataclasses import dataclass
355
+ from sqlalchemy_foundation_kit import (
356
+ PostgresSettingsProtocol,
357
+ ConnectionSettingsProtocol,
358
+ PoolSettingsProtocol,
359
+ QuerySettingsProtocol,
360
+ )
361
+
362
+ @dataclass
363
+ class MyConnectionSettings:
364
+ host: str = "localhost"
365
+ port: int = 5432
366
+ user: str = "postgres"
367
+ database: str = "mydb"
368
+
369
+ @dataclass
370
+ class MyPoolSettings:
371
+ kind: str = "async_adapted_queue"
372
+ size: int | None = 10
373
+ max_overflow: int | None = 20
374
+ pre_ping: bool = True
375
+ recycle: int | None = 3600
376
+ timeout: float | None = 30.0
377
+
378
+ @dataclass
379
+ class MyQuerySettings:
380
+ echo: bool = False
381
+ statement_cache_size: int | None = 0
382
+ prepared_statement_cache_size: int | None = 0
383
+ isolation_level: str | None = None
384
+
385
+ class PostgresConfig:
386
+ connection: ConnectionSettingsProtocol = MyConnectionSettings()
387
+ pool: PoolSettingsProtocol = MyPoolSettings()
388
+ query: QuerySettingsProtocol = MyQuerySettings()
389
+ application_name: str = "my-service"
390
+ db_schema: str | None = None
391
+ use_orjson_serialization: bool = True
392
+ jit: str | None = "off"
393
+
394
+ def to_dsn(self) -> str:
395
+ return f"postgresql+asyncpg://{self.connection.user}@{self.connection.host}:{self.connection.port}/{self.connection.database}"
396
+ ```
397
+
398
+ ### 2. Define ORM Models
399
+
400
+ ```python
401
+ from sqlalchemy.orm import Mapped, mapped_column
402
+ from sqlalchemy_foundation_kit import BaseTable, DatetimeColumnsMixin
403
+
404
+ class UserDB(BaseTable, DatetimeColumnsMixin):
405
+ __tablename__ = "users"
406
+ __created_at_index__ = True # Index on created_at
407
+
408
+ id: Mapped[UUID] = mapped_column(primary_key=True)
409
+ email: Mapped[str] = mapped_column(unique=True)
410
+ username: Mapped[str]
411
+ ```
412
+
413
+ ### 3. Create Session Manager
414
+
415
+ ```python
416
+ from sqlalchemy_foundation_kit import create_async_session_manager
417
+
418
+ async def main():
419
+ session_manager = create_async_session_manager(
420
+ settings.postgres,
421
+ metrics=postgres_metrics, # optional
422
+ )
423
+
424
+ async with session_manager.get_transaction() as session:
425
+ user = UserDB(id=uuid4(), email="user@example.com", username="user")
426
+ session.add(user)
427
+ # Auto-commit on exit
428
+ ```
429
+
430
+ ### 4. Unit of Work Pattern
431
+
432
+ ```python
433
+ from unit_of_work_kit import AsyncSQLAlchemyUnitOfWork, AsyncSQLAlchemyUowTransaction
434
+
435
+ # Define your transaction with repositories
436
+ class MyTransaction(AsyncSQLAlchemyUowTransaction):
437
+ @property
438
+ def users(self) -> UserRepository:
439
+ if self._users is None:
440
+ self._users = PostgresUserRepository(self.session)
441
+ return self._users
442
+
443
+ # Create UoW
444
+ class MyUnitOfWork(AsyncSQLAlchemyUnitOfWork[MyTransaction]):
445
+ def __init__(self, session_maker):
446
+ super().__init__(session_maker, transaction_factory=MyTransaction)
447
+
448
+ # Usage in use case
449
+ class CreateUserUseCase:
450
+ def __init__(self, uow: MyUnitOfWork):
451
+ self._uow = uow
452
+
453
+ async def execute(self, email: str) -> User:
454
+ async with self._uow.transaction() as tx:
455
+ user = await tx.users.create(email=email)
456
+ await tx.outbox.create(UserCreatedEvent(...))
457
+ return user
458
+ ```
459
+
460
+ ## What's Included
461
+
462
+ ### Core (always available)
463
+ - **Session Management**: `AsyncSessionManager`, `AsyncCConnection`
464
+ - **Base ORM**: `Base`, `BaseTable`, `DatetimeColumnsMixin`, `UnConstrainedEnum`, `PydanticJSONB`
465
+ - **Unit of Work**: `AsyncUnitOfWork`, `AsyncSQLAlchemyUnitOfWork`, `IsolationLevel`
466
+ - **Protocols**: `PostgresSettingsProtocol`, `PostgresMetricsProtocol`
467
+ - **Utilities**: `build_engine_kwargs`, `resolve_pool_class`, `load_orm_metadata`
468
+
469
+ ### Contrib (optional dependencies)
470
+
471
+ #### `contrib.settings` (requires `[settings]`)
472
+ ```python
473
+ from sqlalchemy_foundation_kit.contrib.settings import (
474
+ BasePostgresConfig,
475
+ BasePostgresMigrationsConfig,
476
+ )
477
+ ```
478
+ - `BasePostgresConfig` — Pydantic-based PostgreSQL configuration
479
+ - `BasePostgresMigrationsConfig` — Migrations configuration
480
+
481
+ #### `contrib.metrics` (requires `[metrics]`)
482
+ ```python
483
+ from sqlalchemy_foundation_kit.contrib.metrics import PostgresMetrics
484
+ ```
485
+ - `PostgresMetrics` — Prometheus metrics for connection pool
486
+ - Tracks: pool size, checked out connections, checkout duration, errors
487
+
488
+ #### `contrib.di` (requires `[dishka]`)
489
+ ```python
490
+ from sqlalchemy_foundation_kit.contrib.di import (
491
+ AsyncDatabaseProvider,
492
+ AsyncUnitOfWorkProvider,
493
+ PrometheusPostgresMetricsProvider,
494
+ )
495
+ ```
496
+ - `AsyncDatabaseProvider` — Provides `AsyncSessionManager` and `async_sessionmaker`
497
+ - `AsyncUnitOfWorkProvider` — Provides `AsyncUnitOfWork`
498
+ - `PrometheusPostgresMetricsProvider` — Provides Prometheus metrics integration
499
+
500
+ **Example with Dishka:**
501
+ ```python
502
+ from dishka import make_async_container
503
+ from sqlalchemy_foundation_kit.contrib.di import (
504
+ AsyncDatabaseProvider,
505
+ AsyncUnitOfWorkProvider,
506
+ PrometheusPostgresMetricsProvider,
507
+ )
508
+
509
+ container = make_async_container(
510
+ AsyncDatabaseProvider(),
511
+ AsyncUnitOfWorkProvider(),
512
+ PrometheusPostgresMetricsProvider(),
513
+ # ... your providers
514
+ )
515
+ ```
516
+
517
+ #### `contrib.dependency_injector` (requires `[dependency-injector]`)
518
+ ```python
519
+ from sqlalchemy_foundation_kit.contrib.dependency_injector import (
520
+ DatabaseContainer,
521
+ AsyncDatabaseResourceProvider,
522
+ PrometheusMetricsContainer,
523
+ )
524
+ ```
525
+ - `DatabaseContainer` — Container providing `session_manager`, `session_maker`, and `uow`
526
+ - `AsyncDatabaseResourceProvider` — Manual lifecycle management helper
527
+ - `PrometheusMetricsContainer` — Container for Prometheus metrics integration
528
+
529
+ **Example with dependency-injector:**
530
+ ```python
531
+ from dependency_injector import containers, providers
532
+ from sqlalchemy_foundation_kit.contrib.dependency_injector import (
533
+ DatabaseContainer,
534
+ PrometheusMetricsContainer,
535
+ )
536
+
537
+ class AppContainer(containers.DeclarativeContainer):
538
+ config = providers.Singleton(Settings)
539
+
540
+ metrics = providers.Container(
541
+ PrometheusMetricsContainer,
542
+ metrics_settings=config.provided.metrics,
543
+ default_prefix=providers.Object("myapp"),
544
+ postgres_settings=config.provided.postgres,
545
+ )
546
+
547
+ database = providers.Container(
548
+ DatabaseContainer,
549
+ postgres_config=config.provided.postgres,
550
+ metrics=metrics.postgres_metrics,
551
+ )
552
+
553
+ container = AppContainer()
554
+ await container.init_resources()
555
+
556
+ # Use dependencies
557
+ uow = container.database.uow()
558
+ async with uow.transaction() as tx:
559
+ user = await tx.users.create(...)
560
+ ```
561
+
562
+ #### `contrib.telemetry` (requires `[telemetry]`)
563
+ ```python
564
+ from sqlalchemy_foundation_kit.contrib.telemetry import (
565
+ instrument_sqlalchemy,
566
+ instrument_asyncpg,
567
+ TracedAsyncUnitOfWork,
568
+ )
569
+ ```
570
+ - `instrument_sqlalchemy()` — OpenTelemetry instrumentation for SQLAlchemy
571
+ - `instrument_asyncpg()` — OpenTelemetry instrumentation for asyncpg
572
+ - `TracedAsyncUnitOfWork` — UoW with automatic span creation
573
+
574
+ **Example with OpenTelemetry:**
575
+ ```python
576
+ from opentelemetry import trace
577
+ from opentelemetry.sdk.trace import TracerProvider
578
+ from opentelemetry.sdk.trace.export import ConsoleSpanExporter, BatchSpanProcessor
579
+
580
+ # Setup tracer
581
+ provider = TracerProvider()
582
+ processor = BatchSpanProcessor(ConsoleSpanExporter())
583
+ provider.add_span_processor(processor)
584
+ trace.set_tracer_provider(provider)
585
+
586
+ # Instrument SQLAlchemy
587
+ from sqlalchemy_foundation_kit.contrib.telemetry import (
588
+ instrument_sqlalchemy,
589
+ TracedAsyncUnitOfWork,
590
+ )
591
+
592
+ instrument_sqlalchemy(engine=engine)
593
+
594
+ # Use traced UoW
595
+ uow = TracedAsyncUnitOfWork(
596
+ session_maker=session_maker,
597
+ transaction_factory=MyTransaction,
598
+ service_name="my-service",
599
+ )
600
+
601
+ async with uow.transaction() as tx:
602
+ # Automatically creates span "uow.transaction"
603
+ user = await tx.users.create(...)
604
+ ```
605
+
606
+ ## Architecture
607
+
608
+ ```mermaid
609
+ graph LR
610
+ A[Your Service] --> B[sqlalchemy-foundation-kit]
611
+ B --> C[SQLAlchemy asyncio]
612
+ B --> D[Pydantic]
613
+ B -.optional.-> E[Prometheus]
614
+ B -.optional.-> F[OpenTelemetry]
615
+ B -.optional.-> G[dishka / dependency-injector]
616
+ ```
617
+
618
+ ## Documentation
619
+
620
+ Full documentation is available at [https://bedrock-python.github.io/sqlalchemy-foundation-kit/](https://bedrock-python.github.io/sqlalchemy-foundation-kit/)
621
+
622
+ ## License
623
+
624
+ This project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details.
@@ -0,0 +1,49 @@
1
+ sqlalchemy_foundation_kit/__init__.py,sha256=xtcURKDp2xFv-I_5YuynsV5Gq2hvGgWxw6iPyaqbH5I,2914
2
+ sqlalchemy_foundation_kit/__version__.py,sha256=ShXQBVjyiSOHxoQJS2BvNG395W4KZfqMxZWBAR0MZrE,22
3
+ sqlalchemy_foundation_kit/_typing.py,sha256=YCdPX-UBlReYnRC1QHmyUsSnIiYURiYFjESkp6YyOJI,740
4
+ sqlalchemy_foundation_kit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ sqlalchemy_foundation_kit/base/__init__.py,sha256=nGXKR1miz-AonBihfAkIXWjBmykOQlbrPctdv3z5Td4,1257
6
+ sqlalchemy_foundation_kit/base/_optional.py,sha256=kjBfLP1KT416ldQMrfMCVS5o3b2wjOvdqWkBXTQ7vgg,1120
7
+ sqlalchemy_foundation_kit/base/engine.py,sha256=tFXDwIuD1JYVfy60_eUUCMC_OT1RgIiKRksYFlSasSU,8030
8
+ sqlalchemy_foundation_kit/base/metadata.py,sha256=VVHMGRBqhwP2gkcDNW_KhTkY5WDYmUl-b5LazevFp0Y,1949
9
+ sqlalchemy_foundation_kit/base/models.py,sha256=-U8awfKRVdm8_nZ7JLC-A5PSu5CZtqd0umzs0D1mETs,3071
10
+ sqlalchemy_foundation_kit/base/serialization.py,sha256=SFWQRJtfCiWfkcZMu8Ory77_vBRMGYnxwQ7ES_NGvCc,2640
11
+ sqlalchemy_foundation_kit/base/types.py,sha256=2DbcIskR2PQlek_oG3wJB24fY9ME0Vs2hJue5CMPkF8,2398
12
+ sqlalchemy_foundation_kit/config/__init__.py,sha256=fbdChslutQVSHHqA2D-7u6Hudse0zNXF00ue8LAb2yA,353
13
+ sqlalchemy_foundation_kit/config/postgres.py,sha256=rpxcOO8FBKxA1WghVfbgRWeOV-L5LWmgKEcHT5cYPGE,5741
14
+ sqlalchemy_foundation_kit/contrib/__init__.py,sha256=t4Ua_wMb9GlYGu3MtcNDRF-vIedweXsxEwjUrlLTpPU,124
15
+ sqlalchemy_foundation_kit/contrib/_metrics_utils.py,sha256=dXXUjaNPZ3Rdmf6Xi1-O75CLoTyFbXe1YvTtivyQTGo,657
16
+ sqlalchemy_foundation_kit/contrib/dependency_injector/__init__.py,sha256=Ctd0Oyo1LwKmltUDRZzrm1AiJ3AeGK8oBl1PbvSt4FM,635
17
+ sqlalchemy_foundation_kit/contrib/dependency_injector/_base.py,sha256=kDcu007F1OtCMHGtOLJnbdNZ-77_VcQbYyJwHgiTo-8,1047
18
+ sqlalchemy_foundation_kit/contrib/dependency_injector/_deps.py,sha256=lCzWEqGj5L6n6ZtKx51FWo4C2F3Mw5B6GZqgmXGrA4g,1011
19
+ sqlalchemy_foundation_kit/contrib/dependency_injector/database.py,sha256=io3iOIGF-vM-TwfEo3Qc3Vfvx_u8Yc6ZYarepoCBdTc,6796
20
+ sqlalchemy_foundation_kit/contrib/dependency_injector/metrics.py,sha256=vwA5bdYPiqFoZVVIaICLh6yPugNOwJtueSaY7t04mQk,2890
21
+ sqlalchemy_foundation_kit/contrib/di/__init__.py,sha256=SAIWxHDw2oS6-UxBhBCuqiSm3ElKlFcXvnAGVZn9meM,493
22
+ sqlalchemy_foundation_kit/contrib/di/_base.py,sha256=SezOBBH-5Br-MRxkqnIJod0NFGtvslAAcdUCnbzBum0,809
23
+ sqlalchemy_foundation_kit/contrib/di/_deps.py,sha256=K6Ln3gxaqEH24OpHZ-e3VMLcV6qT4nEkgiv-17SMKDQ,872
24
+ sqlalchemy_foundation_kit/contrib/di/database.py,sha256=_3-XZ2wWdWL3lk_VMakqYTN5frylfES8E9D1k73jZQ8,5936
25
+ sqlalchemy_foundation_kit/contrib/di/metrics.py,sha256=s8fbF1fgteJOj0e-New-5PM1OoYrhUYFska7FemNCoA,2029
26
+ sqlalchemy_foundation_kit/contrib/metrics/__init__.py,sha256=Vt_Rf1JTwQOqxeer5UsKJmAiJzkGgC2kI2G6u_FVvlo,144
27
+ sqlalchemy_foundation_kit/contrib/metrics/postgres.py,sha256=9ahHRqxN3DKOejxPGTWUFxommTZ_AHimZEX1LWYgJMs,4636
28
+ sqlalchemy_foundation_kit/contrib/settings/__init__.py,sha256=oqycBh88yICRu4Qmis0o48_mpYlulnXpVTQpZFQb2og,363
29
+ sqlalchemy_foundation_kit/contrib/settings/postgres.py,sha256=JgRuiKAdKCR3Uwqovxbl612ak4gWcHlbv0QNRGrR420,7225
30
+ sqlalchemy_foundation_kit/contrib/telemetry/__init__.py,sha256=-DZqccnNgJDx_8yr-4J0x4JV2_wCIwjvB9kGFjet6ks,349
31
+ sqlalchemy_foundation_kit/contrib/telemetry/instrumentations.py,sha256=s7-J3iozoYLkz32Vq_LaAkaNKUvjcZa9aQEgoVLINBY,3483
32
+ sqlalchemy_foundation_kit/contrib/telemetry/uow.py,sha256=L45693SRt1tfl3JVcDoc3pKLSSm2Etbze4D-ClpekcE,7532
33
+ sqlalchemy_foundation_kit/protocols/__init__.py,sha256=tzPF_J0-sE1_xDbypoH3fUbsUlr2gD0N79hHCAlBTBM,475
34
+ sqlalchemy_foundation_kit/protocols/metrics.py,sha256=VuyvHdvgk4gDqCEpqWHN9jsNuv-LPygZ5eBaXu7zkuI,2505
35
+ sqlalchemy_foundation_kit/session/__init__.py,sha256=3UYIjcNLk0yYqaoOzcATPueb8Oxw9W4O0vGjaHusT74,701
36
+ sqlalchemy_foundation_kit/session/builder.py,sha256=-furDMJZMizNREhM9I80nD-rT0DXys0XEarwGVDIQgA,9402
37
+ sqlalchemy_foundation_kit/session/connection.py,sha256=y1nx7MOG8DeWW1s37cFWvs39Tm1lyAgjt6MN0JBpZzQ,913
38
+ sqlalchemy_foundation_kit/session/factories.py,sha256=h-yKru8N2HJLjPEdj4gRzPWc9ID6qwC3SPBMYHBddnM,4487
39
+ sqlalchemy_foundation_kit/session/locks.py,sha256=8ciOLHWnjlaCiG_KAIAtlvzKl3w0zn3hbCgmmuQ7RXI,2178
40
+ sqlalchemy_foundation_kit/session/manager.py,sha256=3wx9AByzFo1zs2lwC0AtFMD3BH5WD3EwvH5i-bfZzVI,9576
41
+ sqlalchemy_foundation_kit/session/retry.py,sha256=d_JJNt-2xWzpkBZhfIiya18j6ZJCb_rMXOFcIsVXFy0,2504
42
+ sqlalchemy_foundation_kit/uow/__init__.py,sha256=TZuySWNtPcQIBFWxp3GCgAAQ7nE38IxF6dECzCcoj2o,539
43
+ sqlalchemy_foundation_kit/uow/enums.py,sha256=zqjo_lDK-qORptX6baigCIyj8RdW74NrVT8Uqv0CjIg,463
44
+ sqlalchemy_foundation_kit/uow/protocols.py,sha256=eO3Cb7LCkcFP4-6sq8PDyeY6R5Pz0rnrJSPwFG1CosE,3138
45
+ sqlalchemy_foundation_kit/uow/sqlalchemy.py,sha256=fqu80OzJVVhrguNHDq1LOo2icSe-lN4o0HyxotHvG94,16068
46
+ sqlalchemy_foundation_kit-0.0.0.dist-info/METADATA,sha256=lPSIBB4vamJId63Lim6xBHyMPsi9rk2SDl6D8LzHbOg,27598
47
+ sqlalchemy_foundation_kit-0.0.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
48
+ sqlalchemy_foundation_kit-0.0.0.dist-info/licenses/LICENSE,sha256=HqasrACfRh7mgdbiXMVrs_X8dOCZed1b8KXY7i6Ch14,10239
49
+ sqlalchemy_foundation_kit-0.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any