百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
E

effect-qb

> 编程语言
开源

effect-qb 面向效果的 TypeScript 应用程序的 SQL 查询构建。effect-qb 允许您一次定义表,组合带类型的查询,并将其存储在数据库中。

189 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

effect-qb 面向效果的 TypeScript 应用程序的 SQL 查询构建。effect-qb 允许您一次定义表,组合带类型的查询,并将其存储在数据库中。

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.

Contents

  • Getting Started
    • Install
    • Quick Start
  • Core Concepts
    • How effect-qb Works
    • Defining Tables
    • Column Types and Runtime Schemas
    • Casing and Naming
  • Type Safety
    • Table Shape and Payloads
    • Conflict Targets
    • Result Rows and Predicate Facts
    • JSON and JSONB Paths
    • Casting and Type Comparison
    • Source Completeness and Aliases
    • Dialect Compatibility
    • Runtime Boundaries
  • Query Lifecycle
    • Writing Queries
    • Rendering SQL
    • Executing Queries
  • Dialects
    • Portable Standard Surface
    • Postgres
    • MySQL
    • SQLite
  • Recipes
  • Guarantees and Boundaries
    • Limitations
    • Companion Package: effect-db
  • Reference
    • API Map
    • Development

Getting Started

Install

bash
bun add effect-qb effect

Runtime requirements:

  • Node.js >=22
  • Bun >=1.3.5 for this repository's development scripts

Public query-builder import paths:

  • effect-qb - portable table, column, table-option, query, function, renderer, and casing modules
  • effect-qb/postgres - Postgres column extensions, option modifiers, renderer, executor, schema helpers
  • effect-qb/mysql - MySQL extensions, renderer, executor
  • effect-qb/sqlite - SQLite extensions, renderer, executor

Quick Start

Define 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.

Core Concepts

How effect-qb Works

effect-qb is built around a small pipeline:

Table + Column definitions
  -> typed Query plan
  -> dialect Renderer
  -> SQL + params + projection metadata
  -> dialect Executor
  -> decoded typed rows
  • Column 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.

Defining Tables

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.

typescript
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.email

Column Types and Runtime Schemas

The portable column surface includes:

  • uuid
  • text, varchar, char
  • int, bigint, number, real
  • boolean
  • date, time, datetime, timestamp
  • blob
  • json

Columns can refine their select/insert/update schemas.

typescript
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.

Casing and Naming

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

typescript
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

typescript
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

typescript
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:

  • tables
  • columns
  • schemas
  • indexes
  • constraints
  • types
  • sequences

Built-in casing styles:

  • "preserve"
  • "snake_case"
  • "camelCase"
  • "PascalCase"
  • "kebab-case"
  • "SCREAMING_SNAKE_CASE"
  • (name: string) => string

Type Safety

effect-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 Shape and Payloads

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.

Conflict Targets

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.

Result Rows and Predicate Facts

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.

JSON and JSONB Paths

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.

typescript
const count = Cast.to(docs.payload.profile.metrics.count, Pg.Type.float8())

type Count = Scalar.RuntimeOf
// number

Key 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· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

TypeScript

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言