npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

symmetria

v3.7.1

Published

Type-safe, SQL-first PostgreSQL query builder for Node.js and Bun.

Readme

Symmetria

A type-safe, SQL-first PostgreSQL query builder for Node.js and Bun. The result you describe in TypeScript becomes exactly one SQL statement, however deep the nesting, typed to the field and as fast as hand-written SQL. Declare the schema once; it drives queries, migrations, drift detection and pull for existing databases.

Node.js 24.11+ or Bun 1.4.4+ · ESM · MIT

Core concepts explains shapes, relationships, nullability and bigint step by step.

const authors = await db.users(
  ({ name, posts }) => ({
    name,
    posts: posts(
      ({ title, views }) => ({
        title,
        views,
      }),
      {
        orderBy: ({ id }) => id.descending,
        limit: 3,
      },
    ),
  }),
  { orderBy: ({ id }) => id.ascending, limit: 20 },
);
// { name: string; posts: { title: string; views: bigint }[] }[]

One SQL statement, three latest posts per author, exact types throughout.

Install

bun add symmetria
bun add -d symmetria-kit

For Node.js: npm install symmetria pg and npm install -D symmetria-kit. Import postgres from symmetria/pg; use symmetria/bun for Bun's native pool.

The runtime provides schemas, queries, drivers and opt-in profiling. symmetria-kit provides migrations, the symmetria command and interactive inspection. Use matching package versions.

Define a schema

// schema.ts
import {
  schema,
  table,
  one,
  many,
  int,
  text,
  bigint,
  oneOf,
  timestamptz,
} from "symmetria";

const users = table({
  id: int.auto,
  name: text,
  email: text.unique,
  posts: many,
});

const posts = table({
  id: int.auto,
  title: text,
  author: one(users.posts),
  views: bigint.default(0n),
  state: oneOf("draft", "published").default("draft"),
  createdAt: timestamptz.now,
});

export const appSchema = schema({ users, posts });

Each table can live in its own module. author: one(users.posts) declares a foreign key, its index and the posts.author relationship, and claims the slot posts: many that users declares for the other side; maybe() is the optional form, many(tags.posts) a many-to-many relation with its junction table. author: users.index is the earlier spelling of the same key. Columns are non-null by default. Property names map from camelCase to snake_case. users.by("email") references a unique column instead of the primary key and users.column("created_by") keeps a legacy column name. Tables that relate through plain columns declare the join predicate instead: table({...}).relations((post, { to }) => ({ author: to(users).one((user) => post.authorName.is(user.name)) })) adds a relation without a foreign key. numeric and varchar work bare or with arguments; schema mistakes name the table and column and explain the fix.

Create the tables

// symmetria.config.ts
import { defineMigrationConfig } from "symmetria-kit";
import { appSchema } from "./schema.ts";

export default defineMigrationConfig({
  schema: appSchema,
  directory: "./migrations",
  databaseUrl: process.env.DATABASE_URL,
});

Set DATABASE_URL to a PostgreSQL connection URL, then generate and review the migration before applying it:

bunx --package symmetria-kit symmetria generate initial
bunx --package symmetria-kit symmetria migrate

Write and query

// main.ts — bun main.ts
import { createDatabase } from "symmetria";
import { postgres } from "symmetria/bun";
import { appSchema } from "./schema.ts";

const db = createDatabase({
  schema: appSchema,
  driver: postgres({ url: process.env.DATABASE_URL! }),
});

try {
  await db.users
    .insert({ name: "Ada", email: "[email protected]" })
    .onConflict("email")
    .doNothing();

  const author = await db.users.get({ email: "[email protected]" });
  await db.posts.insert({ title: "Typed SQL", authorId: author.id });

  const authors = await db.users(({ name, posts }) => ({
    name,
    posts: posts(({ title, views }) => ({ title, views }), {
      orderBy: ({ id }) => id.descending,
      limit: 3,
    }),
  }));
  // { name: string; posts: { title: string; views: bigint }[] }[]

  console.log(authors);
} finally {
  await db.$close();
}

Nested collections load in one statement, with limits applied per parent. Empty collections are []; optional to-one selections are null. await query and .execute() both execute; .toSQL() only compiles SQL and bound parameters. Relation paths such as posts.author.name add the required JOINs.

JOINs and composition

Tables, relations, aliases and CTEs share one callable SELECT API. The projection selects fields; a separate options object accepts where, orderBy, groupBy, having, limit, offset, distinct, forUpdate and forShare. Each option can be a value or a synchronous callback receiving the same typed source and SQL tools.

const feed = db.posts(
  ({ title, authorId }, { join }) => ({ title, author: join(authorId).name }),
  { orderBy: ({ id }) => id.descending },
);
const page = feed({ limit: 10 });

