Skip to main content

Projection[A]

Projection[A] is the declarative description of a read model A built from events. It encodes which event sources to listen to, how to route each event to a specific entity or shard, and what each event type does to the read model's shape. A Projection is pure data — it carries no effects and makes no I/O calls; a ProjectionEngine reads it and drives the actual event processing.

Creating a Projection​

The Projection companion object provides three factory methods. Each returns a new projection with no sources yet, ready for the builder chain:

object Projection {
def apply[A: Schema: EntityPath](name: String): Projection[A]
def global[A: Schema](name: String): Projection[A]
def apply[A](name: String, entityPath: EntityPath[A])(using schema: Schema[A]): Projection[A]
}
  • Projection[A](name) keeps one row for each entity ID, in the folder of its EntityPath[A]. It needs a Schema[A] and an EntityPath[A] in implicit scope.
  • Projection.global[A](name) keeps every row in one shared store, global/<name>.db, which suits totals and counters. It needs only a Schema[A]. With no EntityPath, the store looks for an ID column called id, so name the ID field id.
  • Projection[A](name, entityPath) is the first one with the EntityPath[A] passed explicitly, for example to keep a projection of the same type in another folder.

The name is also the file name of the store, so it may contain only letters, digits, _ and -:

import zio.blocks.projection.*
import zio.blocks.schema.{Modifier, Schema}

case class UserProfile(@Modifier.id userId: String, name: String)
object UserProfile {
implicit val schema: Schema[UserProfile] = Schema.derived[UserProfile]
implicit val entityPath: EntityPath[UserProfile] = EntityPath.derived[UserProfile]
}

case class DailyStats(@Modifier.id id: String, userCount: Long)
object DailyStats {
implicit val schema: Schema[DailyStats] = Schema.derived[DailyStats]
}

val profiles = Projection[UserProfile]("user_profiles") // users/user_profiles.db
val stats = Projection.global[DailyStats]("daily_stats") // global/daily_stats.db
val archived = Projection[UserProfile]("old_profiles", EntityPath.derived[UserProfile]("archive")) // archive/old_profiles.db

Entity Paths​

EntityPath[A] describes where a projection's SQLite files live and which field of A holds the entity identifier. The ID field is marked with @Modifier.id, from zio.blocks.schema.Modifier. An entity path is required for per-entity and cross-entity projections; global projections do not use it, see Projection Scope.

trait EntityPath[A] {
def basePath: String // folder name, e.g. "users"
def entityIdField: String // field name, e.g. "userId"
}

The engine uses basePath to construct the path to each SQLite file and entityIdField to locate the primary-key column in A's schema. Both fields are exposed as read-only members and are set at construction time.

Manual Construction​

EntityPath.apply[A] accepts explicit strings for both fields, giving full control over the folder name and the id field without relying on derivation:

import zio.blocks.projection.*
import zio.blocks.schema.{Modifier, Schema}

case class MyEntity(@Modifier.id id: String, value: Int)
object MyEntity {
implicit val schema: Schema[MyEntity] = Schema.derived[MyEntity]
implicit val entityPath: EntityPath[MyEntity] = EntityPath[MyEntity]("my_entities", "id")
}

Derived Construction​

EntityPath.derived[A] inspects Schema[A] and applies a four-step algorithm to produce both values automatically:

  1. Find the id field: prefer the field annotated @Modifier.id, then fall back to any field named "id". If there is neither, derived fails with Entity <type> must have @Modifier.id field or field named 'id'. A type that is not a case class fails too.
  2. Use that field's name as entityIdField.
  3. Strip the "Id" suffix (case-insensitive) from the field name, and a _ left in front of it, so user_id gives user as well. A field named exactly id is left alone.
  4. Convert the result to snake_case and pluralize it to obtain basePath. The plural follows English for common endings: box becomes boxes and category becomes categories.

The table below shows the outcome for three representative types:

TypeId FieldDerived basePath
case class UserAccount(@Modifier.id userId: String, ...)userId"users"
case class OrderRecord(@Modifier.id orderId: String, ...)orderId"orders"
case class Item(@Modifier.id itemId: String, ...)itemId"items"

If the ID field is exactly id, basePath is ids. Prefer a name such as userId, or override the folder as shown in the next two subsections.

A concrete derivation looks like this:

import zio.blocks.projection.*
import zio.blocks.schema.{Modifier, Schema}

case class UserProfile(@Modifier.id userId: String, name: String, email: String)
object UserProfile {
implicit val schema: Schema[UserProfile] = Schema.derived[UserProfile]
implicit val entityPath: EntityPath[UserProfile] = EntityPath.derived[UserProfile]
}
// basePath = "users", entityIdField = "userId"

Overriding the Folder Name​

EntityPath.derived[A](pathOverride) keeps the standard id-field derivation but substitutes an explicit basePath, which is useful when the conventional pluralized name conflicts with an existing schema:

implicit val ep: EntityPath[OrderRecord] = EntityPath.derived[OrderRecord]("custom_orders")
// basePath = "custom_orders"
// entityIdField = "orderId" (still derived normally)

The path can have several folders, such as "example2/orders".

The @path Annotation​

Placing @path("folder") on a case class type overrides the derived folder name at the declaration site rather than at each call to derived:

import zio.blocks.projection.*
import zio.blocks.schema.{Modifier, Schema}

@path("custom_users")
case class UserProfile(@Modifier.id id: String, name: String)
object UserProfile {
implicit val schema: Schema[UserProfile] = Schema.derived[UserProfile]
implicit val entityPath: EntityPath[UserProfile] = EntityPath.derived[UserProfile]
}
// basePath = "custom_users" (the annotation overrides the derived "ids"), entityIdField = "id"

The annotation takes precedence over the derivation algorithm, but not over an explicit pathOverride argument — when pathOverride is provided to EntityPath.derived[A](pathOverride), it is used unconditionally and the annotation is ignored.

Sources and Routing​

A projection says which event sources it reads with from, and how the events of each source are routed with one of the routing methods that follow it.

Defining Sources​

final class Projection[A] {
def from(sourceName: String): FromBuilder[A]
}

from adds a source to the projection: the event store that the engine is given under the name sourceName. It returns a FromBuilder[A], on which you call one of the routing methods. The on[E] handlers after it belong to that source, up to the next from, so a projection that reads several sources calls from once for each:

import zio.blocks.projection.*
import zio.blocks.schema.{Modifier, Schema}

case class RepoCreated(ownerId: String, repoName: String)
object RepoCreated {
implicit val schema: Schema[RepoCreated] = Schema.derived[RepoCreated]
}

case class IssueOpened(ownerId: String, title: String)
object IssueOpened {
implicit val schema: Schema[IssueOpened] = Schema.derived[IssueOpened]
}

