DBQC for Scala 3

Schema discovery generates typed row proxies. Scala's operators then become the SQL expression language while DBQC retains the relational dependency graph, orders CTEs, checks strata and SQL types, and targets every supported dialect.

import com.volvwealth.dbqc.api.*
import com.volvwealth.dbqc.impl.Compiler
import DbqcSchema.*

The ordinary case

val ids: Source = restaurants
   .where(_.city === "New York")
   .select(_.id)
val directory: Source = restaurants
   .where(r => r.city === "New York" && r.status === "active")
   .select(_.id, _.name)

=== is DBQC null-safe equality (IS NOT DISTINCT FROM). The compiler may emit = when nullability proves it equivalent. A wrong value type or misspelled generated field fails at Scala compile time.

Predicates and joins

val highValue: Source = restaurants
   .join(orders)((restaurant, order) =>
      restaurant.id === order.restaurantId
   )
   .where(_.right.total > BigDecimal("100.00"))
   .orderBy(_.right.total.desc)
   .select(_.left.name, _.right.total)

Scala uses native-looking ===, !==, <, <=, >, >=, &&, ||, and !. No public column or literal constructor appears in generated-table queries. Joined proxies expose .left and .right, which keeps same-named columns unambiguous.

Runtime parameters

val input = Dbqc.param[java.util.UUID]("restaurantId", SqlType.Uuid)

val byId: Source = restaurants
   .join(input)((restaurant, restaurantId) =>
      restaurant.id === restaurantId
   )
   .select(_.left.id, _.left.name)

val compiled = Compiler.compile(byId)

The compiled paramOrder determines driver binding order. DBQC never interpolates runtime values into SQL.

Aggregates and HAVING

val revenue: Source = orders
   .groupBy(_.restaurantId)
   .having(order => sum(order.total) > BigDecimal("0.00"))
   .select(
      _.restaurantId,
      order => sum(order.total).as("revenue"),
   )

Grouping columns retain their generated names. Only computed output needs .as(...). Scala's stratified expression types reject aggregates in WHERE and windows in predicates at compile time.

Reusable queries and CTE ordering

val revenue: Source = orders
   .groupBy(_.restaurantId)
   .select(
      _.restaurantId,
      order => sum(order.total).as("revenue"),
   )
   .as("revenue")

val revenueRestaurantId =
   revenue.col[java.util.UUID]("restaurant_id", SqlType.Uuid)
val revenueAmount =
   revenue.col[BigDecimal]("revenue", SqlType.Numeric(12, 2))

val ranked: Source = Restaurants.source
   .join(revenue)(Restaurants.id === revenueRestaurantId)
   .where(revenueAmount > BigDecimal("1000.00"))
   .select(
      "name" -> Restaurants.name,
      "revenue" -> revenueAmount,
   )

A newly computed heading is typed once; generated base tables remain zero-ceremony. DBQC derives the dependency DAG and emits CTEs in valid order.

Windows, JSON, and pagination

val feed: Source = orders
   .select(
      _.id,
      order => Dbqc.window(
         rowNumber,
         partitionBy = Vector(order.restaurantId),
         orderBy = Vector(order.createdAt.desc),
      ).as("number"),
   )
val contacts: Source = restaurants.select(
   _.id,
   restaurant =>
      restaurant.metadata.jsonPathText("$.contact.email").as("email"),
)

Use .page(limit, offset)(_.createdAt.desc) before projection when pagination is required.

Writes

The generated proxy also types assignments:

val created: Source = restaurants.insert(
   _.id := java.util.UUID.randomUUID(),
   _.name := "Saffron",
   _.city := "New York",
)

val moved: Source = restaurants.update(_.id === restaurantId)(
   _.city := "Brooklyn",
)

val removed: Source = restaurants.delete(_.status === "closed")

The explicit Dbqc overloads add returning columns, insert-from-select, update-from, conflict policies, locks, transactions, and procedures for their less-common shapes.

Recursive queries

Recursive output is dynamic, so its heading is declared once:

val seed: Source = roots.select(_.id, _.parentId)

val tree: Source = letRec("tree", seed)(
   self =>
      Nodes.source
         .join(self)(
            Nodes.parentId ===
               self.col[java.util.UUID]("id", SqlType.Uuid)
         )
         .select(
            "id" -> Nodes.id,
            "parent_id" -> Nodes.parentId,
         )
)(
   self => self
)

Use letRecDistinct when recursive UNION semantics are required for deduplication or cycle termination.

Compile and execute

val compiled = Compiler.compile(ranked).output.toOption.get
val rows = session.prepare(compiled.sql).use { statement =>
   // bind values in compiled.paramOrder, then execute
}

DBQC compiles and describes results; Doobie, Skunk, JDBC, or another normal driver executes them.

Escape hatch

RawExpr and Source.RawSource support vendor features DBQC does not model. Keep them isolated so ordinary queries retain type checks, dependency ordering, strata safety, and dialect portability.