join, innerJoin and leftJoin infer the target and ON condition from a relation or FK column. Smart join uses INNER for required forward references and LEFT for optional/reverse relations and for a target a $scope() filters. Repeated sources and self-JOINs receive automatic aliases. Explicit sources use an ON callback; a query with its own fields or options joins only as a subquery named with .as("name"). crossJoin creates a Cartesian product. Options-only calls preserve the previous selection; branches are immutable.

Smart JOINs also use LEFT for junction relations and propagate optional ancestry. crossJoin can infer its target from an FK or relation, without an ON condition. Explicit aliases must be unique within the query. Filters, ordering and grouping append; new selected fields replace the projection and new LIMIT/OFFSET replace previous counts. Fixed counts are validated integer literals; explicit prepared count parameters remain bound placeholders.

Reusable projections and aggregates

Reusable projections bind to each source occurrence, including aliases and relations:

const userCard = db.users.shape((user) => ({ name: user.name }));
const feed = db.posts((post) => ({
  title: post.title,
  author: post.author(userCard),
}));

.shape() stores a synchronous callback and evaluates it on each application. A projection belongs to its defining table and selects at least one field; field names starting with $ are reserved. Apply options at use sites, for example db.users(userCard, { limit: 20 }). It can be defined on an offline schema and used on its connected or transaction-bound tables. To-one selections are typed as an object or null.

Relations offer count, exists, sum, average, minimum and maximum:

const totals = db.users(({ name, posts }) => ({
  name,
  totalViews: posts.sum.views,
  latestPost: posts.maximum.createdAt,
  recentViews: posts({
    where: ({ state }) => state.is.published,
    orderBy: ({ id }) => id.descending,
    limit: 3,
  }).sum.views,
  weightedViews: posts.sum((post) => post.views.multiply(2n)),
}));

Plain columns aggregate through properties (posts.sum.views); expressions use the callback form. Filters and pagination select input rows before aggregation. sum / average return decimal strings or null. minimum / maximum keep the column's value type and codec, plus null, and take any column: booleans, uuid and bytea too, and JSON values, which they order as jsonb does (numbers by value). Empty or all-NULL value inputs produce null; count() returns 0 and exists() returns false for empty inputs.

Enum mappings

const labels = db.posts((post) => ({
  title: post.title,
  status: post.state.match({ draft: "Draft", published: "Published" }),
  visibleViews: post.state.match({ draft: 0n, published: post.views }),
}));

.match() emits SQL CASE with exactly one branch per enum member. Branches accept scalar literals or compatible SQL expressions. Nullable inputs produce null; bigint, Date and expression codecs survive nested results, aliases and CTEs.

Write callbacks

const updated = await db.posts
  .byId(42)
  .update((post) => ({ views: post.views.plus(1n) }))
  .returning("id", "views");

const userCard = db.users.shape(({ id, name }) => ({ id, name }));
await db.users.by
  .email("[email protected]")
  .update({ name: "Ada Lovelace" })
  .returning(userCard);

await db.users
  .insert({ name: "Ada Lovelace", email: "[email protected]" })
  .onConflict("email")
  .doUpdate((user, excluded) => ({ email: user.email, name: excluded.name }));

await db.posts.update({ state: "draft" }).all(); // whole table, spelled out

byId() and .by.<key>() lookups update and delete directly, in one statement. returning() accepts column names, a callback or a row-local reusable projection of the same table. UPDATE, WHERE and RETURNING callbacks receive the row directly, including nested-insert RETURNING. Upserts receive the existing row first and the proposed excluded row second. .doUpdate("name") copies a field from excluded. An UPDATE or DELETE without where() is refused unless .all() confirms it, and so is one whose filter holds for every row, such as and() or notIn([]).

