symmetria 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mikhail Demidoff
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,350 @@
1
+ # Symmetria
2
+
3
+ A type-safe, SQL-first PostgreSQL query builder for Node.js and Bun. Declare
4
+ schemas in TypeScript, compose immutable queries and infer the exact result
5
+ shape, including relationships and nullable joins.
6
+
7
+ **Node.js 24.11+ or Bun 1.4.4+ · ESM · MIT**
8
+
9
+ [Core concepts](https://github.com/nokturnal3301/symmetria/blob/main/docs/guide.md)
10
+ explains shapes, relationships, nullability and bigint step by step.
11
+
12
+ ```ts
13
+ const authors = await db.users(
14
+ ({ name, posts }) => ({
15
+ name,
16
+ posts: posts(
17
+ ({ title, views }) => ({
18
+ title,
19
+ views,
20
+ }),
21
+ {
22
+ orderBy: ({ id }) => id.descending,
23
+ limit: 3,
24
+ },
25
+ ),
26
+ }),
27
+ { orderBy: ({ id }) => id.ascending, limit: 20 },
28
+ );
29
+ // { name: string; posts: { title: string; views: bigint }[] }[]
30
+ ```
31
+
32
+ One SQL statement, three latest posts per author, exact types throughout.
33
+
34
+ ## Install
35
+
36
+ ```sh
37
+ bun add symmetria
38
+ bun add -d symmetria-kit
39
+ ```
40
+
41
+ For Node.js: `npm install symmetria pg` and `npm install -D symmetria-kit`.
42
+ Import `postgres` from `symmetria/pg`; use `symmetria/bun` for Bun's native
43
+ pool.
44
+
45
+ The runtime provides schemas, queries, drivers and opt-in profiling.
46
+ [`symmetria-kit`](https://www.npmjs.com/package/symmetria-kit) provides
47
+ migrations, the `symmetria` command and interactive inspection. Use matching
48
+ package versions.
49
+
50
+ ## Define a schema
51
+
52
+ ```ts
53
+ // schema.ts
54
+ import {
55
+ schema,
56
+ table,
57
+ int,
58
+ text,
59
+ bigint,
60
+ oneOf,
61
+ timestamptz,
62
+ } from "symmetria";
63
+
64
+ const users = table({
65
+ id: int.auto,
66
+ name: text,
67
+ email: text.unique,
68
+ });
69
+
70
+ const posts = table({
71
+ id: int.auto,
72
+ title: text,
73
+ author: users.index,
74
+ views: bigint.default(0n),
75
+ state: oneOf("draft", "published").default("draft"),
76
+ createdAt: timestamptz.now,
77
+ });
78
+
79
+ export const appSchema = schema({ users, posts });
80
+ ```
81
+
82
+ Each table can live in its own module. `author: users.index` declares a foreign
83
+ key, its index and the `posts.author` / `users.posts` relationships. Columns are
84
+ non-null by default. Property names map from camelCase to snake_case.
85
+ `users.by("email")` references a unique column instead of the primary key and
86
+ `users.column("created_by")` keeps a legacy column name. Tables that relate
87
+ through plain columns declare the join predicate instead:
88
+ `table({...}).relations((post, { to }) => ({ author: to(users).one((user) => post.authorName.is(user.name)) }))`
89
+ adds a relation without a foreign key. `numeric` and `varchar` work bare or with
90
+ arguments; schema mistakes name the table and column and explain the fix.
91
+
92
+ ## Create the tables
93
+
94
+ ```ts
95
+ // symmetria.config.ts
96
+ import { defineMigrationConfig } from "symmetria-kit";
97
+ import { appSchema } from "./schema.ts";
98
+
99
+ export default defineMigrationConfig({
100
+ schema: appSchema,
101
+ directory: "./migrations",
102
+ databaseUrl: process.env.DATABASE_URL,
103
+ });
104
+ ```
105
+
106
+ Set `DATABASE_URL` to a PostgreSQL connection URL, then generate and review the
107
+ migration before applying it:
108
+
109
+ ```sh
110
+ bunx --package symmetria-kit symmetria generate initial
111
+ bunx --package symmetria-kit symmetria migrate
112
+ ```
113
+
114
+ ## Write and query
115
+
116
+ ```ts
117
+ // main.ts — bun main.ts
118
+ import { createDatabase } from "symmetria";
119
+ import { postgres } from "symmetria/bun";
120
+ import { appSchema } from "./schema.ts";
121
+
122
+ const database = createDatabase({
123
+ schema: appSchema,
124
+ driver: postgres({ url: process.env.DATABASE_URL! }),
125
+ });
126
+
127
+ try {
128
+ await database.users
129
+ .insert({ name: "Ada", email: "ada@example.com" })
130
+ .onConflict("email")
131
+ .doNothing();
132
+
133
+ const author = await database.users.by.email("ada@example.com").one();
134
+ await database.posts.insert({ title: "Typed SQL", authorId: author.id });
135
+
136
+ const authors = await database.users(({ name, posts }) => ({
137
+ name,
138
+ posts: posts(({ title, views }) => ({ title, views }), {
139
+ orderBy: ({ id }) => id.descending,
140
+ limit: 3,
141
+ }),
142
+ }));
143
+ // { name: string; posts: { title: string; views: bigint }[] }[]
144
+
145
+ console.log(authors);
146
+ } finally {
147
+ await database.$close();
148
+ }
149
+ ```
150
+
151
+ Nested collections load in one statement, with limits applied per parent. Empty
152
+ collections are `[]`; optional to-one selections are `null`. `await query` and
153
+ `.execute()` both execute; `.toSQL()` only compiles SQL and bound parameters.
154
+ Relation paths such as `posts.author.name` add the required JOINs.
155
+
156
+ ## JOINs and composition
157
+
158
+ Tables, relations, aliases and CTEs share one callable SELECT API. The
159
+ projection selects fields; a separate options object accepts `where`, `orderBy`,
160
+ `groupBy`, `having`, `limit`, `offset`, `distinct`, `forUpdate` and `forShare`.
161
+ Each option can be a value or a synchronous callback receiving the same typed
162
+ source and SQL tools.
163
+
164
+ ```ts
165
+ const feed = database.posts(
166
+ ({ title, authorId }, { join }) => ({ title, author: join(authorId).name }),
167
+ { orderBy: ({ id }) => id.descending },
168
+ );
169
+ const page = feed({ limit: 10 });
170
+ ```
171
+
172
+ `join`, `innerJoin` and `leftJoin` infer the target and ON condition from a
173
+ relation or FK column. Smart `join` uses INNER for required forward references
174
+ and LEFT for optional/reverse relations. Repeated sources and self-JOINs receive
175
+ automatic aliases. Explicit sources use an ON callback; `crossJoin` creates a
176
+ Cartesian product. Options-only calls preserve the previous selection; branches
177
+ are immutable.
178
+
179
+ Smart JOINs also use LEFT for junction relations and propagate optional
180
+ ancestry. `crossJoin` can infer its target from an FK or relation, without an ON
181
+ condition. Explicit aliases must be unique within the query. Filters, ordering
182
+ and grouping append; new selected fields replace the projection and new
183
+ LIMIT/OFFSET replace previous counts. Fixed counts are validated integer
184
+ literals; explicit prepared count parameters remain bound placeholders.
185
+
186
+ ## Reusable projections and aggregates
187
+
188
+ Reusable projections bind to each source occurrence, including aliases and
189
+ relations:
190
+
191
+ ```ts
192
+ const userCard = database.users.shape((user) => ({ name: user.name }));
193
+ const feed = database.posts((post) => ({
194
+ title: post.title,
195
+ author: post.author(userCard),
196
+ }));
197
+ ```
198
+
199
+ `.shape()` stores a synchronous callback and evaluates it on each application. A
200
+ projection belongs to its defining table, contains at least one selected field
201
+ and has no `$...` controls. Apply options at use sites, for example
202
+ `database.users(userCard, { limit: 20 })`. It can be defined on an offline
203
+ schema and used on its connected or transaction-bound tables. To-one selections
204
+ are typed as an object or `null`.
205
+
206
+ Relations offer `count`, `exists`, `sum`, `average`, `minimum` and `maximum`:
207
+
208
+ ```ts
209
+ const totals = database.users(({ name, posts }) => ({
210
+ name,
211
+ totalViews: posts.sum.views,
212
+ latestPost: posts.maximum.createdAt,
213
+ recentViews: posts({
214
+ where: ({ state }) => state.is.published,
215
+ orderBy: ({ id }) => id.descending,
216
+ limit: 3,
217
+ }).sum.views,
218
+ weightedViews: posts.sum((post) => post.views.multiply(2n)),
219
+ }));
220
+ ```
221
+
222
+ Plain columns aggregate through properties (`posts.sum.views`); expressions use
223
+ the callback form. Filters and pagination select input rows before aggregation.
224
+ `sum` / `average` return decimal strings or `null`; `minimum` / `maximum`
225
+ preserve the column's value type and codec, plus `null`. Empty or all-NULL value
226
+ inputs produce `null`; `count()` returns `0` and `exists()` returns `false` for
227
+ empty inputs.
228
+
229
+ ## Enum mappings
230
+
231
+ ```ts
232
+ const labels = database.posts((post) => ({
233
+ title: post.title,
234
+ status: post.state.match({ draft: "Draft", published: "Published" }),
235
+ visibleViews: post.state.match({ draft: 0n, published: post.views }),
236
+ }));
237
+ ```
238
+
239
+ `.match()` emits SQL CASE with exactly one branch per enum member. Branches
240
+ accept scalar literals or compatible SQL expressions. Nullable inputs produce
241
+ `null`; bigint, Date and expression codecs survive nested results, aliases and
242
+ CTEs.
243
+
244
+ ## Write callbacks
245
+
246
+ ```ts
247
+ const updated = await database.posts
248
+ .byId(42)
249
+ .update((post) => ({ views: post.views.plus(1n) }))
250
+ .returning((post) => ({ id: post.id, views: post.views }));
251
+
252
+ const userCard = database.users.shape(({ id, name }) => ({ id, name }));
253
+ await database.users.by
254
+ .email("ada@example.com")
255
+ .update({ name: "Ada Lovelace" })
256
+ .returning(userCard);
257
+
258
+ await database.users
259
+ .insert({ name: "Ada Lovelace", email: "ada@example.com" })
260
+ .onConflict("email")
261
+ .doUpdate((user, excluded) => ({ email: user.email, name: excluded.name }));
262
+
263
+ await database.posts.update({ state: "draft" }).all(); // whole table, spelled out
264
+ ```
265
+
266
+ `byId()` and `.by.<key>()` lookups update and delete directly, in one statement.
267
+ `returning()` accepts a callback or a row-local reusable projection of the same
268
+ table. UPDATE, WHERE and RETURNING callbacks receive the row directly, including
269
+ nested-insert RETURNING. Upserts receive the existing row first and the proposed
270
+ `excluded` row second. `.doUpdate("name")` copies a field from `excluded`. An
271
+ UPDATE or DELETE without `where()` is refused unless `.all()` confirms it.
272
+
273
+ ## Capabilities
274
+
275
+ - Shape-first projections, explicit or FK-inferred JOINs, `some`/`none`/`every`.
276
+ - CRUD, bulk writes, upserts, unique-key lookups with direct writes, reusable
277
+ RETURNING projections and atomic nested inserts.
278
+ - CTEs, recursive CTEs, window functions, aggregates and subqueries.
279
+ - Callable prepared queries with `one` / `maybeOne` / `first` / `count` /
280
+ `exists` / `inspect`, keyset pagination in both directions and `pages()` async
281
+ iteration; `count()` and `exists()` on any table or filtered source.
282
+ - Transactions, nested savepoints, isolation options and row locks.
283
+ - `Transaction<typeof database>` for schema-specific transaction helpers.
284
+ - `$scope()` filters for reads, updates and deletes, including related tables.
285
+ - Bigint, decimal-string, Date and custom codecs, including nested JSON results;
286
+ `smallint`, `real`, `doublePrecision`, `date`, `time`, `interval`, `bytea` and
287
+ `inet` as first-class builders.
288
+ - Conditional upserts: `doUpdate(values, { where: (current, incoming) => … })`.
289
+ - Arrays, full-text search with stored `tsvector` columns, weighted documents,
290
+ ranking and headlines, pgvector embeddings with distance operators and HNSW
291
+ indexes (`symmetria/vector`), typed JSON paths and Standard Schema JSON
292
+ validation.
293
+ - Computed fields, branded IDs, indexes, primary keys and CHECK constraints.
294
+ - Condition relations (`.relations()`) that join by a predicate without a
295
+ foreign key, in both directions, invisible to migrations.
296
+ - `stream()` server-side cursors, `$transaction` retries after serialization
297
+ failures and deadlocks, `Infer` / `InferInsert` / `InferUpdate` / `InferShape`
298
+ type aliases, predicate lists that skip `undefined`, `null` and `false`, and
299
+ "did you mean" hints for unknown columns and relations.
300
+
301
+ `count()` and ranking functions return `number`; PostgreSQL `bigint` columns
302
+ decode to `bigint`, and `numeric()` values retain decimal precision as strings.
303
+ Single-object `insert().returning()` returns one row; bulk inserts return
304
+ arrays.
305
+
306
+ ## Inspect and profile
307
+
308
+ ```ts
309
+ await query.inspect(); // Requires symmetria-kit for the terminal UI.
310
+
311
+ const report = await query.inspect({ interactive: false });
312
+ console.log(report.sql, report.parameters); // Works with the runtime alone.
313
+ ```
314
+
315
+ The interactive inspector offers SQL, Parameters, Results and Explain tabs.
316
+ `createProfiler()` adds opt-in request traces with build, compile, database and
317
+ decode timings. Pass it to `postgres({ url, profiler })`, wrap requests with
318
+ `profiler.fetch(handler)` and expose the local endpoint with
319
+ `await profiler.serve()`. Every request to it carries a token; set
320
+ `SYMMETRIA_PROFILE_TOKEN` for the application and the CLI, then open
321
+ `bunx --package symmetria-kit symmetria profile`.
322
+
323
+ ## Drivers
324
+
325
+ Official drivers ship with `symmetria` and are maintained and released together:
326
+
327
+ ```ts
328
+ import { createDatabase } from "symmetria";
329
+ import { postgres } from "symmetria/pg";
330
+
331
+ const database = createDatabase({
332
+ schema: appSchema,
333
+ driver: postgres({ url: process.env.DATABASE_URL!, max: 10 }),
334
+ });
335
+ ```
336
+
337
+ `symmetria/driver` re-exports `symmetria/pg`. Install `pg` when using either;
338
+ `symmetria/bun` needs no external database driver. Each accepts a URL or its
339
+ underlying pool options plus `url` and `profiler`.
340
+
341
+ Both adapters return `{ rows, affectedRows }`, preserve bigint/numeric
342
+ precision, support nested transactions and pinned sessions, and drain accepted
343
+ operations on close. Session settings belong to a connection: use
344
+ `driver.session()` for multi-statement workflows. For isolated PostgreSQL test
345
+ schemas, use `testDatabase()` from `symmetria-kit/testing`, optionally passing a
346
+ `driver` factory.
347
+
348
+ ## License
349
+
350
+ [MIT](https://opensource.org/license/mit).