case class OwnerActivity(@Modifier.id id: String, ownerId: String, kind: String, text: String)
object OwnerActivity {
implicit val schema: Schema[OwnerActivity] = Schema.derived[OwnerActivity]
implicit val entityPath: EntityPath[OwnerActivity] = EntityPath.derived[OwnerActivity]
}

val activity = Projection[OwnerActivity]("ownerActivity")
.from("repos") // first source
.routedBy[RepoCreated](_.ownerId)
.on[RepoCreated]
.insert((e, ctx) => OwnerActivity(ctx.entityId, e.ownerId, "repo", e.repoName))
.from("issues") // second source
.routedBy[IssueOpened](_.ownerId)
.on[IssueOpened]
.insert((e, ctx) => OwnerActivity(ctx.entityId, e.ownerId, "issue", e.title))

// activity.sourceNames == List("repos", "issues")
// activity.scope == ProjectionScope.CrossEntity(...)

The engine then needs an event store for each name, here "repos" and "issues". A projection with no from reads one source named "_default", see Default Source.

Defining Routes​

After from, call one of the routing methods to finish the source binding. Each method returns a Projection[A] with the source added, so you can continue the builder chain with on[E] handlers or another from. The routing methods are:

final class FromBuilder[A] {
def routeToSelf: Projection[A]
def routeToAll: Projection[A]
def routedBy[E](selector: E => String): Projection[A]
def routedByField[E](selector: E => Any): Projection[A] // inline macro
}

Each routing method finishes the from call and returns the projection. Only routedBy and routedByField choose where events go: they split the projection's rows by a key read from the event. routeToSelf and routeToAll choose no key: in a projection without routedBy, every event goes to the projection's one store and changes the row with the ID it was recorded under.

routeToSelf​

routeToSelf is for a projection that keeps one row for each entity: each event changes the row of the entity it was recorded under. It is what a projection with no from uses:

Projection[UserProfile]("userProfiles")
.from("users").routeToSelf
.on[UserCreated].insert((e, ctx) => UserProfile(ctx.entityId, e.name, e.email))

routeToAll​

routeToAll is for a source whose events all feed shared rows, typically in a projection made with Projection.global[A]. It does not make the projection global, which only Projection.global does, and it does not merge rows: to count everything in one row, record the events under one ID, such as a date:

Projection.global[DailyStats]("dailyStats")
.from("users").routeToAll
.on[UserCreated].aggregate(FieldUpdate.Increment("user_count", 1L))

routedBy​

routedBy[E] reads a key from each event with selector. Events with the same key go to the same store, called a shard, <basePath>/<name>_shard_<key>.db, even when they were recorded under different entities. Within a shard, the row is still the one with the event's entity ID. Using it on any source makes the projection CrossEntity:

Projection[CustomerOrder]("customer_orders")
.from("orders").routedBy[OrderEvent](_.customerId)
.on[OrderPlaced].insert((e, ctx) => CustomerOrder(ctx.entityId, e.customerId, e.product))

routedByField​

routedByField[E] is routedBy for a selector that returns any type, such as an Int or a UUID: the value is turned into the key with toString. routedByField[E](_.customerId) is the same as routedBy[E](e => e.customerId.toString):

Projection[CustomerOrder]("customer_orders")
.from("orders").routedByField[OrderEvent](_.customerId)
.on[OrderPlaced].insert((e, ctx) => CustomerOrder(ctx.entityId, e.customerId, e.product))

The full example below reads two sources: it routes the orders by customer with routedBy, and feeds a global row of shop totals with routeToAll:

projection-examples/src/main/scala/projection/examples/Example3CrossEntity.scala
/*
* Example 3 of 13: a cross-entity projection.
*
* Read Example2PerEntity first. Next: Example4InsertAndDelete.
*
* In Example 2 every event belongs to the entity it was recorded under. Here the
* events are recorded per order (`order-1`, `order-2`, ...), but they are viewed
* per customer, and the customer is a field inside the event. `routedBy` tells the
* projection to read that key from each event and send the event to the store for
* that key, called a shard. So one customer's orders are kept together, apart from
* everyone else's.
*
* Two kinds of event are involved, `OrderPlaced` and `OrderShipped`. Both carry the
* `customerId`, so both are routed to the same shard. That is what lets
* `OrderShipped` update a row that `OrderPlaced` created earlier: the row has the
* ID of the order, and it is in the shard of its customer.
*
* A second projection, `ShopStats`, shows the other side: one global row with the
* numbers for the whole shop (customers, orders, shipped, pending, revenue). It
* is a global projection, so it ignores the customer and counts everything. Its
* counters update the row whose ID the event was recorded under, and the orders
* are recorded under their own IDs, so each event is also written to a second
* feed, "shop", under the single ID "shop". That feed is what the stats read.
*
* This example runs on real SQLite files: the events are kept in
* `.projection-examples/example3/events/orders.db`, and the projection in
* `.projection-examples/example3/orders/`, where each customer gets their own file next to
* the main one, for example `customer_orders_shard_alice.db`.
*
* It shows:
* - `routedBy`, which makes the projection's scope `CrossEntity`
* - the routing key chooses the shard, while the row keeps the ID of the order
* - several event types converging on the same projection
* - an update landing on the right row, because routing is the same for every
* event of a customer
* - an engine on SQLite files, and the shard files that appear
* - reading a row back by ID, which looks in the main store and then in the
* shards. The engine has no call that lists the rows of a shard
* - a global projection with several counters, some of them going up and down
* (`pending`), fed by three kinds of event
*
* Run it from the repository root with:
* sbt "projection-examples/runMain projection.examples.Example3CrossEntity"
*/

package projection.examples

import zio.*
import zio.blocks.chunk.Chunk
import zio.blocks.projection.*
import zio.blocks.schema.{Modifier, Schema}

import Polling.pollUntil

