codecraftai-storage-database 1.2.0__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.
@@ -0,0 +1,204 @@
1
+ # Code Craft AI - Source Available License
2
+ Version 1.0, October 2026
3
+
4
+ Copyright (C) 2026, Code Craft AI LLC
5
+
6
+ Everyone is permitted to copy and distribute verbatim copies of *This License* document, but changing it is not allowed.
7
+
8
+ *This License* covers the Python Automation Kit, the full suite of software published by *Licensor* that consists of every `codecraftai-*` package, every `pychestrate` package, and the `pychestrate` server.
9
+
10
+ *The Software* is source available. Its source code is published so that anyone can read it, learn from it, and use it, but *This License* is not an open source license. *The Software* is free to use for *Non-Commercial Use*. *Commercial Use* is permitted in exchange for a *Usage Fee* that is based on a reasonable estimation of the income derived from *The Software*, as described in section 5. When a company migrates a product or service to *The Software* from another code base, the *Profit* from that product or service is not counted toward the *Usage Fee* for two years, as described in section 5.4. For assurance of costs, a company can disclose its usage and estimated returns to *Licensor* and negotiate a fixed license cost, as described in section 5.10.
11
+
12
+ ## 1. Definitions
13
+
14
+ ### 1.1 *This License* or *The License*
15
+ **This License** or **The License** refers to version 1.0 of the Code Craft AI - Source Available License.
16
+
17
+ ### 1.2 Licensor
18
+ **Licensor** refers to Code Craft AI LLC.
19
+
20
+ ### 1.3 The Software
21
+ **The Software** refers to the Python Automation Kit, the full suite of software that *Licensor* publishes under *This License*. The Python Automation Kit consists of the following components (each, a **Component**), together with their source code, documentation, and other materials:
22
+
23
+ 1. Every Python package published by *Licensor* whose name begins with `codecraftai-`
24
+ 2. Every Python package published by *Licensor* whose name begins with `pychestrate`
25
+ 3. The `pychestrate` server
26
+
27
+ ### 1.4 You
28
+ **You** refers to the individual or legal entity that exercises rights under *This License*. When an individual exercises rights under *This License* on behalf of a company, organization, or other legal entity, **You** refers to that entity.
29
+
30
+ ### 1.5 Use
31
+ **Use** means to install, execute, load, access, operate, display, copy, modify, configure, customize, and otherwise use.
32
+
33
+ ### 1.6 Non-Commercial Use
34
+ **Non-Commercial Use** means any *Use* of *The Software* that is not *Commercial Use*. Examples of *Non-Commercial Use* include personal use, hobby projects, study, teaching, academic research, evaluation, and use by a non-profit organization for its non-profit purposes.
35
+
36
+ ### 1.7 Commercial Use
37
+ **Commercial Use** means any *Use* of *The Software* by or on behalf of a for-profit entity, and any *Use* of *The Software* in connection with a product, service, or activity that generates revenue. *Commercial Use* includes, without limitation, *Use* of *The Software* to develop, build, test, validate, deploy, operate, or support commercial products and services, and *Use* of *The Software* to provide services to others.
38
+
39
+ ### 1.8 Commercial Activity
40
+ **Commercial Activity** means the products, services, and business operations in connection with which *You* make *Commercial Use* of *The Software*.
41
+
42
+ ### 1.9 Fiscal Year
43
+ **Fiscal Year** means the annual accounting period that *You* use for financial reporting.
44
+
45
+ ### 1.10 Profit
46
+ **Profit** means the net profit that *You* earn from the *Commercial Activity* during a *Fiscal Year*, determined under the accounting principles that *You* regularly use for financial reporting.
47
+
48
+ ### 1.11 Contribution Estimate
49
+ **Contribution Estimate** means *Your* reasonable, good faith estimate of the portion of the *Profit* that *The Software* contributed to, expressed as a number from 0 to 1.
50
+
51
+ ### 1.12 Derived Income
52
+ **Derived Income** means the portion of the *Profit* for a *Fiscal Year* that is derived from *The Software*, calculated as described in section 5.2.
53
+
54
+ ### 1.13 Usage Fee
55
+ **Usage Fee** means the yearly fee for *Commercial Use* that is set by the table in section 5.3.
56
+
57
+ ### 1.14 Migration
58
+ **Migration** means moving the work for one of *Your* products or services from a code base other than *The Software*, such as another framework, another library, or *Your* own code, to *The Software*.
59
+
60
+ ### 1.15 Migration Period
61
+ **Migration Period** means the two (2) year period, described in section 5.4, during which the *Profit* from a product or service that *You* are migrating to *The Software* is not counted.
62
+
63
+ ## 2. License Grant
64
+
65
+ Subject to the terms and conditions of *This License*, *Licensor* hereby grants to *You* a non-exclusive, worldwide, non-transferable license to *Use*, copy, modify, create derivative works of, and distribute *The Software*.
66
+
67
+ *Licensor* also grants to *You* a license under any patents that *Licensor* can license, and that are necessarily infringed by *The Software*, for the same purposes and subject to the same conditions as the license granted above.
68
+
69
+ *This License* covers the Python Automation Kit as a whole. *Use* of one, some, or all of the *Components* is *Use* of *The Software*.
70
+
71
+ The licenses granted by *This License* are free of charge for *Non-Commercial Use*. The licenses granted by *This License* for *Commercial Use* are conditioned on the payment of the *Usage Fee* described in section 5.
72
+
73
+ ## 3. Conditions
74
+
75
+ ### 3.1 License Notice
76
+ Every copy of *The Software* that *You* distribute, in original or modified form, must include a complete copy of *This License* and must keep all copyright, patent, trademark, and attribution notices that appear in *The Software*.
77
+
78
+ ### 3.2 Recipients
79
+ Anyone who receives *The Software* from *You* receives it under the terms of *This License*. *You* may not impose terms on a recipient that conflict with *This License*, and *You* may not grant a recipient rights that *This License* does not grant to *You*.
80
+
81
+ ### 3.3 Modified Versions
82
+ *You* must clearly mark any modified version of *The Software* as modified. *The Software* is published by *Licensor* under a specific identity, such as a package name. *You* may not publish a modified version of *The Software* under the identity that *Licensor* originally published it under. Every copy of *The Software* that *You* redistribute under its original identity must be an exact copy of *The Software* as *Licensor* published it.
83
+
84
+ ### 3.4 Trademarks
85
+ *This License* does not grant any rights to use the names, logos, or trademarks of *Licensor*, except as required to comply with section 3.1 and to describe the origin of *The Software*.
86
+
87
+ ## 4. Non-Commercial Use
88
+
89
+ *Non-Commercial Use* of *The Software* is free. No *Usage Fee*, registration, or report is required for *Non-Commercial Use*.
90
+
91
+ ## 5. Commercial Use
92
+
93
+ ### 5.1 Usage Fee Obligation
94
+ For each *Fiscal Year* in which *You* make *Commercial Use* of *The Software*, *You* must pay *Licensor* a *Usage Fee*. A single *Usage Fee* covers all of *Your* *Commercial Use* of the *Components*. *Usage Fees* are not owed separately for each *Component*.
95
+
96
+ ### 5.2 Derived Income
97
+ The *Derived Income* for a *Fiscal Year* is calculated as follows:
98
+
99
+ (Contribution Estimate) * (Profit) = (Derived Income)
100
+
101
+ If *You* make *Commercial Use* of *The Software* for more than one product or service, calculate the *Derived Income* for each product or service using its own *Contribution Estimate* and *Profit*, and add the results together. The *Profit* from a product or service that is in its *Migration Period* is not counted, as described in section 5.4.
102
+
103
+ If the *Profit* from a product or service for a *Fiscal Year* is zero or less, then the *Derived Income* from that product or service for that *Fiscal Year* is zero.
104
+
105
+ ### 5.3 Usage Fee
106
+ The *Usage Fee* for a *Fiscal Year* is set by the *Derived Income* for that *Fiscal Year*, as shown in the following table.
107
+
108
+ | Derived Income for the Fiscal Year | Usage Fee per Fiscal Year |
109
+ |------------------------------------|---------------------------|
110
+ | 1,000,000 or less | Free |
111
+ | More than 1,000,000, up to and including 10,000,000 | 50,000 |
112
+ | More than 10,000,000, up to and including 100,000,000 | 100,000 |
113
+ | More than 100,000,000, up to and including 1,000,000,000 | 250,000 |
114
+ | More than 1,000,000,000 | 500,000 |
115
+
116
+ All amounts in this section 5 are in United States dollars. If *You* report *Profit* in a different currency, convert the *Derived Income* to United States dollars using the average exchange rate for the *Fiscal Year*.
117
+
118
+ ### 5.4 Migration Allowance
119
+ When *You* migrate a product or service to *The Software*, the *Profit* from that product or service is not counted when calculating the *Derived Income* during its *Migration Period* (the **Migration Allowance**).
120
+
121
+ The *Migration Period* for a product or service begins on the date that *You* first make *Commercial Use* of *The Software* for that product or service as part of its *Migration*, and ends two (2) years after that date.
122
+
123
+ The *Migration Allowance* applies to each product or service separately, and *You* may use it for every product or service that *You* migrate. Each product or service has only one *Migration Period*.
124
+
125
+ If a *Fiscal Year* is only partly within the *Migration Period* of a product or service, the *Profit* from that product or service for that *Fiscal Year* is reduced in proportion to the number of days of that *Fiscal Year* that fall within its *Migration Period*.
126
+
127
+ For example, a company tests product A with *The Software* and pays a *Usage Fee* based on the *Profit* from product A. On March 1, 2027, the company begins moving the testing of product B from a different test framework to *The Software*. The company does not count the *Profit* from product B in its *Derived Income* from March 1, 2027 until March 1, 2029. Starting March 1, 2029, the *Profit* from product B is counted. If the company later migrates product C, the *Profit* from product C is not counted for two years from the start of its own *Migration*.
128
+
129
+ ### 5.5 Contribution Estimate
130
+ *You* are responsible for making the *Contribution Estimate*. A *Contribution Estimate* must be reasonable and made in good faith. The *Contribution Estimate* for a product or service covers all of the *Components* that *You* *Use* for that product or service. When making the *Contribution Estimate*, *You* should consider how important *The Software* is to the *Commercial Activity*, how much of the *Commercial Activity* depends on *The Software*, and the effort and cost that *You* would otherwise need to spend to accomplish what *The Software* accomplishes for *You*.
131
+
132
+ The following table is a guide for making the *Contribution Estimate*. When *Your* *Commercial Use* of *The Software* matches an entry in the table, the *Contribution Estimate* in that entry is a reasonable *Contribution Estimate*. When *Your* *Commercial Use* does not match an entry in the table, make the *Contribution Estimate* by comparing *Your* *Commercial Use* with the entries in the table. When more than one entry matches the same *Commercial Activity*, use the entry with the highest *Contribution Estimate*.
133
+
134
+ | Commercial Use of *The Software* | Contribution Estimate |
135
+ |----------------------------------|-----------------------|
136
+ | Quality Assurance (QA) and Continuous Integration (CI): *The Software* is used to test or validate the products or services of the *Commercial Activity*, or to run their build and test pipelines | 0.3 |
137
+ | Products Completely Based on *The Software*: the products or services of the *Commercial Activity* are built completely on *The Software* | 0.5 |
138
+
139
+ ### 5.6 Examples
140
+ A company earns 1,000,000,000 in *Profit* from a product line during a *Fiscal Year*. The company uses *The Software* for the QA and CI of that product line, so the *Contribution Estimate* is 0.3.
141
+
142
+ 0.3 * 1,000,000,000 = 300,000,000
143
+
144
+ The *Derived Income* of 300,000,000 is more than 100,000,000 and not more than 1,000,000,000, so the *Usage Fee* for that *Fiscal Year* is 250,000.
145
+
146
+ A company earns 4,000,000 in *Profit* from a product during a *Fiscal Year*. The product is built completely on *The Software*, so the *Contribution Estimate* is 0.5.
147
+
148
+ 0.5 * 4,000,000 = 2,000,000
149
+
150
+ The *Derived Income* of 2,000,000 is more than 1,000,000 and not more than 10,000,000, so the *Usage Fee* for that *Fiscal Year* is 50,000.
151
+
152
+ A company earns 3,000,000 in *Profit* from a product line during a *Fiscal Year*. The company uses *The Software* for the QA and CI of that product line, so the *Contribution Estimate* is 0.3.
153
+
154
+ 0.3 * 3,000,000 = 900,000
155
+
156
+ The *Derived Income* of 900,000 is 1,000,000 or less, so there is no *Usage Fee* for that *Fiscal Year*.
157
+
158
+ ### 5.7 Reporting and Payment
159
+ Within one hundred twenty (120) days after the end of each *Fiscal Year* for which a *Usage Fee* is owed, *You* must pay the *Usage Fee* to *Licensor* and provide *Licensor* with a written statement that shows the *Profit*, the *Contribution Estimate*, the reasoning used to make the *Contribution Estimate*, the *Derived Income*, and the *Usage Fee*. *Usage Fees* are payable in United States dollars. If any *Profit* is not counted under section 5.4, the statement must also identify each product or service that is in a *Migration Period* and show the dates of its *Migration Period*. No statement is required for a *Fiscal Year* in which no *Usage Fee* is owed.
160
+
161
+ ### 5.8 Records and Review
162
+ *You* must keep records that reasonably support each *Contribution Estimate*, each *Profit* figure, and the dates of any *Migration Period* for at least three (3) years after the end of the *Fiscal Year* that they apply to. No more than once in any twelve (12) month period, *Licensor* may ask in writing for the records that support a statement, and *You* must provide them within sixty (60) days of the request. *Licensor* will treat those records as confidential.
163
+
164
+ ### 5.9 Disputes About the Usage Fee
165
+ If *Licensor* believes that a *Contribution Estimate*, a *Profit* figure, or the dates of a *Migration Period* are not reasonable, *Licensor* will notify *You* in writing and explain why. *You* and *Licensor* will then negotiate in good faith for at least sixty (60) days to agree on a reasonable *Usage Fee*. If *You* and *Licensor* cannot agree, either party may resolve the dispute as described in section 8.
166
+
167
+ ### 5.10 Fixed License Cost
168
+ For assurance of costs, *You* may disclose to *Licensor* how *You* *Use* *The Software* and the returns that *You* estimate *You* will derive from it, and negotiate a fixed license cost with *Licensor*. A fixed license cost, and any other terms that *You* and *Licensor* agree to, must be set out in a writing signed by both *You* and *Licensor* (a **Fixed License Agreement**).
169
+
170
+ While a *Fixed License Agreement* is in effect, the fixed license cost replaces the *Usage Fee* for the *Commercial Use* that the *Fixed License Agreement* covers, and sections 5.7 through 5.9 apply to that *Commercial Use* only as the *Fixed License Agreement* provides. To the extent that a *Fixed License Agreement* conflicts with this section 5, the *Fixed License Agreement* controls.
171
+
172
+ *Licensor* will treat the information that *You* disclose under this section 5.10 as confidential.
173
+
174
+ ## 6. Termination
175
+
176
+ If *You* violate *This License*, the licenses granted to *You* by *This License* end. If *Licensor* notifies *You* in writing of the violation and *You* correct the violation within thirty (30) days of receiving the notice, including by paying any *Usage Fee* that is owed, then the licenses granted to *You* are reinstated. This reinstatement is available to *You* only once. Termination does not release *You* from any *Usage Fee* that is owed for *Commercial Use* that took place before the termination.
177
+
178
+ ## 7. No Warranty and Limitation of Liability
179
+
180
+ ### 7.1 No Warranty
181
+ *THE SOFTWARE* IS PROVIDED "AS IS", WITHOUT ANY WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING THE IMPLIED WARRANTIES OF MERCHANTABILITY, TITLE, NON-INFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
182
+
183
+ ### 7.2 Limitation of Liability
184
+ TO THE EXTENT PERMITTED BY LAW, IN NO EVENT WILL *LICENSOR* BE LIABLE TO *YOU* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR EXEMPLARY DAMAGES OF ANY KIND ARISING OUT OF OR RELATED TO *THIS LICENSE* OR THE *USE* OF *THE SOFTWARE*, EVEN IF *LICENSOR* HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
185
+
186
+ ### 7.3 Support
187
+ *This License* does not entitle *You* to support, maintenance, or other services. Support and services are available only under a separate written agreement with *Licensor*.
188
+
189
+ ## 8. Governing Law and Jurisdiction
190
+
191
+ *This License* is governed by the laws of the State of Washington and the United States as though fully performed in Washington, without regard to provisions relating to conflicts of laws. The UN Convention for the International Sale of Goods and the Uniform Computer Information Transactions Act (UCITA) will not apply. The state and federal courts located in King County, Washington will have exclusive jurisdiction to adjudicate any disputes arising under *This License*, and *You* and *Licensor* agree to submit to the jurisdiction of those courts.
192
+
193
+ ## 9. General
194
+
195
+ ### 9.1 Severability
196
+ If any provision of *This License* is held to be unenforceable, that provision will be enforced to the maximum extent permitted, and the remaining provisions of *This License* will remain in effect.
197
+
198
+ ### 9.2 Interpretation
199
+ The section headings in *This License* are for reference purposes only and do not modify or restrict any term of *This License*. *This License* is written in the English language, and the English text prevails over any translation.
200
+
201
+ ### 9.3 Contact
202
+ Questions about *This License*, *Usage Fee* statements, payments, and requests to negotiate a *Fixed License Agreement* may be sent to *Licensor* using the contact information published at:
203
+
204
+ https://code-craft.ai
@@ -0,0 +1,89 @@
1
+ Metadata-Version: 2.4
2
+ Name: codecraftai-storage-database
3
+ Version: 1.2.0
4
+ Summary: Code Craft AI - Storage Database
5
+ License-Expression: LicenseRef-CodeCraftAI-Source-Available
6
+ License-File: LICENSE.md
7
+ Keywords: python
8
+ Author: Myron Walker
9
+ Author-email: myron.walker@gmail.com
10
+ Requires-Python: >=3.10,<4.0
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Operating System :: POSIX
13
+ Requires-Dist: codecraftai-credentials (<2.0.0)
14
+ Requires-Dist: codecraftai-dataprofiles (<2.0.0)
15
+ Requires-Dist: codecraftai-foundations (<2.0.0)
16
+ Requires-Dist: codecraftai-runtime (<2.0.0)
17
+ Requires-Dist: psycopg2-binary (>=2.0.10,<3.0.0)
18
+ Requires-Dist: sqlalchemy (>=2.0.43,<3.0.0)
19
+ Requires-Dist: sqlalchemy-utils (>=0.42.0,<0.43.0)
20
+ Project-URL: Issues, https://github.com/code-craft-ai-company/codecraftai-storage-database/issues
21
+ Project-URL: Repository, https://github.com/code-craft-ai-company/codecraftai-storage-database
22
+ Description-Content-Type: text/x-rst
23
+
24
+ ==================================
25
+ Code Craft AI Storage Database
26
+ ==================================
27
+
28
+ The ``codecraftai-storage-database`` package contains the common and shared types and code that provide a standardized way for an application or service to initialize connections, sessions, and to work with databases across the ccai suite.
29
+
30
+ Highlights
31
+ ==========
32
+
33
+ - Shared database-connection initialization primitives.
34
+ - Session management and lifecycle helpers.
35
+ - Base types that downstream packages reuse when exposing persistence.
36
+ - Factors out common patterns so individual applications do not reinvent connection plumbing.
37
+
38
+ Repository Structure
39
+ ====================
40
+
41
+ - ``development/`` - Runtime environment scripts.
42
+ - ``repository-setup/`` - Repository homing and setup scripts.
43
+ - ``source/packages/`` - Package source code.
44
+ - ``source/testroots/ccai/`` - TestBase test roots.
45
+ - ``userguide/`` - Standards, conventions, and documentation.
46
+
47
+ Environment Setup
48
+ =================
49
+
50
+ When working in a Codex container:
51
+
52
+ .. code-block:: bash
53
+
54
+ ./development/setup-agent-container
55
+
56
+ For local development:
57
+
58
+ .. code-block:: bash
59
+
60
+ ./repository-setup/rehome-repository
61
+ ./development/setup-envrionment
62
+
63
+ Running Tests
64
+ =============
65
+
66
+ Activate the virtual environment:
67
+
68
+ .. code-block:: bash
69
+
70
+ source .venv/bin/activate
71
+
72
+ Run the single-host test suite:
73
+
74
+ .. code-block:: bash
75
+
76
+ testbase testing run --root source/testroots/ccai --includes=ccai.tests.singlehost.storage --output=./.output
77
+
78
+ Standards and Conventions
79
+ =========================
80
+
81
+ - Naming conventions: ``userguide/10-02-naming-conventions.rst``
82
+ - Code organization: ``userguide/10-01-code-organization.rst``
83
+ - Coding standards: ``userguide/10-00-coding-standards.rst``
84
+
85
+ Additional Resources
86
+ ====================
87
+
88
+ - User guide entry point: ``userguide/userguide.rst``
89
+
@@ -0,0 +1,65 @@
1
+ ==================================
2
+ Code Craft AI Storage Database
3
+ ==================================
4
+
5
+ The ``codecraftai-storage-database`` package contains the common and shared types and code that provide a standardized way for an application or service to initialize connections, sessions, and to work with databases across the ccai suite.
6
+
7
+ Highlights
8
+ ==========
9
+
10
+ - Shared database-connection initialization primitives.
11
+ - Session management and lifecycle helpers.
12
+ - Base types that downstream packages reuse when exposing persistence.
13
+ - Factors out common patterns so individual applications do not reinvent connection plumbing.
14
+
15
+ Repository Structure
16
+ ====================
17
+
18
+ - ``development/`` - Runtime environment scripts.
19
+ - ``repository-setup/`` - Repository homing and setup scripts.
20
+ - ``source/packages/`` - Package source code.
21
+ - ``source/testroots/ccai/`` - TestBase test roots.
22
+ - ``userguide/`` - Standards, conventions, and documentation.
23
+
24
+ Environment Setup
25
+ =================
26
+
27
+ When working in a Codex container:
28
+
29
+ .. code-block:: bash
30
+
31
+ ./development/setup-agent-container
32
+
33
+ For local development:
34
+
35
+ .. code-block:: bash
36
+
37
+ ./repository-setup/rehome-repository
38
+ ./development/setup-envrionment
39
+
40
+ Running Tests
41
+ =============
42
+
43
+ Activate the virtual environment:
44
+
45
+ .. code-block:: bash
46
+
47
+ source .venv/bin/activate
48
+
49
+ Run the single-host test suite:
50
+
51
+ .. code-block:: bash
52
+
53
+ testbase testing run --root source/testroots/ccai --includes=ccai.tests.singlehost.storage --output=./.output
54
+
55
+ Standards and Conventions
56
+ =========================
57
+
58
+ - Naming conventions: ``userguide/10-02-naming-conventions.rst``
59
+ - Code organization: ``userguide/10-01-code-organization.rst``
60
+ - Coding standards: ``userguide/10-00-coding-standards.rst``
61
+
62
+ Additional Resources
63
+ ====================
64
+
65
+ - User guide entry point: ``userguide/userguide.rst``
@@ -0,0 +1,71 @@
1
+ [project]
2
+ name = "codecraftai-storage-database"
3
+ version = "1.2.0"
4
+ description = "Code Craft AI - Storage Database"
5
+ readme = "README.rst"
6
+ license = "LicenseRef-CodeCraftAI-Source-Available"
7
+ authors = [{name = "Myron Walker", email = "myron.walker@gmail.com"}]
8
+ keywords = [
9
+ "python"
10
+ ]
11
+ classifiers = [
12
+ "Programming Language :: Python :: 3",
13
+ "Operating System :: POSIX",
14
+ ]
15
+ requires-python = ">=3.10,<4.0"
16
+ dependencies = [
17
+ "codecraftai-foundations<2.0.0",
18
+ "codecraftai-runtime<2.0.0",
19
+ "codecraftai-credentials<2.0.0",
20
+ "codecraftai-dataprofiles<2.0.0",
21
+ "sqlalchemy>=2.0.43,<3.0.0",
22
+ "sqlalchemy-utils>=0.42.0,<0.43.0",
23
+ "psycopg2-binary>=2.0.10,<3.0.0",
24
+ ]
25
+
26
+ [project.urls]
27
+ Repository = "https://github.com/code-craft-ai-company/codecraftai-storage-database"
28
+ Issues = "https://github.com/code-craft-ai-company/codecraftai-storage-database/issues"
29
+
30
+ [dependency-groups]
31
+ dev = [
32
+ "codecraftai-testbase<2.0.0",
33
+ ]
34
+
35
+ [tool.poetry]
36
+ packages = [{include="ccai", from="source/packages"}]
37
+
38
+ [tool.poetry.dependencies]
39
+ codecraftai-foundations = {source = "codecraftai"}
40
+ codecraftai-runtime = {source = "codecraftai"}
41
+ codecraftai-credentials = {source = "codecraftai"}
42
+ codecraftai-dataprofiles = {source = "codecraftai"}
43
+
44
+ [tool.poetry.group.dev.dependencies]
45
+ codecraftai-testbase = {source = "codecraftai"}
46
+
47
+ [[tool.poetry.source]]
48
+ name = "codecraftai"
49
+ url = "https://code-craft.ai/licensed-repository/simple/"
50
+ priority = "supplemental"
51
+
52
+ [[tool.uv.index]]
53
+ # Same licensed index as [[tool.poetry.source]]. Listed before PyPI so that
54
+ # codecraftai-* packages (direct and transitive) resolve from it; everything
55
+ # else falls through to PyPI. Credentials: UV_INDEX_CODECRAFTAI_USERNAME /
56
+ # UV_INDEX_CODECRAFTAI_PASSWORD, or `uv auth login`.
57
+ name = "codecraftai"
58
+ url = "https://code-craft.ai/licensed-repository/simple/"
59
+
60
+ [tool.ruff.lint]
61
+ # Deliberately narrow. This gate exists for one reason: a bare `except:`
62
+ # swallows ConfigurationError and SemanticError, which derive from
63
+ # BaseException precisely so that they pass through ordinary handlers and end
64
+ # the run. Catching them hides the original cause behind whatever error
65
+ # happens next. See userguide/10-00-coding-standards.rst, exception-handling
66
+ # rules 5-7. Use `except Exception:` when you mean "any ordinary failure".
67
+ select = ["E722"]
68
+
69
+ [build-system]
70
+ requires = ["poetry-core"]
71
+ build-backend = "poetry.core.masonry.api"
@@ -0,0 +1,382 @@
1
+ """
2
+ .. module:: dbconnection
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: Contains helper functions for working with specific databases
5
+
6
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
7
+ """
8
+
9
+ __author__ = "Myron Walker"
10
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
11
+ __credits__ = []
12
+ __version__ = "1.0.0"
13
+
14
+ from typing import Optional
15
+
16
+ import logging
17
+ import os
18
+
19
+ from sqlalchemy import create_engine
20
+ from sqlalchemy.engine.base import Engine as SqlEngine
21
+
22
+ from ccai.errors.exceptions import ConfigurationError
23
+
24
+ from ccai.credentials.basecredential import BaseCredential
25
+ from ccai.credentials.basiccredential import BasicCredential
26
+ from ccai.credentials.credentialmanager import CredentialManager
27
+
28
+ from ccai.dataprofiles.databasebasicsocketprofile import DatabaseBasicSocketProfile
29
+ from ccai.dataprofiles.databasebasictcpprofile import DatabaseBasicTcpProfile
30
+
31
+
32
+ logger = logging.getLogger()
33
+
34
+
35
+ class DatabaseConnectionFactory:
36
+ """
37
+ Base factory that provides a consistent interface for database engines.
38
+ """
39
+
40
+ def __init__(self, profile_name: str, *, dbprofile: DatabaseBasicSocketProfile, credential: BaseCredential):
41
+ """
42
+ Store the identifying profile information and credential for the factory.
43
+
44
+ :param profile_name: Name of the profile that created the factory.
45
+ :param dbprofile: Database profile that contains the connection parameters.
46
+ :param credential: Credential object used when creating connections.
47
+ """
48
+ self._profile_name = profile_name
49
+ self._dbprofile = dbprofile
50
+ self._credential = credential
51
+ return
52
+
53
+ @property
54
+ def credential(self) -> BaseCredential:
55
+ """
56
+ Return the credential object backing this factory.
57
+ """
58
+ return self._credential
59
+
60
+ @property
61
+ def dbprofile(self) -> DatabaseBasicSocketProfile:
62
+ """
63
+ Return the database profile associated with this factory.
64
+ """
65
+ return self._dbprofile
66
+
67
+ @property
68
+ def profile_name(self) -> str:
69
+ """
70
+ Return the identifier for the originating database profile.
71
+ """
72
+ return self._profile_name
73
+
74
+ def create_engine(self, *, dbname=None, echo=True) -> SqlEngine:
75
+ """
76
+ Placeholder that derived types must implement in order to create engines.
77
+
78
+ :param dbname: Optional name of the database to connect to.
79
+ :param echo: Flag forwarded to SQLAlchemy for logging emitted SQL.
80
+
81
+ :raises: NotImplementedError
82
+ """
83
+ errmsg = "The 'create_engine' method must be overloaded by 'DatabaseConnectionFactory' derived types."
84
+ raise NotImplementedError(errmsg)
85
+
86
+
87
+ def format_connection_string(self, dbname: Optional[str] = None) -> str:
88
+ """
89
+ Placeholder that derived types must implement to format a connection string.
90
+
91
+ :param dbname: Optional database name override for the profile default.
92
+
93
+ :raises: NotImplementedError
94
+ """
95
+ errmsg = "The 'format_connection_string' method must be overloaded by 'DatabaseConnectionFactory' derived types."
96
+ raise NotImplementedError(errmsg)
97
+
98
+
99
+ class BasicSocketDatabaseConnectionFactory(DatabaseConnectionFactory):
100
+ """
101
+ Create SQLAlchemy engines against socket-based database endpoints.
102
+ """
103
+
104
+ def __init__(self, profile_name: str, *, dbprofile: DatabaseBasicSocketProfile, credential: BaseCredential):
105
+ """
106
+ Initialize the factory with the socket profile and credential details.
107
+
108
+ :param profile_name: Name of the profile that created the factory.
109
+ :param dbprofile: Socket based database profile backing the factory.
110
+ :param credential: Credential containing the user information required for login.
111
+ """
112
+ super().__init__(profile_name, dbprofile=dbprofile, credential=credential)
113
+ return
114
+
115
+ def create_engine(self, *, dbname=None, echo=True) -> SqlEngine:
116
+ """
117
+ Create a SQLAlchemy engine using pipe based connectivity.
118
+
119
+ :param dbname: Optional database name override for the profile default.
120
+ :param echo: Flag forwarded to SQLAlchemy for logging emitted SQL.
121
+
122
+ :returns: SQLAlchemy engine instance for the configured socket profile.
123
+ :raises: ConfigurationError
124
+ """
125
+
126
+ socket_path: str = self.dbprofile.socket
127
+
128
+ if dbname is None and self.dbprofile.dbname is not None:
129
+ dbname = self.dbprofile.dbname
130
+
131
+ if dbname is None:
132
+ warnmsg = "BasicSocketDatabaseConnectionFactory.create_engine: dbname was None."
133
+ logger.warn(warnmsg)
134
+
135
+ if isinstance(self.credential, BasicCredential):
136
+ connstr = self.format_connection_string(dbname=dbname)
137
+ dbengine = create_engine(connstr, echo=echo)
138
+ else:
139
+ errmsg = (
140
+ "BasicSocketDatabaseConnectionFactory requires a BasicCredential to "
141
+ "create an engine."
142
+ )
143
+ raise ConfigurationError(errmsg)
144
+
145
+ return dbengine
146
+
147
+ def get_connection_scheme(self):
148
+ """
149
+ Return the SQLAlchemy connection scheme for the configured database profile.
150
+
151
+ :returns: SQLAlchemy connection scheme string.
152
+ :raises: ConfigurationError
153
+ """
154
+
155
+ conn_scheme = None
156
+
157
+ if self.dbprofile.dbtype == "postgresql":
158
+ try:
159
+ import psycopg2 # noqa: F401
160
+ except ImportError:
161
+ errmsg_lines = [
162
+ "In order to create a postgresql database engine, you must install the following dependencies.",
163
+ "DEPENDENCIES",
164
+ " psycopg2",
165
+ ]
166
+ errmsg = os.linesep.join(errmsg_lines)
167
+ raise ConfigurationError(errmsg)
168
+
169
+ conn_scheme = "postgresql+psycopg2"
170
+ else:
171
+ errmsg = "Unsupported database type '{}' for database profile '{}'. Only 'postgresql' is currently supported.".format(
172
+ self.dbprofile.dbtype, self.profile_name)
173
+ raise ConfigurationError(errmsg)
174
+
175
+ return conn_scheme
176
+
177
+ def format_connection_string(self, dbname: Optional[str] = None) -> str:
178
+ """
179
+ Build a connection string for pipe based access.
180
+
181
+ :param dbname: Optional database name override for the profile default.
182
+
183
+ :returns: Connection string usable by SQLAlchemy.
184
+ :raises: ConfigurationError
185
+ """
186
+
187
+ conn_scheme: str = self.get_connection_scheme()
188
+
189
+ socket_path: str = self.dbprofile.socket
190
+
191
+ if not isinstance(self.credential, BasicCredential):
192
+ errmsg = (
193
+ "BasicSocketDatabaseConnectionFactory requires a BasicCredential to "
194
+ "format the connection string."
195
+ )
196
+ raise ConfigurationError(errmsg)
197
+
198
+ credobj: BasicCredential = self.credential
199
+
200
+ username = credobj.username
201
+ password = credobj.password
202
+
203
+ if dbname is None:
204
+ dbname = self.dbprofile.dbname
205
+
206
+ conn_str = f"{conn_scheme}://{username}:{password}@/{dbname}?host={socket_path}"
207
+
208
+ return conn_str
209
+
210
+
211
+ class BasicTcpDatabaseConnectionFactory(DatabaseConnectionFactory):
212
+ """
213
+ Create SQLAlchemy engines against TCP-based database endpoints.
214
+ """
215
+
216
+ def __init__(self, profile_name: str, *, dbprofile: DatabaseBasicTcpProfile, credential: BaseCredential):
217
+ """
218
+ Initialize the factory for TCP database connectivity.
219
+
220
+ :param profile_name: Name of the profile used to create the factory.
221
+ :param dbprofile: TCP database profile backing the factory.
222
+ :param credential: Credential containing the user information required for login.
223
+ """
224
+ super().__init__(profile_name, dbprofile=dbprofile, credential=credential)
225
+ return
226
+
227
+ @property
228
+ def dbprofile(self) -> DatabaseBasicTcpProfile:
229
+ """
230
+ Return the TCP-specific database profile for this factory.
231
+ """
232
+ return self._dbprofile
233
+
234
+ def create_engine(self, *, dbname=None, echo=True) -> SqlEngine:
235
+ """
236
+ Create a SQLAlchemy engine using TCP connectivity.
237
+
238
+ :param dbname: Optional database name override for the profile default.
239
+ :param echo: Flag forwarded to SQLAlchemy for logging emitted SQL.
240
+
241
+ :returns: SQLAlchemy engine instance for the configured TCP profile.
242
+ :raises: ConfigurationError
243
+ """
244
+
245
+ # If the database type we are creating an engine for is postgresql, make sure
246
+ # we can import all of the postgresql dependencies.
247
+ if self.dbprofile.dbtype == 'postgresql':
248
+ try:
249
+ import psycopg2
250
+ except ImportError:
251
+ errmsg_lines = [
252
+ "In order to create a postgresql database engine, you must install the following dependencies.",
253
+ "DEPENDENCIES",
254
+ " psycopg2"
255
+ ]
256
+ errmsg = os.linesep.join(errmsg_lines)
257
+ raise ConfigurationError(errmsg)
258
+
259
+ if dbname is None and self.dbprofile.dbname is not None:
260
+ dbname = self.dbprofile.dbname
261
+
262
+ if dbname is None:
263
+ warnmsg = "BasicTcpDatabaseConnectionFactory.create_engine: dbname was None."
264
+ logger.warn(warnmsg)
265
+
266
+ if isinstance(self.credential, BasicCredential):
267
+ connstr = self.format_connection_string(dbname=dbname)
268
+ dbengine = create_engine(connstr, echo=echo)
269
+ else:
270
+ errmsg = (
271
+ "BasicTcpDatabaseConnectionFactory requires a BasicCredential to "
272
+ "create an engine."
273
+ )
274
+ raise ConfigurationError(errmsg)
275
+
276
+ return dbengine
277
+
278
+ def get_connection_scheme(self):
279
+ """
280
+ Return the SQLAlchemy connection scheme based on the profile type.
281
+
282
+ :returns: SQLAlchemy connection scheme string.
283
+ :raises: ConfigurationError
284
+ """
285
+
286
+ conn_scheme = None
287
+
288
+ # If the database type we are creating an engine for is postgresql, make sure
289
+ # we can import all of the postgresql dependencies.
290
+ if self.dbprofile.dbtype == 'postgresql':
291
+ try:
292
+ import psycopg2
293
+ except ImportError:
294
+ errmsg_lines = [
295
+ "In order to create a postgresql database engine, you must install the following dependencies.",
296
+ "DEPENDENCIES",
297
+ " psycopg2"
298
+ ]
299
+ errmsg = os.linesep.join(errmsg_lines)
300
+ raise ConfigurationError(errmsg)
301
+
302
+ conn_scheme = "postgresql+psycopg2"
303
+ else:
304
+ errmsg = "Unsupported database type '{}' for database profile '{}'. Only 'postgresql' is currently supported.".format(
305
+ self.dbprofile.dbtype, self.profile_name)
306
+ raise ConfigurationError(errmsg)
307
+
308
+ return conn_scheme
309
+
310
+ def format_connection_string(self, dbname: Optional[str]=None) -> str:
311
+ """
312
+ Construct a TCP connection string with optional database name override.
313
+
314
+ :param dbname: Optional database name override for the profile default.
315
+
316
+ :returns: Connection string usable by SQLAlchemy.
317
+ """
318
+
319
+ conn_str = None
320
+
321
+ conn_scheme: str = self.get_connection_scheme()
322
+ host: str = self.dbprofile.host
323
+ port: str = self.dbprofile.port
324
+
325
+ if isinstance(self.credential, BasicCredential):
326
+ credobj: BasicCredential = self.credential
327
+
328
+ username = credobj.username
329
+ password = credobj.password
330
+
331
+ conn_str = f"{conn_scheme}://{username}:{password}@{host}:{port}"
332
+
333
+ if dbname is not None:
334
+ conn_str += f"/{dbname}"
335
+ else:
336
+ conn_str += f"/{self.dbprofile.dbname}"
337
+
338
+ return conn_str
339
+
340
+
341
+ DATABASE_CONNECTION_FACTORIES = {}
342
+
343
+
344
+ def create_database_connection_factory(dbprofile: DatabaseBasicSocketProfile, cred_manager: CredentialManager) -> DatabaseConnectionFactory:
345
+ """
346
+ Return a cached or newly created factory matching the supplied profile.
347
+
348
+ :param dbprofile: Profile describing the database connection parameters.
349
+ :param cred_manager: Credential manager providing database credentials.
350
+
351
+ :returns: Cached or newly constructed database connection factory.
352
+ :raises: ConfigurationError
353
+ """
354
+
355
+ global DATABASE_CONNECTION_FACTORIES
356
+
357
+ conn_factory = None
358
+
359
+ profile_name = dbprofile.identifier
360
+
361
+ if profile_name in DATABASE_CONNECTION_FACTORIES:
362
+ conn_factory = DATABASE_CONNECTION_FACTORIES[profile_name]
363
+
364
+ else:
365
+
366
+ credential_name = dbprofile.credential
367
+
368
+ credential: BaseCredential = cred_manager.credentials[credential_name]
369
+
370
+ category = dbprofile.category
371
+ if category == "basic-socket":
372
+ conn_factory = BasicSocketDatabaseConnectionFactory(profile_name, dbprofile=dbprofile, credential=credential)
373
+ elif category == "basic-tcp":
374
+ conn_factory = BasicTcpDatabaseConnectionFactory(profile_name, dbprofile=dbprofile, credential=credential)
375
+ else:
376
+ errmsg = "Unknown database connection type. profile_name={} category={}".format(
377
+ profile_name, category)
378
+ raise ConfigurationError(errmsg)
379
+
380
+ DATABASE_CONNECTION_FACTORIES[profile_name] = conn_factory
381
+
382
+ return conn_factory
@@ -0,0 +1,170 @@
1
+ """
2
+ .. module:: dbio
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: Contains helper functions for working with specific databases
5
+
6
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
7
+ """
8
+
9
+ __author__ = "Myron Walker"
10
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
11
+ __credits__ = []
12
+ __version__ = "1.0.0"
13
+
14
+
15
+ from typing import Optional
16
+
17
+
18
+ import contextlib
19
+ import logging
20
+
21
+ from sqlalchemy import text
22
+ from sqlalchemy.engine.base import Engine as SqlEngine
23
+ from sqlalchemy.sql.schema import MetaData
24
+
25
+ from sqlalchemy_utils import database_exists as sqlutils_database_exists
26
+ from sqlalchemy_utils import create_database as sqlutils_create_database
27
+ from sqlalchemy_utils import drop_database as sqlutils_drop_database
28
+
29
+ from ccai.errors.exceptions import ConfigurationError
30
+
31
+ from ccai.credentials.credentialmanager import CredentialManager
32
+
33
+ from ccai.dataprofiles.databasebasicsocketprofile import DatabaseBasicSocketProfile
34
+
35
+ from ccai.storage.database.dbconnection import DatabaseConnectionFactory, create_database_connection_factory
36
+
37
+
38
+ logger = logging.getLogger()
39
+
40
+
41
+ def database_exists(conn_factory: DatabaseConnectionFactory, dbname: Optional[str]=None) -> bool:
42
+ """
43
+ Check if the specified database exists.
44
+
45
+ :param conn_factory: Factory used to construct the database connection string.
46
+ :param dbname: Optional database name override for the profile default.
47
+
48
+ :returns: ``True`` if the database exists, otherwise ``False``.
49
+ """
50
+ conn_str = conn_factory.format_connection_string(dbname=dbname)
51
+
52
+ exists = sqlutils_database_exists(conn_str)
53
+
54
+ return exists
55
+
56
+
57
+ def database_create(conn_factory: DatabaseConnectionFactory, dbname: Optional[str]=None, dbmetadata: Optional[MetaData]=None):
58
+ """
59
+ Create the specified database.
60
+
61
+ :param conn_factory: Factory used to construct the database connection string.
62
+ :param dbname: Optional database name override for the profile default.
63
+ :param dbmetadata: SQLAlchemy metadata describing the schema to realize.
64
+ """
65
+
66
+ conn_str = conn_factory.format_connection_string(dbname=dbname)
67
+
68
+ sqlutils_create_database(conn_str)
69
+
70
+ if dbmetadata is not None:
71
+ engine = conn_factory.create_engine(dbname=dbname)
72
+ dbmetadata.create_all(engine)
73
+
74
+ return
75
+
76
+
77
+ def create_network_attached_database(db_profile: DatabaseBasicSocketProfile, cred_manager: CredentialManager, orm_metadata: MetaData, *, reset: bool = False):
78
+ """
79
+ Create a network attached database if it does not exist, optionally resetting it first.
80
+
81
+ :param db_profile: Database profile containing the connection configuration.
82
+ :param cred_manager: Credential manager instance for obtaining credentials.
83
+ :param orm_metadata: Object relational mapping used to create database structures.
84
+ :param reset: When ``True`` drop the existing database before creation.
85
+
86
+ :raises: ConfigurationError
87
+ """
88
+ db_name = db_profile.dbname
89
+
90
+ conn_factory = create_database_connection_factory(db_profile, cred_manager)
91
+ if conn_factory is None:
92
+ db_profile_name = db_profile.identifier
93
+ errmsg = "'create_ccai_enterprise_database' could not get a connection factory for profile={}".format(
94
+ db_profile_name
95
+ )
96
+ raise ConfigurationError(errmsg)
97
+
98
+ if reset and database_exists(conn_factory, db_name):
99
+ conn_str = conn_factory.format_connection_string(dbname=db_name)
100
+ sqlutils_drop_database(conn_str)
101
+
102
+ if not database_exists(conn_factory, db_name):
103
+ database_create(conn_factory, db_name)
104
+
105
+ engine = conn_factory.create_engine(dbname=db_name, echo=True)
106
+
107
+ orm_metadata.create_all(engine, checkfirst=True)
108
+
109
+ return
110
+
111
+
112
+ def open_network_attached_database(db_profile: DatabaseBasicSocketProfile, cred_manager: CredentialManager) -> SqlEngine:
113
+ """
114
+ Open a network attached database and return a SQLAlchemy engine.
115
+
116
+ :param db_profile: Database profile containing the connection configuration.
117
+ :param cred_manager: Credential manager instance for obtaining credentials.
118
+
119
+ :returns: SQLAlchemy engine configured for the specified database.
120
+ :raises: ConfigurationError
121
+ """
122
+ dbname = db_profile.dbname
123
+
124
+ conn_factory = create_database_connection_factory(db_profile, cred_manager)
125
+ if conn_factory is None:
126
+ db_profile_name = db_profile.identifier
127
+ errmsg = "'open_pychestrate_database' could not get a connection factory for profile={}".format(
128
+ db_profile_name
129
+ )
130
+ raise ConfigurationError(errmsg)
131
+
132
+ engine = conn_factory.create_engine(dbname=dbname, echo=True)
133
+
134
+ return engine
135
+
136
+
137
+ def reset_network_attached_database(db_profile: DatabaseBasicSocketProfile, cred_manager: CredentialManager, orm_metadata: MetaData):
138
+ """
139
+ Reset a network attached database by truncating all mapped tables.
140
+
141
+ :param db_profile: Database profile containing the connection configuration.
142
+ :param cred_manager: Credential manager instance for obtaining credentials.
143
+ :param orm_metadata: Object relational mapping that identifies the tables to truncate.
144
+
145
+ :raises: ConfigurationError
146
+ """
147
+ dbname = db_profile.dbname
148
+
149
+ conn_factory = create_database_connection_factory(db_profile, cred_manager)
150
+ if conn_factory is None:
151
+ db_profile_name = db_profile.identifier
152
+ errmsg = "'reset_pychestrate_database' could not get a connection factory for profile={}".format(
153
+ db_profile_name
154
+ )
155
+ raise ConfigurationError(errmsg)
156
+
157
+ if database_exists(conn_factory, dbname):
158
+
159
+ engine = conn_factory.create_engine(dbname=dbname, echo=True)
160
+
161
+ with contextlib.closing(engine.connect()) as con:
162
+ trans = con.begin()
163
+ table_names = ','.join(
164
+ table.name for table in reversed(orm_metadata.sorted_tables)
165
+ )
166
+ truncate_statement = text("TRUNCATE {} RESTART IDENTITY;".format(table_names))
167
+ con.execute(truncate_statement)
168
+ trans.commit()
169
+
170
+ return
@@ -0,0 +1,44 @@
1
+ """
2
+ .. module:: defaultvalues
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: Contains helper functions that are used to set default values.
5
+
6
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
7
+ """
8
+
9
+ from typing import Optional
10
+
11
+ from uuid import uuid4
12
+
13
+ from datetime import datetime, timezone, timedelta
14
+
15
+ def new_uuid() -> str:
16
+ """
17
+ Creats a new UUID string in uuid4 format.
18
+ """
19
+ rtnval = str(uuid4())
20
+ return rtnval
21
+
22
+ def utc_now() -> datetime:
23
+ """
24
+ Provides the current UTC time. This is used as a default value for datetime fields in models.
25
+
26
+ :return: datetime
27
+ """
28
+ now = datetime.now(timezone.utc)
29
+ return now
30
+
31
+ def reset_token_expiration(span: Optional[timedelta] = None) -> datetime:
32
+ """
33
+ Provides the expiration time for reset tokens. This is set to 24 hours from now.
34
+
35
+ :param span: The time span that the token will be good for. If not provided the default span is 24 hours.
36
+
37
+ :return: datetime
38
+ """
39
+ if span is None:
40
+ span = timedelta(days=1)
41
+
42
+ expiration = utc_now() + span
43
+
44
+ return expiration
@@ -0,0 +1,47 @@
1
+ """
2
+ .. module:: mixins
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: Contains mixins which can add generic functionality for Model objects.
5
+
6
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
7
+ """
8
+
9
+ __author__ = "Myron Walker"
10
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
11
+ __credits__ = []
12
+ __version__ = "1.0.0"
13
+
14
+ import json
15
+
16
+ from sqlalchemy import inspect
17
+
18
+ class SerializableMixIn:
19
+ """
20
+ Mixin style class that adds serialization to data model objects.
21
+ """
22
+
23
+ def as_dict(self):
24
+ """
25
+ Iterates the formal data attributes of a model and outputs a dictionary
26
+ with the data based on the model.
27
+ """
28
+ dval = {}
29
+
30
+ model = type(self)
31
+ mapper = inspect(model)
32
+ for col in mapper.attrs:
33
+ col_key = col.key
34
+ dval[col_key] = str(getattr(self, col_key))
35
+
36
+ return dval
37
+
38
+
39
+ def to_json(self, indent=4):
40
+ """
41
+ Iterates the formal data attributes of a model and creates a dictionary
42
+ with the data based on the model, then converts the dictionary to a
43
+ JSON string.
44
+ """
45
+ model_dict = self.as_dict()
46
+ json_str = json.dumps(model_dict, indent=indent)
47
+ return json_str