pg-codegen 5.12.0 → 5.13.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 CHANGED
@@ -16,8 +16,6 @@ Type-safe TypeScript from a live PostgreSQL schema: application and row types, r
16
16
 
17
17
  > A database row arrives as `unknown`. `pg-codegen` is what turns it into a value TypeScript can trust, without a hand-written `as string` in sight.
18
18
 
19
- ---
20
-
21
19
  ## ✨ What it generates
22
20
 
23
21
  For every table, view, materialized view and partitioned table in the schemas you name, one module:
package/emit/barrel.js CHANGED
@@ -4,7 +4,12 @@ exports.emitRootIndex = exports.emitSchemaIndex = exports.tableFileName = void 0
4
4
  /** Emits the per-schema and root index modules. */
5
5
  const inflekt_1 = require("inflekt");
6
6
  const babel_1 = require("./babel");
7
- const tableFileName = (tableName) => (0, inflekt_1.toKebabCase)(tableName);
7
+ /** File names the schema directory reserves for its own modules. */
8
+ const RESERVED_FILE_NAMES = new Set(['index', 'db', 'enums']);
9
+ const tableFileName = (tableName) => {
10
+ const name = (0, inflekt_1.toKebabCase)(tableName);
11
+ return RESERVED_FILE_NAMES.has(name) ? `${name}-table` : name;
12
+ };
8
13
  exports.tableFileName = tableFileName;