object Example3CrossEntity extends ZIOAppDefault {

sealed trait OrderEvent { def customerId: String }
object OrderEvent {
case class OrderPlaced(customerId: String, product: String, total: Long) extends OrderEvent
object OrderPlaced {
implicit val schema: Schema[OrderPlaced] = Schema.derived[OrderPlaced]
}
case class OrderShipped(customerId: String) extends OrderEvent
object OrderShipped {
implicit val schema: Schema[OrderShipped] = Schema.derived[OrderShipped]
}
case class CustomerRegistered(customerId: String, name: String) extends OrderEvent
object CustomerRegistered {
implicit val schema: Schema[CustomerRegistered] = Schema.derived[CustomerRegistered]
}
implicit val schema: Schema[OrderEvent] = Schema.derived[OrderEvent]
}
import OrderEvent.*

private val ordersFolder: String = Sqlite.path("example3/orders")

// Not called `Order`: the table is named after the class, and `order` is an SQL keyword.
case class CustomerOrder(@Modifier.id id: String, customerId: String, product: String, total: Long, status: String)
object CustomerOrder {
implicit val schema: Schema[CustomerOrder] = Schema.derived[CustomerOrder]
// The folder is chosen explicitly. Derived from the `id` field, it would be "ids".
implicit val entityPath: EntityPath[CustomerOrder] = EntityPath.derived[CustomerOrder](ordersFolder)
}

// The key is always "shop". Its field is called `id` because a global projection has no `EntityPath`, so its
// SQLite store looks for a column with that name.
case class ShopStats(
@Modifier.id id: String,
customers: Long,
orders: Long,
shipped: Long,
pending: Long,
revenue: Long
)
object ShopStats {
implicit val schema: Schema[ShopStats] = Schema.derived[ShopStats]
implicit val entityPath: EntityPath[ShopStats] = EntityPath.derived[ShopStats]
}

private def show(order: Option[CustomerOrder]): String =
order.map(o => s"${o.customerId}, ${o.product}, ${o.total}, ${o.status}").getOrElse("not found")

// `CrossEntity` holds the routing function, which prints as an unreadable lambda, so only the kind is printed.
private def scopeName(scope: ProjectionScope): String = scope match {
case ProjectionScope.PerEntity => "PerEntity"
case ProjectionScope.CrossEntity(_) => "CrossEntity"
case ProjectionScope.Global => "Global"
}

def demo: ZIO[Any, Throwable, Unit] =
Console.printLine("\n--- Example 3: CrossEntity Projection (orders routed by customerId) ---").orDie *>
ZIO.scoped {
for {
_ <- Sqlite.globalFolder("shop_stats") *> Sqlite.folders(ordersFolder, Sqlite.path("example3/events"))

projection = Projection[CustomerOrder]("customer_orders")
.from("orders")
.routedBy[OrderEvent](_.customerId)
.on[OrderPlaced]
.insert((e, ctx) => CustomerOrder(ctx.entityId, e.customerId, e.product, e.total, "placed"))
.on[OrderShipped]
.updateWithField("status", (_, _) => "shipped")

// One row for the whole shop. `pending` goes up when an order is placed and down when it is shipped.
stats = Projection
.global[ShopStats]("shop_stats")
.from("shop")
.routeToAll
.on[CustomerRegistered]
.aggregate(FieldUpdate.Increment("customers", 1L))
.on[OrderPlaced]
.custom { (e, _) =>
ProjectionAction.Update(
Chunk(
FieldUpdate.Increment("orders", 1L),
FieldUpdate.Increment("pending", 1L),
FieldUpdate.Increment("revenue", e.total)
)
)
}
.on[OrderShipped]
.aggregate(Chunk(FieldUpdate.Increment("shipped", 1L), FieldUpdate.Decrement("pending", 1L)))

_ <-
Console.printLine(s" Scope: ${scopeName(projection.scope)}, stats scope: ${scopeName(stats.scope)}").orDie

cache <- TransactorCache.make()
orders <- Sqlite.eventStore[OrderEvent](cache, Sqlite.path("example3/events/orders.db"))
shop <- Sqlite.eventStore[OrderEvent](cache, Sqlite.path("example3/events/shop.db"))
engine <- ProjectionEngine.makeWithStoresVarargs(
cache,
Map[String, EventStore[?]]("orders" -> orders, "shop" -> shop)
)(projection, stats)
_ <- engine.start

// Order events are recorded under the ID of the order, and carry the customer inside. Each one is also
// written to the "shop" feed under the single ID "shop", which is what the stats read.
record = (orderId: String, event: OrderEvent) => orders.append(orderId, event) *> shop.append("shop", event)

_ <- ZIO.foreachDiscard(List("alice", "bob", "charlie", "dave")) { customer =>
shop.append("shop", CustomerRegistered(customer, customer.capitalize))
}
_ <- record("order-1", OrderPlaced("alice", "keyboard", 80))
_ <- record("order-2", OrderPlaced("alice", "monitor", 250))
_ <- record("order-3", OrderPlaced("bob", "mouse", 25))
_ <- record("order-1", OrderShipped("alice"))
_ <- record("order-3", OrderShipped("bob"))
_ <- record("order-4", OrderPlaced("charlie", "cable", 9))

// Events are applied in order, so once order-4 exists every earlier event has been applied.
order4 <- pollUntil(engine.query(projection, "order-4"))
order1 <- engine.query(projection, "order-1")
order2 <- engine.query(projection, "order-2")
order3 <- engine.query(projection, "order-3")

// The stats are done when all four customers, four orders and two shipments have been counted.
totals <- pollUntil(
engine
.query(stats, "shop")
.map(_.filter(t => t.customers == 4 && t.orders == 4 && t.shipped == 2)),
5.seconds
)

files <- Sqlite.dbFiles(ordersFolder)
_ <- Console.printLine(s" Files in $ordersFolder/: ${files.mkString(", ")}").orDie
_ <- Console.printLine(s" order-1: ${show(order1)}").orDie
_ <- Console.printLine(s" order-2: ${show(order2)}").orDie
_ <- Console.printLine(s" order-3: ${show(order3)}").orDie
_ <- Console.printLine(s" order-4: ${show(order4)}").orDie
_ <- totals match {
case Some(t) =>
Console
.printLine(
s" Stats: customers ${t.customers}, orders ${t.orders}, shipped ${t.shipped}, " +
s"pending ${t.pending}, revenue ${t.revenue}"
)
.orDie
case None =>
Console.printLine(" ⚠ Stats not yet ready (timeout)").orDie
}
_ <- Console.printLine(" ✓ CrossEntity: orders kept per customer in a shard, one global row of stats").orDie
} yield ()
}

def run: ZIO[Any, Throwable, Unit] = demo
}

Defining Handlers​

on[E] opens a handler for events of type E and returns a HandlerBuilder[E, A]. Each handler verb on the builder closes it and returns a new Projection[A] with the handler added to the most recent source binding:

final class Projection[A] {
def on[E: Schema: ClassTag]: HandlerBuilder[E, A]
}

final class HandlerBuilder[E, A] {
def insert(f: (E, ProjectionContext) => A): Projection[A]
def delete: Projection[A]
def custom(f: (E, ProjectionContext) => ProjectionAction[A]): Projection[A]
def aggregate(update: FieldUpdate): Projection[A]
def aggregate(updates: Chunk[FieldUpdate]): Projection[A]
def aggregateField(update: FieldUpdate): Projection[A]
def updateWithField(fieldName: String, f: (E, ProjectionContext) => Any): Projection[A]
def updateField(fieldName: String)(f: (E, ProjectionContext) => Any): Projection[A]
def update(selector: A => Any)(f: (E, ProjectionContext) => Any): Projection[A] // inline macro
}

