better-schemic 0.1.0-beta.4 → 0.1.0-beta.5
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/README.md +88 -65
- package/lib/cli/driver-commands.d.ts +1 -1
- package/lib/cli/index.js +29 -36
- package/lib/cli/index.js.map +24 -24
- package/lib/cli/inspect.d.ts +1 -1
- package/lib/config.d.ts +1 -1
- package/lib/config.js +198 -129
- package/lib/config.js.map +49 -49
- package/lib/connection.js +198 -129
- package/lib/connection.js.map +48 -48
- package/lib/core/cli-kit/config.d.ts +4 -4
- package/lib/core/client.d.ts +4 -4
- package/lib/core/config.d.ts +13 -13
- package/lib/core/connection.d.ts +1 -1
- package/lib/core/driver/driver.d.ts +2 -2
- package/lib/core/driver/sdk.js +3 -3
- package/lib/core/driver/sdk.js.map +5 -5
- package/lib/core/index.d.ts +2 -2
- package/lib/core/index.js +6 -11
- package/lib/core/index.js.map +9 -9
- package/lib/core/kind/registry.d.ts +1 -1
- package/lib/core/testing.d.ts +1 -1
- package/lib/driver.js +25 -34
- package/lib/driver.js.map +21 -21
- package/lib/index.d.ts +1 -1
- package/lib/index.js +9 -9
- package/lib/index.js.map +7 -7
- package/lib/logger.js.map +2 -2
- package/lib/orm/index.d.ts +1 -1
- package/lib/orm/index.js +203 -134
- package/lib/orm/index.js.map +48 -48
- package/lib/otel/index.d.ts +1 -1
- package/lib/otel/index.js.map +1 -1
- package/lib/otel/logger.d.ts +2 -2
- package/lib/plugins/create-only.js +26 -26
- package/lib/plugins/create-only.js.map +9 -9
- package/lib/plugins/hard-delete.js +16 -16
- package/lib/plugins/hard-delete.js.map +6 -6
- package/lib/plugins/rules.js +19 -19
- package/lib/plugins/rules.js.map +6 -6
- package/lib/plugins/soft-delete.js +19 -19
- package/lib/plugins/soft-delete.js.map +8 -8
- package/lib/plugins/tenant.js +37 -37
- package/lib/plugins/tenant.js.map +11 -11
- package/lib/plugins/timestamps.js +19 -19
- package/lib/plugins/timestamps.js.map +8 -8
- package/lib/plugins/zod.js +39 -29
- package/lib/plugins/zod.js.map +9 -9
- package/lib/query.js +4 -4
- package/lib/query.js.map +3 -3
- package/lib/surreal/cli/introspect.d.ts +1 -1
- package/lib/surreal/cli/pull.d.ts +1 -1
- package/lib/surreal/commands.d.ts +1 -1
- package/lib/surreal/connect.d.ts +1 -1
- package/lib/surreal/connection.d.ts +1 -1
- package/lib/surreal/ddl.d.ts +1 -1
- package/lib/surreal/driver/surreal.d.ts +1 -1
- package/lib/surreal/index.d.ts +2 -2
- package/lib/surreal/kinds/explode.d.ts +1 -1
- package/lib/surreal/kinds/portable.d.ts +1 -1
- package/lib/surreal/logger.d.ts +1 -1
- package/lib/surreal/orm/arithmetic.d.ts +11 -1
- package/lib/surreal/orm/client.d.ts +16 -16
- package/lib/surreal/orm/compiler/adjustment.d.ts +10 -0
- package/lib/surreal/orm/compiler/aggregate-entries.d.ts +1 -1
- package/lib/surreal/orm/compiler/aggregate-split.d.ts +1 -1
- package/lib/surreal/orm/compiler/aggregate.d.ts +1 -1
- package/lib/surreal/orm/compiler/shared.d.ts +2 -2
- package/lib/surreal/orm/compiler/write-shared.d.ts +1 -1
- package/lib/surreal/orm/connect.d.ts +10 -10
- package/lib/surreal/orm/delegate.d.ts +2 -2
- package/lib/surreal/orm/errors.d.ts +18 -18
- package/lib/surreal/orm/fn.d.ts +9 -0
- package/lib/surreal/orm/index.d.ts +8 -8
- package/lib/surreal/orm/logger/index.d.ts +3 -3
- package/lib/surreal/orm/results.d.ts +3 -3
- package/lib/surreal/orm/schema.d.ts +4 -4
- package/lib/surreal/orm/transaction.d.ts +1 -1
- package/lib/surreal/orm/types/client.d.ts +3 -3
- package/lib/surreal/orm/types/fn.d.ts +1 -1
- package/lib/surreal/orm/types/hooks.d.ts +3 -3
- package/lib/surreal/orm/types/live.d.ts +1 -1
- package/lib/surreal/orm/types/logger.d.ts +1 -1
- package/lib/surreal/orm/types/plugins.d.ts +1 -1
- package/lib/surreal/orm/types/raw.d.ts +1 -1
- package/lib/surreal/orm/types/schema.d.ts +9 -9
- package/lib/surreal/orm/types/select.d.ts +1 -1
- package/lib/surreal/orm/types/transaction.d.ts +2 -2
- package/lib/surreal/orm/types/write.d.ts +56 -10
- package/lib/surreal/plugins/create-only.d.ts +3 -3
- package/lib/surreal/plugins/hard-delete.d.ts +1 -1
- package/lib/surreal/plugins/rules.d.ts +1 -1
- package/lib/surreal/plugins/soft-delete.d.ts +2 -2
- package/lib/surreal/plugins/tenant-runtime.d.ts +2 -2
- package/lib/surreal/plugins/tenant-shared.d.ts +2 -2
- package/lib/surreal/plugins/tenant.d.ts +5 -5
- package/lib/surreal/plugins/zod.d.ts +1 -1
- package/lib/surreal/pure.d.ts +13 -13
- package/lib/surreal/seed.d.ts +1 -1
- package/lib/testing.js.map +2 -2
- package/package.json +2 -2
- package/src/cli/driver-commands.ts +1 -1
- package/src/cli/index.ts +5 -5
- package/src/cli/inspect.ts +1 -1
- package/src/config.ts +1 -1
- package/src/core/cli-kit/config.ts +15 -21
- package/src/core/cli-kit/merge.ts +4 -2
- package/src/core/client.ts +6 -6
- package/src/core/config.ts +19 -21
- package/src/core/connection.ts +3 -3
- package/src/core/driver/driver.ts +2 -2
- package/src/core/index.ts +3 -3
- package/src/core/kind/registry.ts +1 -1
- package/src/core/testing.ts +3 -3
- package/src/index.ts +2 -1
- package/src/orm/index.ts +1 -1
- package/src/otel/index.ts +1 -1
- package/src/otel/logger.ts +4 -4
- package/src/surreal/cli/format.ts +2 -1
- package/src/surreal/cli/introspect.ts +2 -7
- package/src/surreal/cli/pull.ts +8 -16
- package/src/surreal/cli/scaffold.ts +13 -13
- package/src/surreal/cli/surreal-diff.ts +6 -1
- package/src/surreal/commands.ts +2 -1
- package/src/surreal/connect.ts +1 -1
- package/src/surreal/connection.ts +1 -1
- package/src/surreal/ddl.ts +1 -1
- package/src/surreal/driver/surreal.ts +1 -1
- package/src/surreal/index.ts +11 -11
- package/src/surreal/kinds/explode.ts +2 -2
- package/src/surreal/kinds/portable.ts +1 -1
- package/src/surreal/kinds/registry.ts +1 -1
- package/src/surreal/logger.ts +1 -1
- package/src/surreal/orm/admin.ts +4 -4
- package/src/surreal/orm/api.ts +3 -3
- package/src/surreal/orm/arithmetic.ts +33 -10
- package/src/surreal/orm/auth.ts +3 -3
- package/src/surreal/orm/client.ts +26 -30
- package/src/surreal/orm/compiler/adjustment.ts +171 -14
- package/src/surreal/orm/compiler/aggregate-entries.ts +25 -12
- package/src/surreal/orm/compiler/aggregate-operand.ts +7 -4
- package/src/surreal/orm/compiler/aggregate-split.ts +13 -10
- package/src/surreal/orm/compiler/aggregate.ts +18 -17
- package/src/surreal/orm/compiler/include/count.ts +2 -2
- package/src/surreal/orm/compiler/include/index.ts +2 -2
- package/src/surreal/orm/compiler/keyset.ts +2 -2
- package/src/surreal/orm/compiler/mutate.ts +12 -11
- package/src/surreal/orm/compiler/projection.ts +0 -1
- package/src/surreal/orm/compiler/relate.ts +4 -4
- package/src/surreal/orm/compiler/relations.ts +10 -10
- package/src/surreal/orm/compiler/select.ts +5 -2
- package/src/surreal/orm/compiler/shared.ts +5 -9
- package/src/surreal/orm/compiler/unique.ts +8 -9
- package/src/surreal/orm/compiler/write-shared.ts +9 -4
- package/src/surreal/orm/connect.ts +13 -13
- package/src/surreal/orm/delegate.ts +5 -5
- package/src/surreal/orm/errors.ts +37 -47
- package/src/surreal/orm/execute.ts +3 -3
- package/src/surreal/orm/fn.ts +3 -4
- package/src/surreal/orm/index.ts +14 -13
- package/src/surreal/orm/live.ts +7 -7
- package/src/surreal/orm/logger/index.ts +3 -3
- package/src/surreal/orm/plugins.ts +6 -9
- package/src/surreal/orm/raw.ts +1 -1
- package/src/surreal/orm/results.ts +4 -8
- package/src/surreal/orm/schema.ts +14 -20
- package/src/surreal/orm/transaction.ts +20 -30
- package/src/surreal/orm/types/client.ts +3 -3
- package/src/surreal/orm/types/fn.ts +6 -4
- package/src/surreal/orm/types/hooks.ts +3 -3
- package/src/surreal/orm/types/live.ts +1 -1
- package/src/surreal/orm/types/logger.ts +1 -1
- package/src/surreal/orm/types/plugins.ts +1 -1
- package/src/surreal/orm/types/raw.ts +1 -1
- package/src/surreal/orm/types/schema.ts +10 -12
- package/src/surreal/orm/types/select.ts +19 -7
- package/src/surreal/orm/types/transaction.ts +2 -2
- package/src/surreal/orm/types/write.ts +62 -11
- package/src/surreal/orm/writes.ts +6 -6
- package/src/surreal/plugins/create-only.ts +13 -17
- package/src/surreal/plugins/hard-delete.ts +1 -1
- package/src/surreal/plugins/rules.ts +5 -5
- package/src/surreal/plugins/soft-delete.ts +1 -1
- package/src/surreal/plugins/tenant-runtime.ts +16 -16
- package/src/surreal/plugins/tenant-shared.ts +3 -3
- package/src/surreal/plugins/tenant.ts +9 -9
- package/src/surreal/plugins/timestamps.ts +1 -1
- package/src/surreal/plugins/zod.ts +3 -3
- package/src/surreal/pure.ts +24 -25
- package/src/surreal/seed.ts +1 -1
package/README.md
CHANGED
|
@@ -24,17 +24,17 @@ replay into — `npm i -D @surrealdb/node`).
|
|
|
24
24
|
|
|
25
25
|
## Subpaths
|
|
26
26
|
|
|
27
|
-
| Import
|
|
28
|
-
|
|
|
29
|
-
| `better-schemic`
|
|
30
|
-
| `better-schemic/connection` | `surrealConnection` — the config factory
|
|
31
|
-
| `better-schemic/config`
|
|
32
|
-
| `better-schemic/orm`
|
|
33
|
-
| `better-schemic/query`
|
|
34
|
-
| `better-schemic/plugins/*`
|
|
35
|
-
| `better-schemic/logger`
|
|
36
|
-
| `better-schemic/otel`
|
|
37
|
-
| `better-schemic/driver`
|
|
27
|
+
| Import | What you get |
|
|
28
|
+
| --------------------------- | ---------------------------------------------------------------------------- |
|
|
29
|
+
| `better-schemic` | the authoring surface — `s.*`, `define*`, the `surql` tag (side-effect-free) |
|
|
30
|
+
| `better-schemic/connection` | `surrealConnection` — the config factory |
|
|
31
|
+
| `better-schemic/config` | `defineConfig` + `surrealConnection` — the project config |
|
|
32
|
+
| `better-schemic/orm` | the repository-style ORM client |
|
|
33
|
+
| `better-schemic/query` | fragments & procedural SurrealQL |
|
|
34
|
+
| `better-schemic/plugins/*` | the authoring plugins |
|
|
35
|
+
| `better-schemic/logger` | the query logger |
|
|
36
|
+
| `better-schemic/otel` | OpenTelemetry tracing (`createOtelLogger`) |
|
|
37
|
+
| `better-schemic/driver` | the engine entry (CLI/engine-only — pulls in the DDL emitter) |
|
|
38
38
|
|
|
39
39
|
## Quick start
|
|
40
40
|
|
|
@@ -49,9 +49,9 @@ sc init
|
|
|
49
49
|
|
|
50
50
|
```ts
|
|
51
51
|
// database/schema/tables/user.ts
|
|
52
|
-
import {
|
|
52
|
+
import { table, s, surql } from "better-schemic";
|
|
53
53
|
|
|
54
|
-
export const User =
|
|
54
|
+
export const User = table("user", {
|
|
55
55
|
name: s.string().$assert(surql`string::len($value) > 0`),
|
|
56
56
|
email: s.email().$unique(),
|
|
57
57
|
createdAt: s.datetime().$default(surql`time::now()`).$readonly(),
|
|
@@ -74,7 +74,7 @@ false }` for a transform that requires client input, `{ optional: true }` when t
|
|
|
74
74
|
it without input. A parent mapping can mark the nested keys it fills as optional PER ITEM:
|
|
75
75
|
|
|
76
76
|
```ts
|
|
77
|
-
export const Order =
|
|
77
|
+
export const Order = table("order", {
|
|
78
78
|
products: s
|
|
79
79
|
.array(
|
|
80
80
|
s.object({
|
|
@@ -132,13 +132,13 @@ becomes a `Date`, a `uuid` a string, record links resolve); `encode` and
|
|
|
132
132
|
## The `/orm` client
|
|
133
133
|
|
|
134
134
|
The repository-style ORM lives at `better-schemic/orm`. Declare the
|
|
135
|
-
schema once with `
|
|
135
|
+
schema once with `schema` and wrap an existing (BYO) or managed connection:
|
|
136
136
|
|
|
137
137
|
```ts
|
|
138
|
-
import {
|
|
139
|
-
import {
|
|
138
|
+
import { table, s } from "better-schemic";
|
|
139
|
+
import { orm, createOrm, schema: schemaDef } from "better-schemic/orm";
|
|
140
140
|
|
|
141
|
-
const User =
|
|
141
|
+
const User = table("user", {
|
|
142
142
|
name: s.string(),
|
|
143
143
|
email: s.string(),
|
|
144
144
|
age: s.int(),
|
|
@@ -146,19 +146,19 @@ const User = defineTable("user", {
|
|
|
146
146
|
}).index("user_email", ["email"], { unique: true });
|
|
147
147
|
|
|
148
148
|
// A cart whose lines are the rows the UNWIND+GROUP aggregate below walks.
|
|
149
|
-
const Line =
|
|
150
|
-
const Cart =
|
|
149
|
+
const Line = table("line", { label: s.string(), quantity: s.int() });
|
|
150
|
+
const Cart = table("cart", {
|
|
151
151
|
name: s.string(),
|
|
152
152
|
lines: s.array(s.recordId(() => Line)),
|
|
153
153
|
});
|
|
154
154
|
// Multi-tenant: `email` is unique only WITHIN a tenant, so the index is the pair.
|
|
155
|
-
const Account =
|
|
155
|
+
const Account = table("account", {
|
|
156
156
|
tenant: s.string(),
|
|
157
157
|
email: s.string(),
|
|
158
158
|
name: s.string(),
|
|
159
159
|
}).index("account_tenant_email", ["tenant", "email"], { unique: true });
|
|
160
160
|
|
|
161
|
-
export const
|
|
161
|
+
export const schemaDef = schema({
|
|
162
162
|
users: User,
|
|
163
163
|
carts: Cart,
|
|
164
164
|
lines: Line,
|
|
@@ -166,8 +166,8 @@ export const schema = defineSchema({
|
|
|
166
166
|
audit: "audit_log",
|
|
167
167
|
});
|
|
168
168
|
|
|
169
|
-
const client =
|
|
170
|
-
// or: const client = await
|
|
169
|
+
const client = orm(existingSurreal, { schema: schemaDef }); // BYO: close() is a no-op
|
|
170
|
+
// or: const client = await createOrm({ url, namespace, database, auth, schema: schemaDef });
|
|
171
171
|
|
|
172
172
|
// Reads (M1) — one round-trip, decoded to app values (Date/RecordId/…):
|
|
173
173
|
const adults = await client.users.findMany({
|
|
@@ -288,16 +288,31 @@ const without = await client.users.update({
|
|
|
288
288
|
where: { id: created.id },
|
|
289
289
|
data: { tags: { remove: "beta" } }, // → SET tags -= $p0 (removes EVERY occurrence)
|
|
290
290
|
});
|
|
291
|
+
// Modifiers refine a marker inside the SAME one statement: `when` is a server-side guard, `else`
|
|
292
|
+
// is its fallback (default `"keep"` → the current value; `"throw"` aborts the whole statement, so
|
|
293
|
+
// `updateMany` writes NO row), and `coalesce` seeds an array that is still NONE:
|
|
294
|
+
const guarded = await client.users.update({
|
|
295
|
+
where: { id: created.id },
|
|
296
|
+
data: { age: { increment: 1, when: surql`age < 150`, else: "throw" } },
|
|
297
|
+
// → SET age = IF age < 150 THEN age + $p0 ELSE THROW s"adjustment guard failed on age" END
|
|
298
|
+
});
|
|
299
|
+
const seeded = await client.users.update({
|
|
300
|
+
where: { id: created.id },
|
|
301
|
+
data: { tags: { union: ["vip"], coalesce: [] } },
|
|
302
|
+
// → SET tags = array::union(tags ?? $p0, $p1)
|
|
303
|
+
});
|
|
291
304
|
void aged;
|
|
292
305
|
void previous;
|
|
293
306
|
void tagged;
|
|
294
307
|
void deduped;
|
|
295
308
|
void without;
|
|
309
|
+
void guarded;
|
|
310
|
+
void seeded;
|
|
296
311
|
|
|
297
312
|
// Created ids: every ORM create without an explicit `id` generates a ULID by default
|
|
298
313
|
// (`rand::ulid()` — 26 chars, time-sortable). Pick another strategy per table in authoring:
|
|
299
|
-
//
|
|
300
|
-
//
|
|
314
|
+
// table("user", { … }).idStrategy("uuid") // rand::uuid() — UUID v7
|
|
315
|
+
// table("legacy", { … }).idStrategy("rand") // rand::id() — the server default (20 chars)
|
|
301
316
|
// An explicit `id` always wins and singleton tables keep their fixed id. The strategy is
|
|
302
317
|
// ORM-only: it emits NO DDL (migrations never diff), raw SQL keeps the server default, and
|
|
303
318
|
// `sc pull` cannot recover it. A pinned uuid v4/v6 `id` field is explicit-only: creates without
|
|
@@ -306,7 +321,7 @@ void without;
|
|
|
306
321
|
// String ids (M15) — opt a table into BARE app id strings (`01M…`); `RecordId` stays on the wire.
|
|
307
322
|
// The emitted DDL is UNCHANGED (`record<…>` — zero migration), and raw `db.query()`, `live` and
|
|
308
323
|
// `changes` still return `RecordId`:
|
|
309
|
-
// const Customer =
|
|
324
|
+
// const Customer = table("customer", { name: s.string(), owner: s.recordId(User) })
|
|
310
325
|
// .stringIds(); // or per field: s.recordId(User).stringIds()
|
|
311
326
|
// const row = await client.customers.create({ data: { name: "A", owner: "aeon" } });
|
|
312
327
|
// row.owner; // "aeon" — the bare id, not a RecordId
|
|
@@ -318,7 +333,7 @@ void without;
|
|
|
318
333
|
// MULTIPLE tables throws (a bare string can't name the table on encode). `User.record()` inherits
|
|
319
334
|
// the mode and `tenant(User)` follows the principal.
|
|
320
335
|
|
|
321
|
-
// Edges live on the relation delegate (`
|
|
336
|
+
// Edges live on the relation delegate (`relation`):
|
|
322
337
|
// const like = await client.likes.relate({ from: "user:1", to: "post:1", data: { score: 5 } });
|
|
323
338
|
// await client.likes.unrelate({ from: "user:1", to: "post:1" });
|
|
324
339
|
|
|
@@ -387,8 +402,7 @@ const scoped = await client.$withContext({ namespace: "tenant_a", database: "app
|
|
|
387
402
|
const plan = await client.users.findMany({ where: { age: 18 } }).explain();
|
|
388
403
|
|
|
389
404
|
// Observation hooks (M6) — logging/tracing around every operation, never mutating it:
|
|
390
|
-
const logged =
|
|
391
|
-
schema,
|
|
405
|
+
const logged = orm(db, { schema: schemaDef,
|
|
392
406
|
hooks: {
|
|
393
407
|
beforeQuery: ({ table, operation, surql }) => logger.debug({ table, operation, surql }),
|
|
394
408
|
afterQuery: ({ durationMs }) => metrics.timing("db.query", durationMs),
|
|
@@ -420,10 +434,10 @@ Official F1 guardrail/validation plugins (M6.3) ship as subpaths:
|
|
|
420
434
|
```ts
|
|
421
435
|
import { recommended } from "better-schemic/plugins/rules";
|
|
422
436
|
import { zod } from "better-schemic/plugins/zod";
|
|
423
|
-
const client =
|
|
424
|
-
schema,
|
|
437
|
+
const client = orm(db, {
|
|
438
|
+
schema: schemaDef,
|
|
425
439
|
plugins: [
|
|
426
|
-
recommended({ maxLimit: 100 }),
|
|
440
|
+
recommended({ maxLimit: 100 }), // noRawUnsafe + no unfiltered writes + required/max limit
|
|
427
441
|
zod({ schemas: { user: z.object({ email: z.email() }) } }),
|
|
428
442
|
],
|
|
429
443
|
});
|
|
@@ -435,16 +449,16 @@ Official F2 plugins (M6.4) — timestamps + a reversible soft delete:
|
|
|
435
449
|
import { timestamps } from "better-schemic/plugins/timestamps";
|
|
436
450
|
import { softDelete } from "better-schemic/plugins/soft-delete";
|
|
437
451
|
|
|
438
|
-
const client =
|
|
439
|
-
schema,
|
|
452
|
+
const client = orm(db, {
|
|
453
|
+
schema: schemaDef,
|
|
440
454
|
plugins: [timestamps(), softDelete({ deletedBy: "deletedBy" })],
|
|
441
455
|
});
|
|
442
456
|
// create/update get `time::now()` stamped automatically (mode "app");
|
|
443
457
|
// delete becomes a soft delete and reads hide deleted rows unless `deleted: "with" | "only"`:
|
|
444
458
|
await client.users.delete({ where: { id }, meta: { actor: currentUserId } });
|
|
445
|
-
const live = await client.users.findMany({});
|
|
446
|
-
const all
|
|
447
|
-
await client.users.restoreById(id);
|
|
459
|
+
const live = await client.users.findMany({}); // deleted rows hidden
|
|
460
|
+
const all = await client.users.findMany({ deleted: "with" }); // include them
|
|
461
|
+
await client.users.restoreById(id); // clear deletedAt
|
|
448
462
|
```
|
|
449
463
|
|
|
450
464
|
Official F3 plugin (M10) — multi-tenant RLS: a schema PRESET (`tenant()`) plus a runtime plugin
|
|
@@ -455,25 +469,28 @@ import { tenant, tenantRls } from "better-schemic/plugins/tenant";
|
|
|
455
469
|
|
|
456
470
|
// Schema: one `.use(tenant(principal, options?))` per table — tenant column + per-op permissions +
|
|
457
471
|
// `{table}_protect_<column>` guard event + indexes (zero-diff with the hand-written recipe).
|
|
458
|
-
const User =
|
|
459
|
-
const Customer =
|
|
472
|
+
const User = table("user", { name: s.string() });
|
|
473
|
+
const Customer = table("customer", {
|
|
460
474
|
name: s.string(),
|
|
461
|
-
deletedAt: s.datetime().optional(),
|
|
475
|
+
deletedAt: s.datetime().optional(), // app-declared tombstone (softDelete: true)
|
|
462
476
|
}).use(tenant(User, { softDelete: true }));
|
|
463
|
-
const Order =
|
|
464
|
-
|
|
477
|
+
const Order = table("order", { total: s.number() }).use(
|
|
478
|
+
tenant(User, { createOnly: true }),
|
|
479
|
+
); // append-only: update = NONE
|
|
465
480
|
|
|
466
481
|
// Runtime: every tenant-tagged table requires a scope BEFORE compiling (fail-closed).
|
|
467
|
-
const client =
|
|
468
|
-
schema:
|
|
482
|
+
const client = orm(db, {
|
|
483
|
+
schema: schema({ users: User, customers: Customer, orders: Order }),
|
|
469
484
|
plugins: [tenantRls({ tenant: () => ctx.tenantId })],
|
|
470
485
|
});
|
|
471
|
-
await client.customers.findMany({});
|
|
472
|
-
await client.customers.$forTenant("user:abc").findMany({});
|
|
486
|
+
await client.customers.findMany({}); // ✗ TenantRequired (no scope)
|
|
487
|
+
await client.customers.$forTenant("user:abc").findMany({}); // ✓ scoped to user:abc
|
|
473
488
|
await client.customers.$forTenant("user:abc").create({ data: { name: "A" } }); // tenant injected
|
|
474
|
-
await client.customers
|
|
489
|
+
await client.customers
|
|
490
|
+
.$forTenant("user:abc")
|
|
491
|
+
.findUnique({ where: { id: "customer:1" } });
|
|
475
492
|
// ✓ reads are scoped too (id and single-field UNIQUE targets) — a cross-tenant id resolves null
|
|
476
|
-
await client.customers.$withoutPlugins().findMany({});
|
|
493
|
+
await client.customers.$withoutPlugins().findMany({}); // explicit admin escape (audited)
|
|
477
494
|
```
|
|
478
495
|
|
|
479
496
|
Official plugin (M14) — create-only (append-only) tables: the `createOnly()` schema PRESET
|
|
@@ -481,21 +498,24 @@ Official plugin (M14) — create-only (append-only) tables: the `createOnly()` s
|
|
|
481
498
|
(fail-fast for privileged sessions, where the DDL permission does not gate):
|
|
482
499
|
|
|
483
500
|
```ts
|
|
484
|
-
import {
|
|
501
|
+
import {
|
|
502
|
+
createOnly,
|
|
503
|
+
createOnlyGuard,
|
|
504
|
+
} from "better-schemic/plugins/create-only";
|
|
485
505
|
|
|
486
506
|
// Schema: PERMISSIONS FOR update NONE + meta.createOnly. `hard: true` also emits an
|
|
487
507
|
// `{table}_create_only` event — events run without permission checks, so root/$withoutPlugins/raw
|
|
488
508
|
// are blocked too. `timestamps()` sees the marker and never stamps `updatedAt` on this table.
|
|
489
|
-
const AuditLog =
|
|
509
|
+
const AuditLog = table("audit_log", {
|
|
490
510
|
action: s.string(),
|
|
491
511
|
createdAt: s.datetime().optional(),
|
|
492
512
|
}).use(createOnly({ hard: true }));
|
|
493
513
|
|
|
494
|
-
const client =
|
|
495
|
-
schema:
|
|
514
|
+
const client = orm(db, {
|
|
515
|
+
schema: schema({ auditLogs: AuditLog }),
|
|
496
516
|
plugins: [timestamps(), createOnlyGuard()],
|
|
497
517
|
});
|
|
498
|
-
await client.auditLogs.create({ data: { action: "login" } });
|
|
518
|
+
await client.auditLogs.create({ data: { action: "login" } }); // createdAt only (no updatedAt)
|
|
499
519
|
await client.auditLogs.update({ where: { id }, data: { action: "x" } }); // ✗ CreateOnlyViolation
|
|
500
520
|
await client.auditLogs.$withoutPlugins().update({ where: { id }, data: {} }); // ✗ hard event THROWs
|
|
501
521
|
// create()/insert({ onDuplicate: "ignore" }) write; delete stays allowed (rows are immutable,
|
|
@@ -508,7 +528,7 @@ Enable the built-in logger with one flag — a framed, syntax-highlighted box fo
|
|
|
508
528
|
with timing, row counts and (optionally) the `EXPLAIN` plan tree:
|
|
509
529
|
|
|
510
530
|
```ts
|
|
511
|
-
const client =
|
|
531
|
+
const client = orm(db, { schema: schemaDef, logger: true });
|
|
512
532
|
// presets: "pretty" (default) | "compact" | "json" (log shippers) | "silent"
|
|
513
533
|
// await client.users.findMany({ where: { age: { gte: 18 } } });
|
|
514
534
|
// ╭─ 🔍 findMany · user ─────────────────────────────╮
|
|
@@ -522,14 +542,14 @@ It observes the **executor** (reads, writes, `$raw`, `fn`, admin, changes, live
|
|
|
522
542
|
plans), never changing the operation:
|
|
523
543
|
|
|
524
544
|
```ts
|
|
525
|
-
const client =
|
|
526
|
-
schema,
|
|
545
|
+
const client = orm(db, {
|
|
546
|
+
schema: schemaDef,
|
|
527
547
|
logger: {
|
|
528
|
-
slowMs: 50,
|
|
529
|
-
explain: "slow",
|
|
530
|
-
verbose: true,
|
|
531
|
-
colors: "auto",
|
|
532
|
-
redact: true,
|
|
548
|
+
slowMs: 50, // mark slow queries (also gates `level: "info"`)
|
|
549
|
+
explain: "slow", // auto-EXPLAIN reads >= slowMs ("all" | "analyze" available)
|
|
550
|
+
verbose: true, // preview the first rows
|
|
551
|
+
colors: "auto", // honours NO_COLOR / FORCE_COLOR / TTY
|
|
552
|
+
redact: true, // mask bound values (`$p0 = [redacted]`) for shared/CI logs
|
|
533
553
|
},
|
|
534
554
|
});
|
|
535
555
|
|
|
@@ -547,7 +567,10 @@ code with `BETTER_SCHEMIC_LOG=1|pretty|json` (`BETTER_SCHEMIC_LOG_LEVEL`, `BETTE
|
|
|
547
567
|
|
|
548
568
|
```ts
|
|
549
569
|
import { createQueryLogger } from "better-schemic/logger";
|
|
550
|
-
const client =
|
|
570
|
+
const client = orm(db, {
|
|
571
|
+
schema: schemaDef,
|
|
572
|
+
logger: createQueryLogger({ format: "json" }),
|
|
573
|
+
});
|
|
551
574
|
```
|
|
552
575
|
|
|
553
576
|
### OTEL tracing (`better-schemic/otel`)
|
|
@@ -564,8 +587,8 @@ bun add better-schemic @opentelemetry/api
|
|
|
564
587
|
```ts
|
|
565
588
|
import { createOtelLogger } from "better-schemic/otel";
|
|
566
589
|
|
|
567
|
-
const client =
|
|
568
|
-
schema,
|
|
590
|
+
const client = orm(db, {
|
|
591
|
+
schema: schemaDef,
|
|
569
592
|
logger: createOtelLogger({
|
|
570
593
|
captureQueryText: true, // default; false omits db.query.text entirely
|
|
571
594
|
maxQueryTextLength: 1000, // default
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { type DriverCommand, type ParsedCommandArgs } from "../core";
|
|
2
1
|
import type { Command } from "commander";
|
|
2
|
+
import { type DriverCommand, type ParsedCommandArgs } from "../core";
|
|
3
3
|
/**
|
|
4
4
|
* Parse a command's raw positionals + commander option bag into {@link ParsedCommandArgs}, per the
|
|
5
5
|
* command's declared `args`. Core collects ALL positionals (the driver validates arity); flags become
|
package/lib/cli/index.js
CHANGED
|
@@ -56,12 +56,7 @@ async function loadProject(opts) {
|
|
|
56
56
|
const root = dirname(path);
|
|
57
57
|
loadDotEnv(root);
|
|
58
58
|
const loaded = await jiti.import(path);
|
|
59
|
-
const config = [
|
|
60
|
-
loaded.default,
|
|
61
|
-
loaded.betterSchemic,
|
|
62
|
-
loaded.schemic,
|
|
63
|
-
loaded
|
|
64
|
-
].find((c) => !!c && typeof c === "object" && ("connections" in c));
|
|
59
|
+
const config = [loaded.default, loaded.orm, loaded.schemic, loaded].find((c) => !!c && typeof c === "object" && ("connections" in c));
|
|
65
60
|
if (config?.connections && Object.keys(config.connections).length > 0) {
|
|
66
61
|
return { config, root };
|
|
67
62
|
}
|
|
@@ -819,7 +814,7 @@ function defineCall(init) {
|
|
|
819
814
|
let n = init;
|
|
820
815
|
while (n) {
|
|
821
816
|
if (n.type === "CallExpression") {
|
|
822
|
-
if (n.callee?.type === "Identifier" && /^define/.test(n.callee.name ?? ""))
|
|
817
|
+
if (n.callee?.type === "Identifier" && (/^define/.test(n.callee.name ?? "") || n.callee.name === "table" || n.callee.name === "relation"))
|
|
823
818
|
return n;
|
|
824
819
|
n = n.callee?.type === "MemberExpression" ? n.callee.object ?? null : n.callee ?? null;
|
|
825
820
|
} else if (n.type === "MemberExpression") {
|
|
@@ -1407,7 +1402,7 @@ async function resolveFromConfig(config, root, opts = {}) {
|
|
|
1407
1402
|
}
|
|
1408
1403
|
function exactlyOne(r) {
|
|
1409
1404
|
if (r.resolved.length !== 1) {
|
|
1410
|
-
throw new Error(`connection "${r.name}" resolved to ${r.resolved.length} configs (${r.labels.join(", ")}) — ` + `a parameterized/bulk connection. Pass args selecting exactly one, e.g.
|
|
1405
|
+
throw new Error(`connection "${r.name}" resolved to ${r.resolved.length} configs (${r.labels.join(", ")}) — ` + `a parameterized/bulk connection. Pass args selecting exactly one, e.g. orm.connect("${r.name}", { ... }).`);
|
|
1411
1406
|
}
|
|
1412
1407
|
return r.resolved[0];
|
|
1413
1408
|
}
|
|
@@ -1426,7 +1421,7 @@ var init_client = __esm(() => {
|
|
|
1426
1421
|
// src/core/connection.ts
|
|
1427
1422
|
function connectionEntry(driver, input, extras) {
|
|
1428
1423
|
return {
|
|
1429
|
-
|
|
1424
|
+
__orm: "connection",
|
|
1430
1425
|
driver,
|
|
1431
1426
|
...extras?.client ? { client: extras.client } : {},
|
|
1432
1427
|
...extras?.label ? { label: extras.label } : {},
|
|
@@ -1437,7 +1432,7 @@ function connectionEntry(driver, input, extras) {
|
|
|
1437
1432
|
};
|
|
1438
1433
|
}
|
|
1439
1434
|
function isConnectionEntry(v) {
|
|
1440
|
-
return typeof v === "object" && v !== null && v.
|
|
1435
|
+
return typeof v === "object" && v !== null && v.__orm === "connection";
|
|
1441
1436
|
}
|
|
1442
1437
|
|
|
1443
1438
|
// src/core/driver/driver.ts
|
|
@@ -2834,7 +2829,7 @@ function stringIdsShape(shape) {
|
|
|
2834
2829
|
function stringIdsOf(schema) {
|
|
2835
2830
|
return findRecordIdField(schema)?.mode === "string";
|
|
2836
2831
|
}
|
|
2837
|
-
function
|
|
2832
|
+
function table(name, shape) {
|
|
2838
2833
|
const resolved = shape === undefined ? {} : typeof shape === "function" ? shape(new RecordIdField([name])) : shape instanceof SObjectField ? shape.fields : shape;
|
|
2839
2834
|
return new TableDef(name, applySmartId(name, resolved), {
|
|
2840
2835
|
schemafull: true
|
|
@@ -2884,7 +2879,7 @@ function relationFields(name, edge, fromNames, toNames, fromMode, toMode) {
|
|
|
2884
2879
|
out: new RecordIdField(toNames, { mode: toMode })
|
|
2885
2880
|
};
|
|
2886
2881
|
}
|
|
2887
|
-
function
|
|
2882
|
+
function relation(name, fields) {
|
|
2888
2883
|
return new RelationDef(name, fields ?? {});
|
|
2889
2884
|
}
|
|
2890
2885
|
|
|
@@ -4134,7 +4129,7 @@ var init_pure = __esm(() => {
|
|
|
4134
4129
|
"readonly"
|
|
4135
4130
|
]);
|
|
4136
4131
|
PERM_OPS = ["select", "create", "update", "delete"];
|
|
4137
|
-
|
|
4132
|
+
table.preset = (preset) => preset;
|
|
4138
4133
|
RelationDef = class RelationDef extends TableDef {
|
|
4139
4134
|
edge;
|
|
4140
4135
|
fromNames;
|
|
@@ -4752,7 +4747,6 @@ var init_connect = __esm(() => {
|
|
|
4752
4747
|
});
|
|
4753
4748
|
|
|
4754
4749
|
// src/cli/index.ts
|
|
4755
|
-
init_core();
|
|
4756
4750
|
import {
|
|
4757
4751
|
existsSync as existsSync7,
|
|
4758
4752
|
watch as fsWatch,
|
|
@@ -4763,7 +4757,10 @@ import { dirname as dirname5, join as join6, relative as relative5 } from "node:
|
|
|
4763
4757
|
import { createInterface as createInterface2 } from "node:readline/promises";
|
|
4764
4758
|
import { Command, Help, Option } from "commander";
|
|
4765
4759
|
// package.json
|
|
4766
|
-
var version = "0.1.0-beta.
|
|
4760
|
+
var version = "0.1.0-beta.5";
|
|
4761
|
+
|
|
4762
|
+
// src/cli/index.ts
|
|
4763
|
+
init_core();
|
|
4767
4764
|
|
|
4768
4765
|
// src/surreal/driver.ts
|
|
4769
4766
|
init_core();
|
|
@@ -7909,7 +7906,7 @@ function renderTableConst(t, ctx) {
|
|
|
7909
7906
|
const idField = t.fields.find((f) => f.name === "id");
|
|
7910
7907
|
const singletonId = idField ? /^'(.*)'$/.exec(idField.kind)?.[1] : undefined;
|
|
7911
7908
|
const name = ctx.constOf(t.name);
|
|
7912
|
-
const factory = isRelation ? "
|
|
7909
|
+
const factory = isRelation ? "relation" : singletonId !== undefined ? "defineSingleton" : "table";
|
|
7913
7910
|
const head = ctx.usesSelf ? `export const ${name} = ${factory}(${JSON.stringify(t.name)}, (self) => ({` : `export const ${name} = ${factory}(${JSON.stringify(t.name)}, {`;
|
|
7914
7911
|
const shapeClose = ctx.usesSelf ? "})" : "}";
|
|
7915
7912
|
const open = singletonId !== undefined && singletonId !== "default" ? `${shapeClose}, { id: ${JSON.stringify(singletonId)} })` : `${shapeClose})`;
|
|
@@ -8258,9 +8255,7 @@ function planFile(abs, units, keepLocal, config, fresh) {
|
|
|
8258
8255
|
function functionUnit(fn) {
|
|
8259
8256
|
const code = renderFunctionConst(fn);
|
|
8260
8257
|
const names = ["defineFunction", ...code.includes("s.") ? ["s"] : []];
|
|
8261
|
-
const imports = [
|
|
8262
|
-
`import { ${names.join(", ")} } from "better-schemic";`
|
|
8263
|
-
];
|
|
8258
|
+
const imports = [`import { ${names.join(", ")} } from "better-schemic";`];
|
|
8264
8259
|
if (code.includes("surql`"))
|
|
8265
8260
|
imports.push(`import { surql } from "surrealdb";`);
|
|
8266
8261
|
return {
|
|
@@ -8484,9 +8479,7 @@ function assembleCombined({
|
|
|
8484
8479
|
factories.sort();
|
|
8485
8480
|
const usesSurql = functions.length > 0 || accesses.length > 0 || ordered.some((r) => r.usesSurql);
|
|
8486
8481
|
const names = ["s", ...factories];
|
|
8487
|
-
const imports = [
|
|
8488
|
-
`import { ${names.join(", ")} } from "better-schemic";`
|
|
8489
|
-
];
|
|
8482
|
+
const imports = [`import { ${names.join(", ")} } from "better-schemic";`];
|
|
8490
8483
|
if (usesSurql)
|
|
8491
8484
|
imports.push(`import { surql } from "surrealdb";`);
|
|
8492
8485
|
const body = [
|
|
@@ -8513,10 +8506,10 @@ var CONFIG = `import { defineConfig, surrealConnection } from "better-schemic/co
|
|
|
8513
8506
|
// factory, so there's no \`driver: "…"\` string to keep in sync. Values are explicit — read env here
|
|
8514
8507
|
// yourself (no implicit SURREAL_* magic). Add more named connections for multi-tenant / multi-DB setups.
|
|
8515
8508
|
//
|
|
8516
|
-
// Exported as \`
|
|
8517
|
-
// your app's DB entrypoint — \`import {
|
|
8518
|
-
// \`await using db = await
|
|
8519
|
-
export const
|
|
8509
|
+
// Exported as \`orm\` (a factory; legacy alias \`schemic\` also works): this config also IS
|
|
8510
|
+
// your app's DB entrypoint — \`import { orm } from "./better-schemic.config"\` then
|
|
8511
|
+
// \`await using db = await orm.connect()\` (typed per connection). The CLI reads the same config.
|
|
8512
|
+
export const orm = defineConfig({
|
|
8520
8513
|
connections: {
|
|
8521
8514
|
default: surrealConnection({
|
|
8522
8515
|
schema: "./database/schema",
|
|
@@ -8532,15 +8525,15 @@ export const betterSchemic = defineConfig({
|
|
|
8532
8525
|
}),
|
|
8533
8526
|
},
|
|
8534
8527
|
});
|
|
8535
|
-
export const schemic =
|
|
8536
|
-
export default
|
|
8528
|
+
export const schemic = orm; // legacy alias (pre-rename scaffolded name)
|
|
8529
|
+
export default orm;
|
|
8537
8530
|
`;
|
|
8538
|
-
var USER_TABLE = `import {
|
|
8531
|
+
var USER_TABLE = `import { table, s, surql } from "better-schemic";
|
|
8539
8532
|
|
|
8540
8533
|
// A SCHEMAFULL \`user\` table. Each field is a \`s.*\` builder (a drop-in for Zod's \`z.*\`) that also
|
|
8541
8534
|
// carries its SurrealQL DDL — \`s.email()\` validates the address, \`.$unique()\` defines a UNIQUE index,
|
|
8542
8535
|
// and \`$default\`/\`$readonly\` map to the DEFAULT / READONLY clauses.
|
|
8543
|
-
export const User =
|
|
8536
|
+
export const User = table("user", {
|
|
8544
8537
|
name: s.string().$assert(surql\`string::len($value) > 0\`),
|
|
8545
8538
|
email: s.email().$unique(),
|
|
8546
8539
|
createdAt: s.datetime().$default(surql\`time::now()\`).$readonly(),
|
|
@@ -8589,21 +8582,21 @@ function scaffoldEntity(kind, name) {
|
|
|
8589
8582
|
const C = pascalCase(name);
|
|
8590
8583
|
switch (kind) {
|
|
8591
8584
|
case "table":
|
|
8592
|
-
return `import {
|
|
8585
|
+
return `import { table, s, surql } from "better-schemic";
|
|
8593
8586
|
|
|
8594
8587
|
// A SCHEMAFULL table. Each field is an \`s.*\` builder (a drop-in for Zod's \`z.*\`) that also carries
|
|
8595
8588
|
// its SurrealQL DDL. Add fields, then run \`better-schemic gen\`.
|
|
8596
|
-
export const ${C} =
|
|
8589
|
+
export const ${C} = table("${name}", {
|
|
8597
8590
|
name: s.string(),
|
|
8598
8591
|
createdAt: s.datetime().$default(surql\`time::now()\`).$readonly(),
|
|
8599
8592
|
}).schemafull();
|
|
8600
8593
|
`;
|
|
8601
8594
|
case "relation":
|
|
8602
|
-
return `import {
|
|
8595
|
+
return `import { relation, s, surql } from "better-schemic";
|
|
8603
8596
|
|
|
8604
8597
|
// A graph edge (\`TYPE RELATION\`). Chain \`.from(A).to(B)\` to restrict the endpoints and
|
|
8605
8598
|
// \`.enforced()\` to require both records to exist on RELATE.
|
|
8606
|
-
export const ${C} =
|
|
8599
|
+
export const ${C} = relation("${name}", {
|
|
8607
8600
|
since: s.datetime().$default(surql\`time::now()\`),
|
|
8608
8601
|
});
|
|
8609
8602
|
// .from(SomeTable).to(OtherTable).enforced()
|
|
@@ -8658,7 +8651,7 @@ export const ${C} = defineAnalyzer("${name}")
|
|
|
8658
8651
|
`;
|
|
8659
8652
|
case "index":
|
|
8660
8653
|
case "field":
|
|
8661
|
-
throw new Error(`SurrealDB ${kind}s are authored inline on a table, not as their own file — add it to a table (e.g. \`
|
|
8654
|
+
throw new Error(`SurrealDB ${kind}s are authored inline on a table, not as their own file — add it to a table (e.g. \`table("…", { … }).index("${name}", [field])\` or \`s.string().$unique()\`). Try \`better-schemic new table <name>\`.`);
|
|
8662
8655
|
default:
|
|
8663
8656
|
throw new Error(`the surrealdb driver can't scaffold a "${kind}" — known kinds: table, relation, view, function, access, event, analyzer.`);
|
|
8664
8657
|
}
|
|
@@ -10982,5 +10975,5 @@ async function bootstrap() {
|
|
|
10982
10975
|
}
|
|
10983
10976
|
bootstrap();
|
|
10984
10977
|
|
|
10985
|
-
//# debugId=
|
|
10978
|
+
//# debugId=744BF9EC5D63714B64756E2164756E21
|
|
10986
10979
|
//# sourceMappingURL=index.js.map
|