9
14
  const emitSchemaIndex = (schema) => {
10
15
  const statements = [];
@@ -14,6 +19,7 @@ const emitSchemaIndex = (schema) => {
14
19
  for (const table of schema.tables) {
15
20
  statements.push(babel_1.t.exportAllDeclaration(babel_1.t.stringLiteral(`./${(0, exports.tableFileName)(table.name)}`)));
16
21
  }
22
+ statements.push(babel_1.t.exportAllDeclaration(babel_1.t.stringLiteral('./db')));
17
23
  return (0, babel_1.generateCode)(statements);
18
24
  };
19
25
  exports.emitSchemaIndex = emitSchemaIndex;
@@ -0,0 +1,5 @@
1
+ import { IrSchema } from '../ir';
2
+ /** The shared runtime, copied verbatim with the template note replaced. */
3
+ export declare const emitClientRuntime: () => string;
4
+ /** The per-schema `db.ts`: a `create<Schema>Db` factory of bound TableClients. */
5
+ export declare const emitSchemaDbModule: (schema: IrSchema) => string;
package/emit/client.js ADDED
@@ -0,0 +1,132 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.emitSchemaDbModule = exports.emitClientRuntime = void 0;
37
+ /**
38
+ * Emits the Prisma-like database client: the shared `client.ts` runtime
39
+ * (copied from a typechecked template) and one `db.ts` per schema binding a
40
+ * TableClient per table over the generated metadata and field decoders.
41
+ */
42
+ const fs = __importStar(require("fs"));
43
+ const inflekt_1 = require("inflekt");
44
+ const path = __importStar(require("path"));
45
+ const babel_1 = require("./babel");
46
+ const barrel_1 = require("./barrel");
47
+ const findTemplateFile = (templateName) => {
48
+ const templatePath = path.join(__dirname, 'templates', templateName);
49
+ if (fs.existsSync(templatePath))
50
+ return templatePath;
51
+ throw new Error(`Could not find template file: ${templateName}. Searched in: ${templatePath}`);
52
+ };
53
+ /** The shared runtime, copied verbatim with the template note replaced. */
54
+ const emitClientRuntime = () => {
55
+ const content = fs.readFileSync(findTemplateFile('client.ts'), 'utf8');
56
+ return content.replace(/ \* NOTE: This file is read at codegen time and written to output\.\n \* Any changes here will affect all generated clients\.\n \*\/\n/, ' * Generated by pg-codegen. DO NOT EDIT.\n */\n/* eslint-disable */\n');
57
+ };
58
+ exports.emitClientRuntime = emitClientRuntime;
59
+ const typeImport = (names, source) => {
60
+ const declaration = (0, babel_1.namedImport)(names, source);
61
+ declaration.importKind = 'type';
62
+ return declaration;
63
+ };
64
+ const modelKey = (table) => (0, inflekt_1.toCamelCase)(table.name);
65
+ /** The per-schema `db.ts`: a `create<Schema>Db` factory of bound TableClients. */
66
+ const emitSchemaDbModule = (schema) => {
67
+ const pascal = (0, inflekt_1.toPascalCase)(schema.name);
68
+ const dbTypeName = `${pascal}Db`;
69
+ const optionsName = `${pascal}DbOptions`;
70
+ const factoryName = `create${pascal}Db`;
71
+ const statements = [
72
+ (0, babel_1.namedImport)(['TableClient'], '../client'),
73
+ typeImport(['Queryable'], '../client')
74
+ ];
75
+ for (const table of schema.tables) {
76
+ const appType = (0, inflekt_1.toPascalCase)(table.name);
77
+ const constant = (0, inflekt_1.toConstantCase)(table.name);
78
+ const file = `./${(0, barrel_1.tableFileName)(table.name)}`;
79
+ statements.push(typeImport([appType], file));
80
+ statements.push((0, babel_1.namedImport)([`${constant}_FIELDS`, `${constant}_TABLE`], file));
81
+ }
82
+ const tableNameProps = schema.tables.map(table => {
83
+ const prop = babel_1.t.tsPropertySignature(babel_1.t.identifier(modelKey(table)), babel_1.t.tsTypeAnnotation(babel_1.t.tsStringKeyword()));
84
+ prop.optional = true;
85
+ return prop;
86
+ });
87
+ const schemaProp = babel_1.t.tsPropertySignature(babel_1.t.identifier('schema'), babel_1.t.tsTypeAnnotation(babel_1.t.tsStringKeyword()));
88
+ schemaProp.optional = true;
89
+ const tablesProp = babel_1.t.tsPropertySignature(babel_1.t.identifier('tables'), babel_1.t.tsTypeAnnotation(babel_1.t.tsTypeLiteral(tableNameProps)));
90
+ tablesProp.optional = true;
91
+ statements.push((0, babel_1.withJsDoc)(babel_1.t.exportNamedDeclaration(babel_1.t.tsInterfaceDeclaration(babel_1.t.identifier(optionsName), null, null, babel_1.t.tsInterfaceBody([schemaProp, tablesProp]))), 'Runtime overrides for the physical schema and per-table names, for tables provisioned into per-tenant schemas.'));
92
+ const dbMembers = schema.tables.map(table => babel_1.t.tsPropertySignature(babel_1.t.identifier(modelKey(table)), babel_1.t.tsTypeAnnotation(babel_1.t.tsTypeReference(babel_1.t.identifier('TableClient'), babel_1.t.tsTypeParameterInstantiation([babel_1.t.tsTypeReference(babel_1.t.identifier((0, inflekt_1.toPascalCase)(table.name)))])))));
93
+ const withParam = babel_1.t.identifier('db');
94
+ withParam.typeAnnotation = babel_1.t.tsTypeAnnotation(babel_1.t.tsTypeReference(babel_1.t.identifier('Queryable')));
95
+ const withMember = babel_1.t.tsMethodSignature(babel_1.t.identifier('$with'), null, [withParam], babel_1.t.tsTypeAnnotation(babel_1.t.tsTypeReference(babel_1.t.identifier(dbTypeName))));
96
+ babel_1.t.addComment(withMember, 'leading', "* Rebind every table client to another connection (e.g. a transaction's PoolClient). ", false);
97
+ dbMembers.push(withMember);
98
+ statements.push(babel_1.t.exportNamedDeclaration(babel_1.t.tsInterfaceDeclaration(babel_1.t.identifier(dbTypeName), null, null, babel_1.t.tsInterfaceBody(dbMembers))));
99
+ const clientProperties = schema.tables.map(table => {
100
+ const constant = (0, inflekt_1.toConstantCase)(table.name);
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(`${constant}_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(`${constant}_TABLE`), babel_1.t.identifier('name')))),
104
+ babel_1.t.objectProperty(babel_1.t.identifier('columnByField'), babel_1.t.memberExpression(babel_1.t.identifier(`${constant}_TABLE`), babel_1.t.identifier('columnByField'))),
105
+ babel_1.t.objectProperty(babel_1.t.identifier('fields'), babel_1.t.identifier(`${constant}_FIELDS`))
106
+ ]);
107
+ const jsonFields = table.columns.filter(column => column.scalar === 'json');
108
+ if (jsonFields.length > 0) {
109
+ spec.properties.push(babel_1.t.objectProperty(babel_1.t.identifier('jsonFields'), babel_1.t.arrayExpression(jsonFields.map(column => babel_1.t.stringLiteral(column.propertyName)))));
110
+ }
111
+ const client = babel_1.t.newExpression(babel_1.t.identifier('TableClient'), [spec, babel_1.t.identifier('db')]);
112
+ client.typeParameters = babel_1.t.tsTypeParameterInstantiation([
113
+ babel_1.t.tsTypeReference(babel_1.t.identifier((0, inflekt_1.toPascalCase)(table.name)))
114
+ ]);
115
+ return babel_1.t.objectProperty(babel_1.t.identifier(modelKey(table)), client);
116
+ });
117
+ const nextParam = babel_1.t.identifier('next');
118
+ nextParam.typeAnnotation = babel_1.t.tsTypeAnnotation(babel_1.t.tsTypeReference(babel_1.t.identifier('Queryable')));
119
+ clientProperties.push(babel_1.t.objectProperty(babel_1.t.identifier('$with'), babel_1.t.arrowFunctionExpression([nextParam], babel_1.t.callExpression(babel_1.t.identifier(factoryName), [babel_1.t.identifier('next'), babel_1.t.identifier('options')]))));
120
+ const dbParam = babel_1.t.identifier('db');
121
+ dbParam.typeAnnotation = babel_1.t.tsTypeAnnotation(babel_1.t.tsTypeReference(babel_1.t.identifier('Queryable')));
122
+ const optionsParam = babel_1.t.assignmentPattern((() => {
123
+ const id = babel_1.t.identifier('options');
124
+ id.typeAnnotation = babel_1.t.tsTypeAnnotation(babel_1.t.tsTypeReference(babel_1.t.identifier(optionsName)));
125
+ return id;
126
+ })(), babel_1.t.objectExpression([]));
127
+ const factory = babel_1.t.arrowFunctionExpression([dbParam, optionsParam], babel_1.t.objectExpression(clientProperties));
128
+ factory.returnType = babel_1.t.tsTypeAnnotation(babel_1.t.tsTypeReference(babel_1.t.identifier(dbTypeName)));
129
+ statements.push((0, babel_1.withJsDoc)((0, babel_1.exportConst)(factoryName, factory), `One Prisma-like client per table over any pg Pool/Client, decoding rows into the generated ${pascal} application types.`));
130
+ return (0, babel_1.generateCode)(statements);
131
+ };
132
+ exports.emitSchemaDbModule = emitSchemaDbModule;
@@ -0,0 +1,135 @@
1
+ /** Anything with pg's `query(text, values)` shape: Pool, PoolClient, Client. */
2
+ export interface Queryable {
3
+ query(text: string, values?: unknown[]): Promise<{
4
+ rows: unknown[];
5
+ rowCount?: number | null;
6
+ }>;
7
+ }
8
+ /** One generated decoder per field, as emitted in the `<TABLE>_FIELDS` constant. */
9
+ export type FieldDecoders<App> = {
10
+ [K in keyof App]: (value: unknown, label?: string) => App[K];
11
+ };
12
+ /** Table wiring supplied by the generated per-schema `db` factory. */
13
+ export interface TableSpec<App> {
14
+ schema: string;
15
+ table: string;
16
+ columnByField: Record<string, string>;
17
+ fields: FieldDecoders<App>;
18
+ /** camelCase fields backed by json/jsonb columns, serialized on writes. */
19
+ jsonFields?: readonly string[];
20
+ }
21
+ /** Select shape: `{ id: true, name: true }` — same as the GraphQL ORM. */
22
+ export type SelectShape<App> = {
23
+ [K in keyof App]?: boolean;
24
+ };
25
+ type TrueKeys<App, S> = {
26
+ [K in keyof S]-?: S[K] extends true ? K & keyof App : never;
27
+ }[keyof S];
28
+ /** Rows narrow to the selected fields; no `select` returns the full record. */
29
+ export type SelectResult<App, S extends SelectShape<App> | undefined> = S extends SelectShape<App> ? [TrueKeys<App, S>] extends [never] ? App : Pick<App, TrueKeys<App, S>> : App;
30
+ /** Per-field operators from the shared query-spec grammar. */
31
+ export interface FieldOps<V> {
32
+ equalTo?: V;
33
+ notEqualTo?: V;
34
+ distinctFrom?: V;
35
+ notDistinctFrom?: V;
36
+ lessThan?: V;
37
+ lessThanOrEqualTo?: V;
38
+ greaterThan?: V;
39
+ greaterThanOrEqualTo?: V;
40
+ in?: V[];
41
+ notIn?: V[];
42
+ like?: string;
43
+ notLike?: string;
44
+ likeInsensitive?: string;
45
+ notLikeInsensitive?: string;
46
+ includes?: string;
47
+ notIncludes?: string;
48
+ includesInsensitive?: string;
49
+ startsWith?: string;
50
+ endsWith?: string;
51
+ isNull?: boolean;
52
+ }
53
+ /**
54
+ * Where filter keyed by camelCase field names. A bare value means `equalTo`
55
+ * (`null` means `isNull`). Extra string keys are physical column names —
56
+ * runtime-configured scope key columns qualify rows the same way any other
57
+ * condition does.
58
+ */
59
+ export type Where<App> = {
60
+ [K in keyof App]?: App[K] | FieldOps<NonNullable<App[K]>>;
61
+ } & {
62
+ [column: string]: unknown;
63
+ } & {
64
+ and?: Where<App>[];
65
+ or?: Where<App>[];
66
+ not?: Where<App>;
67
+ };
68
+ /**
69
+ * Write data keyed by camelCase field names. Extra string keys are physical
70
+ * column names — runtime-configured scope key columns are stamped the same
71
+ * way any other value is.
72
+ */
73
+ export type Data<App> = Partial<App> & {
74
+ [column: string]: unknown;
75
+ };
76
+ export type OrderDirection = 'ASC' | 'DESC';
77
+ /** Order spec keyed by camelCase field names, e.g. `{ createdAt: 'DESC' }`. */
78
+ export type OrderBy<App> = {
79
+ [K in keyof App]?: OrderDirection;
80
+ };
81
+ export interface FindManyArgs<App, S extends SelectShape<App> | undefined> {
82
+ where?: Where<App>;
83
+ select?: S;
84
+ orderBy?: OrderBy<App> | OrderBy<App>[];
85
+ limit?: number;
86
+ offset?: number;
87
+ }
88
+ export interface FindFirstArgs<App, S extends SelectShape<App> | undefined> {
89
+ where?: Where<App>;
90
+ select?: S;
91
+ orderBy?: OrderBy<App> | OrderBy<App>[];
92
+ }
93
+ export interface CreateArgs<App, S extends SelectShape<App> | undefined> {
94
+ data: Data<App>;
95
+ select?: S;
96
+ }
97
+ export interface UpdateArgs<App, S extends SelectShape<App> | undefined> {
98
+ where: Where<App>;
99
+ data: Data<App>;
100
+ select?: S;
101
+ }
102
+ export interface DeleteArgs<App, S extends SelectShape<App> | undefined> {
103
+ where: Where<App>;
104
+ select?: S;
105
+ }
106
+ /** Thrown by `findFirstOrThrow` / `updateOrThrow` when no row matches. */
107
+ export declare class RowNotFoundError extends Error {
108
+ readonly table: string;
109
+ readonly operation: string;
110
+ constructor(table: string, operation: string);
111
+ }
112
+ export declare class TableClient<App> {
113
+ private readonly spec;
114
+ private readonly db;
115
+ constructor(spec: TableSpec<App>, db: Queryable);
116
+ findMany<S extends SelectShape<App> | undefined = undefined>(args?: FindManyArgs<App, S>): Promise<SelectResult<App, S>[]>;
117
+ findFirst<S extends SelectShape<App> | undefined = undefined>(args?: FindFirstArgs<App, S>): Promise<SelectResult<App, S> | null>;
118
+ findFirstOrThrow<S extends SelectShape<App> | undefined = undefined>(args?: FindFirstArgs<App, S>): Promise<SelectResult<App, S>>;
119
+ count(where?: Where<App>): Promise<number>;
120
+ create<S extends SelectShape<App> | undefined = undefined>(args: CreateArgs<App, S>): Promise<SelectResult<App, S>>;
121
+ update<S extends SelectShape<App> | undefined = undefined>(args: UpdateArgs<App, S>): Promise<SelectResult<App, S>[]>;
122
+ updateOrThrow<S extends SelectShape<App> | undefined = undefined>(args: UpdateArgs<App, S>): Promise<SelectResult<App, S>>;
123
+ delete<S extends SelectShape<App> | undefined = undefined>(args: DeleteArgs<App, S>): Promise<SelectResult<App, S>[]>;
124
+ /** Rebind to another connection (e.g. a transaction's PoolClient). */
125
+ $with(db: Queryable): TableClient<App>;
126
+ private baseQuery;
127
+ private column;
128
+ private selectedFields;
129
+ private decodeRow;
130
+ private filter;
131
+ private fieldFilter;
132
+ private applyOrderBy;
133
+ private encodeData;
134
+ }
135
+ export {};
@@ -0,0 +1,214 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TableClient = exports.RowNotFoundError = void 0;
4
+ const query_builder_1 = require("@constructive-io/query-builder");
5
+ const FIELD_OP_NAMES = new Set([
6
+ 'equalTo',
7
+ 'notEqualTo',
8
+ 'distinctFrom',
9
+ 'notDistinctFrom',
10
+ 'lessThan',
11
+ 'lessThanOrEqualTo',
12
+ 'greaterThan',
13
+ 'greaterThanOrEqualTo',
14
+ 'in',
15
+ 'notIn',
16
+ 'like',
17
+ 'notLike',
18
+ 'likeInsensitive',
19
+ 'notLikeInsensitive',
20
+ 'includes',
21
+ 'notIncludes',
22
+ 'includesInsensitive',
23
+ 'startsWith',
24
+ 'endsWith',
25
+ 'isNull'
26
+ ]);
27
+ /** Thrown by `findFirstOrThrow` / `updateOrThrow` when no row matches. */
28
+ class RowNotFoundError extends Error {
29
+ table;
30
+ operation;
31
+ constructor(table, operation) {
32
+ super(`${table}.${operation}: no row matched the given where filter`);
33
+ this.table = table;
34
+ this.operation = operation;
35
+ this.name = 'RowNotFoundError';
36
+ }
37
+ }
38
+ exports.RowNotFoundError = RowNotFoundError;
39
+ const encodeScalar = (value) => {
40
+ if (value === null)
41
+ return null;
42
+ if (value instanceof Date)
43
+ return value.toISOString();
44
+ if (typeof value === 'object' && !Array.isArray(value))
45
+ return JSON.stringify(value);
46
+ return value;
47
+ };
48
+ class TableClient {
49
+ spec;
50
+ db;
51
+ constructor(spec, db) {
52
+ this.spec = spec;
53
+ this.db = db;
54
+ }
55
+ async findMany(args = {}) {
56
+ const fields = this.selectedFields(args.select);
57
+ const query = this.baseQuery().select(fields.map(field => this.column(field)));
58
+ if (args.where)
59
+ query.where(this.filter(args.where));
60
+ this.applyOrderBy(query, args.orderBy);
61
+ if (args.limit !== undefined)
62
+ query.limit(args.limit);
63
+ if (args.offset !== undefined)
64
+ query.offset(args.offset);
65
+ const { text, values } = query.build();
66
+ const { rows } = await this.db.query(text, values);
67
+ return rows.map(row => this.decodeRow(row, fields));
68
+ }
69
+ async findFirst(args = {}) {
70
+ const rows = await this.findMany({ ...args, limit: 1 });
71
+ return rows.length > 0 ? rows[0] : null;
72
+ }
73
+ async findFirstOrThrow(args = {}) {
74
+ const row = await this.findFirst(args);
75
+ if (row === null)
76
+ throw new RowNotFoundError(this.spec.table, 'findFirstOrThrow');
77
+ return row;
78
+ }
79
+ async count(where) {
80
+ const query = this.baseQuery().select([]).selectExpr('count', (0, query_builder_1.fn)('count', [(0, query_builder_1.lit)(1)]));
81
+ if (where)
82
+ query.where(this.filter(where));
83
+ const { text, values } = query.build();
84
+ const { rows } = await this.db.query(text, values);
85
+ const row = rows[0];
86
+ return Number(row.count);
87
+ }
88
+ async create(args) {
89
+ const fields = this.selectedFields(args.select);
90
+ const query = this.baseQuery()
91
+ .insert(this.encodeData(args.data))
92
+ .returning(fields.map(field => this.column(field)));
93
+ const { text, values } = query.build();
94
+ const { rows } = await this.db.query(text, values);
95
+ return this.decodeRow(rows[0], fields);
96
+ }
97
+ async update(args) {
98
+ const fields = this.selectedFields(args.select);
99
+ const query = this.baseQuery()
100
+ .update(this.encodeData(args.data))
101
+ .where(this.filter(args.where))
102
+ .returning(fields.map(field => this.column(field)));
103
+ const { text, values } = query.build();
104
+ const { rows } = await this.db.query(text, values);
105
+ return rows.map(row => this.decodeRow(row, fields));
106
+ }
107
+ async updateOrThrow(args) {
108
+ const rows = await this.update(args);
109
+ if (rows.length === 0)
110
+ throw new RowNotFoundError(this.spec.table, 'updateOrThrow');
111
+ return rows[0];
112
+ }
113
+ async delete(args) {
114
+ const fields = this.selectedFields(args.select);
115
+ const query = this.baseQuery()
116
+ .delete()
117
+ .where(this.filter(args.where))
118
+ .returning(fields.map(field => this.column(field)));
119
+ const { text, values } = query.build();
120
+ const { rows } = await this.db.query(text, values);
121
+ return rows.map(row => this.decodeRow(row, fields));
122
+ }
123
+ /** Rebind to another connection (e.g. a transaction's PoolClient). */
124
+ $with(db) {
125
+ return new TableClient(this.spec, db);
126
+ }
127
+ baseQuery() {
128
+ return new query_builder_1.QueryBuilder().schema(this.spec.schema).table(this.spec.table);
129
+ }
130
+ column(field) {
131
+ return this.spec.columnByField[field] ?? field;
132
+ }
133
+ selectedFields(select) {
134
+ const all = Object.keys(this.spec.columnByField);
135
+ if (!select)
136
+ return all;
137
+ const picked = all.filter(field => select[field] === true);
138
+ return picked.length > 0 ? picked : all;
139
+ }
140
+ decodeRow(row, fields) {
141
+ const raw = row;
142
+ const decoded = {};
143
+ for (const field of fields) {
144
+ decoded[field] = this.spec.fields[field](raw[this.column(field)]);
145
+ }
146
+ return decoded;
147
+ }
148
+ filter(where) {
149
+ const filter = {};
150
+ for (const [key, value] of Object.entries(where)) {
151
+ if (value === undefined)
152
+ continue;
153
+ if (key === 'and' || key === 'or') {
154
+ filter[key] = value.map(nested => this.filter(nested));
155
+ continue;
156
+ }
157
+ if (key === 'not') {
158
+ filter.not = this.filter(value);
159
+ continue;
160
+ }
161
+ filter[this.column(key)] = this.fieldFilter(value);
162
+ }
163
+ return filter;
164
+ }
165
+ fieldFilter(value) {
166
+ if (value === null)
167
+ return { isNull: true };
168
+ if (typeof value === 'object' && !Array.isArray(value) && !(value instanceof Date)) {
169
+ const entries = Object.entries(value);
170
+ if (entries.length > 0 && entries.every(([op]) => FIELD_OP_NAMES.has(op))) {
171
+ const ops = {};
172
+ for (const [op, operand] of entries) {
173
+ if (operand === undefined)
174
+ continue;
175
+ ops[op] = Array.isArray(operand)
176
+ ? operand.map(encodeScalar)
177
+ : op === 'isNull'
178
+ ? operand
179
+ : encodeScalar(operand);
180
+ }
181
+ return ops;
182
+ }
183
+ }
184
+ return { equalTo: encodeScalar(value) };
185
+ }
186
+ applyOrderBy(query, orderBy) {
187
+ if (!orderBy)
188
+ return;
189
+ for (const spec of Array.isArray(orderBy) ? orderBy : [orderBy]) {
190
+ for (const [field, direction] of Object.entries(spec)) {
191
+ if (!direction)
192
+ continue;
193
+ query.orderBy(this.column(field), direction);
194
+ }
195
+ }
196
+ }
197
+ encodeData(data) {
198
+ const encoded = {};
199
+ for (const [field, value] of Object.entries(data)) {
200
+ if (value === undefined)
201
+ continue;
202
+ if (value !== null && this.spec.jsonFields?.includes(field)) {
203
+ encoded[this.column(field)] = JSON.stringify(value);
204
+ continue;
205
+ }
206
+ // pg serializes JS arrays into PostgreSQL array literals.
207
+ encoded[this.column(field)] = Array.isArray(value)
208
+ ? value.map(encodeScalar)
209
+ : encodeScalar(value);
210
+ }
211
+ return encoded;
212
+ }
213
+ }
214
+ exports.TableClient = TableClient;