When an event arrives, the projection looks for a handler by the event's class. A handler matches any event that is an instance of its event type, so a handler for a sealed trait also matches each of its cases. If more than one handler matches, the first one added wins. The engine searches the handlers of all the sources together, in the order the sources were added, and it does not narrow the search to the source the event came from. So when two sources have a handler for the same event type, the handler of the source added first handles the events of both.

Handlers describe changes as ProjectionAction values and cannot perform effects. The engine applies each returned action to the projection store; the handler only decides which action to produce. This separation makes event replay deterministic: running the same sequence of events through the same handlers always yields the same read-model state.

ProjectionContext​

Most handler functions receive a ProjectionContext alongside the event, providing the metadata the engine attached when it processed the event envelope:

final case class ProjectionContext(
entityId: String,
timestamp: java.time.Instant,
seq: Long,
sourceEntityId: Option[String]
)

entityId is the entity the event was recorded under and determines the routing target for RouteToSelf. timestamp is the wall-clock time at which the event was appended. seq is the monotonic sequence number that the engine uses as a resume watermark after a restart. The engine always sets sourceEntityId to Some(entityId), the event's own entity ID, also in a cross-entity projection.

Inserting and Deleting Rows​

insert builds a complete row from the event and context and produces ProjectionAction.Insert, creating a new entry in the projection store:

Projection[UserProfile]("userProfiles")
.from("users").routeToSelf
.on[UserCreated]
.insert((e, ctx) => UserProfile(ctx.entityId, e.name, e.email))
.on[UserDeleted]
.delete

delete removes the entity's row unconditionally, producing ProjectionAction.Delete. It takes no function argument because the target row is always identified by ctx.entityId.

The full example below creates three users, deletes one of them, and reads the rows back. UserCreated inserts a UserProfile and UserDeleted removes it:

projection-examples/src/main/scala/projection/examples/Example4InsertAndDelete.scala
/*
* Example 4 of 13: inserting and deleting rows.
*
* Builds on Example2PerEntity. Read it first. Next: Example5FieldUpdates.
*
* Two handlers add and remove whole rows:
* - `insert` builds a complete row from the event and the `ProjectionContext`
* and adds it to the store
* - `delete` removes the row of the entity the event was recorded under. It
* takes no function, because the row is always the one with `ctx.entityId`
*
* Here `UserCreated` inserts a `UserProfile` and `UserDeleted` removes it, so a
* user's row exists from the moment the user is created until the user is
* deleted.
*
* It shows:
* - `insert`, which builds the row from the event and `ctx.entityId`
* - `delete`, which removes the row for the entity of the event
* - that a deleted row is gone: querying it returns `None`
* - running it in memory with `TestEngine`
*
* Run it from the repository root with:
* sbt "projection-examples/runMain projection.examples.Example4InsertAndDelete"
*/

package projection.examples

import zio.*
import zio.blocks.projection.*
import zio.blocks.projection.testing.TestEngine
import zio.blocks.schema.{Modifier, Schema}

import Polling.pollUntil

object Example4InsertAndDelete extends ZIOAppDefault {

case class UserDeleted()
object UserDeleted {
implicit val schema: Schema[UserDeleted] = Schema.derived[UserDeleted]
}

case class UserProfile(@Modifier.id id: String, name: String, email: String)
object UserProfile {
implicit val schema: Schema[UserProfile] = Schema.derived[UserProfile]
implicit val entityPath: EntityPath[UserProfile] = EntityPath.derived[UserProfile]
}

private def show(profile: Option[UserProfile]): String =
profile.map(p => s"${p.name} <${p.email}>").getOrElse("no row")

def demo: ZIO[Any, Throwable, Unit] =
Console.printLine("\n--- Example 4: Insert and Delete (UserProfile rows) ---").orDie *>
ZIO.scoped {
for {
projection = Projection[UserProfile]("user_profiles")
.from("users")
.routeToSelf
.on[UserCreated]
.insert((e, ctx) => UserProfile(ctx.entityId, e.name, e.email))
.on[UserDeleted]
.delete

engine <- TestEngine.make(projection)

_ <- engine.append("user-1", UserCreated("Alice", "alice@example.com"))
_ <- engine.append("user-2", UserCreated("Bob", "bob@example.com"))
_ <- engine.append("user-3", UserCreated("Charlie", "charlie@example.com"))
_ <- engine.append("user-2", UserDeleted())

// A deleted row cannot be waited for, so the last event is a new user. Events are applied in order, so
// once user-4 exists the deletion has been applied.
_ <- engine.append("user-4", UserCreated("Dave", "dave@example.com"))
_ <- pollUntil(engine.query(projection, "user-4"))

u1 <- engine.query(projection, "user-1")
u2 <- engine.query(projection, "user-2")
u3 <- engine.query(projection, "user-3")

_ <- Console.printLine(s" user-1: ${show(u1)}").orDie
_ <- Console.printLine(s" user-2: ${show(u2)}").orDie
_ <- Console.printLine(s" user-3: ${show(u3)}").orDie
_ <- Console.printLine(" ✓ Insert and delete: user-2 was inserted, then its row was removed").orDie
} yield ()
}

def run: ZIO[Any, Throwable, Unit] = demo
}

Running it prints one line for each user:

  • user-1: Alice <alice@example.com>. The row was inserted and never deleted.
  • user-2: no row. The row was inserted, then removed by delete, so the query returns None.
  • user-3: Charlie <charlie@example.com>. The deletion of user-2 did not touch it, because each delete removes only the row of the entity the event was recorded under.

Field Updates​

updateWithField (and its alias updateField) sets a named column to a value computed from the event. The column name is passed as a raw string and must already be in snake_case to match the generated schema:

.on[OrderShipped]
.updateWithField("status", (_, _) => "shipped")

update is the compile-time macro variant. A selector such as _.firstName is resolved to the column name at compile time, and the macro converts the Scala field name to snake_case automatically — a mistyped field name is a compile error rather than a runtime failure:

.on[UserRenamed]
.update(_.firstName)((e, _) => e.newName)
// _.firstName resolved to column "first_name" at compile time

The full example below registers a user and then changes one column at a time, using each of the three ways to name the column. UserRenamed uses the update macro, EmailChanged uses updateWithField with the column name as a string, and UserVerified uses updateField. Each handler changes only its own column:

projection-examples/src/main/scala/projection/examples/Example5FieldUpdates.scala
/*
* Example 5 of 13: field updates.
*
* Builds on Example2PerEntity. Read it first. Next: Example6GlobalAggregate.
*
* `insert` writes a whole row. When an event changes only one column, a field
* update sets that column and leaves the rest of the row as it is. There are
* three ways to name the column:
* - `update(_.firstName)`, which picks the field with a selector. The name is
* checked by the compiler, and the macro turns it into the column name
* `first_name`, so a typo does not compile
* - `updateWithField("email", ...)`, which takes the column name as a string.
* It must already be the column name, so `snake_case`, and it is not checked
* until the event is applied
* - `updateField("status")(...)`, which is the same as `updateWithField` with
* the function in a second parameter list
*
* Each handler computes the new value from the event, and may also use the
* `ProjectionContext`.
*
* It shows:
* - the three ways to update one column
* - an update changing one column and keeping the others
* - running it in memory with `TestEngine`
*
* Run it from the repository root with:
* sbt "projection-examples/runMain projection.examples.Example5FieldUpdates"
*/

