korbase 0.1.0a1__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 (79) hide show
  1. korbase-0.1.0a1/.agents/skills/korbase/SKILL.md +228 -0
  2. korbase-0.1.0a1/.github/workflows/ci.yml +76 -0
  3. korbase-0.1.0a1/.github/workflows/docs.yml +52 -0
  4. korbase-0.1.0a1/.github/workflows/release.yml +83 -0
  5. korbase-0.1.0a1/.gitignore +9 -0
  6. korbase-0.1.0a1/AGENTS.md +47 -0
  7. korbase-0.1.0a1/CHANGELOG.md +36 -0
  8. korbase-0.1.0a1/CLAUDE.md +1 -0
  9. korbase-0.1.0a1/LICENSE +21 -0
  10. korbase-0.1.0a1/PKG-INFO +129 -0
  11. korbase-0.1.0a1/README.md +96 -0
  12. korbase-0.1.0a1/docs/ai.md +33 -0
  13. korbase-0.1.0a1/docs/glossary.md +153 -0
  14. korbase-0.1.0a1/docs/index.md +91 -0
  15. korbase-0.1.0a1/docs/korvex.md +79 -0
  16. korbase-0.1.0a1/docs/migrations.md +198 -0
  17. korbase-0.1.0a1/docs/models.md +184 -0
  18. korbase-0.1.0a1/docs/queries.md +330 -0
  19. korbase-0.1.0a1/docs/reference/korbase.md +3 -0
  20. korbase-0.1.0a1/docs/reference/korvex.md +3 -0
  21. korbase-0.1.0a1/docs/reference/migrate.md +3 -0
  22. korbase-0.1.0a1/docs/relations.md +142 -0
  23. korbase-0.1.0a1/docs/sqlite.md +144 -0
  24. korbase-0.1.0a1/docs/testing.md +120 -0
  25. korbase-0.1.0a1/docs/transactions.md +139 -0
  26. korbase-0.1.0a1/docs/tutorial.md +442 -0
  27. korbase-0.1.0a1/korbase/__init__.py +50 -0
  28. korbase-0.1.0a1/korbase/_asyncpg.py +91 -0
  29. korbase-0.1.0a1/korbase/_backend.py +80 -0
  30. korbase-0.1.0a1/korbase/_build.py +189 -0
  31. korbase-0.1.0a1/korbase/_db.py +252 -0
  32. korbase-0.1.0a1/korbase/_ddl.py +203 -0
  33. korbase-0.1.0a1/korbase/_dialect.py +189 -0
  34. korbase-0.1.0a1/korbase/_diff.py +382 -0
  35. korbase-0.1.0a1/korbase/_expr.py +371 -0
  36. korbase-0.1.0a1/korbase/_ident.py +30 -0
  37. korbase-0.1.0a1/korbase/_inspect.py +94 -0
  38. korbase-0.1.0a1/korbase/_inspect_sqlite.py +131 -0
  39. korbase-0.1.0a1/korbase/_meta.py +403 -0
  40. korbase-0.1.0a1/korbase/_query.py +382 -0
  41. korbase-0.1.0a1/korbase/_relations.py +101 -0
  42. korbase-0.1.0a1/korbase/_runner.py +228 -0
  43. korbase-0.1.0a1/korbase/_schema.py +58 -0
  44. korbase-0.1.0a1/korbase/_skill/SKILL.md +228 -0
  45. korbase-0.1.0a1/korbase/_sqlite.py +285 -0
  46. korbase-0.1.0a1/korbase/korvex.py +54 -0
  47. korbase-0.1.0a1/korbase/migrate.py +228 -0
  48. korbase-0.1.0a1/korbase/py.typed +0 -0
  49. korbase-0.1.0a1/korbase/stubs.py +196 -0
  50. korbase-0.1.0a1/mkdocs.yml +99 -0
  51. korbase-0.1.0a1/pyproject.toml +81 -0
  52. korbase-0.1.0a1/tests/conftest.py +35 -0
  53. korbase-0.1.0a1/tests/pg/start.sh +39 -0
  54. korbase-0.1.0a1/tests/test_agent_skill.py +69 -0
  55. korbase-0.1.0a1/tests/test_apply.py +271 -0
  56. korbase-0.1.0a1/tests/test_build.py +241 -0
  57. korbase-0.1.0a1/tests/test_compile.py +282 -0
  58. korbase-0.1.0a1/tests/test_db.py +370 -0
  59. korbase-0.1.0a1/tests/test_ddl.py +347 -0
  60. korbase-0.1.0a1/tests/test_dialect.py +160 -0
  61. korbase-0.1.0a1/tests/test_diff.py +312 -0
  62. korbase-0.1.0a1/tests/test_docs_snippets.py +33 -0
  63. korbase-0.1.0a1/tests/test_docs_tutorial.py +83 -0
  64. korbase-0.1.0a1/tests/test_expr.py +122 -0
  65. korbase-0.1.0a1/tests/test_inspect.py +107 -0
  66. korbase-0.1.0a1/tests/test_inspect_sqlite.py +82 -0
  67. korbase-0.1.0a1/tests/test_korvex.py +70 -0
  68. korbase-0.1.0a1/tests/test_meta.py +301 -0
  69. korbase-0.1.0a1/tests/test_migrate.py +308 -0
  70. korbase-0.1.0a1/tests/test_relations.py +284 -0
  71. korbase-0.1.0a1/tests/test_smoke.py +7 -0
  72. korbase-0.1.0a1/tests/test_sqlite_backend.py +238 -0
  73. korbase-0.1.0a1/tests/test_sqlite_concurrency.py +126 -0
  74. korbase-0.1.0a1/tests/test_stubs.py +138 -0
  75. korbase-0.1.0a1/tests/typecheck/columns.py +32 -0
  76. korbase-0.1.0a1/tests/typecheck/gen_models.py +29 -0
  77. korbase-0.1.0a1/tests/typecheck/gen_models_check.py +17 -0
  78. korbase-0.1.0a1/tests/typecheck/gen_models_cols.py +40 -0
  79. korbase-0.1.0a1/uv.lock +1612 -0
@@ -0,0 +1,228 @@
1
+ ---
2
+ name: korbase
3
+ description: Write Postgres data access with korbase, the async ORM built the Korvex way. Use when code imports korbase, or when asked to add models, queries, relations or migrations to a Korvex app.
4
+ ---
5
+
6
+ # korbase
7
+
8
+ korbase is an async Postgres layer: models are plain classes, queries are
9
+ immutable builders you define once and run with parameters. Python 3.10 or
10
+ later. The API can change before 1.0: check `korbase.__version__`.
11
+
12
+ Install with `pip install korbase[asyncpg] msgspec`. Add the `korvex`
13
+ extra to use it inside a Korvex app.
14
+
15
+ ## Models
16
+
17
+ A model is a msgspec `Struct`, a dataclass or a `TypedDict`, decorated with
18
+ `@table`. Markers go in `Annotated`: `PK()`, `FK("users.id")`, `Unique()`,
19
+ `Default(0)` or `Default(sql="now()")`, `SqlType("varchar(80)")`. Table
20
+ options: `@table("name", indexes=(Index("a", "b", unique=True),))`. A
21
+ single integer `PK()` is an identity column. `Optional[X]` means nullable.
22
+
23
+ ```python
24
+ from typing import Annotated, Optional
25
+
26
+ import msgspec
27
+
28
+ from korbase import FK, PK, Rel, Unique, table
29
+
30
+
31
+ @table("authors")
32
+ class Author(msgspec.Struct):
33
+ id: Annotated[int, PK()]
34
+ name: Annotated[str, Unique()]
35
+ books: Annotated[list["Book"], Rel("author_id")] = msgspec.field(default_factory=list)
36
+
37
+
38
+ @table("books")
39
+ class Book(msgspec.Struct):
40
+ id: Annotated[int, PK()]
41
+ author_id: Annotated[int, FK("authors.id")]
42
+ title: str
43
+ ```
44
+
45
+ A `Rel("fk_field")` field is not a column: it holds related rows filled by
46
+ `.load(...)`. Put `Rel` on the side that names the foreign key column.
47
+
48
+ ## Queries
49
+
50
+ Build queries at module level, once. `cols(Model)` gives columns,
51
+ `param("x")` a named parameter filled at run time. Combine conditions with
52
+ `&`, `|`, `~`. `.where(*conditions, **equals)` ANDs several conditions and
53
+ `column=value` pairs; a plain value is fine when it is fixed, and a keyword
54
+ set to `None` means `IS NULL`.
55
+
56
+ ```python
57
+ from korbase import cols, delete, insert, param, select, update, upsert
58
+
59
+ b = cols(Book)
60
+ BY_AUTHOR = select(Book).where(b.title != "", author_id=param("a")).order_by(b.id.asc()).limit(10)
61
+ NEW_BOOK = insert(Book).values(title=param("t"), author_id=param("a"))
62
+ RETITLE = update(Book).set(title=param("t")).where(id=param("id"))
63
+ UNTITLED = delete(Book).where(b.title.is_null() | (b.title == ""))
64
+ ```
65
+
66
+ For editor and type-checker help, generate typed columns:
67
+ `python -m korbase.stubs app.models -o app/columns.py`, then
68
+ `from app.columns import cols`. `cols(Book).title` is a `Column[str]`, a
69
+ typo like `.titel` or `cols(Book).id == "3"` is a type error, and `like`
70
+ and `ilike` only accept `str` columns. It is the same object at runtime.
71
+ Rerun the command after every model change; add `--check` to CI (exit 1 if
72
+ the file is stale). Keyword filters `.where(title=...)` are checked at
73
+ runtime only.
74
+
75
+ Also `.offset()`, `like`, `ilike`, `in_`, `is_not_null`, `.desc()`.
76
+ `upsert(M).on_conflict("col").values(...)` updates the other columns on a
77
+ clash. Guards: `update` and `delete` raise without `.where(...)` unless you
78
+ call `.all_rows()`; `insert` and `upsert` need `.values(...)`.
79
+
80
+ ## Running
81
+
82
+ ```python
83
+ db = await Database.connect(dsn) # a pool; `async with` closes it
84
+ books = await db.run(BY_AUTHOR, a=1) # select: list[Book]
85
+ [book] = await db.run(NEW_BOOK, t="Dune", a=1) # insert/upsert: the new rows
86
+ one = await db.first(BY_AUTHOR, a=1) # first row or None
87
+ n = await db.run(RETITLE, t="Dune II", id=1) # update/delete: an int row count
88
+ gone = await db.run(delete(Book).where(id=1).returning()) # rows instead of a count
89
+ ```
90
+
91
+ `run` and `first` take parameters as keywords. Results are typed by the
92
+ model. `insert` and `upsert` always return rows. `update` and `delete`
93
+ return the number of rows changed; add `.returning()` to get the rows
94
+ (`first` needs it too). A `param` compared with `==`, `!=` or `in_()` cannot
95
+ be `None`: `run` raises. Use `.where(col=None)` or `.is_null()`.
96
+
97
+ ## Relations
98
+
99
+ `select(Author).load(cols(Author).books)` runs one extra query per
100
+ relation (not one per row) and fills the field. Loads work both ways
101
+ (one-to-many and many-to-one), on `first` too, and inside transactions.
102
+ Composite primary keys are not supported by `.load`.
103
+
104
+ ## Transactions and raw SQL
105
+
106
+ ```python
107
+ async with db.transaction() as tx: # commits, or rolls back on an exception
108
+ await tx.run(NEW_BOOK, t="A", a=1)
109
+ ```
110
+
111
+ `tx` has the same `run`, `first`, `fetch`, `fetchrow`, `execute` as `db`.
112
+ Raw SQL: `await db.fetch("SELECT ... WHERE x = $1", 5, model=Book)` maps
113
+ columns to the model by name; without `model` rows are tuples. Always pass
114
+ values as `$1` arguments, never format them into the string.
115
+
116
+ ## Migrations
117
+
118
+ `create_all(db, models)` (from `korbase.migrate`) creates tables: use it in
119
+ tests. For real databases use files:
120
+
121
+ 1. `KORBASE_DSN=... python -m korbase.migrate make --models app.models --dir migrations -m add_books`
122
+ compares the models' tables with the database and writes
123
+ `0001_add_books.sql`. Other tables are ignored; add `--all-tables` to
124
+ compare the whole schema, which is the only way to drop the table of a
125
+ removed model.
126
+ 2. Review the file. Lines `-- korbase:review ...` flag dangerous changes
127
+ (dropped data, new NOT NULL). Edit the SQL if needed, then delete each
128
+ review line once you have read it: `apply` refuses files that keep one.
129
+ 3. `python -m korbase.migrate apply --dir migrations` runs pending files;
130
+ `status` lists them.
131
+
132
+ For local work, `python -m korbase.migrate dev --models app.models --dir
133
+ migrations` runs make then apply in one step (stops on a review line).
134
+ Never use it on production.
135
+
136
+ Never edit or delete an applied file: `apply` refuses a changed one. Fix
137
+ mistakes with a new migration. Prefer `KORBASE_DSN` to `--dsn` (visible in
138
+ `ps`).
139
+
140
+ ## Korvex
141
+
142
+ ```python
143
+ from korvex import App, Depends
144
+
145
+ from korbase.korvex import install
146
+
147
+ app = App()
148
+ kdb = install(app, "postgresql://user:pass@localhost/db") # opens/closes the pool
149
+
150
+
151
+ @app.get("/books/{id}")
152
+ async def get_book(id: int, tx=Depends(kdb.transaction)):
153
+ return await tx.first(select(Book).where(cols(Book).id == param("i")), i=id)
154
+ ```
155
+
156
+ `Depends(kdb.database)` gives the `Database`; `Depends(kdb.transaction)` a
157
+ `Transaction` per request, committed unless the handler raises.
158
+
159
+ ## SQLite
160
+
161
+ `Database.connect("sqlite:///app.db")` (or `"sqlite::memory:"`, one
162
+ connection only) uses the standard library: nothing to install, SQLite
163
+ 3.35 or later. Models, queries and migrations are the same. Differences:
164
+
165
+ - Raw SQL takes `?` placeholders, not `$1`, and returns stored values:
166
+ `1` for `True`, text for UUID, Decimal and dates (UTC datetimes), JSON
167
+ text for dict and list. Pass `model=` to get Python types back.
168
+ - `ilike` ignores case for ASCII letters only. One writer at a time:
169
+ `db.transaction()` is `BEGIN IMMEDIATE`; a busy file raises
170
+ `sqlite3.OperationalError: database is locked` after `busy_timeout_ms`.
171
+ - `migrate make` cannot alter a type, nullability, default or key in place:
172
+ it writes a `-- korbase:review` block with `-- intended:`. Replace it with a
173
+ table rebuild (new table, copy, drop, rename), see `docs/sqlite.md`.
174
+ - Not in the builder yet: partial indexes, aggregates. Use raw SQL.
175
+
176
+ ## Common mistakes
177
+
178
+ - `and` / `or` / `not` on conditions: they raise. Use `&`, `|`, `~`, and
179
+ parenthesize each side.
180
+ - `col == None`: use `col.is_null()`. A `None` given to a `param` compared
181
+ with `==` raises: use `.where(col=None)`.
182
+ - `update` and `delete` return a count (an `int`), not rows: add
183
+ `.returning()` when you need the rows. `insert` and `upsert` have no
184
+ `.returning()`; they always return rows.
185
+ - Expecting `make` to drop a removed model's table: it only diffs the
186
+ models' tables; use `--all-tables`.
187
+ - Changing a model and not rerunning `python -m korbase.stubs`: the
188
+ generated `cols` is then out of date and the type checker flags (or
189
+ misses) the wrong fields. Add `--check` to CI.
190
+ - Building queries inside a hot loop or handler: build once at module level.
191
+ - Editing an applied migration, or applying one with a review line left.
192
+ - Formatting values into raw SQL: pass `$1` arguments.
193
+
194
+ ## A complete script
195
+
196
+ ```python
197
+ import asyncio
198
+ import os
199
+
200
+ from korbase import Database, cols, insert, param, select
201
+ from korbase.migrate import create_all
202
+
203
+ b = cols(Book)
204
+ ADD_AUTHOR = insert(Author).values(name=param("n"))
205
+ ADD_BOOK = insert(Book).values(title=param("t"), author_id=param("a"))
206
+ AUTHORS = select(Author).order_by(cols(Author).id.asc()).load(cols(Author).books)
207
+
208
+
209
+ async def main(dsn: str) -> list[Author]:
210
+ async with await Database.connect(dsn) as db:
211
+ await create_all(db, [Author, Book])
212
+ async with db.transaction() as tx:
213
+ ada = await tx.first(ADD_AUTHOR, n="Ada")
214
+ await tx.run(ADD_BOOK, t="Notes", a=ada.id)
215
+ return await db.run(AUTHORS)
216
+
217
+
218
+ if __name__ == "__main__":
219
+ print(asyncio.run(main(os.environ["KORBASE_DSN"])))
220
+ ```
221
+
222
+ Its check:
223
+
224
+ ```python
225
+ def test_script(dsn):
226
+ [ada] = asyncio.run(main(dsn))
227
+ assert ada.name == "Ada" and [x.title for x in ada.books] == ["Notes"]
228
+ ```
@@ -0,0 +1,76 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ permissions:
9
+ contents: read
10
+
11
+ # A new push to a pull request stops the run of the one before.
12
+ concurrency:
13
+ group: ci-${{ github.ref }}
14
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
15
+
16
+ jobs:
17
+ lint:
18
+ name: Lint and types
19
+ runs-on: ubuntu-latest
20
+ timeout-minutes: 20
21
+ steps:
22
+ - uses: actions/checkout@v7
23
+
24
+ - name: Install uv
25
+ uses: astral-sh/setup-uv@v10.3.3
26
+
27
+ - name: Install
28
+ run: uv sync
29
+
30
+ - name: Ruff
31
+ run: uv run --no-sync ruff check --output-format=github .
32
+
33
+ - name: Python formatting
34
+ run: uv run --no-sync ruff format --check .
35
+
36
+ - name: Pyright
37
+ run: uv run --no-sync pyright
38
+
39
+ test:
40
+ name: Python ${{ matrix.python }}
41
+ runs-on: ubuntu-latest
42
+ timeout-minutes: 30
43
+ strategy:
44
+ fail-fast: false
45
+ matrix:
46
+ python: ["3.10", "3.11", "3.12", "3.13", "3.14", "3.14t"]
47
+ steps:
48
+ - uses: actions/checkout@v7
49
+
50
+ - name: Start Postgres
51
+ run: bash tests/pg/start.sh
52
+
53
+ - name: Install uv
54
+ uses: astral-sh/setup-uv@v10.3.3
55
+
56
+ - name: Install
57
+ run: uv sync --python ${{ matrix.python }}
58
+
59
+ # On 3.14t, -W error::RuntimeWarning fails the run if any module
60
+ # turns the GIL back on, which would undo the point.
61
+ - name: Tests
62
+ run: uv run --no-sync pytest ${{ endsWith(matrix.python, 't') && '-W error::RuntimeWarning' || '' }}
63
+
64
+ docs:
65
+ name: Documentation
66
+ runs-on: ubuntu-latest
67
+ timeout-minutes: 20
68
+ steps:
69
+ - uses: actions/checkout@v7
70
+
71
+ - name: Install uv
72
+ uses: astral-sh/setup-uv@v10.3.3
73
+
74
+ # Builds the site with strict checks; the repo is private, so nothing is deployed.
75
+ - name: Build the docs
76
+ run: uv run --group docs mkdocs build --strict -d site
@@ -0,0 +1,52 @@
1
+ name: Docs
2
+
3
+ # Builds the documentation site on every pull request (a broken link or
4
+ # reference fails it), and publishes it to GitHub Pages from main.
5
+ # The reference is read from the source.
6
+
7
+ on:
8
+ push:
9
+ branches: [main]
10
+ pull_request:
11
+
12
+ permissions:
13
+ contents: read
14
+
15
+ concurrency:
16
+ group: docs-${{ github.ref }}
17
+ cancel-in-progress: true
18
+
19
+ jobs:
20
+ build:
21
+ runs-on: ubuntu-latest
22
+ timeout-minutes: 10
23
+ steps:
24
+ - uses: actions/checkout@v7
25
+
26
+ - name: Install uv
27
+ uses: astral-sh/setup-uv@v10.3.3
28
+
29
+ - name: Build
30
+ env:
31
+ NO_MKDOCS_2_WARNING: "1"
32
+ run: uv run --python 3.13 --group docs mkdocs build --strict -d site
33
+
34
+ - name: Upload
35
+ if: github.event_name == 'push'
36
+ uses: actions/upload-pages-artifact@v5.0.0
37
+ with:
38
+ path: site
39
+
40
+ deploy:
41
+ if: github.event_name == 'push'
42
+ needs: build
43
+ runs-on: ubuntu-latest
44
+ permissions:
45
+ pages: write
46
+ id-token: write
47
+ environment:
48
+ name: github-pages
49
+ url: ${{ steps.deployment.outputs.page_url }}
50
+ steps:
51
+ - id: deployment
52
+ uses: actions/deploy-pages@v5.0.1
@@ -0,0 +1,83 @@
1
+ # On a `v*` tag: build the sdist and wheel, check the tag matches the
2
+ # version, smoke-test the wheel in a fresh venv, then publish to PyPI.
3
+ # Run by hand (workflow_dispatch) to build and test without publishing.
4
+ name: Release
5
+
6
+ on:
7
+ push:
8
+ tags:
9
+ - "v*"
10
+ workflow_dispatch:
11
+
12
+ permissions:
13
+ contents: read
14
+
15
+ jobs:
16
+ build:
17
+ runs-on: ubuntu-latest
18
+ timeout-minutes: 15
19
+ steps:
20
+ - uses: actions/checkout@v7
21
+ - uses: astral-sh/setup-uv@v10.3.3
22
+ - name: Check the tag matches the version
23
+ if: startsWith(github.ref, 'refs/tags/')
24
+ run: |
25
+ version=$(python3 -c "import tomllib;print(tomllib.load(open('pyproject.toml','rb'))['project']['version'])")
26
+ test "v$version" = "${GITHUB_REF_NAME}" || { echo "tag ${GITHUB_REF_NAME} != v$version"; exit 1; }
27
+ - run: uv build
28
+ - uses: actions/upload-artifact@v7
29
+ with:
30
+ name: dist
31
+ path: dist
32
+
33
+ smoke:
34
+ needs: build
35
+ runs-on: ubuntu-latest
36
+ timeout-minutes: 10
37
+ strategy:
38
+ matrix:
39
+ python: ["3.10", "3.14"]
40
+ steps:
41
+ - uses: astral-sh/setup-uv@v10.3.3
42
+ - uses: actions/download-artifact@v8
43
+ with:
44
+ name: dist
45
+ path: dist
46
+ - name: Install the wheel and run a SQLite smoke test
47
+ run: |
48
+ uv venv --python ${{ matrix.python }} /tmp/venv
49
+ uv pip install --python /tmp/venv/bin/python dist/*.whl
50
+ cat > /tmp/smoke.py <<'PY'
51
+ import asyncio
52
+ from korbase import Database
53
+
54
+ async def main():
55
+ db = await Database.connect("sqlite::memory:")
56
+ await db.execute("CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT)")
57
+ await db.execute("INSERT INTO t (name) VALUES ('a')")
58
+ rows = await db.fetch("SELECT name FROM t")
59
+ assert len(rows) == 1, rows
60
+ print(rows)
61
+
62
+ asyncio.run(main())
63
+ PY
64
+ /tmp/venv/bin/python -I /tmp/smoke.py
65
+
66
+ publish:
67
+ name: Publish to PyPI
68
+ runs-on: ubuntu-latest
69
+ timeout-minutes: 10
70
+ if: startsWith(github.ref, 'refs/tags/')
71
+ needs: [build, smoke]
72
+ environment: pypi
73
+ permissions:
74
+ id-token: write # PyPI trusted publishing
75
+ steps:
76
+ - uses: actions/download-artifact@v8
77
+ with:
78
+ name: dist
79
+ path: dist
80
+ - name: Publish to PyPI
81
+ uses: pypa/gh-action-pypi-publish@release/v1
82
+ with:
83
+ packages-dir: dist
@@ -0,0 +1,9 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ build/
6
+ dist/
7
+ .pytest_cache/
8
+ .ruff_cache/
9
+ .pyright/
@@ -0,0 +1,47 @@
1
+ # Working on korbase
2
+
3
+ Instructions for AI coding agents working on this repository.
4
+
5
+ korbase is an async ORM for Postgres, with SQLite to come. It is pure
6
+ Python. Models are msgspec Structs, dataclasses or TypedDicts. It runs on
7
+ korpg or asyncpg, and has an optional Korvex integration.
8
+
9
+ ## Setup and checks
10
+
11
+ ```sh
12
+ uv sync # Python, the tools, and the dependencies
13
+ ```
14
+
15
+ Before saying a change is done, run what CI runs:
16
+
17
+ ```sh
18
+ uv run ruff check . && uv run ruff format .
19
+ uv run pyright
20
+ uv run pytest
21
+ ```
22
+
23
+ Tests need a Postgres server, named by the `KORBASE_TEST_DSN` environment
24
+ variable. To start one, run `bash tests/pg/start.sh`. It starts Postgres 18 in
25
+ Docker on port 55433 and prints the export line:
26
+
27
+ ```sh
28
+ eval "$(bash tests/pg/start.sh | grep '^export')"
29
+ ```
30
+
31
+ Async tests call `asyncio.run` inside a plain test function. Do not add
32
+ pytest-asyncio.
33
+
34
+ ## Rules
35
+
36
+ - **Python 3.10 and later.** Write `X | Y` only in annotations, with
37
+ `from __future__ import annotations` at the top of the module. Use
38
+ `Union[X, Y]` and `Optional[X]` elsewhere.
39
+ - **msgspec and pydantic are optional.** Import them lazily, only where
40
+ a model of that kind is used, never at the top of a module.
41
+ - **Pure Python.** Do not add a compiled dependency to korbase itself.
42
+ - **Before 1.0, break the API directly**: no deprecation shims. Every
43
+ change goes in `CHANGELOG.md` under `## Unreleased`, with how to update.
44
+ - **New behavior needs a test.**
45
+ - **Docstrings are documentation.** Write them for users, in plain English.
46
+ - **Code, comments, docs and commit messages are in English.** Commits
47
+ follow Conventional Commits (`feat:`, `fix:`, `docs:`, `perf:`...).
@@ -0,0 +1,36 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0a1
4
+
5
+ First alpha: models, typed queries, relations, transactions, migrations, Postgres and SQLite, Korvex integration.
6
+
7
+ - Project skeleton.
8
+ - Models: `@table` on msgspec Structs, dataclasses and TypedDicts, with `PK`, `FK`, `Unique`, `Default`, `Index` and `Rel` markers. No upgrade needed, since there was no API before.
9
+ - Queries: `select`, `insert`, `update`, `delete` and `upsert` builders, compiled to SQL with `$n` placeholders. Columns come from `cols(Model).field`.
10
+ - `Database` and `Transaction` with `run`, `first`, `fetch`, `fetchrow`, `execute` and `transaction()` (a nested transaction is a savepoint). The asyncpg backend is installed with `korbase[asyncpg]`.
11
+ - `.load(...)` for one-to-many and many-to-one relations, one extra query per relation.
12
+ - Korvex integration: `korbase.korvex.install(app, dsn)`, with `Depends(kdb.database)` and `Depends(kdb.transaction)`.
13
+ - Migrations: `python -m korbase.migrate make|apply|status` and `korbase.migrate.make/apply/status/create_all`. `make` diffs the models against the live schema and writes a numbered SQL file to review; risky statements carry `-- korbase:review`, which `apply` refuses until removed. `apply` checks checksums and order, takes an advisory lock and runs each file in its own transaction.
14
+ - New markers for migrations: `SqlType`, `PK(identity=...)`, `FK(..., on_delete=...)`, `Default(sql=...)`.
15
+ - Documentation site (MkDocs): tutorial, guide, glossary, API reference, and an agent skill shipped in the package.
16
+
17
+ ### Changed (breaking)
18
+
19
+ - `insert` and `upsert` always return the rows they wrote, and have no `.returning()`. To update: delete `.returning()` from every `insert(...)` and `upsert(...)`; `run` gives a list and `first` gives the row.
20
+ - `run` on an `update` or a `delete` returns the number of rows changed, an `int`, not the command tag such as `"UPDATE 1"`. To update: use the number, for example `if await db.run(q) == 0`, or add `.returning()` to get the rows as a list. `first` on an `update` or `delete` still needs `.returning()`.
21
+ - A `None` given to a `param` that is compared with `==`, `!=` or `in_()` now raises `KorbaseError`, where it used to match nothing. To update: use `.where(column=None)` or `column.is_null()` when you mean NULL, and check the value before you run the query when it may be absent.
22
+ - `make` only compares the tables of the models you pass, so other tables in `public` are no longer reported as drops. To update: nothing, unless you relied on `make` to drop the table of a removed model. Run `make --all-tables` (or `make(..., all_tables=True)`) for that, then keep only the `DROP TABLE` lines you want.
23
+
24
+ ### Added
25
+
26
+ - `.where(*conditions, **equals)` on `select`, `update` and `delete`: several conditions in one call, and `column=value` pairs, which accept a plain value or a `param`. A keyword set to `None` means `IS NULL`.
27
+ - `python -m korbase.migrate dev` and `korbase.migrate.dev(db, models, directory, message)`: `make` then `apply` in one step, for local work. It stops and applies nothing when the new file holds a `-- korbase:review` line.
28
+ - Typed results: `select`, `insert`, `upsert`, `update` and `delete` are generic over the model, so `run` is typed as `list[Model]` or `int`, and `first` as `Model | None`. `fetch` and `fetchrow` with `model=` are typed the same way.
29
+ - `python -m korbase.stubs <models.module> -o <file>` generates a module with a typed `cols()`: `cols(Post).title` is a `Column[str]` and `cols(Post).titel` is a type error. At runtime it is the same object as `korbase.cols`. Rerun it after changing models; `--check` exits 1 if the file is out of date, for CI.
30
+ - Column operators are typed: `like` and `ilike` only on `str` columns, and `<`, `==` and `in_()` take values of the column type. Keyword filters such as `.where(title=...)` are still checked at runtime only.
31
+ - `@table` keeps the class type, so `run(select(Post))` is `list[Post]` for the type checker.
32
+ - SQLite backend on the standard library `sqlite3` (SQLite 3.35 or later): `Database.connect("sqlite:///app.db")` or `"sqlite::memory:"`, with `size=` and `busy_timeout_ms=`. WAL, foreign keys and a busy timeout are set on each connection; transactions use `BEGIN IMMEDIATE`, so one process writes at a time. Migrations work on SQLite, but it cannot alter a column type, nullability, default, primary key, unique constraint or foreign key in place: `make` writes a `-- korbase:review` block with the intended change, and you write the table rebuild by hand (see `docs/sqlite.md`). Limits: `sqlite::memory:` uses one connection; `ilike` only ignores case for ASCII letters; raw SQL uses `?` placeholders and returns stored values (`1` for `True`, text for dates and decimals); partial indexes and aggregates are not in the builder yet. No upgrade needed.
33
+
34
+ ### Changed (typing only)
35
+
36
+ - Comparing a typed column with a value of another type, such as `Column[int] == "3"`, is now a type error. Nothing changes at runtime. To update: fix the value or the column, or add `# type: ignore` where it is on purpose.
@@ -0,0 +1 @@
1
+ @AGENTS.md
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 3d3n-pyc
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.