effect-qb 面向效果的 TypeScript 应用程序的 SQL 查询构建。effect-qb 允许您一次定义表,组合带类型的查询,并将其存储在数据库中。
effect-qb 面向效果的 TypeScript 应用程序的 SQL 查询构建。effect-qb 允许您一次定义表,组合带类型的查询,并将其存储在数据库中。
Typed SQL query building for Effect-oriented TypeScript applications.
effect-qb lets you define tables once, compose typed query plans, render those
plans for a concrete SQL dialect, and execute them through Effect SQL clients or a
custom driver. It is a query builder, not an ORM: table definitions describe SQL
shape and runtime schemas, while query plans stay explicit and inspectable.
…Columns reference their own table (users.id), so a query starts with
Query.select(...) and pipes from, where, and orderBy onto it. The order
of the piped steps does not change the SQL that is generated.
bun add effect-qb effectRuntime requirements:
>=22>=1.3.5 for this repository's development scriptsPublic query-builder import paths:
effect-qb - portable table, column, table-option, query, function, renderer, and casing moduleseffect-qb/postgres - Postgres column extensions, option modifiers, renderer, executor, schema helperseffect-qb/mysql - MySQL extensions, renderer, executoreffect-qb/sqlite - SQLite extensions, renderer, executorDefine a table, build a query, derive its result-row type, then render the one plan for each dialect. The plan does not change between dialects; only the rendered SQL does.
…This plan is portable because it only uses root effect-qb modules. Reach for a
dialect module (effect-qb/postgres, etc.) only when a query depends on that
dialect's SQL.
effect-qb is built around a small pipeline:
Table + Column definitions
-> typed Query plan
-> dialect Renderer
-> SQL + params + projection metadata
-> dialect Executor
-> decoded typed rowsColumn carries SQL type metadata, runtime schema information, nullability,
defaults, generated metadata, and driver value mapping hints.Table carries table identity, fields, primary key metadata, schema metadata,
constraints, indexes, and derived select/insert/update schemas.Query creates typed plans. Plans track source requirements, result rows,
capabilities, and dialect compatibility.Renderer turns a compatible complete plan into sql, params,
dialect, projections, and optional valueMappings.Executor runs rendered plans and uses projection metadata plus runtime
schemas to normalize and decode rows.The root namespace is the standard portable authoring layer. Dialect-specific helpers narrow a plan to that concrete dialect. Mixing two different concrete dialects is rejected at type level.
Standard versus concrete dialects
A plan that only uses effect-qb root modules has the standard dialect tag.
Standard plans can render through Postgres, MySQL, and SQLite renderers.
If a plan uses Pg.Column.jsonb(...), Jsonb.* from effect-qb/postgres, or a standard table
option piped through a Postgres modifier such as Pg.Index.using("btree"),
it becomes a Postgres plan. Render and execute that plan with the Postgres
renderer or executor.
MySQL and SQLite follow the same rule: use root modules for portable SQL, and concrete modules only when the query depends on concrete SQL.
Table.make is the primary table factory.
…Root option modules cover portable constraints and metadata:
PrimaryKey.make(...)Unique.make(...)Index.make(...)ForeignKey.make(...)Check.make(...)Table keeps table construction and row/schema helpers:
Table.alias(...)Table.selectSchema(...), Table.insertSchema(...), Table.updateSchema(...)Class-style tables
Table.Class exists for class-style declarations and advanced schema-centric
workflows. Prefer Table.make unless your codebase already uses class-style
table definitions.
import { Column, Index, Table } from "effect-qb"
class Users extends Table.Class("users")({
id: Column.uuid().pipe(Column.primaryKey),
email: Column.text(),
displayName: Column.text().pipe(Column.nullable)
}) {
static readonly [Table.options] = [
Index.make((table) => table.email).pipe(Index.named("users_email_idx"))
]
}
const usersByEmail = Users.emailThe portable column surface includes:
uuidtext, varchar, charint, bigint, number, realbooleandate, time, datetime, timestampblobjsonColumns can refine their select/insert/update schemas.
import * as Schema from "effect/Schema"
import { Column, Table } from "effect-qb"
const events = Table.make("events", {
id: Column.uuid().pipe(Column.primaryKey),
happenedOn: Column.date().pipe(Column.schema(Schema.DateFromString)),
payload: Column.json(Schema.Struct({
visits: Schema.Number
}))
})
type EventRow = Table.SelectOf
// {
// readonly id: string
// readonly happenedOn: Date // decoded by Schema.DateFromString
// readonly payload: { readonly visits: number }
// }
type EventInsert = Table.InsertOf
Postgres adds concrete types such as jsonb, bytea, arrays, identity
columns, timestamp variants, and custom typed references or Cast.to(...)
targets.
Use Casing when model identifiers and physical database identifiers do not
use the same naming convention.
Casing is usually a renderer concern: pipe Casing.withCasing(...) into a
built-in renderer to map physical table, column, schema, index, constraint,
type, and sequence names without changing model keys.
…Override casing for one table
import { Casing, Column, Table } from "effect-qb"
const users = Table.make("UserAccounts", {
id: Column.uuid().pipe(Column.primaryKey),
createdAt: Column.datetime()
}).pipe(
Casing.withCasing("snake_case")
)
Create a casing-aware table factory
import { Casing, Column } from "effect-qb"
const Snake = Casing.make("snake_case")
const users = Snake.table("UserAccounts", {
id: Column.uuid().pipe(Column.primaryKey),
createdAt: Column.datetime()
})
Apply casing to a Postgres schema factory
import { Casing, Column } from "effect-qb"
import * as Pg from "effect-qb/postgres"
const Analytics = Pg.Schema.make("analytics").pipe(
Casing.withCasing({
tables: "snake_case",
columns: "snake_case",
types: "snake_case",
sequences: "snake_case"
})
)
const events = Analytics.table("Events", {
id: Column.uuid().pipe(Column.primaryKey),
createdAt: Column.datetime()
})
Casing categories and styles
Casing categories:
tablescolumnsschemasindexesconstraintstypessequencesBuilt-in casing styles:
"preserve""snake_case""camelCase""PascalCase""kebab-case""SCREAMING_SNAKE_CASE"(name: string) => stringeffect-qb pushes checks into TypeScript when the public API has enough
information to know the answer before SQL is rendered. The main idea is that
tables, columns, predicates, source availability, and dialects all carry type
metadata through the plan.
If you just want to write, render, and execute queries end to end, skip ahead to Query Lifecycle. This section explains what TypeScript catches for you before any SQL runs.
Table definitions derive select, insert, and update payloads from column metadata. Generated columns are omitted from inserts, nullable/default columns become optional for inserts, and primary keys are omitted from updates.
…The same column metadata also produces Effect Schemas for runtime validation,
so the parsed types match the InsertOf/UpdateOf types above.
…table.schemas.select, table.schemas.insert, and table.schemas.update
expose the same schemas, so Effect Schema validation and TypeScript payload
types stay aligned.
Optional mutation fields may be omitted, but an explicitly supplied undefined
is rejected by the derived schema. Use null only for nullable columns. Omit a
field to use its insert default or leave it unchanged in an update.
onConflict and upsert column targets must match table arbiter metadata:
a primary key, unique constraint, or unconditional unique index. This catches
ordinary columns before rendering SQL.
…Query.upsert(table, values, target, update) is shorthand for an insert with a
single-column onConflict, and checks the target the same way.
Query.ResultRow is the canonical row type for a plan. It is not
only the projection shape: it also includes facts introduced by joins and
predicates. Left-joined sources become nullable until a predicate proves the
source is present, and predicates such as isNotNull, eq, in, and
notIn narrow selected values.
…Literal predicates can narrow finite unions too. This applies to ordinary columns and to selected expressions that retain enough path metadata.
…These refinements are implemented by the predicate implication layer. It tracks which column and JSON-path facts are guaranteed, which optional sources have been promoted, and which row shapes are impossible under the current assumptions.
A JSON column carries its Effect Schema encoded shape through property-path
access. Paths address stored keys and return stored values, not decoded leaves.
For example, a NumberFromString field is a string when selected through a JSON
path. Whole-column selection still decodes the complete document with its codec.
Schema.encodeKeys changes the keys available to paths, not the decoded row keys.
Use root Json for portable Column.json(...) columns and Pg.Jsonb for
Postgres jsonb columns; the path shape is identical.
JSON mutations and JSON constructors return stored values too. Shape-changing expressions remain selectable; INSERT/UPDATE checks SQL expression assignments against the destination encoded shape. Plain JavaScript document inputs still use the decoded column shape and are encoded on write.
…Json.text and Jsonb.text extract SQL text. They do not parse JSON numbers
into JavaScript numbers, so cast a schema-known numeric path when you need
numeric SQL semantics.
const count = Cast.to(docs.payload.profile.metrics.count, Pg.Type.float8())
type Count = Scalar.RuntimeOf
// numberKey checks and deletes use the same paths. Deleting a path that the column schema requires makes the value stop matching that schema, which TypeScript rejects befor
暂无开放 Issues,或尚未同步最近议题。