package projection.examples

import zio.*
import zio.blocks.projection.*
import zio.blocks.projection.testing.TestEngine
import zio.blocks.schema.{Modifier, Schema}

import Polling.pollUntil

object Example5FieldUpdates extends ZIOAppDefault {

case class UserRegistered(firstName: String, email: String)
object UserRegistered {
implicit val schema: Schema[UserRegistered] = Schema.derived[UserRegistered]
}

case class UserRenamed(newName: String)
object UserRenamed {
implicit val schema: Schema[UserRenamed] = Schema.derived[UserRenamed]
}

case class EmailChanged(newEmail: String)
object EmailChanged {
implicit val schema: Schema[EmailChanged] = Schema.derived[EmailChanged]
}

case class UserVerified()
object UserVerified {
implicit val schema: Schema[UserVerified] = Schema.derived[UserVerified]
}

case class UserProfile(@Modifier.id id: String, firstName: String, email: String, status: String)
object UserProfile {
implicit val schema: Schema[UserProfile] = Schema.derived[UserProfile]
implicit val entityPath: EntityPath[UserProfile] = EntityPath.derived[UserProfile]
}

private def show(profile: Option[UserProfile]): String =
profile.map(p => s"${p.firstName} <${p.email}>, ${p.status}").getOrElse("not found")

def demo: ZIO[Any, Throwable, Unit] =
Console.printLine("\n--- Example 5: Field Updates (update, updateWithField, updateField) ---").orDie *>
ZIO.scoped {
for {
projection = Projection[UserProfile]("user_profiles")
.from("users")
.routeToSelf
.on[UserRegistered]
.insert((e, ctx) => UserProfile(ctx.entityId, e.firstName, e.email, "pending"))
.on[UserRenamed]
.update(_.firstName)((e, _) => e.newName)
.on[EmailChanged]
.updateWithField("email", (e, _) => e.newEmail)
.on[UserVerified]
.updateField("status")((_, _) => "verified")

engine <- TestEngine.make(projection)

_ <- engine.append("user-1", UserRegistered("Alice", "alice@example.com"))
_ <- engine.append("user-2", UserRegistered("Bob", "bob@example.com"))
_ <- engine.append("user-1", UserRenamed("Alicia"))
_ <- engine.append("user-1", EmailChanged("alicia@example.com"))
_ <- engine.append("user-1", UserVerified())
_ <- engine.append("user-2", UserRenamed("Robert"))

// Events are applied in order, so once the last one is visible every earlier event has been applied.
u2 <- pollUntil(engine.query(projection, "user-2").map(_.filter(_.firstName == "Robert")))
u1 <- engine.query(projection, "user-1")

_ <- Console.printLine(s" user-1: ${show(u1)}").orDie
_ <- Console.printLine(s" user-2: ${show(u2)}").orDie
_ <- Console.printLine(" ✓ Field updates: each event changed one column and kept the others").orDie
} yield ()
}

def run: ZIO[Any, Throwable, Unit] = demo
}

Running it prints one line for each user:

  • user-1: Alicia <alicia@example.com>, verified. The name, the email and the status were each changed by a separate event.
  • user-2: Robert <bob@example.com>, pending. Only the name changed, so the email and the status are as they were registered.

Aggregating Fields​

aggregate and aggregateField apply one or more FieldUpdate operations, producing ProjectionAction.Update. This rewrites individual columns rather than the entire row, and numeric operations such as Increment are executed in SQL without reading the row first. The available FieldUpdate operations are Set, Increment, Decrement, Max, and Min. aggregateField is an alias for the single-update overload of aggregate:

Projection.global[DailyStats]("dailyStats")
.from("users").routeToAll
.on[UserCreated]
.aggregate(FieldUpdate.Increment("user_count", 1L))
.from("repos").routeToAll
.on[RepoCreated]
.aggregate(Chunk(
FieldUpdate.Increment("repo_count", 1L),
FieldUpdate.Max("peak", 100L)
))

To change several columns for one event, pass a Chunk of updates, as the RepoCreated handler above does. The SQLite store applies them in one transaction.

The FieldUpdate values are fixed when the projection is declared, so they cannot use data from the event. When an update needs the event's data, for example adding an order's total to revenue, build the update inside custom with ProjectionAction.Update.

Each operation is one change to a column, run as SQL:

OperationSQLEffect
Set(field, value)SET col = ?Replace the value
Increment(field, by)SET col = COALESCE(col, 0) + ?Add to a counter
Decrement(field, by)SET col = COALESCE(col, 0) - ?Subtract from a counter
Max(field, value)SET col = MAX(COALESCE(col, ?), ?)Keep the highest value
Min(field, value)SET col = MIN(COALESCE(col, ?), ?)Keep the lowest value

Before it applies the updates, the store runs INSERT OR IGNORE, which creates the row with the default value of each column if it is missing. Incrementing a counter of a row that does not exist yet therefore gives 1, and COALESCE treats a missing value as 0. The updates of one event run in one transaction, and the arithmetic happens inside SQL, so several fibers incrementing the same counter produce the correct total without lost updates.

A field can also be named with a selector instead of a string. FieldUpdate.increment[DailyStats](_.userCount) picks the field at compile time and maps it to the column user_count, as update does, so a typo does not compile. The factories are setValue, increment, decrement, maxValue and minValue.

The full example below counts users and repositories into one DailyStats row. Each source is bound with routeToAll, so the events of both sources land in the same row, and each handler adds one to its own counter with FieldUpdate.Increment. The row is created on the first event, with the other counters at zero:

projection-examples/src/main/scala/projection/examples/Example6GlobalAggregate.scala
/*
* Example 6 of 13: a global aggregate projection.
*
* Read Examples 2 and 3 first. Next: Example7CustomActions.
*
* A global projection keeps one shared store for the whole projection, which is
* the place for totals and counters. Here `UserCreated` events from the "users"
* source and `RepoCreated` events from the "repos" source both feed a single
* `DailyStats` row.
*
* This example runs on real SQLite files: the events are kept in
* `.projection-examples/example6/events/users.db` and `.projection-examples/example6/events/repos.db`,
* and the projection in `global/dailyStats.db`. The engine always keeps the store
* of a global projection in a folder called `global`, so it is not inside
* `.projection-examples`.
*
* It shows:
* - `Projection.global`, with `routeToAll` on each source
* - `aggregate` with `FieldUpdate.Increment`, which adds to a counter in SQL
* without reading the row first
* - one projection listening to more than one source, each with its own
* event store
*
* Run it from the repository root with:
* sbt "projection-examples/runMain projection.examples.Example6GlobalAggregate"
*/