Capabilities

  • Relations declared on both sides (posts: many, author: one(users.posts), tags: many(tags.posts)), checked by the types and when the schema is built.
  • $batch(): several reads as one statement, with one snapshot of the data.
  • get(id) / find(id), whole-row reads (users({ where: { active: true } })), object filters and ordering, aggregate(), upsert(), and write filters as options.
  • Error classes for instanceof: NotFoundError, UniqueViolation, ForeignKeyViolation and the rest, with the constraint, table and column.
  • Shape-first projections, explicit or FK-inferred JOINs, some/none/every.
  • CRUD, bulk writes, upserts, unique-key lookups with direct writes, reusable RETURNING projections and atomic nested inserts.
  • CTEs, recursive CTEs, window functions, aggregates and subqueries.
  • Callable prepared queries with one / maybeOne / first / count / exists / inspect, keyset pagination in both directions and pages() async iteration; count() and exists() on any table or filtered source.
  • Transactions, nested savepoints, isolation options and row locks.
  • Transaction<typeof db> for schema-specific transaction helpers.
  • $scope() filters for reads, updates and deletes, including related and joined tables, and checks every row a scoped insert, upsert or update writes, like row-level security's WITH CHECK (SYMMETRIA_OUT_OF_SCOPE); reused and prepared queries bind the current tenant at every execution. A scope filter that holds for every row, such as and(tenant && post.tenantId.is(tenant)) without a tenant, is refused instead of reading every tenant's rows.
  • Bigint, decimal-string, Date and custom codecs, including nested JSON results; smallint, real, doublePrecision, date, time, interval, bytea and inet as first-class builders.
  • Conditional upserts: doUpdate(values, { where: (current, incoming) => … }).
  • Any SQL names: casing: "preserve" for camelCase databases such as Prisma's, .named() on tables and columns, .onUpdate.cascade foreign keys and timestamp(3) columns read as UTC dates; enum types named and shared with oneOf(...).typeName("Role"), collations with text.collate("C"), int.auto.byDefault identities that also accept explicit ids, and derived names over 63 bytes shortened with a hash.
  • Exact arithmetic typed as PostgreSQL computes it: quantity.multiply(price) and quantity.divide(2) are Decimal (division never truncates), quantity.quotient(2) is integer division, real columns stay floats.
  • databaseError(error) describes unique, foreign-key, not-null and check violations and lost connections the same way on both drivers; one() errors carry a code. Invalid values (out-of-range numbers, invalid jsonb(schema) input, null for NOT NULL columns) reject the query's promise when it runs; mistakes in the query's shape throw where it is built.
  • table.search(): hybrid search declared on the table, by words (full text or BM25) and by meaning (embeddings computed on insert), merged in one statement (symmetria/search; models from symmetria/voyage, openai, cohere, google, mistral, jina, ollama).
  • symmetria/better-auth: a better-auth adapter; npx auth generate writes the auth tables as part of your schema.
  • Arrays, full-text search with stored tsvector columns, weighted documents, ranking and headlines, pgvector embeddings with distance operators and HNSW and IVFFlat indexes (symmetria/vector), typed JSON paths and Standard Schema JSON validation.
  • Computed fields, branded IDs, indexes, primary keys and CHECK constraints.
  • Condition relations (.relations()) that join by a predicate without a foreign key, in both directions, invisible to migrations.
  • stream() server-side cursors, $transaction retries after serialization failures and deadlocks, Infer / InferInsert / InferUpdate / InferShape type aliases, predicate lists that skip undefined, null and false, and "did you mean" hints for unknown columns and relations.

count() and ranking functions return number; PostgreSQL bigint columns decode to bigint, and numeric() values retain decimal precision as strings. Single-object insert().returning() returns one row; bulk inserts return arrays.

Inspect and profile

await query.inspect(); // Requires symmetria-kit for the terminal UI.

const report = await query.inspect({ interactive: false });
console.log(report.sql, report.parameters); // Works with the runtime alone.

The interactive inspector offers SQL, Parameters, Results and Explain tabs. createProfiler() adds opt-in request traces with build, compile, database and decode timings. Pass it to postgres({ url, profiler }), wrap requests with profiler.fetch(handler) and expose the local endpoint with await profiler.serve(). Every request to it carries a token; set SYMMETRIA_PROFILE_TOKEN for the application and the CLI, then open bunx --package symmetria-kit symmetria profile.

traced(driver, { tracer }) from symmetria/opentelemetry reports every statement and transaction as an OpenTelemetry span.

Drivers

Official drivers ship with symmetria and are maintained and released together:

import { createDatabase } from "symmetria";
import { postgres } from "symmetria/pg";

const db = createDatabase({
  schema: appSchema,
  driver: postgres({ url: process.env.DATABASE_URL!, max: 10 }),
});

symmetria/driver re-exports symmetria/pg. Install pg when using either (Symmetria declares the pool options itself, so @types/pg is not needed); symmetria/bun needs no external database driver. Each accepts a URL or its underlying pool options plus url and profiler.

Both adapters return { rows, affectedRows }, read values the same way, preserve bigint/numeric precision and support nested transactions and pinned sessions. On close they refuse new work, end the transactions of open stream() loops and wait for the other operations they accepted. Operations on a transaction or session run one at a time in call order. Session settings belong to a connection: use driver.session() for multi-statement workflows; its connection is closed afterwards, so its settings, locks and temporary tables never reach other queries. For isolated PostgreSQL test schemas, use testDatabase() from symmetria-kit/testing, optionally passing a driver factory.

Behind a transaction-mode pooler such as PgBouncer, queries, transactions, streams and prepared queries work on both adapters; pass prepare: false to symmetria/bun unless the pooler tracks named statements (PgBouncer 1.21+ with max_prepared_statements), and set search_path on the role rather than in the URL. driver.session() cannot pin a server connection there. See transaction pooling.

License

MIT.