keelmodel 0.1.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.
Files changed (40) hide show
  1. keelmodel-0.1.0/LICENSE +21 -0
  2. keelmodel-0.1.0/PKG-INFO +292 -0
  3. keelmodel-0.1.0/README.md +267 -0
  4. keelmodel-0.1.0/pyproject.toml +84 -0
  5. keelmodel-0.1.0/pyproject.toml.orig +62 -0
  6. keelmodel-0.1.0/src/keeliam/__init__.py +12 -0
  7. keelmodel-0.1.0/src/keeliam/context.py +155 -0
  8. keelmodel-0.1.0/src/keeliam/principal.py +58 -0
  9. keelmodel-0.1.0/src/keelmodel/__init__.py +1 -0
  10. keelmodel-0.1.0/src/keelmodel/adoption/__init__.py +4 -0
  11. keelmodel-0.1.0/src/keelmodel/adoption/__main__.py +28 -0
  12. keelmodel-0.1.0/src/keelmodel/adoption/decision-guide.md +98 -0
  13. keelmodel-0.1.0/src/keelmodel/adoption/quickstart.md +98 -0
  14. keelmodel-0.1.0/src/keelmodel/adoption/recovery.md +104 -0
  15. keelmodel-0.1.0/src/keelmodel/adoption/reference.md +265 -0
  16. keelmodel-0.1.0/src/keelmodel/authz.py +562 -0
  17. keelmodel-0.1.0/src/keelmodel/extensions/audit/__init__.py +3 -0
  18. keelmodel-0.1.0/src/keelmodel/extensions/audit/audit.py +169 -0
  19. keelmodel-0.1.0/src/keelmodel/generation.py +110 -0
  20. keelmodel-0.1.0/src/keelmodel/migrations.py +161 -0
  21. keelmodel-0.1.0/src/keelmodel/py.typed +0 -0
  22. keelmodel-0.1.0/src/keelmodel/registry.py +209 -0
  23. keelmodel-0.1.0/src/keelmodel/runtime/base.py +6 -0
  24. keelmodel-0.1.0/src/keelmodel/runtime/constraints.py +72 -0
  25. keelmodel-0.1.0/src/keelmodel/runtime/context.py +18 -0
  26. keelmodel-0.1.0/src/keelmodel/runtime/errors.py +29 -0
  27. keelmodel-0.1.0/src/keelmodel/runtime/filtering.py +81 -0
  28. keelmodel-0.1.0/src/keelmodel/runtime/models.py +307 -0
  29. keelmodel-0.1.0/src/keelmodel/runtime/operations.py +22 -0
  30. keelmodel-0.1.0/src/keelmodel/runtime/results.py +13 -0
  31. keelmodel-0.1.0/src/keelmodel/runtime/serialization.py +285 -0
  32. keelmodel-0.1.0/src/keelmodel/runtime/session.py +2344 -0
  33. keelmodel-0.1.0/src/keelmodel/schema.py +779 -0
  34. keelmodel-0.1.0/src/keelmodel/ui/__init__.py +17 -0
  35. keelmodel-0.1.0/src/keelmodel/ui/introspection.py +289 -0
  36. keelmodel-0.1.0/src/keelmodel/ui/loader.py +307 -0
  37. keelmodel-0.1.0/src/keelpolicy/__init__.py +1 -0
  38. keelmodel-0.1.0/src/keelpolicy/evaluator.py +117 -0
  39. keelmodel-0.1.0/src/keelpolicy/parser.py +133 -0
  40. keelmodel-0.1.0/src/keelpolicy/types.py +26 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dat Giang
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,292 @@
1
+ Metadata-Version: 2.4
2
+ Name: keelmodel
3
+ Version: 0.1.0
4
+ Summary: A strict, sync-first data SDK for business applications
5
+ Keywords: pre-erp,data-model,yaml,orm,sqlalchemy,authorization
6
+ Author: Dat Giang
7
+ Author-email: Dat Giang <datgs@users.noreply.github.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Topic :: Database
16
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
17
+ Requires-Dist: sqlalchemy>=2.0,<3.0
18
+ Requires-Dist: pyyaml>=6.0,<7.0
19
+ Requires-Dist: packaging>=24.0,<27.0
20
+ Requires-Dist: psycopg[binary]>=3.2
21
+ Requires-Dist: alembic>=1.14
22
+ Requires-Dist: pymysql>=1.1
23
+ Requires-Python: >=3.12
24
+ Description-Content-Type: text/markdown
25
+
26
+ # keelmodel
27
+
28
+ [![PyPI](https://img.shields.io/pypi/v/keelmodel)](https://pypi.org/project/keelmodel/)
29
+ [![Python](https://img.shields.io/pypi/pyversions/keelmodel)](https://pypi.org/project/keelmodel/)
30
+ [![CI](https://github.com/datgs/keelmodel/actions/workflows/ci.yml/badge.svg)](https://github.com/datgs/keelmodel/actions/workflows/ci.yml)
31
+ [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
32
+
33
+ **Declare your business models once — in strict YAML — and get typed Python
34
+ classes, a synchronous data SDK, and YAML-declared authorization over
35
+ PostgreSQL, MySQL, or SQLite.**
36
+
37
+ KeelModel is a pre-ERP data platform: the boring, repetitive parts of business
38
+ applications (CRUD, relations, constraints, bulk writes, audit, row/field
39
+ security) become declarations and contracts instead of hand-rolled ORM code.
40
+ One schema drives generated Python classes *and* migration drafts, so code and
41
+ database can never silently drift.
42
+
43
+ ```bash
44
+ pip install keelmodel
45
+ ```
46
+
47
+ ```yaml
48
+ # models/invoice.yaml
49
+ version: 1
50
+ module: sales
51
+ model: Invoice
52
+ mixins: [uuid_pk, timestamps, versioned]
53
+ fields:
54
+ number: {type: text, required: true, length: 40}
55
+ total: {type: decimal, required: true, default: 0}
56
+ relations:
57
+ customer: {type: many_to_one, target: sales.Customer, required: true}
58
+ ```
59
+
60
+ ```python
61
+ km = KeelModel("postgresql://app:secret@db/shop", registry, authz=authz)
62
+
63
+ page = km.query(
64
+ "sales.Invoice", ctx,
65
+ filters={"field": "total", "op": "gte", "value": 0},
66
+ order=["-created_at"],
67
+ include=["customer"], # batched — no N+1
68
+ )
69
+
70
+ km.upsert(
71
+ "sales.Invoice", values, ctx,
72
+ conflict_target="number", # primary key or declared unique group
73
+ update_fields=["total"],
74
+ )
75
+ ```
76
+
77
+ ## Why keelmodel — and when *not*
78
+
79
+ | | SQLAlchemy / Django ORM | keelmodel |
80
+ |---|---|---|
81
+ | Schema lives in | Python model classes | **Strict, versioned YAML** — reviewable, generated, drift-checked |
82
+ | Row-level security | You build it (usually in service code, easy to forget) | **Compiled into the SQL predicate** of every SDK operation, plus post-write verification |
83
+ | Field-level security | Custom serializers per endpoint | **Default-deny field grants** — denied columns are never SELECTed into memory |
84
+ | Optimistic locking | Manual `version_id_col` setup (flush-only; bulk UPDATEs bypass it) | **One flag per model**; enforced in conditional DML, works for direct updates and upserts |
85
+ | Multi-dialect | Supported, your code tests the differences | One contract suite proves identical behavior on PG/MySQL/SQLite |
86
+ | Bulk + upsert | `executemany` / dialect-specific inserts, wired by hand | Atomic `bulk` + per-branch authorized `upsert` with a declared conflict target |
87
+ | Audit | Hooks you write and test | Same-transaction audit extension with field redaction |
88
+ | Migrations | Alembic autogenerate against models | Alembic drafts generated from YAML — reviewed, never auto-applied |
89
+
90
+ **Choose keelmodel if** you're building an ERP, ERP-lite, or business
91
+ application where several modules share a data layer, where *who may see or
92
+ change which fields* is a first-class requirement rather than an afterthought,
93
+ and where "the YAML is the contract" beats a codebase full of near-identical
94
+ model classes.
95
+
96
+ **Don't choose it** if you want a full async stack (sync only, by design), an
97
+ HTTP/REST layer out of the box (there is none — you own the transport), lazy
98
+ `session.query` ergonomics, or a framework that manages authn/users for you.
99
+ If you just want SQLAlchemy with a nicer syntax, use SQLAlchemy — keelmodel's
100
+ value is the *contract and enforcement*, not another query DSL.
101
+
102
+ ## What you get
103
+
104
+ - **One source of truth.** YAML owns fields, relations, constraints, and
105
+ mixins — no schema drift between code and migrations. Generated Python is
106
+ deterministic, committed, and never hand-edited.
107
+ - **Sync, typed SDK.** `create / get / update / delete / query / bulk /
108
+ upsert` with atomic writes, typed errors, bounded offset paging plus
109
+ keyset cursor pagination (`next_cursor`), deterministic ordering, and
110
+ explicit `include` relation loading — batched one query per hop,
111
+ nested paths like `"lines.product"`, authorization-aware, no implicit
112
+ lazy loads. Computed fields derive same-row values in SQL or cross-row
113
+ aggregates in Python inside the write transaction, with opt-in
114
+ dependency-triggered cascading that recomputes each owner exactly once
115
+ per transaction — no Odoo-style per-write recompute storms.
116
+ - **Optimistic concurrency, opt-in.** `mixins: [versioned]` (or
117
+ `version: true` on one integer field) makes every update carry an expected
118
+ version, checked atomically in the conditional `UPDATE` — a stale write is
119
+ a `ConflictError`, never a silent overwrite.
120
+ - **Multi-dialect.** Same model code runs on PostgreSQL, MySQL, and SQLite;
121
+ dialect-specific storage is handled internally and proven by a shared
122
+ contract suite (CRUD, FK/unique/check violations, transactions, atomic
123
+ bulk, versioning, includes, upsert, record-level authz). Accepted
124
+ differences: text/enum fields need `length` when indexed on MySQL, and
125
+ `contains` case-sensitivity is dialect-native (Postgres strict,
126
+ SQLite/MySQL commonly lax — use `icontains` for uniform case-insensitive
127
+ search). Datetimes are SDK-managed UTC writes, so equality, ordering,
128
+ and keyset cursors behave consistently on every dialect.
129
+ - **`keelpolicy` authorization.** Deny-overrides YAML policy engine,
130
+ application-owned, no DB dependency — reusable outside KeelModel.
131
+ - **`keeliam` identity context.** Provider-neutral contracts
132
+ (`VerifiedIdentity`, `AccessContext`) for carrying an already-
133
+ authenticated principal into KeelModel `OperationContext` and KeelFlow
134
+ `Actor`/`JobContext` — no IdP, no token validation, no login; the host
135
+ authenticates, keeliam normalizes the context.
136
+ - **Same-transaction audit.** Optional extension records every SDK mutation
137
+ — create/bulk inserts via the ORM flush, and update/delete/upsert-conflict
138
+ via explicit direct-DML capture — with subject and redacted field diffs,
139
+ committing or rolling back together with the business mutation. Audit is
140
+ a system-level record: not filtered by the caller's read grants; field
141
+ visibility is governed by `redact_fields`.
142
+ - **Alembic draft generation.** Migrations are generated for review — never
143
+ applied silently.
144
+
145
+ ## Authorization trust boundary (opt-in)
146
+
147
+ Authorization is **opt-in** (`KeelModel(..., authz=AuthorizationProvider(path))`)
148
+ and is not enabled by default. With a provider, every SDK operation is
149
+ gated: action+subject deny-overrides checks, `record.*` conditions enforced
150
+ in SQL (query/get predicate, conditional UPDATE/DELETE, post-write
151
+ create/bulk verification inside the transaction), and — with
152
+ `enable_field_rules=True` — **default-deny** field capabilities where every
153
+ field needs an explicit grant for read, create, update, filter and order.
154
+
155
+ Security-relevant boundaries to know before relying on it:
156
+
157
+ - `OperationContext.subject` is **caller-supplied and trusted**. KeelModel
158
+ never authenticates anyone; build the context from your verified auth
159
+ layer. `subject.roles` must be a list/tuple/set of strings — other shapes
160
+ match nothing (fail closed).
161
+ - Subject wildcard `*` matches **any** subject, including empty roles.
162
+ Resource/subject `foo*` is a prefix match — `sales*` also matches
163
+ `salesOther.Doc`. Use exact patterns or `module.*` deliberately.
164
+ - Authorization applies **only** to SDK operations
165
+ (`create/get/update/delete/query/bulk/upsert`). `km.engine`,
166
+ `km.session_factory` and the raw SQLAlchemy session from
167
+ `km.transaction()` bypass it — authorization-bearing callers must go
168
+ through the SDK methods.
169
+ - `authz=None` performs no enforcement at all (trusted application mode).
170
+ - Record conditions compile to per-dialect SQL that matches the Python
171
+ evaluator's semantics (case-sensitive comparisons and substring matching,
172
+ `None` membership in `in` lists, three-valued-logic-safe deny handling).
173
+ - Create, update, bulk and upsert responses use READ permissions and field
174
+ projection; a successful write returns `{}` when the caller cannot read
175
+ the resulting row.
176
+ - Any SDK `PermissionDenied` inside `km.transaction()` makes the transaction
177
+ roll back, even if application code catches that error inside the block.
178
+ - Field-rule `write` is shorthand for `create` + `update`; explicit deny
179
+ statements and `false` grant entries always win over wildcard grants.
180
+ - `include` re-runs QUERY authorization and field projection on the related
181
+ resource; if correlation columns (the FK or either side's PK) are not
182
+ readable, the include fails closed.
183
+ - Upsert authorization is per-branch: insert requires `create`, conflict
184
+ requires `update` on old and new state. A concurrent insert on the same
185
+ conflict target surfaces `ConflictError`; callers retry the whole upsert.
186
+ - DB-level `on_delete` (restrict/cascade/set_null) may cascade rows that are
187
+ not separately authorized or audited — declare it deliberately. Audit
188
+ entries for a cascaded deletion record only the row deleted through the
189
+ SDK; child rows removed by the database cascade are not audited.
190
+
191
+ ## Upsert, versioning, pagination — the contracts
192
+
193
+ ```python
194
+ # Optimistic locking: update carries the version the caller read
195
+ km.update("sales.Invoice", inv["id"],
196
+ {"version": inv["version"], "status": "approved"}, ctx)
197
+ # → ConflictError("stale version …") if someone committed meanwhile
198
+
199
+ # Upsert: values the caller would insert; conflict_target identifies the row
200
+ km.upsert(
201
+ "sales.Invoice",
202
+ {"number": "INV-1", "total": 120, "note": "insert-only field",
203
+ "version": inv.get("version", 1)},
204
+ ctx,
205
+ conflict_target="number", # must be the PK or a declared unique group
206
+ update_fields=["total"], # only these change on conflict
207
+ )
208
+ # insert → create authz; conflict → update authz on old+new record state;
209
+ # versioned models still require the expected version on conflict.
210
+
211
+ # Paging is bounded (max_page_size, default 500) and deterministic:
212
+ page = km.query("sales.Invoice", ctx, order=["-total"], limit=50, offset=50)
213
+ # PK tie-breakers keep page boundaries stable under duplicate sort values.
214
+
215
+ # At scale, use keyset pagination — constant-cost at any depth and
216
+ # immune to inserts between pages:
217
+ page2 = km.query("sales.Invoice", ctx, order=["-total"],
218
+ limit=50, cursor=page.next_cursor)
219
+ ```
220
+
221
+ ## For AI agents and first-time adopters
222
+
223
+ The wheel ships its own adoption docs, versioned with the code you run:
224
+
225
+ ```bash
226
+ python -m keelmodel.adoption # index
227
+ python -m keelmodel.adoption quickstart # executable quickstart
228
+ python -m keelmodel.adoption decision-guide # use case → primitive mapping
229
+ python -m keelmodel.adoption reference # exact YAML/API grammar
230
+ python -m keelmodel.adoption recovery # error → cause → fix
231
+ ```
232
+
233
+ `llms.txt` in the repo root is the task router for agents. Doc snippets
234
+ are executed by the test suite — they cannot silently drift. Also see
235
+ `docs/api-stability.md`, `docs/compatibility.md`, and
236
+ `docs/known-limitations.md` before depending on this in production.
237
+
238
+ ## Layout
239
+
240
+ | Path | Purpose |
241
+ | ---- | ------- |
242
+ | `src/keelmodel/` | schema, generation, registry, runtime, extensions |
243
+ | `src/keelpolicy/` | standalone YAML policy parser + evaluator |
244
+ | `examples/sales/` | full-feature walkthrough: CRUD, relations, constraints, transaction, record- and field-level authz, generated artifacts, migration draft |
245
+ | `examples/erp/` | heavier module: departments, self-refs, M2M junctions, milestones — with a stress harness |
246
+
247
+ ```bash
248
+ uv run pytest # unit tests
249
+ KEELMODEL_TEST_DB=postgresql://… # + Postgres integration
250
+ KEELMODEL_TEST_MYSQL=mysql+pymysql://… # + MySQL integration
251
+
252
+ # sales walkthrough: SQLite temp DB by default — safe, self-contained
253
+ uv run python examples/sales/demo.py
254
+
255
+ # same walkthrough on a dedicated Postgres test DB (additive only,
256
+ # records namespaced per run — safe to re-run)
257
+ KEELMODEL_DEMO_PG=postgresql://… uv run python examples/sales/demo.py --postgres
258
+
259
+ # erp stress harness: requires an explicit opt-in reset on a dedicated DB
260
+ KEELMODEL_RESET=1 KEELMODEL_DB=postgresql://… \
261
+ uv run python examples/erp/stress.py
262
+ ```
263
+
264
+ ## Experimental: model-driven UI (early)
265
+
266
+ `src/keelmodel/ui/` + `src/keelmodel_serve/` + `ui/renderer/` are an early
267
+ model-driven UI runtime: YAML models plus declarative UI extensions
268
+ (`examples/sales/ui/`) drive list/detail/form screens and a read-only model
269
+ explorer — no hand-written frontend per model. Run it locally:
270
+
271
+ ```bash
272
+ # terminal 1 — JSON-RPC backend on :8700 (dev identity hook,
273
+ # never for production)
274
+ uv run python examples/sales/serve_demo.py
275
+
276
+ # terminal 2 — React renderer on :5173, proxying /rpc
277
+ cd ui/renderer && npm install && npm run dev
278
+
279
+ # open http://localhost:5173
280
+ ```
281
+
282
+ The serve layer mounts into FastAPI/Starlette natively and into WSGI hosts
283
+ via an ASGI bridge; authentication is host-owned through an identity hook.
284
+ Status: experimental, not covered by the stability guarantees in
285
+ `docs/api-stability.md`; a security review is required before any
286
+ production use.
287
+
288
+ ## Status
289
+
290
+ Early development (v0.1). Sync API only; authorization enforcement is opt-in.
291
+ No HTTP layer, no async yet. Deferred: custom composite types, async SDK,
292
+ batch set-based recomputation, per-include collection limits.
@@ -0,0 +1,267 @@
1
+ # keelmodel
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/keelmodel)](https://pypi.org/project/keelmodel/)
4
+ [![Python](https://img.shields.io/pypi/pyversions/keelmodel)](https://pypi.org/project/keelmodel/)
5
+ [![CI](https://github.com/datgs/keelmodel/actions/workflows/ci.yml/badge.svg)](https://github.com/datgs/keelmodel/actions/workflows/ci.yml)
6
+ [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
7
+
8
+ **Declare your business models once — in strict YAML — and get typed Python
9
+ classes, a synchronous data SDK, and YAML-declared authorization over
10
+ PostgreSQL, MySQL, or SQLite.**
11
+
12
+ KeelModel is a pre-ERP data platform: the boring, repetitive parts of business
13
+ applications (CRUD, relations, constraints, bulk writes, audit, row/field
14
+ security) become declarations and contracts instead of hand-rolled ORM code.
15
+ One schema drives generated Python classes *and* migration drafts, so code and
16
+ database can never silently drift.
17
+
18
+ ```bash
19
+ pip install keelmodel
20
+ ```
21
+
22
+ ```yaml
23
+ # models/invoice.yaml
24
+ version: 1
25
+ module: sales
26
+ model: Invoice
27
+ mixins: [uuid_pk, timestamps, versioned]
28
+ fields:
29
+ number: {type: text, required: true, length: 40}
30
+ total: {type: decimal, required: true, default: 0}
31
+ relations:
32
+ customer: {type: many_to_one, target: sales.Customer, required: true}
33
+ ```
34
+
35
+ ```python
36
+ km = KeelModel("postgresql://app:secret@db/shop", registry, authz=authz)
37
+
38
+ page = km.query(
39
+ "sales.Invoice", ctx,
40
+ filters={"field": "total", "op": "gte", "value": 0},
41
+ order=["-created_at"],
42
+ include=["customer"], # batched — no N+1
43
+ )
44
+
45
+ km.upsert(
46
+ "sales.Invoice", values, ctx,
47
+ conflict_target="number", # primary key or declared unique group
48
+ update_fields=["total"],
49
+ )
50
+ ```
51
+
52
+ ## Why keelmodel — and when *not*
53
+
54
+ | | SQLAlchemy / Django ORM | keelmodel |
55
+ |---|---|---|
56
+ | Schema lives in | Python model classes | **Strict, versioned YAML** — reviewable, generated, drift-checked |
57
+ | Row-level security | You build it (usually in service code, easy to forget) | **Compiled into the SQL predicate** of every SDK operation, plus post-write verification |
58
+ | Field-level security | Custom serializers per endpoint | **Default-deny field grants** — denied columns are never SELECTed into memory |
59
+ | Optimistic locking | Manual `version_id_col` setup (flush-only; bulk UPDATEs bypass it) | **One flag per model**; enforced in conditional DML, works for direct updates and upserts |
60
+ | Multi-dialect | Supported, your code tests the differences | One contract suite proves identical behavior on PG/MySQL/SQLite |
61
+ | Bulk + upsert | `executemany` / dialect-specific inserts, wired by hand | Atomic `bulk` + per-branch authorized `upsert` with a declared conflict target |
62
+ | Audit | Hooks you write and test | Same-transaction audit extension with field redaction |
63
+ | Migrations | Alembic autogenerate against models | Alembic drafts generated from YAML — reviewed, never auto-applied |
64
+
65
+ **Choose keelmodel if** you're building an ERP, ERP-lite, or business
66
+ application where several modules share a data layer, where *who may see or
67
+ change which fields* is a first-class requirement rather than an afterthought,
68
+ and where "the YAML is the contract" beats a codebase full of near-identical
69
+ model classes.
70
+
71
+ **Don't choose it** if you want a full async stack (sync only, by design), an
72
+ HTTP/REST layer out of the box (there is none — you own the transport), lazy
73
+ `session.query` ergonomics, or a framework that manages authn/users for you.
74
+ If you just want SQLAlchemy with a nicer syntax, use SQLAlchemy — keelmodel's
75
+ value is the *contract and enforcement*, not another query DSL.
76
+
77
+ ## What you get
78
+
79
+ - **One source of truth.** YAML owns fields, relations, constraints, and
80
+ mixins — no schema drift between code and migrations. Generated Python is
81
+ deterministic, committed, and never hand-edited.
82
+ - **Sync, typed SDK.** `create / get / update / delete / query / bulk /
83
+ upsert` with atomic writes, typed errors, bounded offset paging plus
84
+ keyset cursor pagination (`next_cursor`), deterministic ordering, and
85
+ explicit `include` relation loading — batched one query per hop,
86
+ nested paths like `"lines.product"`, authorization-aware, no implicit
87
+ lazy loads. Computed fields derive same-row values in SQL or cross-row
88
+ aggregates in Python inside the write transaction, with opt-in
89
+ dependency-triggered cascading that recomputes each owner exactly once
90
+ per transaction — no Odoo-style per-write recompute storms.
91
+ - **Optimistic concurrency, opt-in.** `mixins: [versioned]` (or
92
+ `version: true` on one integer field) makes every update carry an expected
93
+ version, checked atomically in the conditional `UPDATE` — a stale write is
94
+ a `ConflictError`, never a silent overwrite.
95
+ - **Multi-dialect.** Same model code runs on PostgreSQL, MySQL, and SQLite;
96
+ dialect-specific storage is handled internally and proven by a shared
97
+ contract suite (CRUD, FK/unique/check violations, transactions, atomic
98
+ bulk, versioning, includes, upsert, record-level authz). Accepted
99
+ differences: text/enum fields need `length` when indexed on MySQL, and
100
+ `contains` case-sensitivity is dialect-native (Postgres strict,
101
+ SQLite/MySQL commonly lax — use `icontains` for uniform case-insensitive
102
+ search). Datetimes are SDK-managed UTC writes, so equality, ordering,
103
+ and keyset cursors behave consistently on every dialect.
104
+ - **`keelpolicy` authorization.** Deny-overrides YAML policy engine,
105
+ application-owned, no DB dependency — reusable outside KeelModel.
106
+ - **`keeliam` identity context.** Provider-neutral contracts
107
+ (`VerifiedIdentity`, `AccessContext`) for carrying an already-
108
+ authenticated principal into KeelModel `OperationContext` and KeelFlow
109
+ `Actor`/`JobContext` — no IdP, no token validation, no login; the host
110
+ authenticates, keeliam normalizes the context.
111
+ - **Same-transaction audit.** Optional extension records every SDK mutation
112
+ — create/bulk inserts via the ORM flush, and update/delete/upsert-conflict
113
+ via explicit direct-DML capture — with subject and redacted field diffs,
114
+ committing or rolling back together with the business mutation. Audit is
115
+ a system-level record: not filtered by the caller's read grants; field
116
+ visibility is governed by `redact_fields`.
117
+ - **Alembic draft generation.** Migrations are generated for review — never
118
+ applied silently.
119
+
120
+ ## Authorization trust boundary (opt-in)
121
+
122
+ Authorization is **opt-in** (`KeelModel(..., authz=AuthorizationProvider(path))`)
123
+ and is not enabled by default. With a provider, every SDK operation is
124
+ gated: action+subject deny-overrides checks, `record.*` conditions enforced
125
+ in SQL (query/get predicate, conditional UPDATE/DELETE, post-write
126
+ create/bulk verification inside the transaction), and — with
127
+ `enable_field_rules=True` — **default-deny** field capabilities where every
128
+ field needs an explicit grant for read, create, update, filter and order.
129
+
130
+ Security-relevant boundaries to know before relying on it:
131
+
132
+ - `OperationContext.subject` is **caller-supplied and trusted**. KeelModel
133
+ never authenticates anyone; build the context from your verified auth
134
+ layer. `subject.roles` must be a list/tuple/set of strings — other shapes
135
+ match nothing (fail closed).
136
+ - Subject wildcard `*` matches **any** subject, including empty roles.
137
+ Resource/subject `foo*` is a prefix match — `sales*` also matches
138
+ `salesOther.Doc`. Use exact patterns or `module.*` deliberately.
139
+ - Authorization applies **only** to SDK operations
140
+ (`create/get/update/delete/query/bulk/upsert`). `km.engine`,
141
+ `km.session_factory` and the raw SQLAlchemy session from
142
+ `km.transaction()` bypass it — authorization-bearing callers must go
143
+ through the SDK methods.
144
+ - `authz=None` performs no enforcement at all (trusted application mode).
145
+ - Record conditions compile to per-dialect SQL that matches the Python
146
+ evaluator's semantics (case-sensitive comparisons and substring matching,
147
+ `None` membership in `in` lists, three-valued-logic-safe deny handling).
148
+ - Create, update, bulk and upsert responses use READ permissions and field
149
+ projection; a successful write returns `{}` when the caller cannot read
150
+ the resulting row.
151
+ - Any SDK `PermissionDenied` inside `km.transaction()` makes the transaction
152
+ roll back, even if application code catches that error inside the block.
153
+ - Field-rule `write` is shorthand for `create` + `update`; explicit deny
154
+ statements and `false` grant entries always win over wildcard grants.
155
+ - `include` re-runs QUERY authorization and field projection on the related
156
+ resource; if correlation columns (the FK or either side's PK) are not
157
+ readable, the include fails closed.
158
+ - Upsert authorization is per-branch: insert requires `create`, conflict
159
+ requires `update` on old and new state. A concurrent insert on the same
160
+ conflict target surfaces `ConflictError`; callers retry the whole upsert.
161
+ - DB-level `on_delete` (restrict/cascade/set_null) may cascade rows that are
162
+ not separately authorized or audited — declare it deliberately. Audit
163
+ entries for a cascaded deletion record only the row deleted through the
164
+ SDK; child rows removed by the database cascade are not audited.
165
+
166
+ ## Upsert, versioning, pagination — the contracts
167
+
168
+ ```python
169
+ # Optimistic locking: update carries the version the caller read
170
+ km.update("sales.Invoice", inv["id"],
171
+ {"version": inv["version"], "status": "approved"}, ctx)
172
+ # → ConflictError("stale version …") if someone committed meanwhile
173
+
174
+ # Upsert: values the caller would insert; conflict_target identifies the row
175
+ km.upsert(
176
+ "sales.Invoice",
177
+ {"number": "INV-1", "total": 120, "note": "insert-only field",
178
+ "version": inv.get("version", 1)},
179
+ ctx,
180
+ conflict_target="number", # must be the PK or a declared unique group
181
+ update_fields=["total"], # only these change on conflict
182
+ )
183
+ # insert → create authz; conflict → update authz on old+new record state;
184
+ # versioned models still require the expected version on conflict.
185
+
186
+ # Paging is bounded (max_page_size, default 500) and deterministic:
187
+ page = km.query("sales.Invoice", ctx, order=["-total"], limit=50, offset=50)
188
+ # PK tie-breakers keep page boundaries stable under duplicate sort values.
189
+
190
+ # At scale, use keyset pagination — constant-cost at any depth and
191
+ # immune to inserts between pages:
192
+ page2 = km.query("sales.Invoice", ctx, order=["-total"],
193
+ limit=50, cursor=page.next_cursor)
194
+ ```
195
+
196
+ ## For AI agents and first-time adopters
197
+
198
+ The wheel ships its own adoption docs, versioned with the code you run:
199
+
200
+ ```bash
201
+ python -m keelmodel.adoption # index
202
+ python -m keelmodel.adoption quickstart # executable quickstart
203
+ python -m keelmodel.adoption decision-guide # use case → primitive mapping
204
+ python -m keelmodel.adoption reference # exact YAML/API grammar
205
+ python -m keelmodel.adoption recovery # error → cause → fix
206
+ ```
207
+
208
+ `llms.txt` in the repo root is the task router for agents. Doc snippets
209
+ are executed by the test suite — they cannot silently drift. Also see
210
+ `docs/api-stability.md`, `docs/compatibility.md`, and
211
+ `docs/known-limitations.md` before depending on this in production.
212
+
213
+ ## Layout
214
+
215
+ | Path | Purpose |
216
+ | ---- | ------- |
217
+ | `src/keelmodel/` | schema, generation, registry, runtime, extensions |
218
+ | `src/keelpolicy/` | standalone YAML policy parser + evaluator |
219
+ | `examples/sales/` | full-feature walkthrough: CRUD, relations, constraints, transaction, record- and field-level authz, generated artifacts, migration draft |
220
+ | `examples/erp/` | heavier module: departments, self-refs, M2M junctions, milestones — with a stress harness |
221
+
222
+ ```bash
223
+ uv run pytest # unit tests
224
+ KEELMODEL_TEST_DB=postgresql://… # + Postgres integration
225
+ KEELMODEL_TEST_MYSQL=mysql+pymysql://… # + MySQL integration
226
+
227
+ # sales walkthrough: SQLite temp DB by default — safe, self-contained
228
+ uv run python examples/sales/demo.py
229
+
230
+ # same walkthrough on a dedicated Postgres test DB (additive only,
231
+ # records namespaced per run — safe to re-run)
232
+ KEELMODEL_DEMO_PG=postgresql://… uv run python examples/sales/demo.py --postgres
233
+
234
+ # erp stress harness: requires an explicit opt-in reset on a dedicated DB
235
+ KEELMODEL_RESET=1 KEELMODEL_DB=postgresql://… \
236
+ uv run python examples/erp/stress.py
237
+ ```
238
+
239
+ ## Experimental: model-driven UI (early)
240
+
241
+ `src/keelmodel/ui/` + `src/keelmodel_serve/` + `ui/renderer/` are an early
242
+ model-driven UI runtime: YAML models plus declarative UI extensions
243
+ (`examples/sales/ui/`) drive list/detail/form screens and a read-only model
244
+ explorer — no hand-written frontend per model. Run it locally:
245
+
246
+ ```bash
247
+ # terminal 1 — JSON-RPC backend on :8700 (dev identity hook,
248
+ # never for production)
249
+ uv run python examples/sales/serve_demo.py
250
+
251
+ # terminal 2 — React renderer on :5173, proxying /rpc
252
+ cd ui/renderer && npm install && npm run dev
253
+
254
+ # open http://localhost:5173
255
+ ```
256
+
257
+ The serve layer mounts into FastAPI/Starlette natively and into WSGI hosts
258
+ via an ASGI bridge; authentication is host-owned through an identity hook.
259
+ Status: experimental, not covered by the stability guarantees in
260
+ `docs/api-stability.md`; a security review is required before any
261
+ production use.
262
+
263
+ ## Status
264
+
265
+ Early development (v0.1). Sync API only; authorization enforcement is opt-in.
266
+ No HTTP layer, no async yet. Deferred: custom composite types, async SDK,
267
+ batch set-based recomputation, per-include collection limits.
@@ -0,0 +1,84 @@
1
+ [project]
2
+ name = "keelmodel"
3
+ version = "0.1.0"
4
+ description = "A strict, sync-first data SDK for business applications"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ keywords = [
9
+ "pre-erp",
10
+ "data-model",
11
+ "yaml",
12
+ "orm",
13
+ "sqlalchemy",
14
+ "authorization",
15
+ ]
16
+ classifiers = [
17
+ "Development Status :: 3 - Alpha",
18
+ "Intended Audience :: Developers",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Topic :: Database",
23
+ "Topic :: Software Development :: Libraries :: Application Frameworks",
24
+ ]
25
+ requires-python = ">=3.12"
26
+ dependencies = [
27
+ "sqlalchemy>=2.0,<3.0",
28
+ "pyyaml>=6.0,<7.0",
29
+ "packaging>=24.0,<27.0",
30
+ "psycopg[binary]>=3.2",
31
+ "alembic>=1.14",
32
+ "pymysql>=1.1",
33
+ ]
34
+
35
+ [[project.authors]]
36
+ name = "Dat Giang"
37
+ email = "datgs@users.noreply.github.com"
38
+
39
+ [dependency-groups]
40
+ dev = [
41
+ "asgiref>=3.13.0",
42
+ "fastapi>=0.165.0",
43
+ "flask>=3.1.3",
44
+ "httpx>=0.29.0",
45
+ "keelflow>=0.1.0a3",
46
+ "pytest>=8.0,<9.0",
47
+ "ruff>=0.11,<1.0",
48
+ "uvicorn>=0.55.0",
49
+ ]
50
+
51
+ [tool.pytest.ini_options]
52
+ testpaths = ["tests"]
53
+
54
+ [tool.ruff]
55
+ line-length = 100
56
+ target-version = "py312"
57
+ extend-exclude = [
58
+ ".agents",
59
+ ".harness-core",
60
+ "**/generated",
61
+ "examples/**/migrations",
62
+ ]
63
+
64
+ [tool.ruff.lint]
65
+ select = [
66
+ "E",
67
+ "F",
68
+ "I",
69
+ "UP",
70
+ ]
71
+
72
+ [tool.uv.build-backend]
73
+ module-name = [
74
+ "keelmodel",
75
+ "keelpolicy",
76
+ "keeliam",
77
+ ]
78
+
79
+ [tool.uv.sources.keelflow]
80
+ path = "../keelflow"
81
+
82
+ [build-system]
83
+ requires = ["uv_build>=0.11.19,<0.12.0"]
84
+ build-backend = "uv_build"