package projection.examples

import zio.*
import zio.blocks.projection.*
import zio.blocks.schema.{Modifier, Schema}

import Polling.pollUntil

object Example6GlobalAggregate extends ZIOAppDefault {

// The key is the date. Its field is called `id` because a global projection has no `EntityPath`, so its
// SQLite store looks for a column with that name.
case class DailyStats(@Modifier.id id: String, userCount: Int, repoCount: Int)
object DailyStats {
implicit val schema: Schema[DailyStats] = Schema.derived[DailyStats]
implicit val entityPath: EntityPath[DailyStats] = EntityPath.derived[DailyStats]
}

def demo: ZIO[Any, Throwable, Unit] =
Console.printLine("\n--- Example 6: Global Aggregate (DailyStats from users + repos) ---").orDie *>
ZIO.scoped {
for {
_ <- Sqlite.globalFolder("dailyStats") *> Sqlite.folders(Sqlite.path("example6/events"))

dateKey = "2025-08-26"

projection = Projection
.global[DailyStats]("dailyStats")
.from("users")
.routeToAll
.on[UserCreated]
.aggregate(FieldUpdate.Increment("user_count", 1L))
.from("repos")
.routeToAll
.on[RepoCreated]
.aggregate(FieldUpdate.Increment("repo_count", 1L))

_ <- Console.printLine(s" Scope: ${projection.scope}").orDie

cache <- TransactorCache.make()
users <- Sqlite.eventStore[UserCreated](cache, Sqlite.path("example6/events/users.db"))
repos <- Sqlite.eventStore[RepoCreated](cache, Sqlite.path("example6/events/repos.db"))
engine <- ProjectionEngine.makeWithStoresVarargs(
cache,
Map[String, EventStore[?]]("users" -> users, "repos" -> repos)
)(projection)
_ <- engine.start

_ <- ZIO.foreachDiscard(1 to 5)(i => users.append(dateKey, UserCreated(s"user-$i", s"u$i@ex.com")))
_ <- ZIO.foreachDiscard(1 to 3)(i => repos.append(dateKey, RepoCreated("any", s"repo-$i")))

stats <- pollUntil(
engine.query(projection, dateKey).map(_.filter(s => s.userCount == 5 && s.repoCount == 3)),
5.seconds
)

files <- Sqlite.dbFiles("global")
_ <- Console.printLine(s" Files in global/: ${files.mkString(", ")}").orDie
_ <- stats match {
case Some(s) =>
Console.printLine(s" Date: $dateKey, Users: ${s.userCount}, Repos: ${s.repoCount}").orDie
case None =>
Console.printLine(" ⚠ Aggregate not yet ready (timeout)").orDie
}
_ <- Console.printLine(" ✓ Global: events from multiple sources converge to single aggregate row").orDie
} yield ()
}

def run: ZIO[Any, Throwable, Unit] = demo
}

Running it appends five UserCreated and three RepoCreated events and reads back one row with Users: 5, Repos: 3.

Custom Actions​

custom accepts any ProjectionAction[A], covering cases the other verbs do not — for example, Upsert (insert or update), Noop (no operation), or Truncate (clear all rows). Its signature is custom(f: (E, ProjectionContext) => ProjectionAction[A]): Projection[A]. Use it when the action depends on the event: the handler looks at the event and returns the action to apply.

The example below handles two events for a user profile, and each handler picks between actions:

  • ProfileImported carries a draft flag. A draft is ignored with Noop, so no row is written. Anything else is written with Upsert, which creates the row or replaces it if it exists. That makes importing the same user twice safe, where Insert would not be.
  • AccountClosed carries an eraseData flag. When it is set, the row is removed with Delete. Otherwise Update changes only the status column and keeps the rest of the row.
projection-examples/src/main/scala/projection/examples/Example7CustomActions.scala
/*
* Example 7 of 13: custom actions.
*
* Builds on Example2PerEntity. Read it first. Next: Example8SchemaEvolution.
*
* `insert`, `delete` and the field updates each produce one fixed action. When
* what should happen depends on the event, `custom` lets the handler look at the
* event and return the action itself. This example uses four of the actions a
* handler can return: `Upsert`, `Noop`, `Delete` and `Update`.
*
* - `ProfileImported` has a `draft` flag. A draft is ignored with `Noop`, so no
* row is written. Anything else is written with `Upsert`, which creates the
* row or replaces it if it exists, so importing the same user twice is safe.
* - `AccountClosed` has an `eraseData` flag. When it is set, the row is removed
* with `Delete`. Otherwise `Update` changes only the `status` column and keeps
* the rest of the row.
*
* It shows:
* - `custom`, which returns a `ProjectionAction` chosen from the event
* - `Upsert` replacing a row, `Noop` writing nothing, `Delete` removing a row
* - `Update` with a `FieldUpdate.Set`, changing one column of an existing row
* - running it in memory with `TestEngine`
*
* Run it from the repository root with:
* sbt "projection-examples/runMain projection.examples.Example7CustomActions"
*/

package projection.examples

import zio.*
import zio.blocks.chunk.Chunk
import zio.blocks.projection.*
import zio.blocks.projection.testing.TestEngine
import zio.blocks.schema.{Modifier, Schema}

import Polling.pollUntil

