pg-codegen 5.13.1 → 5.14.1
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 +138 -59
- package/emit/client.js +7 -7
- package/emit/record.js +3 -3
- package/emit/templates/client.d.ts +29 -4
- package/emit/templates/client.js +32 -7
- package/emit/templates/client.ts +56 -9
- package/esm/emit/client.js +8 -8
- package/esm/emit/record.js +4 -4
- package/esm/emit/templates/client.js +32 -7
- package/esm/emit/templates/client.ts +56 -9
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -12,9 +12,113 @@
|
|
|
12
12
|
<a href="https://www.npmjs.com/package/pg-codegen"><img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/constructive?filename=postgres%2Fpg-codegen%2Fpackage.json"/></a>
|
|
13
13
|
</p>
|
|
14
14
|
|
|
15
|
-
|
|
15
|
+
A Prisma-like, fully typed database client generated from your live PostgreSQL schema — plus the types, decoders and serializers it is built on.
|
|
16
16
|
|
|
17
|
-
>
|
|
17
|
+
> No hand-written row mappers, no `row.created_at as string`, no column lists at the call site. Point it at a database and query.
|
|
18
|
+
|
|
19
|
+
## 🚀 Quick start
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
npm install pg-codegen
|
|
23
|
+
pg-codegen --schema app_public --out src/generated
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
import { Pool } from 'pg';
|
|
28
|
+
import { createAppPublicDb } from './generated/app_public/db';
|
|
29
|
+
|
|
30
|
+
const db = createAppPublicDb(new Pool());
|
|
31
|
+
|
|
32
|
+
// full row, decoded and camelCase — no select needed
|
|
33
|
+
const user = await db.users.findFirst({ where: { email: 'nadia@example.com' } });
|
|
34
|
+
|
|
35
|
+
// narrow it inline; the result type follows
|
|
36
|
+
const names = await db.users.findMany({
|
|
37
|
+
where: { isActive: true, createdAt: { greaterThan: since } },
|
|
38
|
+
select: { id: true, username: true },
|
|
39
|
+
orderBy: { createdAt: 'DESC' },
|
|
40
|
+
limit: 20
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
const created = await db.users.create({ data: { username: 'nadia', email: 'nadia@example.com' } });
|
|
44
|
+
await db.users.updateOrThrow({ where: { id: created.id }, data: { isActive: false } });
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Connection settings come from the standard PG environment (`PGHOST`, `PGPORT`, `PGUSER`, `PGPASSWORD`, `PGDATABASE`) via `pg-env`.
|
|
48
|
+
|
|
49
|
+
## 🧭 The client
|
|
50
|
+
|
|
51
|
+
One `create<Schema>Db(db, options?)` factory per schema, one client per table:
|
|
52
|
+
|
|
53
|
+
| Method | Returns |
|
|
54
|
+
|---|---|
|
|
55
|
+
| `findMany(args?)` | `SelectResult[]` |
|
|
56
|
+
| `findFirst(args?)` | `SelectResult \| null` |
|
|
57
|
+
| `findFirstOrThrow(args?)` | `SelectResult`, else `RowNotFoundError` |
|
|
58
|
+
| `count(where?)` | `number` |
|
|
59
|
+
| `create({ data, select? })` | the inserted row |
|
|
60
|
+
| `update({ where, data, select? })` | the updated rows |
|
|
61
|
+
| `updateOrThrow({ where, data, select? })` | one updated row, else `RowNotFoundError` |
|
|
62
|
+
| `delete({ where, select? })` | the deleted rows |
|
|
63
|
+
| `$with(db)` | the same clients bound to another connection |
|
|
64
|
+
|
|
65
|
+
`where` / `select` / `orderBy` are keyed by camelCase field names and mapped to physical columns for you. `where` speaks the same query-spec grammar as the GraphQL side — `equalTo`, `notEqualTo`, `in`, `notIn`, `lessThan`, `greaterThanOrEqualTo`, `like`, `likeInsensitive`, `startsWith`, `includes`, `isNull`, … — and a bare value means `equalTo` (`null` means `isNull`):
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
await db.posts.findMany({ where: { authorId, status: { in: ['draft', 'review'] }, publishedAt: null } });
|
|
69
|
+
await db.posts.findMany({ where: { or: [{ authorId }, { editorId: authorId }], not: { status: 'archived' } } });
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
`and` / `or` / `not` nest the same shape.
|
|
73
|
+
|
|
74
|
+
`update` and `delete` **require** a `where`: an empty filter throws rather than rewriting the table. Reads accept one and read the table unfiltered.
|
|
75
|
+
|
|
76
|
+
Writes are encoded from the generated column metadata (json/jsonb columns stringified, `Date` → ISO), and every returned row comes back through the generated per-column decoders, so a value that does not match its column's type raises `CoerceError` instead of flowing on as a lie.
|
|
77
|
+
|
|
78
|
+
### Selections type the result
|
|
79
|
+
|
|
80
|
+
`select` is the only projection, stated either way round, and the return type follows it with nothing to annotate:
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
await db.emailIdentities.findFirst({ where: { id } });
|
|
84
|
+
// EmailIdentities | null — every column
|
|
85
|
+
|
|
86
|
+
await db.emailIdentities.findFirst({ select: { id: true, slug: true } });
|
|
87
|
+
// Pick<EmailIdentities, 'id' | 'slug'> | null
|
|
88
|
+
|
|
89
|
+
await db.emailIdentities.findFirst({ select: { databaseId: false } });
|
|
90
|
+
// Omit<EmailIdentities, 'databaseId'> | null
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Excluding is what a caller reaches for when a field must not be carried — a secret's id, row bookkeeping — or when this binding's table genuinely lacks it: an excluded field is absent from the type, so reading it does not compile. Naming any field `true` is a projection and wins outright; the excluded ones are simply not in it.
|
|
94
|
+
|
|
95
|
+
### Transactions
|
|
96
|
+
|
|
97
|
+
`$with` rebinds every table client to another connection, so a transaction is the same code against a different handle:
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
const client = await pool.connect();
|
|
101
|
+
try {
|
|
102
|
+
await client.query('BEGIN');
|
|
103
|
+
const tx = db.$with(client);
|
|
104
|
+
const run = await tx.agentRuns.create({ data: { threadId, status: 'running' } });
|
|
105
|
+
await tx.agentEvents.create({ data: { runId: run.id, seq: 1 } });
|
|
106
|
+
await client.query('COMMIT');
|
|
107
|
+
} finally {
|
|
108
|
+
client.release();
|
|
109
|
+
}
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### Tables provisioned under a different name
|
|
113
|
+
|
|
114
|
+
The schema and physical table names are runtime arguments, so one generated client serves a per-tenant or per-scope deployment of the same tables:
|
|
115
|
+
|
|
116
|
+
```ts
|
|
117
|
+
const routing = createRoutingPublicDb(pool, {
|
|
118
|
+
schema: tenant.schema,
|
|
119
|
+
tables: { emailIdentities: 'platform_email_identities' }
|
|
120
|
+
});
|
|
121
|
+
```
|
|
18
122
|
|
|
19
123
|
## ✨ What it generates
|
|
20
124
|
|
|
@@ -24,25 +128,47 @@ For every table, view, materialized view and partitioned table in the schemas yo
|
|
|
24
128
|
|---|---|
|
|
25
129
|
| `AgentRuns` | application shape, camelCase |
|
|
26
130
|
| `AgentRunsRow` | database row shape, snake_case |
|
|
27
|
-
| `
|
|
28
|
-
| `
|
|
131
|
+
| `agentRunsTable` | `schema`, `name`, `qualifiedName`, `columns`, `primaryKey`, `columnByField` |
|
|
132
|
+
| `agentRunsFields` | one decoder per column, for projections |
|
|
29
133
|
| `decodeAgentRuns` | decode an untrusted camelCase envelope (a wire payload, a parsed body) |
|
|
30
134
|
| `decodeAgentRunsRow` | decode an untrusted database row |
|
|
31
135
|
| `agentRunsFromRow` | row → application shape |
|
|
32
136
|
| `decodeAgentRunsFromRow` | both, composed |
|
|
33
137
|
| `serializeAgentRuns` | `Partial<AgentRuns>` → `Partial<AgentRunsRow>` for INSERT/UPDATE |
|
|
34
138
|
|
|
35
|
-
Plus an `enums.ts`
|
|
139
|
+
Plus, per schema, a `db.ts` (the client above), an `enums.ts` — a literal union, a `readonly` value list and `as*`/`require*` checkers for every PostgreSQL enum a column references — and barrels; and one shared `client.ts` runtime at the root.
|
|
36
140
|
|
|
37
141
|
Every decoder is backed by [`@constructive-io/coerce`](../../packages/coerce): a NOT NULL column throws `CoerceError` naming the offending column, a nullable column answers `null`, and the text forms `pg` returns for `int8`/`numeric` are parsed rather than passed through as strings. Nothing is silently coerced across types, so a malformed row cannot become a default value.
|
|
38
142
|
|
|
39
|
-
##
|
|
143
|
+
## 🔧 Below the client
|
|
40
144
|
|
|
41
|
-
|
|
42
|
-
|
|
145
|
+
The client covers single-table reads and writes. For a join, a function call, or SQL the builder does not model, keep the query and decode its columns — `agentRunsFields` takes an overridable label so the error names the alias the query actually used:
|
|
146
|
+
|
|
147
|
+
```ts
|
|
148
|
+
import { agentRunsFields } from '@my/db-types/codegen_test/agent-runs';
|
|
149
|
+
import { threadsFields } from '@my/db-types/codegen_test/threads';
|
|
150
|
+
|
|
151
|
+
const { rows } = await db.query(`
|
|
152
|
+
SELECT r.id, r.status, t.title AS thread_title
|
|
153
|
+
FROM agent_runs r JOIN threads t ON t.id = r.thread_id
|
|
154
|
+
`);
|
|
155
|
+
|
|
156
|
+
const summaries = rows.map(row => ({
|
|
157
|
+
id: agentRunsFields.id(row.id),
|
|
158
|
+
status: agentRunsFields.status(row.status),
|
|
159
|
+
threadTitle: threadsFields.title(row.thread_title, 'run_summary.thread_title')
|
|
160
|
+
}));
|
|
43
161
|
```
|
|
44
162
|
|
|
45
|
-
|
|
163
|
+
A whole row from a `SELECT *`-shaped query decodes in one call, and each table is its own module so a bundle carries only what it touches:
|
|
164
|
+
|
|
165
|
+
```ts
|
|
166
|
+
import { decodeAgentRunsFromRow } from '@my/db-types/codegen_test/agent-runs';
|
|
167
|
+
|
|
168
|
+
const run = decodeAgentRunsFromRow(rows[0]); // AgentRuns, or CoerceError naming the column
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
## 📟 CLI
|
|
46
172
|
|
|
47
173
|
```bash
|
|
48
174
|
pg-codegen --schema app_public --out src/generated
|
|
@@ -52,9 +178,9 @@ pg-codegen --schema app_public --out src/generated --check
|
|
|
52
178
|
|
|
53
179
|
`--check` re-introspects and compares against the committed output, exiting non-zero on drift — run it in CI so generated types cannot go stale against a migration.
|
|
54
180
|
|
|
55
|
-
|
|
181
|
+
## 🧩 Programmatic use
|
|
56
182
|
|
|
57
|
-
|
|
183
|
+
For a schema whose physical name is per-tenant, say, where you want to rewrite it to a stable alias before emitting:
|
|
58
184
|
|
|
59
185
|
```ts
|
|
60
186
|
import { Client } from 'pg';
|
|
@@ -70,53 +196,6 @@ for (const schema of ir.schemas) {
|
|
|
70
196
|
await writeFileTree(outDir, emitFileTree(ir));
|
|
71
197
|
```
|
|
72
198
|
|
|
73
|
-
## 📟 Example output
|
|
74
|
-
|
|
75
|
-
```ts
|
|
76
|
-
// generated/codegen_test/agent-runs.ts
|
|
77
|
-
export interface AgentRuns {
|
|
78
|
-
id: string;
|
|
79
|
-
threadId: string;
|
|
80
|
-
status: RunStatus;
|
|
81
|
-
tags: string[];
|
|
82
|
-
retrySeconds: number[] | null;
|
|
83
|
-
lastEventSeq: number;
|
|
84
|
-
finishedAt: string | null;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
export const decodeAgentRunsFromRow = (value: unknown, label = 'codegen_test.agent_runs'): AgentRuns =>
|
|
88
|
-
agentRunsFromRow(decodeAgentRunsRow(value, label));
|
|
89
|
-
```
|
|
90
|
-
|
|
91
|
-
Consume per table, so a bundle carries only the tables it touches:
|
|
92
|
-
|
|
93
|
-
```ts
|
|
94
|
-
import { decodeAgentRunsFromRow } from '@my/db-types/codegen_test/agent-runs';
|
|
95
|
-
|
|
96
|
-
const { rows } = await db.query('SELECT * FROM agent_runs WHERE id = $1', [id]);
|
|
97
|
-
const run = decodeAgentRunsFromRow(rows[0]); // AgentRuns, or CoerceError naming the column
|
|
98
|
-
```
|
|
99
|
-
|
|
100
|
-
### Projections
|
|
101
|
-
|
|
102
|
-
A joined or partial SELECT is not a whole row, so a record decoder would reject it. Decode it column by column instead — `FIELDS` takes an overridable label so the error names the alias the query actually used:
|
|
103
|
-
|
|
104
|
-
```ts
|
|
105
|
-
import { AGENT_RUNS_FIELDS } from '@my/db-types/codegen_test/agent-runs';
|
|
106
|
-
import { THREADS_FIELDS } from '@my/db-types/codegen_test/threads';
|
|
107
|
-
|
|
108
|
-
const { rows } = await db.query(`
|
|
109
|
-
SELECT r.id, r.status, t.title AS thread_title
|
|
110
|
-
FROM agent_runs r JOIN threads t ON t.id = r.thread_id
|
|
111
|
-
`);
|
|
112
|
-
|
|
113
|
-
const summaries = rows.map(row => ({
|
|
114
|
-
id: AGENT_RUNS_FIELDS.id(row.id),
|
|
115
|
-
status: AGENT_RUNS_FIELDS.status(row.status),
|
|
116
|
-
threadTitle: THREADS_FIELDS.title(row.thread_title, 'run_summary.thread_title')
|
|
117
|
-
}));
|
|
118
|
-
```
|
|
119
|
-
|
|
120
199
|
## 🧱 How it works
|
|
121
200
|
|
|
122
201
|
```
|
|
@@ -125,7 +204,7 @@ PostgreSQL → introspectron → IR (ir.ts) → emitters (emit/*) → file tree
|
|
|
125
204
|
|
|
126
205
|
`buildIr` normalizes an introspection result into the shape every emitter consumes: columns with a resolved scalar, nullability, defaults, primary keys, and the enums they reference. Domains are unwrapped to their base type, arrays carry their element scalar, and a type with no mapping degrades to `unknown` rather than to `any` — the generator never claims to know a shape it does not.
|
|
127
206
|
|
|
128
|
-
Emission is Babel AST rather than string templates, so output is stable enough to snapshot and to diff in `--check`.
|
|
207
|
+
Emission is Babel AST rather than string templates, so output is stable enough to snapshot and to diff in `--check`. The client runtime is the one exception: `emit/templates/client.ts` is real, typechecked, tested source that is copied into the output, so the runtime every generated client shares is not assembled from AST.
|
|
129
208
|
|
|
130
209
|
---
|
|
131
210
|
|
package/emit/client.js
CHANGED
|
@@ -74,10 +74,10 @@ const emitSchemaDbModule = (schema) => {
|
|
|
74
74
|
];
|
|
75
75
|
for (const table of schema.tables) {
|
|
76
76
|
const appType = (0, inflekt_1.toPascalCase)(table.name);
|
|
77
|
-
const
|
|
77
|
+
const model = (0, inflekt_1.toCamelCase)(table.name);
|
|
78
78
|
const file = `./${(0, barrel_1.tableFileName)(table.name)}`;
|
|
79
79
|
statements.push(typeImport([appType], file));
|
|
80
|
-
statements.push((0, babel_1.namedImport)([`${
|
|
80
|
+
statements.push((0, babel_1.namedImport)([`${model}Fields`, `${model}Table`], file));
|
|
81
81
|
}
|
|
82
82
|
const tableNameProps = schema.tables.map(table => {
|
|
83
83
|
const prop = babel_1.t.tsPropertySignature(babel_1.t.identifier(modelKey(table)), babel_1.t.tsTypeAnnotation(babel_1.t.tsStringKeyword()));
|
|
@@ -97,12 +97,12 @@ const emitSchemaDbModule = (schema) => {
|
|
|
97
97
|
dbMembers.push(withMember);
|
|
98
98
|
statements.push(babel_1.t.exportNamedDeclaration(babel_1.t.tsInterfaceDeclaration(babel_1.t.identifier(dbTypeName), null, null, babel_1.t.tsInterfaceBody(dbMembers))));
|
|
99
99
|
const clientProperties = schema.tables.map(table => {
|
|
100
|
-
const
|
|
100
|
+
const model = (0, inflekt_1.toCamelCase)(table.name);
|
|
101
101
|
const spec = babel_1.t.objectExpression([
|
|
102
|
-
babel_1.t.objectProperty(babel_1.t.identifier('schema'), babel_1.t.logicalExpression('??', babel_1.t.optionalMemberExpression(babel_1.t.identifier('options'), babel_1.t.identifier('schema'), false, true), babel_1.t.memberExpression(babel_1.t.identifier(`${
|
|
103
|
-
babel_1.t.objectProperty(babel_1.t.identifier('table'), babel_1.t.logicalExpression('??', babel_1.t.optionalMemberExpression(babel_1.t.optionalMemberExpression(babel_1.t.identifier('options'), babel_1.t.identifier('tables'), false, true), babel_1.t.identifier(modelKey(table)), false, true), babel_1.t.memberExpression(babel_1.t.identifier(`${
|
|
104
|
-
babel_1.t.objectProperty(babel_1.t.identifier('columnByField'), babel_1.t.memberExpression(babel_1.t.identifier(`${
|
|
105
|
-
babel_1.t.objectProperty(babel_1.t.identifier('fields'), babel_1.t.identifier(`${
|
|
102
|
+
babel_1.t.objectProperty(babel_1.t.identifier('schema'), babel_1.t.logicalExpression('??', babel_1.t.optionalMemberExpression(babel_1.t.identifier('options'), babel_1.t.identifier('schema'), false, true), babel_1.t.memberExpression(babel_1.t.identifier(`${model}Table`), babel_1.t.identifier('schema')))),
|
|
103
|
+
babel_1.t.objectProperty(babel_1.t.identifier('table'), babel_1.t.logicalExpression('??', babel_1.t.optionalMemberExpression(babel_1.t.optionalMemberExpression(babel_1.t.identifier('options'), babel_1.t.identifier('tables'), false, true), babel_1.t.identifier(modelKey(table)), false, true), babel_1.t.memberExpression(babel_1.t.identifier(`${model}Table`), babel_1.t.identifier('name')))),
|
|
104
|
+
babel_1.t.objectProperty(babel_1.t.identifier('columnByField'), babel_1.t.memberExpression(babel_1.t.identifier(`${model}Table`), babel_1.t.identifier('columnByField'))),
|
|
105
|
+
babel_1.t.objectProperty(babel_1.t.identifier('fields'), babel_1.t.identifier(`${model}Fields`))
|
|
106
106
|
]);
|
|
107
107
|
const jsonFields = table.columns.filter(column => column.scalar === 'json');
|
|
108
108
|
if (jsonFields.length > 0) {
|
package/emit/record.js
CHANGED
|
@@ -118,7 +118,7 @@ const decodeExpression = (column, value, label, usage) => {
|
|
|
118
118
|
: babel_1.t.callExpression(babel_1.t.identifier(fnName), [value, label]);
|
|
119
119
|
};
|
|
120
120
|
/**
|
|
121
|
-
* `<
|
|
121
|
+
* `<table>Fields`: one decoder per column, for rows that are NOT a whole
|
|
122
122
|
* table row — a joined projection, an aliased column, a partial SELECT — where
|
|
123
123
|
* a record decoder would reject the absent columns.
|
|
124
124
|
*
|
|
@@ -164,8 +164,8 @@ const emitRecordModule = (table) => {
|
|
|
164
164
|
const usage = { coerceImports: new Set(), enumImports: new Set() };
|
|
165
165
|
const pascal = (0, inflekt_1.toPascalCase)(table.name);
|
|
166
166
|
const rowTypeName = `${pascal}Row`;
|
|
167
|
-
const metadataName = `${(0, inflekt_1.
|
|
168
|
-
const fieldsName = `${(0, inflekt_1.
|
|
167
|
+
const metadataName = `${(0, inflekt_1.toCamelCase)(table.name)}Table`;
|
|
168
|
+
const fieldsName = `${(0, inflekt_1.toCamelCase)(table.name)}Fields`;
|
|
169
169
|
const qualified = `${table.schema}.${table.name}`;
|
|
170
170
|
const statements = [];
|
|
171
171
|
// Application (camelCase) interface.
|
|
@@ -5,7 +5,7 @@ export interface Queryable {
|
|
|
5
5
|
rowCount?: number | null;
|
|
6
6
|
}>;
|
|
7
7
|
}
|
|
8
|
-
/** One generated decoder per field, as emitted in the `<
|
|
8
|
+
/** One generated decoder per field, as emitted in the `<table>Fields` constant. */
|
|
9
9
|
export type FieldDecoders<App> = {
|
|
10
10
|
[K in keyof App]: (value: unknown, label?: string) => App[K];
|
|
11
11
|
};
|
|
@@ -18,15 +18,32 @@ export interface TableSpec<App> {
|
|
|
18
18
|
/** camelCase fields backed by json/jsonb columns, serialized on writes. */
|
|
19
19
|
jsonFields?: readonly string[];
|
|
20
20
|
}
|
|
21
|
-
/**
|
|
21
|
+
/**
|
|
22
|
+
* Select shape — same as the GraphQL ORM, stated either way round:
|
|
23
|
+
*
|
|
24
|
+
* - `{ id: true, name: true }` reads those fields and nothing else;
|
|
25
|
+
* - `{ databaseId: false }` reads every field except that one, for the field a
|
|
26
|
+
* record has in general but this binding's table does not (a scope's copy of
|
|
27
|
+
* a table without the scope key column) or that a caller must not carry (a
|
|
28
|
+
* secret's id, row bookkeeping).
|
|
29
|
+
*
|
|
30
|
+
* Naming a field `true` is a projection and wins outright: the excluded ones
|
|
31
|
+
* are simply not in it.
|
|
32
|
+
*/
|
|
22
33
|
export type SelectShape<App> = {
|
|
23
34
|
[K in keyof App]?: boolean;
|
|
24
35
|
};
|
|
25
36
|
type TrueKeys<App, S> = {
|
|
26
37
|
[K in keyof S]-?: S[K] extends true ? K & keyof App : never;
|
|
27
38
|
}[keyof S];
|
|
28
|
-
|
|
29
|
-
|
|
39
|
+
type FalseKeys<App, S> = {
|
|
40
|
+
[K in keyof S]-?: S[K] extends false ? K & keyof App : never;
|
|
41
|
+
}[keyof S];
|
|
42
|
+
/**
|
|
43
|
+
* Rows narrow to what the select states: the picked fields, else the record
|
|
44
|
+
* minus the excluded ones. No `select` returns the full record.
|
|
45
|
+
*/
|
|
46
|
+
export type SelectResult<App, S extends SelectShape<App> | undefined> = S extends SelectShape<App> ? [TrueKeys<App, S>] extends [never] ? [FalseKeys<App, S>] extends [never] ? App : Omit<App, FalseKeys<App, S>> : Pick<App, TrueKeys<App, S>> : App;
|
|
30
47
|
/** Per-field operators from the shared query-spec grammar. */
|
|
31
48
|
export interface FieldOps<V> {
|
|
32
49
|
equalTo?: V;
|
|
@@ -127,6 +144,14 @@ export declare class TableClient<App> {
|
|
|
127
144
|
private column;
|
|
128
145
|
private selectedFields;
|
|
129
146
|
private decodeRow;
|
|
147
|
+
/**
|
|
148
|
+
* The predicate to apply, or nothing to apply: a caller that spreads a
|
|
149
|
+
* conditional key column (a scope that records none) states an empty filter,
|
|
150
|
+
* and an unqualified read is what it asked for.
|
|
151
|
+
*/
|
|
152
|
+
private predicate;
|
|
153
|
+
/** A write says which rows: an empty filter would mean the whole table. */
|
|
154
|
+
private required;
|
|
130
155
|
private filter;
|
|
131
156
|
private fieldFilter;
|
|
132
157
|
private applyOrderBy;
|
package/emit/templates/client.js
CHANGED
|
@@ -55,8 +55,9 @@ class TableClient {
|
|
|
55
55
|
async findMany(args = {}) {
|
|
56
56
|
const fields = this.selectedFields(args.select);
|
|
57
57
|
const query = this.baseQuery().select(fields.map(field => this.column(field)));
|
|
58
|
-
|
|
59
|
-
|
|
58
|
+
const predicate = this.predicate(args.where);
|
|
59
|
+
if (predicate)
|
|
60
|
+
query.where(predicate);
|
|
60
61
|
this.applyOrderBy(query, args.orderBy);
|
|
61
62
|
if (args.limit !== undefined)
|
|
62
63
|
query.limit(args.limit);
|
|
@@ -78,8 +79,9 @@ class TableClient {
|
|
|
78
79
|
}
|
|
79
80
|
async count(where) {
|
|
80
81
|
const query = this.baseQuery().select([]).selectExpr('count', (0, query_builder_1.fn)('count', [(0, query_builder_1.lit)(1)]));
|
|
81
|
-
|
|
82
|
-
|
|
82
|
+
const predicate = this.predicate(where);
|
|
83
|
+
if (predicate)
|
|
84
|
+
query.where(predicate);
|
|
83
85
|
const { text, values } = query.build();
|
|
84
86
|
const { rows } = await this.db.query(text, values);
|
|
85
87
|
const row = rows[0];
|
|
@@ -98,7 +100,7 @@ class TableClient {
|
|
|
98
100
|
const fields = this.selectedFields(args.select);
|
|
99
101
|
const query = this.baseQuery()
|
|
100
102
|
.update(this.encodeData(args.data))
|
|
101
|
-
.where(this.
|
|
103
|
+
.where(this.required(args.where, 'update'))
|
|
102
104
|
.returning(fields.map(field => this.column(field)));
|
|
103
105
|
const { text, values } = query.build();
|
|
104
106
|
const { rows } = await this.db.query(text, values);
|
|
@@ -114,7 +116,7 @@ class TableClient {
|
|
|
114
116
|
const fields = this.selectedFields(args.select);
|
|
115
117
|
const query = this.baseQuery()
|
|
116
118
|
.delete()
|
|
117
|
-
.where(this.
|
|
119
|
+
.where(this.required(args.where, 'delete'))
|
|
118
120
|
.returning(fields.map(field => this.column(field)));
|
|
119
121
|
const { text, values } = query.build();
|
|
120
122
|
const { rows } = await this.db.query(text, values);
|
|
@@ -135,7 +137,11 @@ class TableClient {
|
|
|
135
137
|
if (!select)
|
|
136
138
|
return all;
|
|
137
139
|
const picked = all.filter(field => select[field] === true);
|
|
138
|
-
|
|
140
|
+
if (picked.length > 0)
|
|
141
|
+
return picked;
|
|
142
|
+
// Nothing picked: the select either excludes fields or says nothing at all,
|
|
143
|
+
// and both read what is left.
|
|
144
|
+
return all.filter(field => select[field] !== false);
|
|
139
145
|
}
|
|
140
146
|
decodeRow(row, fields) {
|
|
141
147
|
const raw = row;
|
|
@@ -145,6 +151,25 @@ class TableClient {
|
|
|
145
151
|
}
|
|
146
152
|
return decoded;
|
|
147
153
|
}
|
|
154
|
+
/**
|
|
155
|
+
* The predicate to apply, or nothing to apply: a caller that spreads a
|
|
156
|
+
* conditional key column (a scope that records none) states an empty filter,
|
|
157
|
+
* and an unqualified read is what it asked for.
|
|
158
|
+
*/
|
|
159
|
+
predicate(where) {
|
|
160
|
+
if (!where)
|
|
161
|
+
return undefined;
|
|
162
|
+
const filter = this.filter(where);
|
|
163
|
+
return Object.keys(filter).length > 0 ? filter : undefined;
|
|
164
|
+
}
|
|
165
|
+
/** A write says which rows: an empty filter would mean the whole table. */
|
|
166
|
+
required(where, operation) {
|
|
167
|
+
const predicate = this.predicate(where);
|
|
168
|
+
if (!predicate) {
|
|
169
|
+
throw new Error(`${this.spec.table}.${operation}: refusing an empty where filter, which would match every row`);
|
|
170
|
+
}
|
|
171
|
+
return predicate;
|
|
172
|
+
}
|
|
148
173
|
filter(where) {
|
|
149
174
|
const filter = {};
|
|
150
175
|
for (const [key, value] of Object.entries(where)) {
|
package/emit/templates/client.ts
CHANGED
|
@@ -18,7 +18,7 @@ export interface Queryable {
|
|
|
18
18
|
query(text: string, values?: unknown[]): Promise<{ rows: unknown[]; rowCount?: number | null }>;
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
-
/** One generated decoder per field, as emitted in the `<
|
|
21
|
+
/** One generated decoder per field, as emitted in the `<table>Fields` constant. */
|
|
22
22
|
export type FieldDecoders<App> = {
|
|
23
23
|
[K in keyof App]: (value: unknown, label?: string) => App[K];
|
|
24
24
|
};
|
|
@@ -33,18 +33,38 @@ export interface TableSpec<App> {
|
|
|
33
33
|
jsonFields?: readonly string[];
|
|
34
34
|
}
|
|
35
35
|
|
|
36
|
-
/**
|
|
36
|
+
/**
|
|
37
|
+
* Select shape — same as the GraphQL ORM, stated either way round:
|
|
38
|
+
*
|
|
39
|
+
* - `{ id: true, name: true }` reads those fields and nothing else;
|
|
40
|
+
* - `{ databaseId: false }` reads every field except that one, for the field a
|
|
41
|
+
* record has in general but this binding's table does not (a scope's copy of
|
|
42
|
+
* a table without the scope key column) or that a caller must not carry (a
|
|
43
|
+
* secret's id, row bookkeeping).
|
|
44
|
+
*
|
|
45
|
+
* Naming a field `true` is a projection and wins outright: the excluded ones
|
|
46
|
+
* are simply not in it.
|
|
47
|
+
*/
|
|
37
48
|
export type SelectShape<App> = { [K in keyof App]?: boolean };
|
|
38
49
|
|
|
39
50
|
type TrueKeys<App, S> = {
|
|
40
51
|
[K in keyof S]-?: S[K] extends true ? K & keyof App : never;
|
|
41
52
|
}[keyof S];
|
|
42
53
|
|
|
43
|
-
|
|
54
|
+
type FalseKeys<App, S> = {
|
|
55
|
+
[K in keyof S]-?: S[K] extends false ? K & keyof App : never;
|
|
56
|
+
}[keyof S];
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Rows narrow to what the select states: the picked fields, else the record
|
|
60
|
+
* minus the excluded ones. No `select` returns the full record.
|
|
61
|
+
*/
|
|
44
62
|
export type SelectResult<App, S extends SelectShape<App> | undefined> =
|
|
45
63
|
S extends SelectShape<App>
|
|
46
64
|
? [TrueKeys<App, S>] extends [never]
|
|
47
|
-
? App
|
|
65
|
+
? [FalseKeys<App, S>] extends [never]
|
|
66
|
+
? App
|
|
67
|
+
: Omit<App, FalseKeys<App, S>>
|
|
48
68
|
: Pick<App, TrueKeys<App, S>>
|
|
49
69
|
: App;
|
|
50
70
|
|
|
@@ -182,7 +202,8 @@ export class TableClient<App> {
|
|
|
182
202
|
): Promise<SelectResult<App, S>[]> {
|
|
183
203
|
const fields = this.selectedFields(args.select);
|
|
184
204
|
const query = this.baseQuery().select(fields.map(field => this.column(field)));
|
|
185
|
-
|
|
205
|
+
const predicate = this.predicate(args.where);
|
|
206
|
+
if (predicate) query.where(predicate);
|
|
186
207
|
this.applyOrderBy(query, args.orderBy);
|
|
187
208
|
if (args.limit !== undefined) query.limit(args.limit);
|
|
188
209
|
if (args.offset !== undefined) query.offset(args.offset);
|
|
@@ -208,7 +229,8 @@ export class TableClient<App> {
|
|
|
208
229
|
|
|
209
230
|
async count(where?: Where<App>): Promise<number> {
|
|
210
231
|
const query = this.baseQuery().select([]).selectExpr('count', fn('count', [lit(1)]));
|
|
211
|
-
|
|
232
|
+
const predicate = this.predicate(where);
|
|
233
|
+
if (predicate) query.where(predicate);
|
|
212
234
|
const { text, values } = query.build();
|
|
213
235
|
const { rows } = await this.db.query(text, values);
|
|
214
236
|
const row = rows[0] as { count: string | number };
|
|
@@ -233,7 +255,7 @@ export class TableClient<App> {
|
|
|
233
255
|
const fields = this.selectedFields(args.select);
|
|
234
256
|
const query = this.baseQuery()
|
|
235
257
|
.update(this.encodeData(args.data))
|
|
236
|
-
.where(this.
|
|
258
|
+
.where(this.required(args.where, 'update'))
|
|
237
259
|
.returning(fields.map(field => this.column(field)));
|
|
238
260
|
const { text, values } = query.build();
|
|
239
261
|
const { rows } = await this.db.query(text, values);
|
|
@@ -254,7 +276,7 @@ export class TableClient<App> {
|
|
|
254
276
|
const fields = this.selectedFields(args.select);
|
|
255
277
|
const query = this.baseQuery()
|
|
256
278
|
.delete()
|
|
257
|
-
.where(this.
|
|
279
|
+
.where(this.required(args.where, 'delete'))
|
|
258
280
|
.returning(fields.map(field => this.column(field)));
|
|
259
281
|
const { text, values } = query.build();
|
|
260
282
|
const { rows } = await this.db.query(text, values);
|
|
@@ -278,7 +300,10 @@ export class TableClient<App> {
|
|
|
278
300
|
const all = Object.keys(this.spec.columnByField) as (keyof App & string)[];
|
|
279
301
|
if (!select) return all;
|
|
280
302
|
const picked = all.filter(field => select[field] === true);
|
|
281
|
-
|
|
303
|
+
if (picked.length > 0) return picked;
|
|
304
|
+
// Nothing picked: the select either excludes fields or says nothing at all,
|
|
305
|
+
// and both read what is left.
|
|
306
|
+
return all.filter(field => select[field] !== false);
|
|
282
307
|
}
|
|
283
308
|
|
|
284
309
|
private decodeRow<S extends SelectShape<App> | undefined>(
|
|
@@ -293,6 +318,28 @@ export class TableClient<App> {
|
|
|
293
318
|
return decoded as SelectResult<App, S>;
|
|
294
319
|
}
|
|
295
320
|
|
|
321
|
+
/**
|
|
322
|
+
* The predicate to apply, or nothing to apply: a caller that spreads a
|
|
323
|
+
* conditional key column (a scope that records none) states an empty filter,
|
|
324
|
+
* and an unqualified read is what it asked for.
|
|
325
|
+
*/
|
|
326
|
+
private predicate(where: Where<App> | undefined): Filter | undefined {
|
|
327
|
+
if (!where) return undefined;
|
|
328
|
+
const filter = this.filter(where);
|
|
329
|
+
return Object.keys(filter).length > 0 ? filter : undefined;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/** A write says which rows: an empty filter would mean the whole table. */
|
|
333
|
+
private required(where: Where<App>, operation: string): Filter {
|
|
334
|
+
const predicate = this.predicate(where);
|
|
335
|
+
if (!predicate) {
|
|
336
|
+
throw new Error(
|
|
337
|
+
`${this.spec.table}.${operation}: refusing an empty where filter, which would match every row`
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
return predicate;
|
|
341
|
+
}
|
|
342
|
+
|
|
296
343
|
private filter(where: Where<App>): Filter {
|
|
297
344
|
const filter: Filter = {};
|
|
298
345
|
for (const [key, value] of Object.entries(where)) {
|
package/esm/emit/client.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* TableClient per table over the generated metadata and field decoders.
|
|
5
5
|
*/
|
|
6
6
|
import * as fs from 'fs';
|
|
7
|
-
import { toCamelCase,
|
|
7
|
+
import { toCamelCase, toPascalCase } from 'inflekt';
|
|
8
8
|
import * as path from 'path';
|
|
9
9
|
import { exportConst, generateCode, namedImport, t, withJsDoc } from './babel';
|
|
10
10
|
import { tableFileName } from './barrel';
|
|
@@ -37,10 +37,10 @@ export const emitSchemaDbModule = (schema) => {
|
|
|
37
37
|
];
|
|
38
38
|
for (const table of schema.tables) {
|
|
39
39
|
const appType = toPascalCase(table.name);
|
|
40
|
-
const
|
|
40
|
+
const model = toCamelCase(table.name);
|
|
41
41
|
const file = `./${tableFileName(table.name)}`;
|
|
42
42
|
statements.push(typeImport([appType], file));
|
|
43
|
-
statements.push(namedImport([`${
|
|
43
|
+
statements.push(namedImport([`${model}Fields`, `${model}Table`], file));
|
|
44
44
|
}
|
|
45
45
|
const tableNameProps = schema.tables.map(table => {
|
|
46
46
|
const prop = t.tsPropertySignature(t.identifier(modelKey(table)), t.tsTypeAnnotation(t.tsStringKeyword()));
|
|
@@ -60,12 +60,12 @@ export const emitSchemaDbModule = (schema) => {
|
|
|
60
60
|
dbMembers.push(withMember);
|
|
61
61
|
statements.push(t.exportNamedDeclaration(t.tsInterfaceDeclaration(t.identifier(dbTypeName), null, null, t.tsInterfaceBody(dbMembers))));
|
|
62
62
|
const clientProperties = schema.tables.map(table => {
|
|
63
|
-
const
|
|
63
|
+
const model = toCamelCase(table.name);
|
|
64
64
|
const spec = t.objectExpression([
|
|
65
|
-
t.objectProperty(t.identifier('schema'), t.logicalExpression('??', t.optionalMemberExpression(t.identifier('options'), t.identifier('schema'), false, true), t.memberExpression(t.identifier(`${
|
|
66
|
-
t.objectProperty(t.identifier('table'), t.logicalExpression('??', t.optionalMemberExpression(t.optionalMemberExpression(t.identifier('options'), t.identifier('tables'), false, true), t.identifier(modelKey(table)), false, true), t.memberExpression(t.identifier(`${
|
|
67
|
-
t.objectProperty(t.identifier('columnByField'), t.memberExpression(t.identifier(`${
|
|
68
|
-
t.objectProperty(t.identifier('fields'), t.identifier(`${
|
|
65
|
+
t.objectProperty(t.identifier('schema'), t.logicalExpression('??', t.optionalMemberExpression(t.identifier('options'), t.identifier('schema'), false, true), t.memberExpression(t.identifier(`${model}Table`), t.identifier('schema')))),
|
|
66
|
+
t.objectProperty(t.identifier('table'), t.logicalExpression('??', t.optionalMemberExpression(t.optionalMemberExpression(t.identifier('options'), t.identifier('tables'), false, true), t.identifier(modelKey(table)), false, true), t.memberExpression(t.identifier(`${model}Table`), t.identifier('name')))),
|
|
67
|
+
t.objectProperty(t.identifier('columnByField'), t.memberExpression(t.identifier(`${model}Table`), t.identifier('columnByField'))),
|
|
68
|
+
t.objectProperty(t.identifier('fields'), t.identifier(`${model}Fields`))
|
|
69
69
|
]);
|
|
70
70
|
const jsonFields = table.columns.filter(column => column.scalar === 'json');
|
|
71
71
|
if (jsonFields.length > 0) {
|
package/esm/emit/record.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* snake_case row interface, coerce-backed decoders for both, row/application
|
|
4
4
|
* converters, a serializer for writes, and typed table metadata.
|
|
5
5
|
*/
|
|
6
|
-
import { toCamelCase,
|
|
6
|
+
import { toCamelCase, toPascalCase } from 'inflekt';
|
|
7
7
|
import { asConst, exportConst, generateCode, labelTemplate, namedImport, t, withJsDoc } from './babel';
|
|
8
8
|
import { enumAsName, enumRequireName, enumTypeName } from './enums';
|
|
9
9
|
const COERCERS = {
|
|
@@ -115,7 +115,7 @@ const decodeExpression = (column, value, label, usage) => {
|
|
|
115
115
|
: t.callExpression(t.identifier(fnName), [value, label]);
|
|
116
116
|
};
|
|
117
117
|
/**
|
|
118
|
-
* `<
|
|
118
|
+
* `<table>Fields`: one decoder per column, for rows that are NOT a whole
|
|
119
119
|
* table row — a joined projection, an aliased column, a partial SELECT — where
|
|
120
120
|
* a record decoder would reject the absent columns.
|
|
121
121
|
*
|
|
@@ -161,8 +161,8 @@ export const emitRecordModule = (table) => {
|
|
|
161
161
|
const usage = { coerceImports: new Set(), enumImports: new Set() };
|
|
162
162
|
const pascal = toPascalCase(table.name);
|
|
163
163
|
const rowTypeName = `${pascal}Row`;
|
|
164
|
-
const metadataName = `${
|
|
165
|
-
const fieldsName = `${
|
|
164
|
+
const metadataName = `${toCamelCase(table.name)}Table`;
|
|
165
|
+
const fieldsName = `${toCamelCase(table.name)}Fields`;
|
|
166
166
|
const qualified = `${table.schema}.${table.name}`;
|
|
167
167
|
const statements = [];
|
|
168
168
|
// Application (camelCase) interface.
|
|
@@ -51,8 +51,9 @@ export class TableClient {
|
|
|
51
51
|
async findMany(args = {}) {
|
|
52
52
|
const fields = this.selectedFields(args.select);
|
|
53
53
|
const query = this.baseQuery().select(fields.map(field => this.column(field)));
|
|
54
|
-
|
|
55
|
-
|
|
54
|
+
const predicate = this.predicate(args.where);
|
|
55
|
+
if (predicate)
|
|
56
|
+
query.where(predicate);
|
|
56
57
|
this.applyOrderBy(query, args.orderBy);
|
|
57
58
|
if (args.limit !== undefined)
|
|
58
59
|
query.limit(args.limit);
|
|
@@ -74,8 +75,9 @@ export class TableClient {
|
|
|
74
75
|
}
|
|
75
76
|
async count(where) {
|
|
76
77
|
const query = this.baseQuery().select([]).selectExpr('count', fn('count', [lit(1)]));
|
|
77
|
-
|
|
78
|
-
|
|
78
|
+
const predicate = this.predicate(where);
|
|
79
|
+
if (predicate)
|
|
80
|
+
query.where(predicate);
|
|
79
81
|
const { text, values } = query.build();
|
|
80
82
|
const { rows } = await this.db.query(text, values);
|
|
81
83
|
const row = rows[0];
|
|
@@ -94,7 +96,7 @@ export class TableClient {
|
|
|
94
96
|
const fields = this.selectedFields(args.select);
|
|
95
97
|
const query = this.baseQuery()
|
|
96
98
|
.update(this.encodeData(args.data))
|
|
97
|
-
.where(this.
|
|
99
|
+
.where(this.required(args.where, 'update'))
|
|
98
100
|
.returning(fields.map(field => this.column(field)));
|
|
99
101
|
const { text, values } = query.build();
|
|
100
102
|
const { rows } = await this.db.query(text, values);
|
|
@@ -110,7 +112,7 @@ export class TableClient {
|
|
|
110
112
|
const fields = this.selectedFields(args.select);
|
|
111
113
|
const query = this.baseQuery()
|
|
112
114
|
.delete()
|
|
113
|
-
.where(this.
|
|
115
|
+
.where(this.required(args.where, 'delete'))
|
|
114
116
|
.returning(fields.map(field => this.column(field)));
|
|
115
117
|
const { text, values } = query.build();
|
|
116
118
|
const { rows } = await this.db.query(text, values);
|
|
@@ -131,7 +133,11 @@ export class TableClient {
|
|
|
131
133
|
if (!select)
|
|
132
134
|
return all;
|
|
133
135
|
const picked = all.filter(field => select[field] === true);
|
|
134
|
-
|
|
136
|
+
if (picked.length > 0)
|
|
137
|
+
return picked;
|
|
138
|
+
// Nothing picked: the select either excludes fields or says nothing at all,
|
|
139
|
+
// and both read what is left.
|
|
140
|
+
return all.filter(field => select[field] !== false);
|
|
135
141
|
}
|
|
136
142
|
decodeRow(row, fields) {
|
|
137
143
|
const raw = row;
|
|
@@ -141,6 +147,25 @@ export class TableClient {
|
|
|
141
147
|
}
|
|
142
148
|
return decoded;
|
|
143
149
|
}
|
|
150
|
+
/**
|
|
151
|
+
* The predicate to apply, or nothing to apply: a caller that spreads a
|
|
152
|
+
* conditional key column (a scope that records none) states an empty filter,
|
|
153
|
+
* and an unqualified read is what it asked for.
|
|
154
|
+
*/
|
|
155
|
+
predicate(where) {
|
|
156
|
+
if (!where)
|
|
157
|
+
return undefined;
|
|
158
|
+
const filter = this.filter(where);
|
|
159
|
+
return Object.keys(filter).length > 0 ? filter : undefined;
|
|
160
|
+
}
|
|
161
|
+
/** A write says which rows: an empty filter would mean the whole table. */
|
|
162
|
+
required(where, operation) {
|
|
163
|
+
const predicate = this.predicate(where);
|
|
164
|
+
if (!predicate) {
|
|
165
|
+
throw new Error(`${this.spec.table}.${operation}: refusing an empty where filter, which would match every row`);
|
|
166
|
+
}
|
|
167
|
+
return predicate;
|
|
168
|
+
}
|
|
144
169
|
filter(where) {
|
|
145
170
|
const filter = {};
|
|
146
171
|
for (const [key, value] of Object.entries(where)) {
|
|
@@ -18,7 +18,7 @@ export interface Queryable {
|
|
|
18
18
|
query(text: string, values?: unknown[]): Promise<{ rows: unknown[]; rowCount?: number | null }>;
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
-
/** One generated decoder per field, as emitted in the `<
|
|
21
|
+
/** One generated decoder per field, as emitted in the `<table>Fields` constant. */
|
|
22
22
|
export type FieldDecoders<App> = {
|
|
23
23
|
[K in keyof App]: (value: unknown, label?: string) => App[K];
|
|
24
24
|
};
|
|
@@ -33,18 +33,38 @@ export interface TableSpec<App> {
|
|
|
33
33
|
jsonFields?: readonly string[];
|
|
34
34
|
}
|
|
35
35
|
|
|
36
|
-
/**
|
|
36
|
+
/**
|
|
37
|
+
* Select shape — same as the GraphQL ORM, stated either way round:
|
|
38
|
+
*
|
|
39
|
+
* - `{ id: true, name: true }` reads those fields and nothing else;
|
|
40
|
+
* - `{ databaseId: false }` reads every field except that one, for the field a
|
|
41
|
+
* record has in general but this binding's table does not (a scope's copy of
|
|
42
|
+
* a table without the scope key column) or that a caller must not carry (a
|
|
43
|
+
* secret's id, row bookkeeping).
|
|
44
|
+
*
|
|
45
|
+
* Naming a field `true` is a projection and wins outright: the excluded ones
|
|
46
|
+
* are simply not in it.
|
|
47
|
+
*/
|
|
37
48
|
export type SelectShape<App> = { [K in keyof App]?: boolean };
|
|
38
49
|
|
|
39
50
|
type TrueKeys<App, S> = {
|
|
40
51
|
[K in keyof S]-?: S[K] extends true ? K & keyof App : never;
|
|
41
52
|
}[keyof S];
|
|
42
53
|
|
|
43
|
-
|
|
54
|
+
type FalseKeys<App, S> = {
|
|
55
|
+
[K in keyof S]-?: S[K] extends false ? K & keyof App : never;
|
|
56
|
+
}[keyof S];
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Rows narrow to what the select states: the picked fields, else the record
|
|
60
|
+
* minus the excluded ones. No `select` returns the full record.
|
|
61
|
+
*/
|
|
44
62
|
export type SelectResult<App, S extends SelectShape<App> | undefined> =
|
|
45
63
|
S extends SelectShape<App>
|
|
46
64
|
? [TrueKeys<App, S>] extends [never]
|
|
47
|
-
? App
|
|
65
|
+
? [FalseKeys<App, S>] extends [never]
|
|
66
|
+
? App
|
|
67
|
+
: Omit<App, FalseKeys<App, S>>
|
|
48
68
|
: Pick<App, TrueKeys<App, S>>
|
|
49
69
|
: App;
|
|
50
70
|
|
|
@@ -182,7 +202,8 @@ export class TableClient<App> {
|
|
|
182
202
|
): Promise<SelectResult<App, S>[]> {
|
|
183
203
|
const fields = this.selectedFields(args.select);
|
|
184
204
|
const query = this.baseQuery().select(fields.map(field => this.column(field)));
|
|
185
|
-
|
|
205
|
+
const predicate = this.predicate(args.where);
|
|
206
|
+
if (predicate) query.where(predicate);
|
|
186
207
|
this.applyOrderBy(query, args.orderBy);
|
|
187
208
|
if (args.limit !== undefined) query.limit(args.limit);
|
|
188
209
|
if (args.offset !== undefined) query.offset(args.offset);
|
|
@@ -208,7 +229,8 @@ export class TableClient<App> {
|
|
|
208
229
|
|
|
209
230
|
async count(where?: Where<App>): Promise<number> {
|
|
210
231
|
const query = this.baseQuery().select([]).selectExpr('count', fn('count', [lit(1)]));
|
|
211
|
-
|
|
232
|
+
const predicate = this.predicate(where);
|
|
233
|
+
if (predicate) query.where(predicate);
|
|
212
234
|
const { text, values } = query.build();
|
|
213
235
|
const { rows } = await this.db.query(text, values);
|
|
214
236
|
const row = rows[0] as { count: string | number };
|
|
@@ -233,7 +255,7 @@ export class TableClient<App> {
|
|
|
233
255
|
const fields = this.selectedFields(args.select);
|
|
234
256
|
const query = this.baseQuery()
|
|
235
257
|
.update(this.encodeData(args.data))
|
|
236
|
-
.where(this.
|
|
258
|
+
.where(this.required(args.where, 'update'))
|
|
237
259
|
.returning(fields.map(field => this.column(field)));
|
|
238
260
|
const { text, values } = query.build();
|
|
239
261
|
const { rows } = await this.db.query(text, values);
|
|
@@ -254,7 +276,7 @@ export class TableClient<App> {
|
|
|
254
276
|
const fields = this.selectedFields(args.select);
|
|
255
277
|
const query = this.baseQuery()
|
|
256
278
|
.delete()
|
|
257
|
-
.where(this.
|
|
279
|
+
.where(this.required(args.where, 'delete'))
|
|
258
280
|
.returning(fields.map(field => this.column(field)));
|
|
259
281
|
const { text, values } = query.build();
|
|
260
282
|
const { rows } = await this.db.query(text, values);
|
|
@@ -278,7 +300,10 @@ export class TableClient<App> {
|
|
|
278
300
|
const all = Object.keys(this.spec.columnByField) as (keyof App & string)[];
|
|
279
301
|
if (!select) return all;
|
|
280
302
|
const picked = all.filter(field => select[field] === true);
|
|
281
|
-
|
|
303
|
+
if (picked.length > 0) return picked;
|
|
304
|
+
// Nothing picked: the select either excludes fields or says nothing at all,
|
|
305
|
+
// and both read what is left.
|
|
306
|
+
return all.filter(field => select[field] !== false);
|
|
282
307
|
}
|
|
283
308
|
|
|
284
309
|
private decodeRow<S extends SelectShape<App> | undefined>(
|
|
@@ -293,6 +318,28 @@ export class TableClient<App> {
|
|
|
293
318
|
return decoded as SelectResult<App, S>;
|
|
294
319
|
}
|
|
295
320
|
|
|
321
|
+
/**
|
|
322
|
+
* The predicate to apply, or nothing to apply: a caller that spreads a
|
|
323
|
+
* conditional key column (a scope that records none) states an empty filter,
|
|
324
|
+
* and an unqualified read is what it asked for.
|
|
325
|
+
*/
|
|
326
|
+
private predicate(where: Where<App> | undefined): Filter | undefined {
|
|
327
|
+
if (!where) return undefined;
|
|
328
|
+
const filter = this.filter(where);
|
|
329
|
+
return Object.keys(filter).length > 0 ? filter : undefined;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/** A write says which rows: an empty filter would mean the whole table. */
|
|
333
|
+
private required(where: Where<App>, operation: string): Filter {
|
|
334
|
+
const predicate = this.predicate(where);
|
|
335
|
+
if (!predicate) {
|
|
336
|
+
throw new Error(
|
|
337
|
+
`${this.spec.table}.${operation}: refusing an empty where filter, which would match every row`
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
return predicate;
|
|
341
|
+
}
|
|
342
|
+
|
|
296
343
|
private filter(where: Where<App>): Filter {
|
|
297
344
|
const filter: Filter = {};
|
|
298
345
|
for (const [key, value] of Object.entries(where)) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pg-codegen",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.14.1",
|
|
4
4
|
"author": "Constructive <developers@constructive.io>",
|
|
5
5
|
"description": "Type-safe TypeScript codegen from live PostgreSQL schemas: row types, coerce-backed decoders, serializers, table metadata, and enum unions",
|
|
6
6
|
"main": "index.js",
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
"@babel/generator": "^7.29.1",
|
|
47
47
|
"@babel/types": "^7.29.0",
|
|
48
48
|
"@constructive-io/coerce": "^0.3.0",
|
|
49
|
-
"@constructive-io/query-builder": "^3.10.
|
|
49
|
+
"@constructive-io/query-builder": "^3.10.5",
|
|
50
50
|
"inflekt": "^0.8.1",
|
|
51
51
|
"introspectron": "^5.12.0",
|
|
52
52
|
"pg": "^8.21.0",
|
|
@@ -58,5 +58,5 @@
|
|
|
58
58
|
"makage": "^0.3.0",
|
|
59
59
|
"pgsql-test": "^5.11.0"
|
|
60
60
|
},
|
|
61
|
-
"gitHead": "
|
|
61
|
+
"gitHead": "13e2212f24fa050e8bcd9e805ec30a94918bf8fd"
|
|
62
62
|
}
|