better-schemic 0.1.0-alpha.8 → 0.1.0-beta.2
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 +1 -1
- package/README.md +586 -4
- package/lib/authoring.d.ts +2 -0
- package/lib/authoring.js +216 -0
- package/lib/authoring.js.map +12 -0
- package/lib/cli/action.d.ts +2 -0
- package/lib/cli/driver-commands.d.ts +16 -0
- package/lib/cli/index.d.ts +1 -0
- package/lib/cli/index.js +10986 -0
- package/lib/cli/index.js.map +57 -0
- package/lib/cli/init.d.ts +11 -0
- package/lib/cli/inspect.d.ts +23 -0
- package/lib/cli/migrate.d.ts +103 -0
- package/lib/cli/portable-diff.d.ts +8 -0
- package/lib/cli/resolve.d.ts +40 -0
- package/lib/config.d.ts +23 -0
- package/lib/config.js +13845 -0
- package/lib/config.js.map +93 -0
- package/lib/connection.d.ts +2 -0
- package/lib/connection.js +13821 -0
- package/lib/connection.js.map +92 -0
- package/lib/core/authoring.d.ts +111 -0
- package/lib/core/cli-kit/config.d.ts +70 -0
- package/lib/core/cli-kit/diff.d.ts +79 -0
- package/lib/core/cli-kit/filter.d.ts +56 -0
- package/lib/core/cli-kit/merge.d.ts +78 -0
- package/lib/core/cli-kit/meta.d.ts +45 -0
- package/lib/core/cli-kit/pager.d.ts +13 -0
- package/lib/core/cli-kit/schema.d.ts +34 -0
- package/lib/core/cli-kit/style.d.ts +16 -0
- package/lib/core/client.d.ts +60 -0
- package/lib/core/config.d.ts +116 -0
- package/lib/core/connection.d.ts +80 -0
- package/lib/core/driver/driver.d.ts +309 -0
- package/lib/core/driver/index.d.ts +5 -0
- package/lib/core/driver/portable-ir.d.ts +39 -0
- package/lib/core/driver/portable.d.ts +104 -0
- package/lib/core/driver/sdk.d.ts +9 -0
- package/lib/core/driver/sdk.js +471 -0
- package/lib/core/driver/sdk.js.map +15 -0
- package/lib/core/index.d.ts +25 -0
- package/lib/core/index.js +1597 -0
- package/lib/core/index.js.map +25 -0
- package/lib/core/kind/index.d.ts +2 -0
- package/lib/core/kind/plan.d.ts +75 -0
- package/lib/core/kind/registry.d.ts +188 -0
- package/lib/core/secrets.d.ts +24 -0
- package/lib/core/seed.d.ts +14 -0
- package/lib/core/testing.d.ts +143 -0
- package/lib/driver.d.ts +7 -0
- package/lib/driver.js +9499 -0
- package/lib/driver.js.map +49 -0
- package/lib/index.d.ts +19 -0
- package/lib/index.js +3469 -0
- package/lib/index.js.map +21 -0
- package/lib/logger.d.ts +2 -0
- package/lib/logger.js +1064 -0
- package/lib/logger.js.map +15 -0
- package/lib/orm/index.d.ts +2 -0
- package/lib/orm/index.js +13844 -0
- package/lib/orm/index.js.map +91 -0
- package/lib/plugins/create-only.d.ts +2 -0
- package/lib/plugins/create-only.js +4343 -0
- package/lib/plugins/create-only.js.map +26 -0
- package/lib/plugins/hard-delete.d.ts +2 -0
- package/lib/plugins/hard-delete.js +377 -0
- package/lib/plugins/hard-delete.js.map +13 -0
- package/lib/plugins/rules.d.ts +2 -0
- package/lib/plugins/rules.js +448 -0
- package/lib/plugins/rules.js.map +13 -0
- package/lib/plugins/soft-delete.d.ts +2 -0
- package/lib/plugins/soft-delete.js +3991 -0
- package/lib/plugins/soft-delete.js.map +24 -0
- package/lib/plugins/tenant.d.ts +2 -0
- package/lib/plugins/tenant.js +4593 -0
- package/lib/plugins/tenant.js.map +28 -0
- package/lib/plugins/timestamps.d.ts +2 -0
- package/lib/plugins/timestamps.js +3990 -0
- package/lib/plugins/timestamps.js.map +25 -0
- package/lib/plugins/zod.d.ts +2 -0
- package/lib/plugins/zod.js +3808 -0
- package/lib/plugins/zod.js.map +22 -0
- package/lib/query.d.ts +2 -0
- package/lib/query.js +3703 -0
- package/lib/query.js.map +21 -0
- package/lib/surreal/checks.d.ts +56 -0
- package/lib/surreal/cli/engine.d.ts +33 -0
- package/lib/surreal/cli/format.d.ts +22 -0
- package/lib/surreal/cli/introspect.d.ts +49 -0
- package/lib/surreal/cli/lower.d.ts +24 -0
- package/lib/surreal/cli/pull.d.ts +22 -0
- package/lib/surreal/cli/scaffold.d.ts +9 -0
- package/lib/surreal/cli/struct.d.ts +35 -0
- package/lib/surreal/cli/structure.d.ts +205 -0
- package/lib/surreal/cli/surreal-diff.d.ts +36 -0
- package/lib/surreal/cli/surreal-filter.d.ts +15 -0
- package/lib/surreal/commands.d.ts +3 -0
- package/lib/surreal/config.d.ts +84 -0
- package/lib/surreal/connect.d.ts +6 -0
- package/lib/surreal/connection.d.ts +29 -0
- package/lib/surreal/ddl.d.ts +169 -0
- package/lib/surreal/driver/surql-type.d.ts +9 -0
- package/lib/surreal/driver/surreal.d.ts +4 -0
- package/lib/surreal/driver.d.ts +13 -0
- package/lib/surreal/fn-name.d.ts +14 -0
- package/lib/surreal/fn.d.ts +370 -0
- package/lib/surreal/frag.d.ts +15 -0
- package/lib/surreal/ident.d.ts +26 -0
- package/lib/surreal/index.d.ts +67 -0
- package/lib/surreal/kinds/explode.d.ts +34 -0
- package/lib/surreal/kinds/portable.d.ts +104 -0
- package/lib/surreal/kinds/registry.d.ts +11 -0
- package/lib/surreal/logger.d.ts +11 -0
- package/lib/surreal/orm/admin.d.ts +4 -0
- package/lib/surreal/orm/api.d.ts +4 -0
- package/lib/surreal/orm/arithmetic.d.ts +25 -0
- package/lib/surreal/orm/auth.d.ts +4 -0
- package/lib/surreal/orm/changes.d.ts +22 -0
- package/lib/surreal/orm/client.d.ts +216 -0
- package/lib/surreal/orm/compiler/adjustment.d.ts +38 -0
- package/lib/surreal/orm/compiler/aggregate-entries.d.ts +96 -0
- package/lib/surreal/orm/compiler/aggregate-operand.d.ts +29 -0
- package/lib/surreal/orm/compiler/aggregate-split.d.ts +7 -0
- package/lib/surreal/orm/compiler/aggregate.d.ts +73 -0
- package/lib/surreal/orm/compiler/include/count.d.ts +4 -0
- package/lib/surreal/orm/compiler/include/edges.d.ts +4 -0
- package/lib/surreal/orm/compiler/include/index.d.ts +12 -0
- package/lib/surreal/orm/compiler/include/links.d.ts +6 -0
- package/lib/surreal/orm/compiler/include/projection.d.ts +46 -0
- package/lib/surreal/orm/compiler/include/specs.d.ts +117 -0
- package/lib/surreal/orm/compiler/keyset.d.ts +45 -0
- package/lib/surreal/orm/compiler/live.d.ts +13 -0
- package/lib/surreal/orm/compiler/mutate.d.ts +47 -0
- package/lib/surreal/orm/compiler/pagination.d.ts +123 -0
- package/lib/surreal/orm/compiler/projection.d.ts +127 -0
- package/lib/surreal/orm/compiler/relate.d.ts +47 -0
- package/lib/surreal/orm/compiler/relations.d.ts +63 -0
- package/lib/surreal/orm/compiler/select.d.ts +54 -0
- package/lib/surreal/orm/compiler/shared.d.ts +143 -0
- package/lib/surreal/orm/compiler/unique.d.ts +35 -0
- package/lib/surreal/orm/compiler/where.d.ts +64 -0
- package/lib/surreal/orm/compiler/write-shared.d.ts +287 -0
- package/lib/surreal/orm/compiler/write.d.ts +11 -0
- package/lib/surreal/orm/connect.d.ts +58 -0
- package/lib/surreal/orm/context.d.ts +19 -0
- package/lib/surreal/orm/decode.d.ts +8 -0
- package/lib/surreal/orm/delegate.d.ts +240 -0
- package/lib/surreal/orm/delta.d.ts +20 -0
- package/lib/surreal/orm/errors.d.ts +94 -0
- package/lib/surreal/orm/execute.d.ts +109 -0
- package/lib/surreal/orm/fn.d.ts +4 -0
- package/lib/surreal/orm/hooks.d.ts +52 -0
- package/lib/surreal/orm/index.d.ts +49 -0
- package/lib/surreal/orm/live.d.ts +17 -0
- package/lib/surreal/orm/logger/colors.d.ts +27 -0
- package/lib/surreal/orm/logger/emit.d.ts +44 -0
- package/lib/surreal/orm/logger/highlight.d.ts +29 -0
- package/lib/surreal/orm/logger/index.d.ts +13 -0
- package/lib/surreal/orm/logger/logger.d.ts +24 -0
- package/lib/surreal/orm/logger/plan.d.ts +28 -0
- package/lib/surreal/orm/meta.d.ts +132 -0
- package/lib/surreal/orm/plugins.d.ts +64 -0
- package/lib/surreal/orm/raw.d.ts +34 -0
- package/lib/surreal/orm/reads.d.ts +4 -0
- package/lib/surreal/orm/results.d.ts +94 -0
- package/lib/surreal/orm/schema.d.ts +20 -0
- package/lib/surreal/orm/transaction.d.ts +60 -0
- package/lib/surreal/orm/types/admin.d.ts +77 -0
- package/lib/surreal/orm/types/api.d.ts +29 -0
- package/lib/surreal/orm/types/auth.d.ts +21 -0
- package/lib/surreal/orm/types/changes.d.ts +62 -0
- package/lib/surreal/orm/types/client.d.ts +154 -0
- package/lib/surreal/orm/types/context.d.ts +40 -0
- package/lib/surreal/orm/types/fn.d.ts +50 -0
- package/lib/surreal/orm/types/hooks.d.ts +145 -0
- package/lib/surreal/orm/types/include.d.ts +130 -0
- package/lib/surreal/orm/types/live.d.ts +95 -0
- package/lib/surreal/orm/types/logger.d.ts +151 -0
- package/lib/surreal/orm/types/plugins.d.ts +116 -0
- package/lib/surreal/orm/types/raw.d.ts +35 -0
- package/lib/surreal/orm/types/relations.d.ts +64 -0
- package/lib/surreal/orm/types/schema.d.ts +89 -0
- package/lib/surreal/orm/types/select.d.ts +387 -0
- package/lib/surreal/orm/types/transaction.d.ts +69 -0
- package/lib/surreal/orm/types/where.d.ts +203 -0
- package/lib/surreal/orm/types/write.d.ts +460 -0
- package/lib/surreal/orm/writes.d.ts +16 -0
- package/lib/surreal/plugins/create-only-shared.d.ts +26 -0
- package/lib/surreal/plugins/create-only.d.ts +55 -0
- package/lib/surreal/plugins/hard-delete.d.ts +32 -0
- package/lib/surreal/plugins/rules.d.ts +38 -0
- package/lib/surreal/plugins/soft-delete.d.ts +91 -0
- package/lib/surreal/plugins/tenant-runtime.d.ts +95 -0
- package/lib/surreal/plugins/tenant-shared.d.ts +11 -0
- package/lib/surreal/plugins/tenant.d.ts +115 -0
- package/lib/surreal/plugins/timestamps.d.ts +15 -0
- package/lib/surreal/plugins/zod.d.ts +27 -0
- package/lib/surreal/pure.d.ts +2291 -0
- package/lib/surreal/query.d.ts +11 -0
- package/lib/surreal/seed.d.ts +14 -0
- package/lib/surreal/surql/block.d.ts +107 -0
- package/lib/surreal/surql/predicate.d.ts +198 -0
- package/lib/surreal/surql/ref.d.ts +19 -0
- package/lib/surreal/surql/render.d.ts +30 -0
- package/lib/surreal/surql-type-expr.d.ts +4 -0
- package/lib/surreal/wire.d.ts +40 -0
- package/lib/testing.d.ts +2 -0
- package/lib/testing.js +619 -0
- package/lib/testing.js.map +12 -0
- package/package.json +173 -7
- package/src/authoring.ts +2 -0
- package/src/cli/action.ts +40 -0
- package/src/cli/driver-commands.ts +195 -0
- package/src/cli/index.ts +1344 -0
- package/src/cli/init.ts +56 -0
- package/src/cli/inspect.ts +318 -0
- package/src/cli/migrate.ts +606 -0
- package/src/cli/portable-diff.ts +91 -0
- package/src/cli/resolve.ts +266 -0
- package/src/config.ts +23 -0
- package/src/connection.ts +2 -0
- package/src/core/authoring.ts +371 -0
- package/src/core/cli-kit/config.ts +239 -0
- package/src/core/cli-kit/diff.ts +298 -0
- package/src/core/cli-kit/filter.ts +159 -0
- package/src/core/cli-kit/merge.ts +440 -0
- package/src/core/cli-kit/meta.ts +163 -0
- package/src/core/cli-kit/pager.ts +120 -0
- package/src/core/cli-kit/schema.ts +152 -0
- package/src/core/cli-kit/style.ts +24 -0
- package/src/core/client.ts +248 -0
- package/src/core/config.ts +199 -0
- package/src/core/connection.ts +120 -0
- package/src/core/driver/driver.ts +413 -0
- package/src/core/driver/index.ts +31 -0
- package/src/core/driver/portable-ir.ts +51 -0
- package/src/core/driver/portable.ts +124 -0
- package/src/core/driver/sdk.ts +73 -0
- package/src/core/index.ts +181 -0
- package/src/core/kind/index.ts +28 -0
- package/src/core/kind/plan.ts +515 -0
- package/src/core/kind/registry.ts +288 -0
- package/src/core/secrets.ts +68 -0
- package/src/core/seed.ts +14 -0
- package/src/core/testing.ts +556 -0
- package/src/driver.ts +7 -0
- package/src/index.ts +19 -0
- package/src/logger.ts +2 -0
- package/src/orm/index.ts +2 -0
- package/src/plugins/create-only.ts +2 -0
- package/src/plugins/hard-delete.ts +2 -0
- package/src/plugins/rules.ts +2 -0
- package/src/plugins/soft-delete.ts +2 -0
- package/src/plugins/tenant.ts +2 -0
- package/src/plugins/timestamps.ts +2 -0
- package/src/plugins/zod.ts +2 -0
- package/src/query.ts +2 -0
- package/src/surreal/checks.ts +280 -0
- package/src/surreal/cli/engine.ts +267 -0
- package/src/surreal/cli/format.ts +231 -0
- package/src/surreal/cli/introspect.ts +304 -0
- package/src/surreal/cli/lower.ts +487 -0
- package/src/surreal/cli/pull.ts +1356 -0
- package/src/surreal/cli/scaffold.ts +181 -0
- package/src/surreal/cli/struct.ts +485 -0
- package/src/surreal/cli/structure.ts +834 -0
- package/src/surreal/cli/surreal-diff.ts +371 -0
- package/src/surreal/cli/surreal-filter.ts +77 -0
- package/src/surreal/commands.ts +502 -0
- package/src/surreal/config.ts +94 -0
- package/src/surreal/connect.ts +188 -0
- package/src/surreal/connection.ts +104 -0
- package/src/surreal/ddl.ts +1167 -0
- package/src/surreal/driver/surql-type.ts +175 -0
- package/src/surreal/driver/surreal.ts +392 -0
- package/src/surreal/driver.ts +40 -0
- package/src/surreal/fn-name.ts +19 -0
- package/src/surreal/fn.ts +503 -0
- package/src/surreal/frag.ts +18 -0
- package/src/surreal/ident.ts +67 -0
- package/src/surreal/index.ts +266 -0
- package/src/surreal/kinds/explode.ts +221 -0
- package/src/surreal/kinds/portable.ts +141 -0
- package/src/surreal/kinds/registry.ts +235 -0
- package/src/surreal/logger.ts +25 -0
- package/src/surreal/orm/admin.ts +140 -0
- package/src/surreal/orm/api.ts +115 -0
- package/src/surreal/orm/arithmetic.ts +102 -0
- package/src/surreal/orm/auth.ts +72 -0
- package/src/surreal/orm/changes.ts +232 -0
- package/src/surreal/orm/client.ts +604 -0
- package/src/surreal/orm/compiler/adjustment.ts +234 -0
- package/src/surreal/orm/compiler/aggregate-entries.ts +340 -0
- package/src/surreal/orm/compiler/aggregate-operand.ts +131 -0
- package/src/surreal/orm/compiler/aggregate-split.ts +140 -0
- package/src/surreal/orm/compiler/aggregate.ts +234 -0
- package/src/surreal/orm/compiler/include/count.ts +181 -0
- package/src/surreal/orm/compiler/include/edges.ts +385 -0
- package/src/surreal/orm/compiler/include/index.ts +134 -0
- package/src/surreal/orm/compiler/include/links.ts +157 -0
- package/src/surreal/orm/compiler/include/projection.ts +380 -0
- package/src/surreal/orm/compiler/include/specs.ts +142 -0
- package/src/surreal/orm/compiler/keyset.ts +121 -0
- package/src/surreal/orm/compiler/live.ts +118 -0
- package/src/surreal/orm/compiler/mutate.ts +1345 -0
- package/src/surreal/orm/compiler/pagination.ts +474 -0
- package/src/surreal/orm/compiler/projection.ts +754 -0
- package/src/surreal/orm/compiler/relate.ts +376 -0
- package/src/surreal/orm/compiler/relations.ts +332 -0
- package/src/surreal/orm/compiler/select.ts +423 -0
- package/src/surreal/orm/compiler/shared.ts +661 -0
- package/src/surreal/orm/compiler/unique.ts +212 -0
- package/src/surreal/orm/compiler/where.ts +949 -0
- package/src/surreal/orm/compiler/write-shared.ts +879 -0
- package/src/surreal/orm/compiler/write.ts +339 -0
- package/src/surreal/orm/connect.ts +148 -0
- package/src/surreal/orm/context.ts +134 -0
- package/src/surreal/orm/decode.ts +660 -0
- package/src/surreal/orm/delegate.ts +502 -0
- package/src/surreal/orm/delta.ts +92 -0
- package/src/surreal/orm/errors.ts +401 -0
- package/src/surreal/orm/execute.ts +254 -0
- package/src/surreal/orm/fn.ts +137 -0
- package/src/surreal/orm/hooks.ts +308 -0
- package/src/surreal/orm/index.ts +358 -0
- package/src/surreal/orm/live.ts +471 -0
- package/src/surreal/orm/logger/colors.ts +87 -0
- package/src/surreal/orm/logger/emit.ts +169 -0
- package/src/surreal/orm/logger/highlight.ts +462 -0
- package/src/surreal/orm/logger/index.ts +28 -0
- package/src/surreal/orm/logger/logger.ts +588 -0
- package/src/surreal/orm/logger/plan.ts +245 -0
- package/src/surreal/orm/meta.ts +159 -0
- package/src/surreal/orm/plugins.ts +268 -0
- package/src/surreal/orm/raw.ts +395 -0
- package/src/surreal/orm/reads.ts +551 -0
- package/src/surreal/orm/results.ts +197 -0
- package/src/surreal/orm/schema.ts +428 -0
- package/src/surreal/orm/transaction.ts +492 -0
- package/src/surreal/orm/types/admin.ts +81 -0
- package/src/surreal/orm/types/api.ts +31 -0
- package/src/surreal/orm/types/auth.ts +22 -0
- package/src/surreal/orm/types/changes.ts +76 -0
- package/src/surreal/orm/types/client.ts +227 -0
- package/src/surreal/orm/types/context.ts +45 -0
- package/src/surreal/orm/types/fn.ts +77 -0
- package/src/surreal/orm/types/hooks.ts +194 -0
- package/src/surreal/orm/types/include.ts +263 -0
- package/src/surreal/orm/types/live.ts +115 -0
- package/src/surreal/orm/types/logger.ts +168 -0
- package/src/surreal/orm/types/plugins.ts +154 -0
- package/src/surreal/orm/types/raw.ts +40 -0
- package/src/surreal/orm/types/relations.ts +139 -0
- package/src/surreal/orm/types/schema.ts +151 -0
- package/src/surreal/orm/types/select.ts +621 -0
- package/src/surreal/orm/types/transaction.ts +93 -0
- package/src/surreal/orm/types/where.ts +362 -0
- package/src/surreal/orm/types/write.ts +641 -0
- package/src/surreal/orm/writes.ts +638 -0
- package/src/surreal/plugins/create-only-shared.ts +60 -0
- package/src/surreal/plugins/create-only.ts +243 -0
- package/src/surreal/plugins/hard-delete.ts +74 -0
- package/src/surreal/plugins/rules.ts +182 -0
- package/src/surreal/plugins/soft-delete.ts +110 -0
- package/src/surreal/plugins/tenant-runtime.ts +496 -0
- package/src/surreal/plugins/tenant-shared.ts +35 -0
- package/src/surreal/plugins/tenant.ts +269 -0
- package/src/surreal/plugins/timestamps.ts +72 -0
- package/src/surreal/plugins/zod.ts +80 -0
- package/src/surreal/pure.ts +6090 -0
- package/src/surreal/query.ts +11 -0
- package/src/surreal/seed.ts +18 -0
- package/src/surreal/surql/block.ts +354 -0
- package/src/surreal/surql/predicate.ts +569 -0
- package/src/surreal/surql/ref.ts +24 -0
- package/src/surreal/surql/render.ts +130 -0
- package/src/surreal/surql-type-expr.ts +36 -0
- package/src/surreal/wire.ts +405 -0
- package/src/testing.ts +2 -0
- package/bin.mjs +0 -15
package/LICENSE
CHANGED
package/README.md
CHANGED
|
@@ -1,7 +1,589 @@
|
|
|
1
1
|
# better-schemic
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Schema-as-code for [SurrealDB](https://surrealdb.com) — author your database schema in TypeScript
|
|
4
|
+
and generate SurrealQL DDL, types, and migrations from that one definition.
|
|
4
5
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
6
|
+
- Define tables and relations with `s.*`, a drop-in for [Zod](https://zod.dev)'s `z.*`.
|
|
7
|
+
- Generate `DEFINE TABLE` / `DEFINE FIELD` DDL, run reviewable migrations, and introspect a live database back into TypeScript.
|
|
8
|
+
- Read and write rows as typed values via codecs (`datetime` ⇄ `Date`, `uuid`, record links, …).
|
|
9
|
+
- One package: the authoring surface, the DDL/diff/migration engine and the `better-schemic` / `sc` CLI.
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
bun add better-schemic
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
That is the whole install. Zod and the SurrealDB SDK are **dependencies** of this package (not
|
|
18
|
+
peers), so there is exactly one copy of each — `s.*` extends Zod's builders, and a second Zod in
|
|
19
|
+
your app would break `instanceof` checks inside Zod. If you need raw Zod, import it from here so
|
|
20
|
+
you get the same copy: `import { z } from "better-schemic"`.
|
|
21
|
+
|
|
22
|
+
`@surrealdb/node` is an optional peer (the embedded in-memory engine `better-schemic check` can
|
|
23
|
+
replay into — `npm i -D @surrealdb/node`).
|
|
24
|
+
|
|
25
|
+
## Subpaths
|
|
26
|
+
|
|
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/driver` | the engine entry (CLI/engine-only — pulls in the DDL emitter) |
|
|
37
|
+
|
|
38
|
+
## Quick start
|
|
39
|
+
|
|
40
|
+
Scaffold a project (`sc` is the short alias for `better-schemic`):
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
sc init
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
`init` writes a `better-schemic.config.ts`, a sample `user` schema, a seed stub, and
|
|
47
|
+
`.env.example`. The sample schema:
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
// database/schema/tables/user.ts
|
|
51
|
+
import { defineTable, s, surql } from "better-schemic";
|
|
52
|
+
|
|
53
|
+
export const User = defineTable("user", {
|
|
54
|
+
name: s.string().$assert(surql`string::len($value) > 0`),
|
|
55
|
+
email: s.email().$unique(),
|
|
56
|
+
createdAt: s.datetime().$default(surql`time::now()`).$readonly(),
|
|
57
|
+
}).schemafull();
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
…which generates this SurrealQL DDL (the `id` field is provided automatically):
|
|
61
|
+
|
|
62
|
+
```surql
|
|
63
|
+
DEFINE TABLE user TYPE NORMAL SCHEMAFULL;
|
|
64
|
+
DEFINE FIELD name ON TABLE user TYPE string ASSERT string::len($value) > 0;
|
|
65
|
+
DEFINE FIELD email ON TABLE user TYPE string ASSERT string::is_email($value);
|
|
66
|
+
DEFINE INDEX user_email_idx ON TABLE user FIELDS email UNIQUE;
|
|
67
|
+
DEFINE FIELD createdAt ON TABLE user TYPE datetime DEFAULT time::now() READONLY;
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
`$value` computes/coerces on write and is **create-optional by default** (`time::now()`, a total
|
|
71
|
+
derived from other fields). An expression that reads `$value` declares its intent — `{ optional:
|
|
72
|
+
false }` for a transform that requires client input, `{ optional: true }` when the DB may compute
|
|
73
|
+
it without input. A parent mapping can mark the nested keys it fills as optional PER ITEM:
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
export const Order = defineTable("order", {
|
|
77
|
+
products: s
|
|
78
|
+
.array(
|
|
79
|
+
s.object({
|
|
80
|
+
product: s.string(),
|
|
81
|
+
quantity: s.int(),
|
|
82
|
+
sellingPriceAtOrder: s.number(),
|
|
83
|
+
}),
|
|
84
|
+
)
|
|
85
|
+
.$value(
|
|
86
|
+
surql`$value.map(|$p| { RETURN { product: $p.product, quantity: $p.quantity, sellingPriceAtOrder: 1 } })`,
|
|
87
|
+
{ optional: true, computes: ["sellingPriceAtOrder"] },
|
|
88
|
+
),
|
|
89
|
+
});
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
The connection lives in `better-schemic.config.ts` — a named connection from the
|
|
93
|
+
`surrealConnection` factory (no `driver:` string to keep in sync):
|
|
94
|
+
|
|
95
|
+
```ts
|
|
96
|
+
import { defineConfig, surrealConnection } from "better-schemic/config";
|
|
97
|
+
|
|
98
|
+
export default defineConfig({
|
|
99
|
+
connections: {
|
|
100
|
+
default: surrealConnection({
|
|
101
|
+
schema: "./database/schema",
|
|
102
|
+
url: process.env.SURREAL_URL ?? "ws://127.0.0.1:8000/rpc",
|
|
103
|
+
namespace: process.env.SURREAL_NAMESPACE ?? "app",
|
|
104
|
+
database: process.env.SURREAL_DATABASE ?? "app",
|
|
105
|
+
username: process.env.SURREAL_USER,
|
|
106
|
+
password: process.env.SURREAL_PASS,
|
|
107
|
+
authLevel: "root", // "root" | "namespace" | "database"
|
|
108
|
+
}),
|
|
109
|
+
},
|
|
110
|
+
});
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
Then drive it from the CLI:
|
|
114
|
+
|
|
115
|
+
```bash
|
|
116
|
+
sc diff # preview changes vs the last snapshot (--ts for a TypeScript view)
|
|
117
|
+
sc gen # write a migration for the pending change
|
|
118
|
+
sc migrate # apply pending migrations
|
|
119
|
+
sc seed # run database/seed.ts against a connection
|
|
120
|
+
sc status # show applied vs pending migrations
|
|
121
|
+
sc pull # introspect a live database back into TypeScript
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
## Reading & writing rows
|
|
125
|
+
|
|
126
|
+
A table definition carries codecs that bridge your app values and the database
|
|
127
|
+
wire format. `decode` turns a returned row into typed values (a `datetime`
|
|
128
|
+
becomes a `Date`, a `uuid` a string, record links resolve); `encode` and
|
|
129
|
+
`encodePartial` build the payloads you write back.
|
|
130
|
+
|
|
131
|
+
## The `/orm` client
|
|
132
|
+
|
|
133
|
+
The repository-style ORM lives at `better-schemic/orm`. Declare the
|
|
134
|
+
schema once with `defineSchema` and wrap an existing (BYO) or managed connection:
|
|
135
|
+
|
|
136
|
+
```ts
|
|
137
|
+
import { defineTable, s } from "better-schemic";
|
|
138
|
+
import { betterSchemic, createBetterSchemic, defineSchema } from "better-schemic/orm";
|
|
139
|
+
|
|
140
|
+
const User = defineTable("user", {
|
|
141
|
+
name: s.string(),
|
|
142
|
+
email: s.string(),
|
|
143
|
+
age: s.int(),
|
|
144
|
+
tags: s.array(s.string()),
|
|
145
|
+
}).index("user_email", ["email"], { unique: true });
|
|
146
|
+
|
|
147
|
+
// A cart whose lines are the rows the UNWIND+GROUP aggregate below walks.
|
|
148
|
+
const Line = defineTable("line", { label: s.string(), quantity: s.int() });
|
|
149
|
+
const Cart = defineTable("cart", {
|
|
150
|
+
name: s.string(),
|
|
151
|
+
lines: s.array(s.recordId(() => Line)),
|
|
152
|
+
});
|
|
153
|
+
// Multi-tenant: `email` is unique only WITHIN a tenant, so the index is the pair.
|
|
154
|
+
const Account = defineTable("account", {
|
|
155
|
+
tenant: s.string(),
|
|
156
|
+
email: s.string(),
|
|
157
|
+
name: s.string(),
|
|
158
|
+
}).index("account_tenant_email", ["tenant", "email"], { unique: true });
|
|
159
|
+
|
|
160
|
+
export const schema = defineSchema({
|
|
161
|
+
users: User,
|
|
162
|
+
carts: Cart,
|
|
163
|
+
lines: Line,
|
|
164
|
+
accounts: Account,
|
|
165
|
+
audit: "audit_log",
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
const client = betterSchemic(existingSurreal, { schema }); // BYO: close() is a no-op
|
|
169
|
+
// or: const client = await createBetterSchemic({ url, namespace, database, auth, schema });
|
|
170
|
+
|
|
171
|
+
// Reads (M1) — one round-trip, decoded to app values (Date/RecordId/…):
|
|
172
|
+
const adults = await client.users.findMany({
|
|
173
|
+
where: { age: { gte: 18 }, tags: { containsAny: ["db", "graph"] } },
|
|
174
|
+
select: { id: true, name: true },
|
|
175
|
+
orderBy: [{ age: "desc" }],
|
|
176
|
+
limit: 20,
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
const user = await client.users.findUnique({ where: { email } }).throw();
|
|
180
|
+
const total = await client.users.count({ where: { age: { gte: 18 } } });
|
|
181
|
+
const byTag = await client.users.aggregate({
|
|
182
|
+
select: { tags: "tags", _count: true, avgAge: { avg: "age" } },
|
|
183
|
+
groupBy: ["tags"], // the alias OR the path — both are valid group keys
|
|
184
|
+
});
|
|
185
|
+
// `math::*` only aggregates NUMBERS and answers 0/null/{}/silently for anything else, so the
|
|
186
|
+
// operand is checked against the schema: a wrong path is a compile error, not a R$ 0,00 report.
|
|
187
|
+
// Aggregating PER ELEMENT of an array is `split` (UNWIND in a subquery + GROUP outside):
|
|
188
|
+
const perUser = await client.carts.aggregate({
|
|
189
|
+
split: "lines",
|
|
190
|
+
select: { name: "name", total: { sum: "lines[*].quantity" } },
|
|
191
|
+
groupBy: ["name"], // where filters the PARENT rows
|
|
192
|
+
});
|
|
193
|
+
const page = await client.users.paginate({ orderBy: [{ id: "asc" }], limit: 20, start: 0 });
|
|
194
|
+
const next = await client.users.cursor({
|
|
195
|
+
select: { name: true }, // keyset fields ride reserved `_keyset_<n>` aliases
|
|
196
|
+
orderBy: [{ age: "desc" }, { id: "asc" }], // the LAST field must be unique — a type error now
|
|
197
|
+
limit: 20, // (`id`, or a field with a single-field UNIQUE index)
|
|
198
|
+
after: { age: 30, id: "user:42" },
|
|
199
|
+
});
|
|
200
|
+
// Cursor values carry the STORED value (`s.datetime()` round-trips a `DateTime` with nanoseconds;
|
|
201
|
+
// `id` a `RecordId`) — never the codec-decoded app value, so `after`/`before` never lose precision.
|
|
202
|
+
|
|
203
|
+
// Writes (M2) — validated by the codec, one round-trip, decoded rows back:
|
|
204
|
+
const created = await client.users.create({
|
|
205
|
+
data: { name: "Aeon", email: "aeon@x.dev", age: 30, tags: ["db"] },
|
|
206
|
+
});
|
|
207
|
+
const inserted = await client.users.insertMany({
|
|
208
|
+
data: externalUsers, // ids in the payload
|
|
209
|
+
onDuplicate: "update", // INSERT … ON DUPLICATE KEY UPDATE
|
|
210
|
+
});
|
|
211
|
+
const updated = await client.users
|
|
212
|
+
.update({ where: { id: created.id }, data: { age: 31 } }) // never creates
|
|
213
|
+
.throw();
|
|
214
|
+
const patched = await client.users.patch({
|
|
215
|
+
where: { id: created.id },
|
|
216
|
+
patches: [{ op: "replace", path: "/age", value: 32 }],
|
|
217
|
+
});
|
|
218
|
+
const upserted = await client.users.upsert({
|
|
219
|
+
where: { email: "aeon@x.dev" }, // id, a UNIQUE index (single field, or the fields
|
|
220
|
+
data: { email: "aeon@x.dev", age: 33 }, // of a COMPOSITE one) — or infer from `data.id`
|
|
221
|
+
onMissing: "create", // STRICT by default: a miss rejects ResultNotFound
|
|
222
|
+
});
|
|
223
|
+
// The multi-tenant shape: `email` is unique only WITHIN a tenant, so the `[tenant, email]` index IS
|
|
224
|
+
// the unique key — pass every field of the group (a partial `where` would match many rows):
|
|
225
|
+
const tenantUpserted = await client.accounts.upsert({
|
|
226
|
+
where: { tenant: "acme", email: "aeon@x.dev" },
|
|
227
|
+
data: { name: "Aeon" },
|
|
228
|
+
});
|
|
229
|
+
const saved = await client.users.upsert({
|
|
230
|
+
data: { id: created.id, age: 33 }, // `data.id` infers the target — strict UPDATE ONLY
|
|
231
|
+
});
|
|
232
|
+
const fresh = await client.users.upsert({
|
|
233
|
+
data: { name: "Nova", email: "nova@x.dev", age: 1, tags: [] }, // no target at all → CREATE
|
|
234
|
+
});
|
|
235
|
+
const { record, created, before, delta, changed } = await client.users.upsertDelta({
|
|
236
|
+
where: { id: created.id }, // or a UNIQUE field, or `data.id`, or omitted to create
|
|
237
|
+
data: { age: 34 },
|
|
238
|
+
onMissing: "create", // strict by default here too
|
|
239
|
+
});
|
|
240
|
+
// ONE statement, `RETURN VALUE { before, after }` — no read-then-write race. On a create
|
|
241
|
+
// `created: true` and `before`/`delta` are null; on an update `delta.old`/`delta.new` carry ONLY
|
|
242
|
+
// the changed fields as DECODED app values (server-computed for surql expressions), and
|
|
243
|
+
// `changed` names them. Both upserts resolve the target the same way (`where` > `data.id` > no
|
|
244
|
+
// target = plain create) and are STRICT by default — a targeted miss rejects `ResultNotFound`;
|
|
245
|
+
// `onMissing: "create"` (above) restores create-or-update:
|
|
246
|
+
const strict = await client.users.upsert({
|
|
247
|
+
where: { id: created.id },
|
|
248
|
+
data: { age: 35 }, // UPDATE ONLY — never creates, never resolves null
|
|
249
|
+
});
|
|
250
|
+
void before;
|
|
251
|
+
void delta;
|
|
252
|
+
void changed;
|
|
253
|
+
void strict;
|
|
254
|
+
const removed = await client.users.delete({ where: { id: created.id } });
|
|
255
|
+
|
|
256
|
+
// Write projections + counters — every write accepts the same `select`/`omit` as reads. The
|
|
257
|
+
// server carries the projection in its own RETURN clause when it can (`RETURN id, age`,
|
|
258
|
+
// `RETURN *, upper`); BEFORE/`delete`/`upsertDelta`/`omit` rows are decoded whole and projected
|
|
259
|
+
// client-side (expression entries only exist server-side, so those states reject them). Types
|
|
260
|
+
// follow the projection exactly like reads (`{ id: true, age: true }` → `{ id, age }`).
|
|
261
|
+
// `{ increment }`/`{ decrement }` adjust a numeric field in ONE read-modify-write — no lost update
|
|
262
|
+
// between a client read and write:
|
|
263
|
+
const aged = await client.users.update({
|
|
264
|
+
where: { id: created.id },
|
|
265
|
+
data: { age: { increment: 1 } }, // → UPDATE user:… SET age += $p0
|
|
266
|
+
select: { id: true, age: true }, // → … RETURN id, age
|
|
267
|
+
});
|
|
268
|
+
const previous = await client.users
|
|
269
|
+
.update({
|
|
270
|
+
where: { id: created.id },
|
|
271
|
+
data: { age: { decrement: 2 } }, // → SET age -= $p0
|
|
272
|
+
return: "before", // → RETURN BEFORE (projected client-side)
|
|
273
|
+
select: { age: true },
|
|
274
|
+
})
|
|
275
|
+
.throw();
|
|
276
|
+
// Array fields have their own markers, each ONE server-side write (so a UNIQUE index over the
|
|
277
|
+
// whole array stays correct — the server is what swaps the key):
|
|
278
|
+
const tagged = await client.users.update({
|
|
279
|
+
where: { id: created.id },
|
|
280
|
+
data: { tags: { append: "vip" } }, // → SET tags += $p0 (append, NO dedup)
|
|
281
|
+
});
|
|
282
|
+
const deduped = await client.users.update({
|
|
283
|
+
where: { id: created.id },
|
|
284
|
+
data: { tags: { union: ["vip", "beta"] } }, // → SET tags = array::union(tags, $p0) (dedups)
|
|
285
|
+
});
|
|
286
|
+
const without = await client.users.update({
|
|
287
|
+
where: { id: created.id },
|
|
288
|
+
data: { tags: { remove: "beta" } }, // → SET tags -= $p0 (removes EVERY occurrence)
|
|
289
|
+
});
|
|
290
|
+
void aged;
|
|
291
|
+
void previous;
|
|
292
|
+
void tagged;
|
|
293
|
+
void deduped;
|
|
294
|
+
void without;
|
|
295
|
+
|
|
296
|
+
// Created ids: every ORM create without an explicit `id` generates a ULID by default
|
|
297
|
+
// (`rand::ulid()` — 26 chars, time-sortable). Pick another strategy per table in authoring:
|
|
298
|
+
// defineTable("user", { … }).idStrategy("uuid") // rand::uuid() — UUID v7
|
|
299
|
+
// defineTable("legacy", { … }).idStrategy("rand") // rand::id() — the server default (20 chars)
|
|
300
|
+
// An explicit `id` always wins and singleton tables keep their fixed id. The strategy is
|
|
301
|
+
// ORM-only: it emits NO DDL (migrations never diff), raw SQL keeps the server default, and
|
|
302
|
+
// `sc pull` cannot recover it. A pinned uuid v4/v6 `id` field is explicit-only: creates without
|
|
303
|
+
// an `id` fail at compile time (no strategy can generate that format).
|
|
304
|
+
|
|
305
|
+
// String ids (M15) — opt a table into BARE app id strings (`01M…`); `RecordId` stays on the wire.
|
|
306
|
+
// The emitted DDL is UNCHANGED (`record<…>` — zero migration), and raw `db.query()`, `live` and
|
|
307
|
+
// `changes` still return `RecordId`:
|
|
308
|
+
// const Customer = defineTable("customer", { name: s.string(), owner: s.recordId(User) })
|
|
309
|
+
// .stringIds(); // or per field: s.recordId(User).stringIds()
|
|
310
|
+
// const row = await client.customers.create({ data: { name: "A", owner: "aeon" } });
|
|
311
|
+
// row.owner; // "aeon" — the bare id, not a RecordId
|
|
312
|
+
// const byOwner = await client.customers.findMany({ where: { owner: "aeon" } });
|
|
313
|
+
// const page = await client.customers.cursor({
|
|
314
|
+
// orderBy: [{ id: "asc" }], limit: 20, after: "01M…", // bare cursor; nextCursor bare too
|
|
315
|
+
// });
|
|
316
|
+
// `stringIds()` covers the id + every record link (nested objects/arrays included); a link to
|
|
317
|
+
// MULTIPLE tables throws (a bare string can't name the table on encode). `User.record()` inherits
|
|
318
|
+
// the mode and `tenant(User)` follows the principal.
|
|
319
|
+
|
|
320
|
+
// Edges live on the relation delegate (`defineRelation`):
|
|
321
|
+
// const like = await client.likes.relate({ from: "user:1", to: "post:1", data: { score: 5 } });
|
|
322
|
+
// await client.likes.unrelate({ from: "user:1", to: "post:1" });
|
|
323
|
+
|
|
324
|
+
// Relations & graphs (M3) — links (FETCH), edge traversal and `_count`, still ONE round-trip.
|
|
325
|
+
// Both examples need a `Post`/`Likes` pair in the schema; uncomment when you have one:
|
|
326
|
+
// const posts = await client.posts.findMany({
|
|
327
|
+
// include: {
|
|
328
|
+
// author: { select: { id: true, name: true } }, // FETCH or flat remount
|
|
329
|
+
// likes: { where: { score: { gte: 4 } }, select: { title: true } }, // per-parent subquery
|
|
330
|
+
// _count: { select: { likes: true } }, // correlated count -> _count.likes
|
|
331
|
+
// },
|
|
332
|
+
// where: { likes: { some: { score: { gte: 4 } } } }, // relational filter
|
|
333
|
+
// });
|
|
334
|
+
|
|
335
|
+
// Transactions (M4) — `tx` is a full client bound to the managed transaction:
|
|
336
|
+
const from = await client.transaction(async (tx) => {
|
|
337
|
+
const user = await tx.users
|
|
338
|
+
.update({ where: { id: "user:1" }, mode: "set", data: { age: surql`age + 1` }, return: "after" })
|
|
339
|
+
.throw();
|
|
340
|
+
tx.afterCommit(() => mailer.send(user.email)); // outside effects only after the commit
|
|
341
|
+
return user;
|
|
342
|
+
});
|
|
343
|
+
|
|
344
|
+
// Live queries (M4) — the ORM compiles the LIVE SELECT (typed where/select/fetch):
|
|
345
|
+
const sub = await client.users.live(
|
|
346
|
+
{ where: { active: true }, diff: true },
|
|
347
|
+
(change) => {
|
|
348
|
+
if (change.action === "UPDATE") cache.set(change.recordId, change.diff);
|
|
349
|
+
},
|
|
350
|
+
);
|
|
351
|
+
// for await (const change of sub) { … }
|
|
352
|
+
await sub.kill(); // or: await client.kill(sub.uuid)
|
|
353
|
+
|
|
354
|
+
// Changefeeds (M4) — DEFINE TABLE t CHANGEFEED 1d (INCLUDE ORIGINAL for before/diff):
|
|
355
|
+
const sets = await client.changes({ table: "users", since: 0, limit: 100 });
|
|
356
|
+
for (const { versionstamp, changes } of sets) {
|
|
357
|
+
for (const change of changes) {
|
|
358
|
+
if (change.action === "DELETE") cache.delete(change.recordId);
|
|
359
|
+
}
|
|
360
|
+
void versionstamp; // paginate with `versionstamp + 1`
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// Escape hatches & admin (M5) — parameterized by default:
|
|
364
|
+
const rows = await client.$raw<User[]>`SELECT * FROM users WHERE email = ${email}`;
|
|
365
|
+
const [users, posts] = await client.$query<[User[], Post[]]>`
|
|
366
|
+
SELECT * FROM users LIMIT 10; SELECT * FROM posts LIMIT 10;
|
|
367
|
+
`;
|
|
368
|
+
// A curried tag carries options into the template form (e.g. under `raw.requireComment`):
|
|
369
|
+
// const seeded = await client.$raw({ meta: { comment: "seed" } })`CREATE …`;
|
|
370
|
+
const tier = await client.fn.call<string>("fn::customer_tier", [15000]);
|
|
371
|
+
// Typed shortcut per `defineFunction` (named args -> positional):
|
|
372
|
+
// const tier = await client.fn.customerTier({ total: 15000 });
|
|
373
|
+
const articles = await client.api.get<Article[]>("/articles", { query: { limit: 10 } });
|
|
374
|
+
const info = await client.info("db"); // INFO FOR DB
|
|
375
|
+
const dump = await client.export();
|
|
376
|
+
await client.import(dump);
|
|
377
|
+
|
|
378
|
+
// Multi-tenant scope (M5.3) — `USE NS … DB …;` per operation, no global state:
|
|
379
|
+
const tenantA = client.$withContext({ namespace: "tenant_a", database: "app" });
|
|
380
|
+
await tenantA.invoices.findMany({ where: { status: "open" } });
|
|
381
|
+
await tenantA.invoices.findMany({ context: { database: "analytics" } }); // per-call override
|
|
382
|
+
// `api`/`auth`/`export`/`live` are session-bound; fork a scoped session when you need them:
|
|
383
|
+
const scoped = await client.$withContext({ namespace: "tenant_a", database: "app", auth: token });
|
|
384
|
+
|
|
385
|
+
// Diagnostics without executing:
|
|
386
|
+
const plan = await client.users.findMany({ where: { age: 18 } }).explain();
|
|
387
|
+
|
|
388
|
+
// Observation hooks (M6) — logging/tracing around every operation, never mutating it:
|
|
389
|
+
const logged = betterSchemic(db, {
|
|
390
|
+
schema,
|
|
391
|
+
hooks: {
|
|
392
|
+
beforeQuery: ({ table, operation, surql }) => logger.debug({ table, operation, surql }),
|
|
393
|
+
afterQuery: ({ durationMs }) => metrics.timing("db.query", durationMs),
|
|
394
|
+
onError: ({ error }) => logger.error({ err: error }),
|
|
395
|
+
},
|
|
396
|
+
});
|
|
397
|
+
|
|
398
|
+
// Plugins (M6) — mutate operations, add typed args, extend the client/delegates:
|
|
399
|
+
import { definePlugin, surql } from "better-schemic/orm";
|
|
400
|
+
const softDelete = definePlugin({
|
|
401
|
+
id: "soft-delete",
|
|
402
|
+
config: { column: "deletedAt" },
|
|
403
|
+
operationArgs: { findMany: { deleted: "without" as "with" | "without" | "only" } },
|
|
404
|
+
transform(op) {
|
|
405
|
+
if (op.kind === "delete") { op.kind = "update"; op.data[this.config.column] = surql`time::now()`; }
|
|
406
|
+
else if (op.kind.startsWith("find") && op.args.deleted !== "with") op.where[this.config.column] = { isNone: true };
|
|
407
|
+
},
|
|
408
|
+
extendModel({ model }) {
|
|
409
|
+
return { restore: (args) => model.update({ where: args.where, mode: "set", data: { [this.config.column]: null } }) };
|
|
410
|
+
},
|
|
411
|
+
});
|
|
412
|
+
// await client.users.findMany({ deleted: "with" });
|
|
413
|
+
// await client.users.delete({ where: { id } }); // soft delete
|
|
414
|
+
// await client.users.restore({ where: { id } });
|
|
415
|
+
```
|
|
416
|
+
|
|
417
|
+
Official F1 guardrail/validation plugins (M6.3) ship as subpaths:
|
|
418
|
+
|
|
419
|
+
```ts
|
|
420
|
+
import { recommended } from "better-schemic/plugins/rules";
|
|
421
|
+
import { zod } from "better-schemic/plugins/zod";
|
|
422
|
+
const client = betterSchemic(db, {
|
|
423
|
+
schema,
|
|
424
|
+
plugins: [
|
|
425
|
+
recommended({ maxLimit: 100 }), // noRawUnsafe + no unfiltered writes + required/max limit
|
|
426
|
+
zod({ schemas: { user: z.object({ email: z.email() }) } }),
|
|
427
|
+
],
|
|
428
|
+
});
|
|
429
|
+
```
|
|
430
|
+
|
|
431
|
+
Official F2 plugins (M6.4) — timestamps + a reversible soft delete:
|
|
432
|
+
|
|
433
|
+
```ts
|
|
434
|
+
import { timestamps } from "better-schemic/plugins/timestamps";
|
|
435
|
+
import { softDelete } from "better-schemic/plugins/soft-delete";
|
|
436
|
+
|
|
437
|
+
const client = betterSchemic(db, {
|
|
438
|
+
schema,
|
|
439
|
+
plugins: [timestamps(), softDelete({ deletedBy: "deletedBy" })],
|
|
440
|
+
});
|
|
441
|
+
// create/update get `time::now()` stamped automatically (mode "app");
|
|
442
|
+
// delete becomes a soft delete and reads hide deleted rows unless `deleted: "with" | "only"`:
|
|
443
|
+
await client.users.delete({ where: { id }, meta: { actor: currentUserId } });
|
|
444
|
+
const live = await client.users.findMany({}); // deleted rows hidden
|
|
445
|
+
const all = await client.users.findMany({ deleted: "with" }); // include them
|
|
446
|
+
await client.users.restoreById(id); // clear deletedAt
|
|
447
|
+
```
|
|
448
|
+
|
|
449
|
+
Official F3 plugin (M10) — multi-tenant RLS: a schema PRESET (`tenant()`) plus a runtime plugin
|
|
450
|
+
(`tenantRls()`) for privileged sessions, where `$auth`/DDL permissions do not filter:
|
|
451
|
+
|
|
452
|
+
```ts
|
|
453
|
+
import { tenant, tenantRls } from "better-schemic/plugins/tenant";
|
|
454
|
+
|
|
455
|
+
// Schema: one `.use(tenant(principal, options?))` per table — tenant column + per-op permissions +
|
|
456
|
+
// `{table}_protect_<column>` guard event + indexes (zero-diff with the hand-written recipe).
|
|
457
|
+
const User = defineTable("user", { name: s.string() });
|
|
458
|
+
const Customer = defineTable("customer", {
|
|
459
|
+
name: s.string(),
|
|
460
|
+
deletedAt: s.datetime().optional(), // app-declared tombstone (softDelete: true)
|
|
461
|
+
}).use(tenant(User, { softDelete: true }));
|
|
462
|
+
const Order = defineTable("order", { total: s.number() })
|
|
463
|
+
.use(tenant(User, { createOnly: true })); // append-only: update = NONE
|
|
464
|
+
|
|
465
|
+
// Runtime: every tenant-tagged table requires a scope BEFORE compiling (fail-closed).
|
|
466
|
+
const client = betterSchemic(db, {
|
|
467
|
+
schema: defineSchema({ users: User, customers: Customer, orders: Order }),
|
|
468
|
+
plugins: [tenantRls({ tenant: () => ctx.tenantId })],
|
|
469
|
+
});
|
|
470
|
+
await client.customers.findMany({}); // ✗ TenantRequired (no scope)
|
|
471
|
+
await client.customers.$forTenant("user:abc").findMany({}); // ✓ scoped to user:abc
|
|
472
|
+
await client.customers.$forTenant("user:abc").create({ data: { name: "A" } }); // tenant injected
|
|
473
|
+
await client.customers.$forTenant("user:abc").findUnique({ where: { id: "customer:1" } });
|
|
474
|
+
// ✓ reads are scoped too (id and single-field UNIQUE targets) — a cross-tenant id resolves null
|
|
475
|
+
await client.customers.$withoutPlugins().findMany({}); // explicit admin escape (audited)
|
|
476
|
+
```
|
|
477
|
+
|
|
478
|
+
Official plugin (M14) — create-only (append-only) tables: the `createOnly()` schema PRESET
|
|
479
|
+
(`update` locked to `NONE`, optional hard event) plus the `createOnlyGuard()` runtime plugin
|
|
480
|
+
(fail-fast for privileged sessions, where the DDL permission does not gate):
|
|
481
|
+
|
|
482
|
+
```ts
|
|
483
|
+
import { createOnly, createOnlyGuard } from "better-schemic/plugins/create-only";
|
|
484
|
+
|
|
485
|
+
// Schema: PERMISSIONS FOR update NONE + meta.createOnly. `hard: true` also emits an
|
|
486
|
+
// `{table}_create_only` event — events run without permission checks, so root/$withoutPlugins/raw
|
|
487
|
+
// are blocked too. `timestamps()` sees the marker and never stamps `updatedAt` on this table.
|
|
488
|
+
const AuditLog = defineTable("audit_log", {
|
|
489
|
+
action: s.string(),
|
|
490
|
+
createdAt: s.datetime().optional(),
|
|
491
|
+
}).use(createOnly({ hard: true }));
|
|
492
|
+
|
|
493
|
+
const client = betterSchemic(db, {
|
|
494
|
+
schema: defineSchema({ auditLogs: AuditLog }),
|
|
495
|
+
plugins: [timestamps(), createOnlyGuard()],
|
|
496
|
+
});
|
|
497
|
+
await client.auditLogs.create({ data: { action: "login" } }); // createdAt only (no updatedAt)
|
|
498
|
+
await client.auditLogs.update({ where: { id }, data: { action: "x" } }); // ✗ CreateOnlyViolation
|
|
499
|
+
await client.auditLogs.$withoutPlugins().update({ where: { id }, data: {} }); // ✗ hard event THROWs
|
|
500
|
+
// create()/insert({ onDuplicate: "ignore" }) write; delete stays allowed (rows are immutable,
|
|
501
|
+
// not tombstones). `createOnlyGuard({ tables: ["audit_log"] })` covers preset-less schemas.
|
|
502
|
+
```
|
|
503
|
+
|
|
504
|
+
### Beautiful query logging (M9)
|
|
505
|
+
|
|
506
|
+
Enable the built-in logger with one flag — a framed, syntax-highlighted box for every round-trip,
|
|
507
|
+
with timing, row counts and (optionally) the `EXPLAIN` plan tree:
|
|
508
|
+
|
|
509
|
+
```ts
|
|
510
|
+
const client = betterSchemic(db, { schema, logger: true });
|
|
511
|
+
// presets: "pretty" (default) | "compact" | "json" (log shippers) | "silent"
|
|
512
|
+
// await client.users.findMany({ where: { age: { gte: 18 } } });
|
|
513
|
+
// ╭─ 🔍 findMany · user ─────────────────────────────╮
|
|
514
|
+
// │ SELECT * FROM user │
|
|
515
|
+
// │ WHERE age >= $p0 │
|
|
516
|
+
// │ $p0 = 18 │
|
|
517
|
+
// ╰─ 2 rows · 12.4ms · #1 · 14:03:22.881 ────────────╯
|
|
518
|
+
```
|
|
519
|
+
|
|
520
|
+
It observes the **executor** (reads, writes, `$raw`, `fn`, admin, changes, live — and `.explain()`
|
|
521
|
+
plans), never changing the operation:
|
|
522
|
+
|
|
523
|
+
```ts
|
|
524
|
+
const client = betterSchemic(db, {
|
|
525
|
+
schema,
|
|
526
|
+
logger: {
|
|
527
|
+
slowMs: 50, // mark slow queries (also gates `level: "info"`)
|
|
528
|
+
explain: "slow", // auto-EXPLAIN reads >= slowMs ("all" | "analyze" available)
|
|
529
|
+
verbose: true, // preview the first rows
|
|
530
|
+
colors: "auto", // honours NO_COLOR / FORCE_COLOR / TTY
|
|
531
|
+
redact: true, // mask bound values (`$p0 = [redacted]`) for shared/CI logs
|
|
532
|
+
},
|
|
533
|
+
});
|
|
534
|
+
|
|
535
|
+
// .explain() / explain: true render the server plan as an operator tree:
|
|
536
|
+
// ╭─ 🔎 EXPLAIN findMany · user ─────────────────────────────────╮
|
|
537
|
+
// │ SELECT * FROM user WHERE age >= $p0 │
|
|
538
|
+
// │ plan │
|
|
539
|
+
// │ SelectProject [ctx: Db, projections: *] │
|
|
540
|
+
// │ └─ TableScan [ctx: Db, table: user, direction: Forward] ⚠ full scan
|
|
541
|
+
// ╰─ 0.11ms · #2 ───────────────────────────────────────────────╯
|
|
542
|
+
```
|
|
543
|
+
|
|
544
|
+
Construct one explicitly (or use another preset) via the dedicated subpath, and enable it without
|
|
545
|
+
code with `BETTER_SCHEMIC_LOG=1|pretty|json` (`BETTER_SCHEMIC_LOG_LEVEL`, `BETTER_SCHEMIC_LOG_SLOW_MS`):
|
|
546
|
+
|
|
547
|
+
```ts
|
|
548
|
+
import { createQueryLogger } from "better-schemic/logger";
|
|
549
|
+
const client = betterSchemic(db, { schema, logger: createQueryLogger({ format: "json" }) });
|
|
550
|
+
```
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
`client.users.$model` is the delegate metadata; `client.repository("user")` looks
|
|
554
|
+
up by schema key OR physical name; `client.tables` lists the keys; `client.$sdk`
|
|
555
|
+
is the raw `surrealdb` connection (escape hatch).
|
|
556
|
+
|
|
557
|
+
**Status:** the typed-query arc (M0–M7) is **complete** — reads (M1), writes (M2 —
|
|
558
|
+
`create`/`insert`/`update`/`patch`/`upsert`/`delete`/`updateEach` plus `relate`/`unrelate` on edge
|
|
559
|
+
delegates), relations/graphs (M3 — `include` links/edges/`_count`, relational `where`
|
|
560
|
+
`is`/`isNot`/`some`/`every`/`none`), transactions/live/changefeeds (M4 — `client.transaction` with
|
|
561
|
+
retries and `afterCommit`/`afterRollback`, `live()` + `LiveSubscription` with reconnect, `changes()`),
|
|
562
|
+
escape hatches/admin/context (M5 — `$raw`/`$query`/`$unsafe`, `fn`/`api`/`auth`/`info`/`version`/
|
|
563
|
+
`ping`/`export`/`import`, `$withContext` multi-tenant scoping with per-call `context`) and
|
|
564
|
+
plugins/hooks (M6 — observation `hooks`, `definePlugin` with transforms/typed `operationArgs`/
|
|
565
|
+
`extendClient`/`extendModel`, plus the official plugins `plugins/rules`, `plugins/zod`,
|
|
566
|
+
`plugins/timestamps`, `plugins/soft-delete` and `plugins/tenant`). M9 adds the built-in query logger
|
|
567
|
+
(`logger: true` / `better-schemic/logger`) with `EXPLAIN` plan rendering, and M14 adds
|
|
568
|
+
`plugins/create-only` (append-only tables: preset + runtime guard + optional hard event).
|
|
569
|
+
|
|
570
|
+
The runtime surface is mapped exhaustively in [`docs/ORM-COVERAGE.md`](docs/ORM-COVERAGE.md), the
|
|
571
|
+
live-verified SurrealQL facts live in [`docs/orm-syntax-map.md`](docs/orm-syntax-map.md), the
|
|
572
|
+
milestone plan is in [`ROADMAP.md`](../../ROADMAP.md), and the verified examples are in
|
|
573
|
+
[`examples/`](examples) (authoring → DDL) and [`examples/orm/`](examples/orm) (delegate call →
|
|
574
|
+
runtime SurrealQL). Fragments & procedural SurrealQL (`block()`) stay at
|
|
575
|
+
`better-schemic/query`.
|
|
576
|
+
|
|
577
|
+
## Docs
|
|
578
|
+
|
|
579
|
+
Full guides, concepts, and reference live at
|
|
580
|
+
[docs](https://github.com/NONSTANDARDCODE/better-schemic). Feature maps:
|
|
581
|
+
[docs/COVERAGE.md](docs/COVERAGE.md) (schema/DDL) and
|
|
582
|
+
[docs/ORM-COVERAGE.md](docs/ORM-COVERAGE.md) (runtime ORM surface); the live-verified SurrealQL the
|
|
583
|
+
ORM emits is [docs/orm-syntax-map.md](docs/orm-syntax-map.md), and the milestone plan is
|
|
584
|
+
[ROADMAP.md](../../ROADMAP.md). This package is part of the
|
|
585
|
+
[Better-schemic](https://github.com/NONSTANDARDCODE/better-schemic) toolkit.
|
|
586
|
+
|
|
587
|
+
## License
|
|
588
|
+
|
|
589
|
+
[MIT](./LICENSE) © NONSTANDARDCODE
|