object Example7CustomActions extends ZIOAppDefault {

case class ProfileImported(name: String, email: String, draft: Boolean)
object ProfileImported {
implicit val schema: Schema[ProfileImported] = Schema.derived[ProfileImported]
}

case class AccountClosed(eraseData: Boolean)
object AccountClosed {
implicit val schema: Schema[AccountClosed] = Schema.derived[AccountClosed]
}

case class UserProfile(@Modifier.id id: String, name: String, email: String, status: String)
object UserProfile {
implicit val schema: Schema[UserProfile] = Schema.derived[UserProfile]
implicit val entityPath: EntityPath[UserProfile] = EntityPath.derived[UserProfile]
}

private def show(profile: Option[UserProfile]): String =
profile.map(p => s"${p.name} <${p.email}>, ${p.status}").getOrElse("no row")

def demo: ZIO[Any, Throwable, Unit] =
Console.printLine("\n--- Example 7: Custom Actions (Upsert, Noop, Delete, Update) ---").orDie *>
ZIO.scoped {
for {
projection = Projection[UserProfile]("user_profiles")
.from("users")
.routeToSelf
.on[ProfileImported]
.custom { (e, ctx) =>
if (e.draft) ProjectionAction.Noop
else ProjectionAction.Upsert(UserProfile(ctx.entityId, e.name, e.email, "active"))
}
.on[AccountClosed]
.custom { (e, _) =>
if (e.eraseData) ProjectionAction.Delete
else ProjectionAction.Update(Chunk(FieldUpdate.Set("status", "closed")))
}

engine <- TestEngine.make(projection)

_ <- engine.append("user-1", ProfileImported("Alice", "alice@example.com", draft = false))
_ <- engine.append("user-1", ProfileImported("Alice B.", "alice@example.com", draft = false))
_ <- engine.append("user-2", ProfileImported("Bob", "bob@example.com", draft = true))
_ <- engine.append("user-3", ProfileImported("Carol", "carol@example.com", draft = false))
_ <- engine.append("user-3", AccountClosed(eraseData = false))
_ <- engine.append("user-4", ProfileImported("Dave", "dave@example.com", draft = false))
_ <- engine.append("user-4", AccountClosed(eraseData = true))
// Two of the users end up without a row, so there is nothing to wait for on them. Events are applied in
// order, so once this last user exists every earlier event has been applied.
_ <- engine.append("user-5", ProfileImported("Erin", "erin@example.com", draft = false))

_ <- pollUntil(engine.query(projection, "user-5"))
u1 <- engine.query(projection, "user-1")
u2 <- engine.query(projection, "user-2")
u3 <- engine.query(projection, "user-3")
u4 <- engine.query(projection, "user-4")

_ <- Console.printLine(s" user-1: ${show(u1)}").orDie
_ <- Console.printLine(s" user-2: ${show(u2)}").orDie
_ <- Console.printLine(s" user-3: ${show(u3)}").orDie
_ <- Console.printLine(s" user-4: ${show(u4)}").orDie
_ <- Console.printLine(" ✓ Custom: the handler chose Upsert, Noop, Update or Delete for each event").orDie
} yield ()
}

def run: ZIO[Any, Throwable, Unit] = demo
}

Running it prints one line for each user:

  • user-1: Alice B. <alice@example.com>, active. The second import replaced the first.
  • user-2: no row. The draft was a Noop, so no row was ever written.
  • user-3: Carol <carol@example.com>, closed. Only status changed.
  • user-4: no row. The row was created, then removed by Delete.

Default Source​

Most projections read one event feed and keep each entity's row under its own ID. Writing .from("some-name").routeToSelf for that would mean inventing a name for a feed that has only one meaning, so the library lets you skip it. When you add the first handler to a projection that has no source binding yet, with on[E] and no from() before it, the library creates the binding for you:

  • The source is named "_default".
  • The routing is RouteToSelf, so each event goes to the row of the entity it was recorded under (ctx.entityId).
  • The handler is put in that binding.
Projection[UserProfile]("userProfiles")
.on[UserCreated] // implicitly creates "_default" binding with RouteToSelf
.insert((e, ctx) => UserProfile(ctx.entityId, e.name, e.email))

This is the same projection as the one below, with the binding written out:

Projection[UserProfile]("userProfiles")
.from("_default").routeToSelf
.on[UserCreated]
.insert((e, ctx) => UserProfile(ctx.entityId, e.name, e.email))

The shortcut is purely a convenience. It gives nothing that .from("_default").routeToSelf does not, and nothing requires you to use it.

The engine looks each source name up in the event stores it was given. If no store has that name, it uses the store under "_default", and if there is none, the first store in the map, so a misspelt name reads another store instead of failing. With a single event store, every source reads that store.

What the shortcut does and does not do:

  • Only the first handler creates the binding. A second on[E] attaches to the binding that already exists, whether it is "_default" or one made by an earlier from().
  • A from() after the handlers adds a second binding. The projection then has two sources, "_default" and the new one, and needs an event store for each.
  • It can only give RouteToSelf. For any other routing, write from() yourself.

Projection Scope​

A scope is the way the rows of a projection are organized. To see what that means, picture a shop that writes a note every time something happens: "Alice placed order 7", "order 7 shipped". These notes are the events. To answer questions quickly ("is order 7 shipped?", "how many orders so far?"), someone files each note into a cabinet as it arrives. The filed result is the read model, and the scope is how that cabinet is arranged.

ProjectionScope is the type that describes it. It answers two questions: which ProjectionStore an event is applied to, and which file that store lives in.

sealed trait ProjectionScope
object ProjectionScope {
case object PerEntity extends ProjectionScope
case object Global extends ProjectionScope
case class CrossEntity(routedBy: Any => String) extends ProjectionScope
}

You never set a scope directly. It is worked out from how the projection is built, and projection.scope returns it:

  1. A projection made with Projection.global has the scope Global.
  2. Otherwise, if any source uses routedBy or routedByField, it has the scope CrossEntity. The key function of the first such source is kept in the CrossEntity case.
  3. Otherwise it has the scope PerEntity, which is the default.

Note that routeToAll alone does not make a projection global. It only sends the events of its source to the same store. Only Projection.global gives the scope Global and puts the store in the global/ folder.

The three scopes keep their files in different places:

ScopeFile Location
PerEntity (default)<basePath>/<name>.db
CrossEntity(routedBy)<basePath>/<name>_shard_<key>.db per key
Globalglobal/<name>.db
import zio.blocks.projection.*
import zio.blocks.schema.{Modifier, Schema}

case class UserRegistered(name: String)
object UserRegistered {
implicit val schema: Schema[UserRegistered] = Schema.derived[UserRegistered]
}

case class OrderPlaced(customerId: String, total: Long)
object OrderPlaced {
implicit val schema: Schema[OrderPlaced] = Schema.derived[OrderPlaced]
}

case class UserProfile(@Modifier.id id: String, name: String)
object UserProfile {
implicit val schema: Schema[UserProfile] = Schema.derived[UserProfile]
implicit val entityPath: EntityPath[UserProfile] = EntityPath.derived[UserProfile]
}

case class CustomerOrder(@Modifier.id id: String, customerId: String, total: Long)
object CustomerOrder {
implicit val schema: Schema[CustomerOrder] = Schema.derived[CustomerOrder]
implicit val entityPath: EntityPath[CustomerOrder] = EntityPath.derived[CustomerOrder]
}

case class OrderStats(@Modifier.id id: String, orders: Long)
object OrderStats {
implicit val schema: Schema[OrderStats] = Schema.derived[OrderStats]
}

// PerEntity: one row for each entity ID.
val profiles = Projection[UserProfile]("userProfiles")
.from("users")
.routeToSelf
.on[UserRegistered]
.insert((e, ctx) => UserProfile(ctx.entityId, e.name))

// CrossEntity: events are grouped by a key read from the event.
val ordersByCustomer = Projection[CustomerOrder]("ordersByCustomer")
.from("orders")
.routedBy[OrderPlaced](_.customerId)
.on[OrderPlaced]
.insert((e, ctx) => CustomerOrder(ctx.entityId, e.customerId, e.total))

