@schemic/postgres 0.1.0-alpha.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 Vertio Solutions
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,103 @@
1
+ # @schemic/postgres
2
+
3
+ The PostgreSQL driver for [Schemic](https://github.com/schemichq/schemic) —
4
+ author your Postgres schema in TypeScript and emit, introspect, and diff it as
5
+ native SQL DDL.
6
+
7
+ > [!NOTE]
8
+ > **Alpha.** Today the driver runs on embedded [PGlite](https://pglite.dev):
9
+ > authoring, DDL emit, introspection, and migrations round-trip against it. A
10
+ > client for hosted Postgres servers is planned. See
11
+ > [docs/COVERAGE.md](docs/COVERAGE.md) for the feature-by-feature status.
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ bun add @schemic/cli @schemic/postgres @electric-sql/pglite
17
+ ```
18
+
19
+ `@electric-sql/pglite` is the embedded engine (the only engine today). `zod`
20
+ ships with the driver — add it yourself only if you import `z` directly for
21
+ custom codecs.
22
+
23
+ ## Quick start
24
+
25
+ Scaffold a Postgres project (`sc` is the short alias for `schemic`):
26
+
27
+ ```bash
28
+ sc init --driver postgres
29
+ ```
30
+
31
+ `init` writes a `schemic.config.ts`, a sample schema, a seed stub, and
32
+ `.env.example`. The sample schema:
33
+
34
+ ```ts
35
+ // database/schema/tables.ts
36
+ import { defineTable, s, sqlExpr } from "@schemic/postgres";
37
+
38
+ export const user = defineTable("user", {
39
+ email: s.varchar(255).$unique(),
40
+ name: s.text(),
41
+ age: s.smallint().optional(),
42
+ createdAt: s.timestamptz().$default(sqlExpr("now()")),
43
+ });
44
+ ```
45
+
46
+ …which emits this Postgres DDL (an `id` primary key is added automatically):
47
+
48
+ ```sql
49
+ CREATE TABLE "user" (
50
+ "id" text PRIMARY KEY,
51
+ "age" smallint,
52
+ "createdAt" timestamp with time zone NOT NULL DEFAULT now(),
53
+ "email" varchar(255) NOT NULL,
54
+ "name" text NOT NULL
55
+ );
56
+ CREATE UNIQUE INDEX "user_email_key" ON "user" ("email");
57
+ ```
58
+
59
+ The connection lives in `schemic.config.ts` — a named connection from the
60
+ `postgresConnection` factory (no `driver:` string to keep in sync):
61
+
62
+ ```ts
63
+ import { defineConfig } from "@schemic/core/config";
64
+ import { postgresConnection } from "@schemic/postgres";
65
+
66
+ export default defineConfig({
67
+ connections: {
68
+ default: postgresConnection({
69
+ schema: "./database/schema",
70
+ // PGlite (embedded): `file:<dir>` persists to a data dir; "" is in-memory.
71
+ url: process.env.DATABASE_URL ?? "file:./.pgdata",
72
+ }),
73
+ },
74
+ });
75
+ ```
76
+
77
+ Then drive it from the CLI:
78
+
79
+ ```bash
80
+ sc diff # preview changes vs the last snapshot
81
+ sc gen # write a migration for the pending change
82
+ sc migrate # apply pending migrations
83
+ sc seed # run database/seed.ts against a connection
84
+ sc status # show applied vs pending migrations
85
+ ```
86
+
87
+ ## Authoring
88
+
89
+ `s.*` is a [Zod](https://zod.dev) superset with Postgres-native types —
90
+ `s.varchar(n)`, `s.text()`, `s.smallint()`, `s.timestamptz()`, and more — plus
91
+ DDL modifiers like `.$unique()` and `.$default(sqlExpr(...))`. Reach for
92
+ `sqlExpr` to drop raw SQL into defaults and other expressions.
93
+
94
+ ## Docs
95
+
96
+ Feature-by-feature coverage: [docs/COVERAGE.md](docs/COVERAGE.md). This package
97
+ is part of the [Schemic](https://github.com/schemichq/schemic) toolkit — shared
98
+ concepts (schema-as-code, the migration model, codecs) are at
99
+ [schemic.dev](https://schemic.dev).
100
+
101
+ ## License
102
+
103
+ [MIT](./LICENSE) © Vertio Solutions
package/lib/index.d.ts ADDED
@@ -0,0 +1,240 @@
1
+ import { ConnectionConfigBase, ConnectionEntry, ResolveContext, Driver } from '@schemic/core/driver';
2
+ import { SFieldBase, AnyField, SchemaOf } from '@schemic/core/authoring';
3
+ import * as z from 'zod';
4
+
5
+ /** A pg column type token + optional params (`varchar`/[255], `numeric`/[10,2]); the leaf factory sets it. */
6
+ interface PgTypeRef {
7
+ type: string;
8
+ params?: (string | number)[];
9
+ }
10
+ /** Postgres-native field metadata (the `native` slot of {@link PgField}). All optional; merged by `$`-methods. */
11
+ interface PgMeta {
12
+ /** The pg base type (sans option/nullable/array wrappers, which live on the Zod schema). */
13
+ pg?: PgTypeRef;
14
+ /** `DEFAULT <expr>` (verbatim SQL). */
15
+ default?: string;
16
+ /** Field-level `CHECK (<expr>)` (verbatim SQL boolean expr). */
17
+ check?: string;
18
+ /** `GENERATED ALWAYS AS (<expr>) STORED` (verbatim SQL expr). */
19
+ generated?: string;
20
+ /** `GENERATED {ALWAYS|BY DEFAULT} AS IDENTITY` (also how `serial` is modeled). */
21
+ identity?: "always" | "by-default";
22
+ /** Column-level `UNIQUE`. */
23
+ unique?: boolean;
24
+ /** Column is (part of) the PRIMARY KEY. */
25
+ primaryKey?: boolean;
26
+ /** A foreign key to `table(id)` with optional referential actions. */
27
+ references?: {
28
+ table: string;
29
+ onDelete?: string;
30
+ onUpdate?: string;
31
+ };
32
+ /** `COMMENT ON COLUMN`. */
33
+ comment?: string;
34
+ }
35
+ /** A raw SQL expression marker for DDL clauses (`$default`/`$check`/`$generated`) — spliced verbatim. */
36
+ interface SqlExpr {
37
+ readonly __sql: string;
38
+ }
39
+ /** Mark a string as a raw SQL expression (vs a literal value) for a DDL clause: `s.timestamptz().$default(sqlExpr("now()"))`. */
40
+ declare const sqlExpr: (sql: string) => SqlExpr;
41
+ /**
42
+ * A Postgres field: a Zod schema (App/Wire typing) + {@link PgMeta} (pg-native DDL metadata). Extends
43
+ * the neutral {@link SFieldBase}, which supplies the codecs, the Zod wrappers, and the `z.*` passthrough;
44
+ * this subclass re-types the wrappers so a chain stays a `PgField`, and adds the pg `$`-methods.
45
+ */
46
+ declare class PgField<S extends z.ZodType = z.ZodType, Flags extends string = never> extends SFieldBase<S, Flags, PgMeta> {
47
+ protected rebuild<S2 extends z.ZodType, F2 extends string>(schema: S2, native: PgMeta): PgField<S2, F2>;
48
+ protected blank(): PgMeta;
49
+ optional: () => PgField<z.ZodOptional<S>, Flags>;
50
+ nullable: () => PgField<z.ZodNullable<S>, Flags>;
51
+ nullish: () => PgField<z.ZodOptional<z.ZodNullable<S>>, Flags>;
52
+ array: () => PgField<z.ZodArray<S>, Flags>;
53
+ default: (value: z.input<S>) => PgField<z.ZodDefault<S>, Flags>;
54
+ prefault: (value: z.input<S>) => PgField<z.ZodPrefault<S>, Flags>;
55
+ catch: (value: z.output<S>) => PgField<z.ZodCatch<S>, Flags>;
56
+ private with;
57
+ /** `DEFAULT <value>` — a JS literal, or `sqlExpr("now()")` for a raw SQL default. */
58
+ $default(value: z.input<S> | SqlExpr): PgField<S, Flags>;
59
+ /** Field-level `CHECK (<expr>)`. */
60
+ $check(expr: string | SqlExpr): PgField<S, Flags>;
61
+ /** `GENERATED ALWAYS AS (<expr>) STORED` — a computed column. */
62
+ $generated(expr: string | SqlExpr): PgField<S, Flags>;
63
+ /** `GENERATED {ALWAYS|BY DEFAULT} AS IDENTITY` (auto-increment). */
64
+ $identity(mode?: "always" | "by-default"): PgField<S, Flags>;
65
+ /** Column-level `UNIQUE`. */
66
+ $unique(): PgField<S, Flags>;
67
+ /** Mark this column (part of) the PRIMARY KEY. */
68
+ $primaryKey(): PgField<S, Flags>;
69
+ /** Foreign key to `table(id)` with optional `ON DELETE`/`ON UPDATE` actions. */
70
+ $references(table: string, opts?: {
71
+ onDelete?: string;
72
+ onUpdate?: string;
73
+ }): PgField<S, Flags>;
74
+ /** `COMMENT ON COLUMN`. */
75
+ $comment(text: string): PgField<S, Flags>;
76
+ /**
77
+ * ESCAPE HATCH (chainable form) — teach the driver how to STORE this field's value in Postgres:
78
+ * give the **wire type** as an `s.*`/Zod field (its pg column type is taken from it) plus a codec
79
+ * (`encode`: app -> wire, `decode`: wire -> app). This turns an otherwise-unmappable App value
80
+ * (e.g. `s.instanceof(Money)`) into a real pg column. Omit the codec for an identity mapping (the
81
+ * app value is stored as-is). Mirrors SurrealDB's `.$surreal(wire, codec)`; the standalone
82
+ * {@link s.$postgres} factory is the from-scratch equivalent. `$`-prefixed to avoid clashing with Zod.
83
+ */
84
+ $postgres<WF extends AnyField | z.ZodType, A = z.output<S>>(wire: WF, codec?: {
85
+ encode: (app: A) => z.output<SchemaOf<WF>>;
86
+ decode: (wire: z.output<SchemaOf<WF>>) => A;
87
+ }): PgField<z.ZodCodec<SchemaOf<WF>, S>, Flags>;
88
+ }
89
+ /** The Postgres authoring namespace. Zod drop-ins (string/number/…) + native pg types + `$postgres`. */
90
+ declare const s: {
91
+ string: () => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
92
+ number: () => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
93
+ text: () => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
94
+ varchar: (n?: number) => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
95
+ char: (n?: number) => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
96
+ citext: () => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
97
+ smallint: () => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
98
+ integer: () => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
99
+ int: () => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
100
+ bigint: () => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
101
+ serial: () => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
102
+ bigserial: () => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
103
+ numeric: (precision?: number, scale?: number) => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
104
+ decimal: (precision?: number, scale?: number) => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
105
+ real: () => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
106
+ doublePrecision: () => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
107
+ float: () => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
108
+ money: () => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
109
+ boolean: () => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
110
+ bool: () => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
111
+ timestamptz: () => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
112
+ timestamp: () => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
113
+ date: () => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
114
+ time: () => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
115
+ timetz: () => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
116
+ interval: () => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
117
+ uuid: () => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
118
+ bytea: () => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
119
+ inet: () => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
120
+ cidr: () => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
121
+ macaddr: () => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
122
+ jsonb: <T extends z.ZodType = z.ZodUnknown>(shape?: T) => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
123
+ json: <T extends z.ZodType = z.ZodUnknown>(shape?: T) => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
124
+ enum: <const T extends readonly [string, ...string[]]>(values: T) => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
125
+ literal: <const V extends string | number | boolean>(value: V) => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
126
+ object: (shape: Record<string, AnyField | z.ZodType>) => PgField<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, never>;
127
+ array: (elem: AnyField | z.ZodType) => PgField;
128
+ references: (table: string, opts?: {
129
+ onDelete?: string;
130
+ onUpdate?: string;
131
+ }) => PgField;
132
+ /**
133
+ * ESCAPE HATCH — a pg type with no portable meaning, stored via a Zod codec (encode/decode). The
134
+ * column is emitted as `pgType`; App-side reads/writes go through `codec`. Mirrors surreal `$surreal`.
135
+ */
136
+ $postgres: <C extends z.ZodType>(pgType: string, codec: C) => PgField<C>;
137
+ };
138
+ /** Table-level pg config: composite PK, table CHECKs, and secondary indexes. */
139
+ interface PgTableConfig {
140
+ primaryKey?: string[];
141
+ checks?: string[];
142
+ indexes?: {
143
+ name?: string;
144
+ cols: string[];
145
+ unique?: boolean;
146
+ }[];
147
+ }
148
+ /**
149
+ * A Postgres table definition — the `Authored` object the driver's `lower` reads. Structurally a
150
+ * `{ name }` (the neutral `Authored` bound); also carries its `fields` (a `{ col: PgField }` map) and
151
+ * table-level config. Chainable: `.primaryKey(...)`, `.check(expr)`, `.index([...])`.
152
+ */
153
+ declare class PgTableDef<Name extends string = string, F extends Record<string, PgField> = Record<string, PgField>> {
154
+ readonly name: Name;
155
+ readonly fields: F;
156
+ readonly config: PgTableConfig;
157
+ constructor(name: Name, fields: F, config?: PgTableConfig);
158
+ /** Composite / custom PRIMARY KEY (overrides the implicit `id`). */
159
+ primaryKey(...cols: (keyof F & string)[]): PgTableDef<Name, F>;
160
+ /** A table-level `CHECK (<expr>)`. */
161
+ check(expr: string): PgTableDef<Name, F>;
162
+ /** A secondary index over `cols` (optionally `UNIQUE`). */
163
+ index(cols: (keyof F & string)[], opts?: {
164
+ name?: string;
165
+ unique?: boolean;
166
+ }): PgTableDef<Name, F>;
167
+ /**
168
+ * A foreign-key field referencing THIS table (for use in another table's shape):
169
+ * `author: user.record({ onDelete: "cascade" })`. Also satisfies the CLI's structural table check.
170
+ */
171
+ record(opts?: {
172
+ onDelete?: string;
173
+ onUpdate?: string;
174
+ }): PgField;
175
+ }
176
+ /** Declare a Postgres table: `export const user = defineTable("user", { name: s.text(), age: s.integer().optional() })`. */
177
+ declare function defineTable<Name extends string, F extends Record<string, PgField>>(name: Name, fields: F, config?: PgTableConfig): PgTableDef<Name, F>;
178
+ /** The decoded (App-land) row type of a table — `z.output` of each field's schema. */
179
+ type App<T extends PgTableDef> = {
180
+ [K in keyof T["fields"]]: z.output<T["fields"][K]["schema"]>;
181
+ };
182
+ /** The encoded (wire) row type of a table — `z.input` of each field's schema. */
183
+ type Wire<T extends PgTableDef> = {
184
+ [K in keyof T["fields"]]: z.input<T["fields"][K]["schema"]>;
185
+ };
186
+
187
+ interface PgConn {
188
+ query<T = Record<string, unknown>>(sql: string, params?: unknown[]): Promise<{
189
+ rows: T[];
190
+ }>;
191
+ exec(sql: string): Promise<unknown>;
192
+ close(): Promise<void>;
193
+ }
194
+ /** A bound Postgres query: text with positional `$1..$n` placeholders + the values bound to them. */
195
+ interface BoundPgQuery {
196
+ query: string;
197
+ params: unknown[];
198
+ }
199
+ /** A raw SQL fragment spliced VERBATIM into a `pgSql` template (NOT parameterized — caller-trusted). */
200
+ interface PgFragment {
201
+ readonly __pgRaw: string;
202
+ }
203
+ /** Splice a raw SQL string verbatim (NOT parameterized — only for caller-trusted SQL). */
204
+ declare function raw(sql: string): PgFragment;
205
+ /** A safely double-quoted identifier (table/column) to splice into a `pgSql` template. */
206
+ declare function identifier(name: string): PgFragment;
207
+ /**
208
+ * Tagged-template SQL builder — the Postgres analogue of SurrealDB's `surql`. Interpolated values
209
+ * become positional bind params (`$1..$n`), so values are never string-interpolated (injection-safe).
210
+ * Wrap a value in {@link raw} / {@link identifier} to splice SQL STRUCTURE instead of a param, and a
211
+ * nested `pgSql` composes (its placeholders renumber, its params merge). Returns a {@link BoundPgQuery}
212
+ * — it does NOT execute; pass it to `postgresDriver.query` / `conn.query`, or nest it in another `pgSql`.
213
+ *
214
+ * pgSql`SELECT * FROM ${identifier("user")} WHERE id = ${id}`
215
+ * // -> { query: 'SELECT * FROM "user" WHERE id = $1', params: [id] }
216
+ */
217
+ declare function pgSql(strings: TemplateStringsArray, ...values: unknown[]): BoundPgQuery;
218
+ /** Postgres connection params, on top of the dialect-neutral base ({schema, key?, migrations?}). */
219
+ interface PostgresConnectionConfig extends ConnectionConfigBase {
220
+ /**
221
+ * Where to connect. `file:<dir>` (or a bare path) -> embedded PGlite data dir; empty/omitted ->
222
+ * in-memory PGlite. A `postgres://` URL is reserved for a future node-postgres client.
223
+ */
224
+ url?: string;
225
+ }
226
+ /**
227
+ * Typed `postgresConnection(...)` factory — the only thing a config's `connections` map accepts for
228
+ * this driver. Wraps {@link connectionEntry} with the Postgres connection shape. Pass a static config,
229
+ * a resolver yielding one config, or a resolver yielding a keyed COLLECTION (each entry needs `key`).
230
+ */
231
+ declare function postgresConnection(config: PostgresConnectionConfig): ConnectionEntry;
232
+ declare function postgresConnection(resolver: (ctx: ResolveContext) => PostgresConnectionConfig | Promise<PostgresConnectionConfig>): ConnectionEntry;
233
+ declare function postgresConnection(resolver: (ctx: ResolveContext) => (PostgresConnectionConfig & {
234
+ key: string;
235
+ })[] | Promise<(PostgresConnectionConfig & {
236
+ key: string;
237
+ })[]>): ConnectionEntry;
238
+ declare const postgresDriver: Driver<PgConn>;
239
+
240
+ export { type App, type BoundPgQuery, type PgConn, PgField, type PgMeta, type PgTableConfig, PgTableDef, type PgTypeRef, type PostgresConnectionConfig, type SqlExpr, type Wire, defineTable, identifier, pgSql, postgresConnection, postgresDriver, raw, s, sqlExpr };