Skip to content

[kyo-sql] raw and typed queries on the async network stack - #1833

Merged
fwbrasil merged 7 commits into
mainfrom
kyo-sql
Aug 4, 2026
Merged

fwbrasil merged 7 commits into
mainfrom
kyo-sql

Conversation

@fwbrasil

@fwbrasil fwbrasil commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator

Problem

Kyo had no first-party SQL access. Reaching a database meant a JDBC driver and a blocking connection pool bolted onto the side of the effect system: a statement blocked a carrier thread, the dependency on a database was invisible in the type, and none of it worked on Scala.js, Native, or Wasm.

Solution

A new SQL module. A statement is written either as raw SQL or as a typed query; both build the same AST and run through the same execution path, so a raw fragment embeds in a typed query and a typed query embeds in raw SQL. Every driver implements its server's wire protocol directly on Kyo's async network stack, with no JDBC underneath: a statement suspends a fiber rather than blocking a thread, and the whole implementation, protocols included, is one set of shared sources compiled for the JVM, Scala.js, Scala Native, and Wasm.

  • kyo-sql: the backend-agnostic core. The sql"..." interpolator, the typed DSL (Sql.from[T], joins, grouping, aggregates, set operations, CTEs, window functions, inserts/updates/deletes with upsert and RETURNING), the DB effect that makes the database a typed dependency, SqlSchema row/column evidence, the connection pool over kyo-net, transactions and savepoints, advisory locks, and streaming. SQL text is produced at compile time through ordinary Scala 3 inlining where the query's shape allows (.run), required (.runStatic), or deferred to run time (.runDynamic); a folded statement lands in the artifact as a constant and renders once per driver on the compile classpath.
  • kyo-sql-postgres, kyo-sql-mysql: the two shipped drivers, each a direct wire implementation exposing its engine's own capabilities (Postgres COPY and LISTEN/NOTIFY, MySQL LOAD DATA LOCAL INFILE) alongside the portable surface. An engine kyo-sql does not ship plugs in through db.Backend; the URL scheme selects among the drivers a build depends on.
  • kyo-sql-tests: the cross-backend conformance suites, run against real Postgres and MySQL containers.

Supporting changes in existing modules:

  • kyo-core: SecureRandom, a first-class cryptographically secure random capability (nonces, seeds), mirroring Random's ambient/let-scoped design, with per-platform sources (JDK provider, /dev/urandom or BCryptGenRandom on Native, Web Crypto on JS/Wasm); UUID generation and the off-JVM java.security.SecureRandom shim draw from it. Random's default nextBytes now fills the full byte range.
  • kyo-net: the connection pool is generalized and lifted out of kyo-http into kyo.net.internal so both HTTP and SQL clients share it.
  • kyo-data: name-aware record staging (Record.stageNamed, Fields.MapNamed, selectDynamic via Fields.Have) the typed DSL keys on, and Span.constantTimeEquals for credential comparison.
  • kyo-pod: container descriptors the SQL conformance suites run against, and a shell-backend detection fix.

Notes

  • All four platforms build; the conformance suites pass against real Postgres and MySQL.
  • The two drivers are ordinary dependencies of kyo-sql, not privileged: nothing in the core names an engine, and a third-party backend registers the same way the shipped two do.

…ork stack

## Problem

Kyo had no first-party SQL access. Reaching a database meant a JDBC driver
and a blocking connection pool bolted onto the side of the effect system:
a statement blocked a carrier thread, the dependency on a database was
invisible in the type, and none of it worked on Scala.js, Native, or Wasm.

## Solution

A new SQL module. A statement is written either as raw SQL or as a typed
query; both build the same AST and run through the same execution path, so a
raw fragment embeds in a typed query and a typed query embeds in raw SQL.
Every driver implements its server's wire protocol directly on Kyo's async
network stack, with no JDBC underneath: a statement suspends a fiber rather
than blocking a thread, and the whole implementation, protocols included, is
one set of shared sources compiled for the JVM, Scala.js, Scala Native, and
Wasm.

- **kyo-sql**: the backend-agnostic core. The `sql"..."` interpolator, the
  typed DSL (`Sql.from[T]`, joins, grouping, aggregates, set operations,
  CTEs, window functions, inserts/updates/deletes with upsert and
  RETURNING), the `DB` effect that makes the database a typed dependency,
  `SqlSchema` row/column evidence, the connection pool over kyo-net,
  transactions and savepoints, advisory locks, and streaming. SQL text is
  produced at compile time through ordinary Scala 3 inlining where the
  query's shape allows (`.run`), required (`.runStatic`), or deferred to
  run time (`.runDynamic`); a folded statement lands in the artifact as a
  constant and renders once per driver on the compile classpath.