// Global: one shared store, here with a counter.
val stats = Projection
.global[OrderStats]("orderStats")
.from("orders")
.routeToAll
.on[OrderPlaced]
.aggregate(FieldUpdate.Increment("orders", 1L))

// profiles.scope == ProjectionScope.PerEntity
// ordersByCustomer.scope == ProjectionScope.CrossEntity(...)
// stats.scope == ProjectionScope.Global

PerEntity: one card per thing​

Each order, user or product gets its own card, and a new note about order 7 updates the card of order 7 only. This scope answers the question "what is the state of this one thing?", for example "alice, keyboard, shipped".

Every entity has its own row, and the events recorded under an entity ID update that entity's row. The routing mode of the source is routeToSelf, which files a note under the thing it was recorded under, and a handler reads that ID as ProjectionContext#entityId. The store is the file <basePath>/<name>.db, for example users/userProfiles.db. It is the right scope for state that belongs to one thing and is looked up by its own ID, such as a user's profile or the status of an order.

CrossEntity: one drawer per group​

Here the cabinet has a drawer for each customer. The note says "order 7 placed, customer Alice", so it is filed in Alice's drawer and not in a drawer for order 7. Inside the drawer each order still has its own card. This scope answers the question "what belongs together under this customer?".

Events are grouped by a key that is read from the event, not by the ID they were recorded under. You say which part of the event picks the drawer with the routing mode routedBy, for example routedBy[OrderPlaced](_.customerId). Any source that uses routedBy makes the projection CrossEntity. Each routing key gets its own store, called a shard, next to the main one: <basePath>/<name>_shard_<key>.db. With SQLite each shard is its own file, such as customer_orders_shard_alice.db. In the file name the key is cut to 64 characters, and any character other than letters, digits, _ and - is replaced by _. If the key cannot be read from an event, the engine uses the entity ID.

The routing key only chooses the shard. A row keeps its own ID, so two rows in the same shard still need different IDs. To read a row you give its ID: the engine looks in the main store first, and then in the shards it has opened since it was created. It opens a shard when it routes the first event to it. It uses the scope to know that there are shards to look in; it does not use the key to pick one.

It is the right scope for views that group things by a related entity, such as the orders of a customer or the repositories of an owner. See Routing Methods for a full example.

Global: one scoreboard on the wall​

There is no card for each thing and no drawer for each group. Every note, whoever it is about, changes the numbers on one board: orders so far, shipped, pending. This scope answers the question "how many in total?".

All events go to one shared store, global/<name>.db, whichever entity or key they belong to, and from as many sources as the projection reads. The routing mode of its sources is routeToAll, which does not split the events by entity or by key. It does not make a projection global by itself, only Projection.global does. It is the right scope for totals and counters, such as the number of orders or the revenue of a shop. See Aggregating Fields for a full example.

Two details matter in practice:

  • A counter update is applied to the row whose ID the event was recorded under. To keep one row of totals, record all the events under one fixed ID, for example a date or "shop". Otherwise each event updates a different row.
  • A global projection has no EntityPath, so its store looks for an ID column called id. Name the ID field of the row id.

Inspecting a Projection​

Several read-only members expose a completed projection's internal structure. These are primarily useful for debugging, validation, and building custom runners or middleware layers.

Validation​

validate() checks the projection for structural problems and returns a list of warning strings, empty when the projection is well-formed:

val warnings = proj.validate()
// Possible warnings (with <name> replaced by the projection's name):
// "Projection <name> has no bindings"
// "Projection <name> has no handlers"
// "Projection <name> has binding with empty sourceName"
// "Handler for <tag> has null class"

Running validate() before passing a projection to an engine helps catch misconfigured projections early, before any I/O occurs.

Looking Up a Handler and a Routing Key​

Advanced

You do not need this section to define or run a projection. The engine calls handle and routingKey for you, so a normal application never calls them. They are described here to show how the engine decides what an event does and where it goes, and for anyone writing a test or a custom runner.

Two methods show what the projection would do with an event, without an engine. They are what the engine calls for every event: the first finds the handler, and the second finds the key that decides which store gets the event.

final class Projection[A] {
def handle(event: Any, ctx: ProjectionContext, source: Option[String] = None): Option[ProjectionAction[A]]
def routingKey(event: Any, ctx: ProjectionContext, sourceName: String): Option[String]
}
  • handle returns the ProjectionAction of the first handler that matches the event, or None if no handler matches. With source = Some(name) it searches only the handlers of that source. With None, which is what the engine uses, it searches all handlers, in the order the sources were added. It does not apply the action to a store, so it is a way to unit-test a handler without an engine.
  • routingKey returns the key for an event in the named source: ctx.entityId for routeToSelf, the extracted key for routedBy, and None for routeToAll or when there is no source with that name. See Binding Event Sources.

The snippet below shows both methods on a projection with an "orders" source that is routed by customer. It is a fragment: OrderPlaced, OrderShipped and Refunded are event case classes, and ctx is a ProjectionContext for an event recorded under "order-1":

val projection: Projection[CustomerOrder] =
Projection[CustomerOrder]("customer_orders")
.from("orders").routedBy[OrderPlaced](_.customerId)
.on[OrderPlaced].insert((e, ctx) => CustomerOrder(ctx.entityId, e.customerId, e.product, "placed"))
.on[OrderShipped].updateWithField("status", (_, _) => "shipped")

// Which action would each event produce?
projection.handle(OrderPlaced("alice", "keyboard"), ctx)
// Some(Insert(CustomerOrder(order-1,alice,keyboard,placed)))

projection.handle(OrderShipped("alice"), ctx)
// Some(Update(Chunk(Set(status,shipped))))

projection.handle(Refunded("alice"), ctx)
// None: no handler matches this event type

projection.handle(OrderShipped("alice"), ctx, Some("other"))
// None: there is no source named "other"

// Which key picks the shard of the event?
projection.routingKey(OrderPlaced("alice", "keyboard"), ctx, "orders")
// Some(alice): the customer id, because the source is routed by customer

projection.routingKey(OrderPlaced("alice", "keyboard"), ctx, "other")
// None: there is no source named "other"

Nothing was written anywhere by these calls. handle only says that the event would insert a row, or set status, and routingKey says it would go to the shard of alice.

See Also​

  • Projection module overview — module introduction, key concepts, and integration points with zio-blocks-schema, zio-blocks-sql, and ZIO Streams.
  • ProjectionEngine — the runtime that executes Projection[A] descriptors: event dispatch, watermark tracking, schema-change detection, and the SQLite / in-memory store implementations.
  • Migration — renamed event cases, @eventTag, changed event fields, and what happens when the row type changes.