- **kyo-sql-postgres**, **kyo-sql-mysql**: the two shipped drivers, each a
  direct wire implementation exposing its engine's own capabilities (Postgres
  COPY and LISTEN/NOTIFY, MySQL LOAD DATA LOCAL INFILE) alongside the
  portable surface. An engine kyo-sql does not ship plugs in through
  `db.Backend`; the URL scheme selects among the drivers a build depends on.
- **kyo-sql-tests**: the cross-backend conformance suites, run against real
  Postgres and MySQL containers.

Supporting changes in existing modules:

- **kyo-core**: `SecureRandom`, a first-class cryptographically secure random
  capability (nonces, seeds), mirroring `Random`'s ambient/let-scoped design,
  with per-platform sources (JDK provider, `/dev/urandom` or `BCryptGenRandom`
  on Native, Web Crypto on JS/Wasm); UUID generation and the off-JVM
  `java.security.SecureRandom` shim draw from it. `Random`'s default
  `nextBytes` now fills the full byte range.
- **kyo-net**: the connection pool is generalized and lifted out of kyo-http
  into `kyo.net.internal` so both HTTP and SQL clients share it.
- **kyo-data**: name-aware record staging (`Record.stageNamed`,
  `Fields.MapNamed`, `selectDynamic` via `Fields.Have`) the typed DSL keys on,
  and `Span.constantTimeEquals` for credential comparison.
- **kyo-pod**: container descriptors the SQL conformance suites run against,
  and a shell-backend detection fix.

## Notes

- All four platforms build; the conformance suites pass against real Postgres
  and MySQL.
- The two drivers are ordinary dependencies of kyo-sql, not privileged:
  nothing in the core names an engine, and a third-party backend registers the
  same way the shipped two do.
fwbrasil and others added 6 commits August 2, 2026 20:11
The "a held lock excludes a concurrent session" leaf appended "holder-exit"
after withAdvisoryLock returned, i.e. after the lock was released. The
contender appends "contender-enter" only after it acquires, which is also
after that same release, so the two appends raced with no happens-before
between them. On MySQL the lock handoff is fast enough that the contender
occasionally won, producing [holder-enter, contender-enter, holder-exit] and
failing the strict-order assertion even though exclusion had in fact held.

Record "holder-exit" as the last step inside the locked body, before the
release, so it is causally ordered before the contender's post-acquire entry.
The leaf still fails if exclusion is genuinely broken, since contender-enter
would then land between the two holder markers.
Revert every change this PR made to existing Record surface back to main,
keeping only the additive named-staging APIs (stageNamed, StageNamedOps,
stageNamedLoop, MapNamedValue, Fields.MapNamed/HasName/IfHasName), which
no other module references:

- Record.selectDynamic: drop `inline` (back to a plain method)
- Record.~ : drop the `Name <: String & Singleton` narrowing (back to `String`)
- Field.get/set: drop the `N <: Name & String & Singleton` narrowing
- FieldsMacros.haveImpl: back to the first-match findValueType walk

Field.scala and FieldsMacros.scala are now byte-identical to main; Record.scala
and Fields.scala differ from main only by the additive APIs. MapNamedValue
carries its own `& Singleton` so it no longer depends on ~ enforcing it.

kyo-sql adaptation: Record.selectDynamic being `inline` was what let a column
projection (`c.p.age`) expand to `Dict.apply(<rec>.inline$dict, "key")`, the
shape ColumnFromExpr walks to lift a query for compile-time SQL (.runStatic).
With selectDynamic non-inline the projection stays a bare `selectDynamic("key")`
call, so teach ColumnFromExpr.projectChain to also collect keys from that shape.

Validated: kyo-data and kyo-sql/kyo-sql-tests compile; kyo-sqlJVM/test all pass,
including SqlGroupedViewTest FromExpr lifting and the .runStatic static-render
tests. Container conformance (Postgres/MySQL) not yet run.
The linux-arm64 Native job runs the whole-repo aggregate Native build (clang
codegen across ~50 modules) plus the test run in one job. On the slower arm64
runner this exceeds the 240m cap: the job was cancelled at exactly 4h, while
linux-x64 Native completes the same work in ~200m. Raise timeout-minutes to 360
(the GitHub-hosted per-job ceiling) so the arm64 pole finishes instead of timing
out. Every other pole finishes well inside 360m, so this only adds headroom.
@fwbrasil
fwbrasil merged commit 124a6df into main Aug 4, 2026
16 checks passed
@fwbrasil
fwbrasil deleted the kyo-sql branch August 4, 2026 09:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant