@coopenomics/extension-sdk 2026.11.25 → 2026.12.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 +45 -5
- package/dist/auth/extension-access.guard.d.ts +25 -0
- package/dist/auth/extension-access.guard.js +66 -0
- package/dist/config/extension-config.d.ts +27 -2
- package/dist/config/extension-config.js +12 -4
- package/dist/database/app-migrations.d.ts +45 -0
- package/dist/database/app-migrations.js +134 -0
- package/dist/database/index.d.ts +14 -0
- package/dist/database/index.js +30 -0
- package/dist/database/kysely.d.ts +57 -0
- package/dist/database/kysely.js +89 -0
- package/dist/database/relations.d.ts +8 -0
- package/dist/database/relations.js +36 -0
- package/dist/database/sql-builder.d.ts +71 -0
- package/dist/database/sql-builder.js +170 -0
- package/dist/database/table-store.d.ts +122 -0
- package/dist/database/table-store.js +260 -0
- package/dist/database/transaction.d.ts +20 -0
- package/dist/database/transaction.js +28 -0
- package/dist/events/bus-reader.d.ts +113 -0
- package/dist/events/bus-reader.js +188 -0
- package/dist/events/extension-events.module.d.ts +76 -0
- package/dist/events/extension-events.module.js +158 -0
- package/dist/federation/federation.module.d.ts +1 -1
- package/dist/federation/federation.module.js +5 -5
- package/dist/index.d.ts +11 -2
- package/dist/index.js +32 -3
- package/dist/ports/core-ports.client.d.ts +49 -0
- package/dist/ports/core-ports.client.js +114 -0
- package/dist/ports/extension-ports.module.d.ts +88 -0
- package/dist/ports/extension-ports.module.js +90 -0
- package/package.json +28 -2
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.attachOne = attachOne;
|
|
4
|
+
const table_store_1 = require("./table-store");
|
|
5
|
+
/**
|
|
6
|
+
* Подгружает к записям связанную запись другой таблицы и кладёт её в поле
|
|
7
|
+
* `property`. `keys` — соответствие «поле связанной записи → поле своей»;
|
|
8
|
+
* связь по нескольким полям ищется одним запросом и сводится в памяти. Запись
|
|
9
|
+
* без пары остаётся без поля.
|
|
10
|
+
*/
|
|
11
|
+
async function attachOne(records, related, property, keys) {
|
|
12
|
+
if (records.length === 0)
|
|
13
|
+
return;
|
|
14
|
+
const pairs = Object.entries(keys);
|
|
15
|
+
const read = (record, field) => record[field];
|
|
16
|
+
const where = {};
|
|
17
|
+
for (const [relatedField, ownField] of pairs) {
|
|
18
|
+
const values = [...new Set(records.map((record) => read(record, ownField)).filter((value) => value !== null && value !== undefined))];
|
|
19
|
+
if (values.length === 0)
|
|
20
|
+
return;
|
|
21
|
+
where[relatedField] = (0, table_store_1.oneOf)(values);
|
|
22
|
+
}
|
|
23
|
+
const found = await related.find(where);
|
|
24
|
+
const signature = (record, side) => pairs.map((pair) => String(read(record, pair[side]))).join('\u0000');
|
|
25
|
+
const index = new Map();
|
|
26
|
+
for (const candidate of found) {
|
|
27
|
+
const key = signature(candidate, 0);
|
|
28
|
+
if (!index.has(key))
|
|
29
|
+
index.set(key, candidate);
|
|
30
|
+
}
|
|
31
|
+
for (const record of records) {
|
|
32
|
+
const match = index.get(signature(record, 1));
|
|
33
|
+
if (match)
|
|
34
|
+
record[property] = match;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { Kysely } from 'kysely';
|
|
2
|
+
type Params = Record<string, unknown>;
|
|
3
|
+
interface BuilderHost<TRecord> {
|
|
4
|
+
kysely: Kysely<any>;
|
|
5
|
+
table: string;
|
|
6
|
+
primaryKey: string[];
|
|
7
|
+
records(rows: Array<Record<string, unknown>>): TRecord[];
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Сборщик выборки из готовых фрагментов SQL с именованными параметрами — для
|
|
11
|
+
* запросов, которые яснее читать текстом: соединения таблиц, подзапросы,
|
|
12
|
+
* агрегаты. Значения передаются только параметрами (`:имя`, перечень —
|
|
13
|
+
* `:...имя`); в текст запроса данные вызывающего не подставляются. Исполняет
|
|
14
|
+
* запрос Kysely.
|
|
15
|
+
*
|
|
16
|
+
* ```ts
|
|
17
|
+
* store.sqlBuilder('p').where('p.coopname = :coopname', { coopname }).orderBy('p.created_at', 'DESC').getMany();
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
export declare class SqlBuilder<TRecord extends object> {
|
|
21
|
+
private readonly host;
|
|
22
|
+
private readonly alias;
|
|
23
|
+
private selections;
|
|
24
|
+
private distinctRows;
|
|
25
|
+
private joins;
|
|
26
|
+
private conditions;
|
|
27
|
+
private groups;
|
|
28
|
+
private orders;
|
|
29
|
+
private rowLimit?;
|
|
30
|
+
private rowOffset?;
|
|
31
|
+
private params;
|
|
32
|
+
constructor(host: BuilderHost<TRecord>, alias: string);
|
|
33
|
+
/** Выбираемое выражение; псевдоним таблицы целиком — все её колонки (так и по умолчанию). */
|
|
34
|
+
select(expression: string | string[], as?: string): this;
|
|
35
|
+
/**
|
|
36
|
+
* Колонка без своего имени (`te.issue_hash`) в сырой выборке называется
|
|
37
|
+
* `te_issue_hash` — по псевдониму таблицы и имени колонки.
|
|
38
|
+
*/
|
|
39
|
+
addSelect(expression: string | string[], as?: string): this;
|
|
40
|
+
distinct(enabled?: boolean): this;
|
|
41
|
+
innerJoin(table: string, alias: string, on: string, params?: Params): this;
|
|
42
|
+
leftJoin(table: string, alias: string, on: string, params?: Params): this;
|
|
43
|
+
where(condition: string, params?: Params): this;
|
|
44
|
+
andWhere(condition: string, params?: Params): this;
|
|
45
|
+
groupBy(expression: string): this;
|
|
46
|
+
addGroupBy(expression: string): this;
|
|
47
|
+
orderBy(expression: string, direction?: 'ASC' | 'DESC'): this;
|
|
48
|
+
addOrderBy(expression: string, direction?: 'ASC' | 'DESC'): this;
|
|
49
|
+
limit(count?: number): this;
|
|
50
|
+
offset(count?: number): this;
|
|
51
|
+
/** Записи таблицы сборщика. */
|
|
52
|
+
getMany(): Promise<TRecord[]>;
|
|
53
|
+
getOne(): Promise<TRecord | null>;
|
|
54
|
+
/** Число записей таблицы сборщика под условиями; соединения запись не размножают. */
|
|
55
|
+
getCount(): Promise<number>;
|
|
56
|
+
getManyAndCount(): Promise<[TRecord[], number]>;
|
|
57
|
+
/** Строки как есть — для выражений из `select`. */
|
|
58
|
+
getRawMany<TRow = any>(): Promise<TRow[]>;
|
|
59
|
+
getRawOne<TRow = any>(): Promise<TRow | undefined>;
|
|
60
|
+
private join;
|
|
61
|
+
private compile;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Именованные параметры (`:имя`, перечень — `:...имя`) в нумерованные.
|
|
65
|
+
* Приведение типа `::jsonb` параметром не считается.
|
|
66
|
+
*/
|
|
67
|
+
export declare function bindNamed(text: string, params: Params): {
|
|
68
|
+
text: string;
|
|
69
|
+
values: unknown[];
|
|
70
|
+
};
|
|
71
|
+
export {};
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SqlBuilder = void 0;
|
|
4
|
+
exports.bindNamed = bindNamed;
|
|
5
|
+
const kysely_1 = require("./kysely");
|
|
6
|
+
/**
|
|
7
|
+
* Сборщик выборки из готовых фрагментов SQL с именованными параметрами — для
|
|
8
|
+
* запросов, которые яснее читать текстом: соединения таблиц, подзапросы,
|
|
9
|
+
* агрегаты. Значения передаются только параметрами (`:имя`, перечень —
|
|
10
|
+
* `:...имя`); в текст запроса данные вызывающего не подставляются. Исполняет
|
|
11
|
+
* запрос Kysely.
|
|
12
|
+
*
|
|
13
|
+
* ```ts
|
|
14
|
+
* store.sqlBuilder('p').where('p.coopname = :coopname', { coopname }).orderBy('p.created_at', 'DESC').getMany();
|
|
15
|
+
* ```
|
|
16
|
+
*/
|
|
17
|
+
class SqlBuilder {
|
|
18
|
+
host;
|
|
19
|
+
alias;
|
|
20
|
+
selections = [];
|
|
21
|
+
distinctRows = false;
|
|
22
|
+
joins = [];
|
|
23
|
+
conditions = [];
|
|
24
|
+
groups = [];
|
|
25
|
+
orders = [];
|
|
26
|
+
rowLimit;
|
|
27
|
+
rowOffset;
|
|
28
|
+
params = {};
|
|
29
|
+
constructor(host, alias) {
|
|
30
|
+
this.host = host;
|
|
31
|
+
this.alias = alias;
|
|
32
|
+
}
|
|
33
|
+
/** Выбираемое выражение; псевдоним таблицы целиком — все её колонки (так и по умолчанию). */
|
|
34
|
+
select(expression, as) {
|
|
35
|
+
this.selections = [];
|
|
36
|
+
return this.addSelect(expression, as);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Колонка без своего имени (`te.issue_hash`) в сырой выборке называется
|
|
40
|
+
* `te_issue_hash` — по псевдониму таблицы и имени колонки.
|
|
41
|
+
*/
|
|
42
|
+
addSelect(expression, as) {
|
|
43
|
+
for (const item of Array.isArray(expression) ? expression : [expression]) {
|
|
44
|
+
if (item === this.alias)
|
|
45
|
+
continue;
|
|
46
|
+
const column = /^(\w+)\.(\w+)$/.exec(item);
|
|
47
|
+
const name = as ?? (column ? `${column[1]}_${column[2]}` : undefined);
|
|
48
|
+
this.selections.push(name ? `${item} AS "${name}"` : item);
|
|
49
|
+
}
|
|
50
|
+
return this;
|
|
51
|
+
}
|
|
52
|
+
distinct(enabled = true) {
|
|
53
|
+
this.distinctRows = enabled;
|
|
54
|
+
return this;
|
|
55
|
+
}
|
|
56
|
+
innerJoin(table, alias, on, params = {}) {
|
|
57
|
+
return this.join('INNER', table, alias, on, params);
|
|
58
|
+
}
|
|
59
|
+
leftJoin(table, alias, on, params = {}) {
|
|
60
|
+
return this.join('LEFT', table, alias, on, params);
|
|
61
|
+
}
|
|
62
|
+
where(condition, params = {}) {
|
|
63
|
+
this.conditions = [];
|
|
64
|
+
return this.andWhere(condition, params);
|
|
65
|
+
}
|
|
66
|
+
andWhere(condition, params = {}) {
|
|
67
|
+
this.conditions.push(`(${condition})`);
|
|
68
|
+
Object.assign(this.params, params);
|
|
69
|
+
return this;
|
|
70
|
+
}
|
|
71
|
+
groupBy(expression) {
|
|
72
|
+
this.groups = [expression];
|
|
73
|
+
return this;
|
|
74
|
+
}
|
|
75
|
+
addGroupBy(expression) {
|
|
76
|
+
this.groups.push(expression);
|
|
77
|
+
return this;
|
|
78
|
+
}
|
|
79
|
+
orderBy(expression, direction = 'ASC') {
|
|
80
|
+
this.orders = [];
|
|
81
|
+
return this.addOrderBy(expression, direction);
|
|
82
|
+
}
|
|
83
|
+
addOrderBy(expression, direction = 'ASC') {
|
|
84
|
+
// enum-literal: направление сортировки SQL
|
|
85
|
+
this.orders.push(`${expression} ${direction === 'DESC' ? 'DESC' : 'ASC'}`);
|
|
86
|
+
return this;
|
|
87
|
+
}
|
|
88
|
+
limit(count) {
|
|
89
|
+
this.rowLimit = count;
|
|
90
|
+
return this;
|
|
91
|
+
}
|
|
92
|
+
offset(count) {
|
|
93
|
+
this.rowOffset = count;
|
|
94
|
+
return this;
|
|
95
|
+
}
|
|
96
|
+
/** Записи таблицы сборщика. */
|
|
97
|
+
async getMany() {
|
|
98
|
+
const { text, values } = this.compile(`${this.distinctRows ? 'DISTINCT ' : ''}${this.alias}.*`, true);
|
|
99
|
+
return this.host.records(await (0, kysely_1.rawQuery)(this.host.kysely, text, values));
|
|
100
|
+
}
|
|
101
|
+
async getOne() {
|
|
102
|
+
const saved = this.rowLimit;
|
|
103
|
+
this.rowLimit = 1;
|
|
104
|
+
const [record] = await this.getMany();
|
|
105
|
+
this.rowLimit = saved;
|
|
106
|
+
return record ?? null;
|
|
107
|
+
}
|
|
108
|
+
/** Число записей таблицы сборщика под условиями; соединения запись не размножают. */
|
|
109
|
+
async getCount() {
|
|
110
|
+
const key = this.host.primaryKey.map((column) => `${this.alias}."${column}"`).join(', ');
|
|
111
|
+
const { text, values } = this.compile(`COUNT(DISTINCT (${key})) AS count`, false);
|
|
112
|
+
const [row] = await (0, kysely_1.rawQuery)(this.host.kysely, text, values);
|
|
113
|
+
return Number(row?.count ?? 0);
|
|
114
|
+
}
|
|
115
|
+
async getManyAndCount() {
|
|
116
|
+
return [await this.getMany(), await this.getCount()];
|
|
117
|
+
}
|
|
118
|
+
/** Строки как есть — для выражений из `select`. */
|
|
119
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
120
|
+
async getRawMany() {
|
|
121
|
+
const selection = `${this.distinctRows ? 'DISTINCT ' : ''}${this.selections.length ? this.selections.join(', ') : `${this.alias}.*`}`;
|
|
122
|
+
const { text, values } = this.compile(selection, true);
|
|
123
|
+
return (0, kysely_1.rawQuery)(this.host.kysely, text, values);
|
|
124
|
+
}
|
|
125
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
126
|
+
async getRawOne() {
|
|
127
|
+
const [row] = await this.getRawMany();
|
|
128
|
+
return row;
|
|
129
|
+
}
|
|
130
|
+
join(kind, table, alias, on, params) {
|
|
131
|
+
this.joins.push(`${kind} JOIN ${table} ${alias} ON ${on}`);
|
|
132
|
+
Object.assign(this.params, params);
|
|
133
|
+
return this;
|
|
134
|
+
}
|
|
135
|
+
compile(selection, page) {
|
|
136
|
+
const parts = [`SELECT ${selection} FROM ${this.host.table} ${this.alias}`, ...this.joins];
|
|
137
|
+
if (this.conditions.length)
|
|
138
|
+
parts.push(`WHERE ${this.conditions.join(' AND ')}`);
|
|
139
|
+
if (this.groups.length)
|
|
140
|
+
parts.push(`GROUP BY ${this.groups.join(', ')}`);
|
|
141
|
+
if (page && this.orders.length)
|
|
142
|
+
parts.push(`ORDER BY ${this.orders.join(', ')}`);
|
|
143
|
+
if (page && this.rowLimit !== undefined)
|
|
144
|
+
parts.push(`LIMIT ${Number(this.rowLimit)}`);
|
|
145
|
+
if (page && this.rowOffset)
|
|
146
|
+
parts.push(`OFFSET ${Number(this.rowOffset)}`);
|
|
147
|
+
return bindNamed(parts.join(' '), this.params);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
exports.SqlBuilder = SqlBuilder;
|
|
151
|
+
/**
|
|
152
|
+
* Именованные параметры (`:имя`, перечень — `:...имя`) в нумерованные.
|
|
153
|
+
* Приведение типа `::jsonb` параметром не считается.
|
|
154
|
+
*/
|
|
155
|
+
function bindNamed(text, params) {
|
|
156
|
+
const values = [];
|
|
157
|
+
const bound = text.replace(/(?<![:\w]):(\.\.\.)?([A-Za-z_]\w*)/g, (match, spread, name) => {
|
|
158
|
+
if (!(name in params))
|
|
159
|
+
throw new Error(`SQL parameter :${name} is not provided`);
|
|
160
|
+
const value = params[name];
|
|
161
|
+
if (!spread)
|
|
162
|
+
return `$${values.push(value)}`;
|
|
163
|
+
const list = value;
|
|
164
|
+
// Пустой перечень не подходит ни одной строке.
|
|
165
|
+
if (list.length === 0)
|
|
166
|
+
return 'NULL';
|
|
167
|
+
return list.map((item) => `$${values.push(item)}`).join(', ');
|
|
168
|
+
});
|
|
169
|
+
return { text: bound, values };
|
|
170
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { type Kysely } from 'kysely';
|
|
2
|
+
import { SqlBuilder } from './sql-builder';
|
|
3
|
+
/** Значение колонки пусто. */
|
|
4
|
+
export declare const isNull: () => any;
|
|
5
|
+
/** Значение колонки задано. */
|
|
6
|
+
export declare const notNull: () => any;
|
|
7
|
+
/** Значение колонки не равно заданному. */
|
|
8
|
+
export declare const notEqual: <T>(value: T) => any;
|
|
9
|
+
/** Значение колонки меньше заданного. */
|
|
10
|
+
export declare const lessThan: <T>(value: T) => any;
|
|
11
|
+
/** Значение колонки больше заданного. */
|
|
12
|
+
export declare const moreThan: <T>(value: T) => any;
|
|
13
|
+
/** Значение колонки не больше заданного. */
|
|
14
|
+
export declare const lessOrEqual: <T>(value: T) => any;
|
|
15
|
+
/** Значение колонки не меньше заданного. */
|
|
16
|
+
export declare const moreOrEqual: <T>(value: T) => any;
|
|
17
|
+
/** Значение колонки подходит под шаблон LIKE без учёта регистра. */
|
|
18
|
+
export declare const ilike: (pattern: string) => any;
|
|
19
|
+
/** Значение колонки — одно из перечня. */
|
|
20
|
+
export declare const oneOf: <T>(values: readonly T[]) => any;
|
|
21
|
+
/** Значение колонки в границах (обе включительно); незаданная граница не ограничивает. */
|
|
22
|
+
export declare const within: <T>(from?: T | null, to?: T | null) => any;
|
|
23
|
+
/** Json-колонка содержит заданный фрагмент (оператор `@>`). */
|
|
24
|
+
export declare const contains: (fragment: unknown) => any;
|
|
25
|
+
/** Условие отбора: равенство по полям либо условие из помощников выше; массив — «или». */
|
|
26
|
+
export type Where<TRecord> = {
|
|
27
|
+
[K in keyof TRecord]?: unknown;
|
|
28
|
+
};
|
|
29
|
+
export type WhereInput<TRecord> = Where<TRecord> | Where<TRecord>[];
|
|
30
|
+
export interface FindOptions<TRecord> {
|
|
31
|
+
order?: {
|
|
32
|
+
[K in keyof TRecord]?: 'ASC' | 'DESC';
|
|
33
|
+
};
|
|
34
|
+
limit?: number;
|
|
35
|
+
offset?: number;
|
|
36
|
+
}
|
|
37
|
+
export interface TableStoreOptions<TRecord> {
|
|
38
|
+
table: string;
|
|
39
|
+
/** Поля первичного ключа записи. */
|
|
40
|
+
primaryKey: Array<keyof TRecord & string>;
|
|
41
|
+
/** Поля json/jsonb: при записи сериализуются. */
|
|
42
|
+
json?: Array<keyof TRecord & string>;
|
|
43
|
+
/** Поля numeric/bigint: база отдаёт их строкой, в записи они числа. */
|
|
44
|
+
numbers?: Array<keyof TRecord & string>;
|
|
45
|
+
/** Поля типа `date` (без времени): драйвер отдаёт дату объектом, в записи она строка `ГГГГ-ММ-ДД`. */
|
|
46
|
+
dates?: Array<keyof TRecord & string>;
|
|
47
|
+
/** Поле времени правки: при каждой правке ставится текущее время базы. */
|
|
48
|
+
updatedAt?: keyof TRecord & string;
|
|
49
|
+
/**
|
|
50
|
+
* Поля записи. Из перечня выбирается поле сортировки по запросу клиента, и
|
|
51
|
+
* только поля из него пишутся в базу — подгруженные связи и прочие
|
|
52
|
+
* добавленные к записи поля в запрос не попадают.
|
|
53
|
+
*/
|
|
54
|
+
columns?: Array<keyof TRecord & string>;
|
|
55
|
+
/** Имена колонок совпадают с именами полей (иначе поле `camelCase` — колонка `snake_case`). */
|
|
56
|
+
sameNames?: boolean;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Шлюз одной таблицы для кода, который работает с записями целиком: прочитал,
|
|
60
|
+
* поправил, сохранил (C28-81). Запросы — обычные запросы Kysely; отбор — по
|
|
61
|
+
* равенству полей и простым условиям. Всё сложнее (соединения, агрегаты,
|
|
62
|
+
* подзапросы) пишется в хранилище прямо на Kysely.
|
|
63
|
+
*/
|
|
64
|
+
export declare class TableStore<TRecord extends object> {
|
|
65
|
+
private readonly db;
|
|
66
|
+
private readonly options;
|
|
67
|
+
private readonly json;
|
|
68
|
+
private readonly numbers;
|
|
69
|
+
constructor(db: Kysely<any>, options: TableStoreOptions<TRecord>);
|
|
70
|
+
/** Тот же шлюз на другом соединении — внутри транзакции `inTransaction`. */
|
|
71
|
+
on(db: Kysely<any>): TableStore<TRecord>;
|
|
72
|
+
/** Имя таблицы шлюза. */
|
|
73
|
+
get table(): string;
|
|
74
|
+
/**
|
|
75
|
+
* Поле сортировки по запросу клиента: только из перечня полей записи, иначе
|
|
76
|
+
* умолчание. Имя вне перечня до запроса не доходит.
|
|
77
|
+
*/
|
|
78
|
+
sortField(requested: string | undefined, fallback: keyof TRecord & string): keyof TRecord & string;
|
|
79
|
+
/** Сборщик выборки из фрагментов SQL с именованными параметрами: соединения, подзапросы, агрегаты. */
|
|
80
|
+
sqlBuilder(alias: string): SqlBuilder<TRecord>;
|
|
81
|
+
/** Kysely этого шлюза — для запросов сложнее отбора по равенству. */
|
|
82
|
+
get kysely(): Kysely<any>;
|
|
83
|
+
/** Начало выборки из таблицы шлюза: все колонки, условия дописывает вызывающий. */
|
|
84
|
+
select(): import("kysely").SelectQueryBuilder<any, string, {
|
|
85
|
+
[x: string]: any;
|
|
86
|
+
}>;
|
|
87
|
+
/** Строки базы, полученные своим запросом, в записи шлюза. */
|
|
88
|
+
records(rows: Array<Record<string, unknown>>): TRecord[];
|
|
89
|
+
/** Заготовка записи: обычный объект, в базу не пишется. */
|
|
90
|
+
create(fields: Partial<TRecord>): TRecord;
|
|
91
|
+
findOne(where: WhereInput<TRecord>, options?: FindOptions<TRecord>): Promise<TRecord | null>;
|
|
92
|
+
/** Запись по условию; нет такой — ошибка: вызывающий уверен, что она есть. */
|
|
93
|
+
findOneOrFail(where: WhereInput<TRecord>): Promise<TRecord>;
|
|
94
|
+
find(where?: WhereInput<TRecord>, options?: FindOptions<TRecord>): Promise<TRecord[]>;
|
|
95
|
+
/** Страница записей и общее число подходящих. */
|
|
96
|
+
findAndCount(where?: WhereInput<TRecord>, options?: FindOptions<TRecord>): Promise<[TRecord[], number]>;
|
|
97
|
+
exists(where: WhereInput<TRecord>): Promise<boolean>;
|
|
98
|
+
count(where?: WhereInput<TRecord>): Promise<number>;
|
|
99
|
+
/** Вставка новой записи; возвращает её с ключом и умолчаниями базы. */
|
|
100
|
+
insert(fields: Partial<TRecord>): Promise<TRecord>;
|
|
101
|
+
/**
|
|
102
|
+
* Сохранение записи: с заданным ключом — вставка либо правка существующей,
|
|
103
|
+
* без ключа — вставка. Переданный объект дополняется тем, что вернула база
|
|
104
|
+
* (ключ, даты, умолчания), и возвращается.
|
|
105
|
+
*/
|
|
106
|
+
save(record: Partial<TRecord>): Promise<TRecord>;
|
|
107
|
+
save(records: Array<Partial<TRecord>>): Promise<TRecord[]>;
|
|
108
|
+
/** Сохранение нескольких записей по очереди — каждая как в `save`. */
|
|
109
|
+
saveMany(records: Array<Partial<TRecord>>): Promise<TRecord[]>;
|
|
110
|
+
/** Правка записей по условию; возвращает число затронутых. */
|
|
111
|
+
update(where: WhereInput<TRecord>, patch: Partial<TRecord>): Promise<number>;
|
|
112
|
+
/** Удаление записей по условию; возвращает число удалённых. */
|
|
113
|
+
delete(where: WhereInput<TRecord>): Promise<number>;
|
|
114
|
+
private column;
|
|
115
|
+
/** Значения колонок из полей записи; незаданные поля и поля вне перечня пропускаются. */
|
|
116
|
+
private toRow;
|
|
117
|
+
private toRecord;
|
|
118
|
+
/** Колонки к правке: всё переданное, кроме ключа, плюс время правки. */
|
|
119
|
+
private changes;
|
|
120
|
+
private filter;
|
|
121
|
+
private clause;
|
|
122
|
+
}
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TableStore = exports.contains = exports.within = exports.oneOf = exports.ilike = exports.moreOrEqual = exports.lessOrEqual = exports.moreThan = exports.lessThan = exports.notEqual = exports.notNull = exports.isNull = void 0;
|
|
4
|
+
const kysely_1 = require("kysely");
|
|
5
|
+
const kysely_2 = require("./kysely");
|
|
6
|
+
const sql_builder_1 = require("./sql-builder");
|
|
7
|
+
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
8
|
+
const CONDITION = Symbol('TableStore.Condition');
|
|
9
|
+
const condition = (operator, value) => ({ [CONDITION]: true, operator, value });
|
|
10
|
+
/** Значение колонки пусто. */
|
|
11
|
+
const isNull = () => condition('is null');
|
|
12
|
+
exports.isNull = isNull;
|
|
13
|
+
/** Значение колонки задано. */
|
|
14
|
+
const notNull = () => condition('is not null');
|
|
15
|
+
exports.notNull = notNull;
|
|
16
|
+
/** Значение колонки не равно заданному. */
|
|
17
|
+
const notEqual = (value) => condition('<>', value);
|
|
18
|
+
exports.notEqual = notEqual;
|
|
19
|
+
/** Значение колонки меньше заданного. */
|
|
20
|
+
const lessThan = (value) => condition('<', value);
|
|
21
|
+
exports.lessThan = lessThan;
|
|
22
|
+
/** Значение колонки больше заданного. */
|
|
23
|
+
const moreThan = (value) => condition('>', value);
|
|
24
|
+
exports.moreThan = moreThan;
|
|
25
|
+
/** Значение колонки не больше заданного. */
|
|
26
|
+
const lessOrEqual = (value) => condition('<=', value);
|
|
27
|
+
exports.lessOrEqual = lessOrEqual;
|
|
28
|
+
/** Значение колонки не меньше заданного. */
|
|
29
|
+
const moreOrEqual = (value) => condition('>=', value);
|
|
30
|
+
exports.moreOrEqual = moreOrEqual;
|
|
31
|
+
/** Значение колонки подходит под шаблон LIKE без учёта регистра. */
|
|
32
|
+
const ilike = (pattern) => condition('ilike', pattern);
|
|
33
|
+
exports.ilike = ilike;
|
|
34
|
+
/** Значение колонки — одно из перечня. */
|
|
35
|
+
const oneOf = (values) => condition('in', values);
|
|
36
|
+
exports.oneOf = oneOf;
|
|
37
|
+
/** Значение колонки в границах (обе включительно); незаданная граница не ограничивает. */
|
|
38
|
+
const within = (from, to) => condition('range', [from, to]);
|
|
39
|
+
exports.within = within;
|
|
40
|
+
/** Json-колонка содержит заданный фрагмент (оператор `@>`). */
|
|
41
|
+
const contains = (fragment) => condition('contains', fragment);
|
|
42
|
+
exports.contains = contains;
|
|
43
|
+
const toSnake = (key) => key.replace(/[A-Z]/g, (char) => `_${char.toLowerCase()}`);
|
|
44
|
+
/**
|
|
45
|
+
* Шлюз одной таблицы для кода, который работает с записями целиком: прочитал,
|
|
46
|
+
* поправил, сохранил (C28-81). Запросы — обычные запросы Kysely; отбор — по
|
|
47
|
+
* равенству полей и простым условиям. Всё сложнее (соединения, агрегаты,
|
|
48
|
+
* подзапросы) пишется в хранилище прямо на Kysely.
|
|
49
|
+
*/
|
|
50
|
+
class TableStore {
|
|
51
|
+
db;
|
|
52
|
+
options;
|
|
53
|
+
json;
|
|
54
|
+
numbers;
|
|
55
|
+
constructor(db, options) {
|
|
56
|
+
this.db = db;
|
|
57
|
+
this.options = options;
|
|
58
|
+
this.json = new Set(options.json ?? []);
|
|
59
|
+
this.numbers = options.numbers ?? [];
|
|
60
|
+
}
|
|
61
|
+
/** Тот же шлюз на другом соединении — внутри транзакции `inTransaction`. */
|
|
62
|
+
on(db) {
|
|
63
|
+
return new TableStore(db, this.options);
|
|
64
|
+
}
|
|
65
|
+
/** Имя таблицы шлюза. */
|
|
66
|
+
get table() {
|
|
67
|
+
return this.options.table;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Поле сортировки по запросу клиента: только из перечня полей записи, иначе
|
|
71
|
+
* умолчание. Имя вне перечня до запроса не доходит.
|
|
72
|
+
*/
|
|
73
|
+
sortField(requested, fallback) {
|
|
74
|
+
const known = (this.options.columns ?? []);
|
|
75
|
+
return requested && known.includes(requested) ? requested : fallback;
|
|
76
|
+
}
|
|
77
|
+
/** Сборщик выборки из фрагментов SQL с именованными параметрами: соединения, подзапросы, агрегаты. */
|
|
78
|
+
sqlBuilder(alias) {
|
|
79
|
+
return new sql_builder_1.SqlBuilder({ kysely: this.db, table: this.options.table, primaryKey: this.options.primaryKey.map((field) => this.column(field)), records: (rows) => this.records(rows) }, alias);
|
|
80
|
+
}
|
|
81
|
+
/** Kysely этого шлюза — для запросов сложнее отбора по равенству. */
|
|
82
|
+
get kysely() {
|
|
83
|
+
return this.db;
|
|
84
|
+
}
|
|
85
|
+
/** Начало выборки из таблицы шлюза: все колонки, условия дописывает вызывающий. */
|
|
86
|
+
select() {
|
|
87
|
+
return this.db.selectFrom(this.options.table).selectAll();
|
|
88
|
+
}
|
|
89
|
+
/** Строки базы, полученные своим запросом, в записи шлюза. */
|
|
90
|
+
records(rows) {
|
|
91
|
+
return rows.map((row) => this.toRecord(row));
|
|
92
|
+
}
|
|
93
|
+
/** Заготовка записи: обычный объект, в базу не пишется. */
|
|
94
|
+
create(fields) {
|
|
95
|
+
return { ...fields };
|
|
96
|
+
}
|
|
97
|
+
async findOne(where, options = {}) {
|
|
98
|
+
const [record] = await this.find(where, { ...options, limit: 1 });
|
|
99
|
+
return record ?? null;
|
|
100
|
+
}
|
|
101
|
+
/** Запись по условию; нет такой — ошибка: вызывающий уверен, что она есть. */
|
|
102
|
+
async findOneOrFail(where) {
|
|
103
|
+
const record = await this.findOne(where);
|
|
104
|
+
if (!record)
|
|
105
|
+
throw new Error(`No ${this.options.table} row matches the condition`);
|
|
106
|
+
return record;
|
|
107
|
+
}
|
|
108
|
+
async find(where = {}, options = {}) {
|
|
109
|
+
let query = this.db.selectFrom(this.options.table).selectAll().where((eb) => this.filter(eb, where));
|
|
110
|
+
for (const [field, direction] of Object.entries(options.order ?? {})) {
|
|
111
|
+
// enum-literal: направление сортировки SQL
|
|
112
|
+
query = query.orderBy(this.column(field), direction === 'DESC' ? 'desc' : 'asc');
|
|
113
|
+
}
|
|
114
|
+
if (options.offset)
|
|
115
|
+
query = query.offset(options.offset);
|
|
116
|
+
if (options.limit)
|
|
117
|
+
query = query.limit(options.limit);
|
|
118
|
+
return (await query.execute()).map((row) => this.toRecord(row));
|
|
119
|
+
}
|
|
120
|
+
/** Страница записей и общее число подходящих. */
|
|
121
|
+
async findAndCount(where = {}, options = {}) {
|
|
122
|
+
return [await this.find(where, options), await this.count(where)];
|
|
123
|
+
}
|
|
124
|
+
async exists(where) {
|
|
125
|
+
return (await this.findOne(where)) !== null;
|
|
126
|
+
}
|
|
127
|
+
async count(where = {}) {
|
|
128
|
+
const row = await this.db
|
|
129
|
+
.selectFrom(this.options.table)
|
|
130
|
+
.select((eb) => eb.fn.countAll().as('count'))
|
|
131
|
+
.where((eb) => this.filter(eb, where))
|
|
132
|
+
.executeTakeFirstOrThrow();
|
|
133
|
+
return Number(row.count);
|
|
134
|
+
}
|
|
135
|
+
/** Вставка новой записи; возвращает её с ключом и умолчаниями базы. */
|
|
136
|
+
async insert(fields) {
|
|
137
|
+
const row = await this.db.insertInto(this.options.table).values(this.toRow(fields)).returningAll().executeTakeFirstOrThrow();
|
|
138
|
+
return this.toRecord(row);
|
|
139
|
+
}
|
|
140
|
+
async save(record) {
|
|
141
|
+
// Перечень записей сохраняется по очереди — каждая как одиночная.
|
|
142
|
+
if (Array.isArray(record))
|
|
143
|
+
return this.saveMany(record);
|
|
144
|
+
const row = this.toRow(record);
|
|
145
|
+
const keys = this.options.primaryKey.map((field) => this.column(field));
|
|
146
|
+
const hasKey = keys.every((key) => row[key] !== undefined && row[key] !== null);
|
|
147
|
+
const insert = this.db.insertInto(this.options.table).values(row);
|
|
148
|
+
const saved = await (hasKey
|
|
149
|
+
? insert.onConflict((conflict) => conflict.columns(keys).doUpdateSet(this.changes(row, keys)))
|
|
150
|
+
: insert)
|
|
151
|
+
.returningAll()
|
|
152
|
+
.executeTakeFirstOrThrow();
|
|
153
|
+
return Object.assign(record, this.toRecord(saved));
|
|
154
|
+
}
|
|
155
|
+
/** Сохранение нескольких записей по очереди — каждая как в `save`. */
|
|
156
|
+
async saveMany(records) {
|
|
157
|
+
const saved = [];
|
|
158
|
+
for (const record of records)
|
|
159
|
+
saved.push(await this.save(record));
|
|
160
|
+
return saved;
|
|
161
|
+
}
|
|
162
|
+
/** Правка записей по условию; возвращает число затронутых. */
|
|
163
|
+
async update(where, patch) {
|
|
164
|
+
const result = await this.db
|
|
165
|
+
.updateTable(this.options.table)
|
|
166
|
+
.set(this.changes(this.toRow(patch), []))
|
|
167
|
+
.where((eb) => this.filter(eb, where))
|
|
168
|
+
.execute();
|
|
169
|
+
return (0, kysely_2.affectedCount)(result);
|
|
170
|
+
}
|
|
171
|
+
/** Удаление записей по условию; возвращает число удалённых. */
|
|
172
|
+
async delete(where) {
|
|
173
|
+
const result = await this.db
|
|
174
|
+
.deleteFrom(this.options.table)
|
|
175
|
+
.where((eb) => this.filter(eb, where))
|
|
176
|
+
.execute();
|
|
177
|
+
return (0, kysely_2.affectedCount)(result);
|
|
178
|
+
}
|
|
179
|
+
column(field) {
|
|
180
|
+
return this.options.sameNames ? field : toSnake(field);
|
|
181
|
+
}
|
|
182
|
+
/** Значения колонок из полей записи; незаданные поля и поля вне перечня пропускаются. */
|
|
183
|
+
toRow(fields) {
|
|
184
|
+
const row = {};
|
|
185
|
+
const known = this.options.columns;
|
|
186
|
+
for (const [field, value] of Object.entries(fields)) {
|
|
187
|
+
if (value === undefined)
|
|
188
|
+
continue;
|
|
189
|
+
// Поле вне перечня полей записи в базу не идёт: так подгруженная связь
|
|
190
|
+
// (`attachOne`) не превращается в несуществующую колонку.
|
|
191
|
+
if (known && !known.includes(field))
|
|
192
|
+
continue;
|
|
193
|
+
row[this.column(field)] = this.json.has(field) && value !== null ? JSON.stringify(value) : value;
|
|
194
|
+
}
|
|
195
|
+
return row;
|
|
196
|
+
}
|
|
197
|
+
toRecord(row) {
|
|
198
|
+
const record = (this.options.sameNames ? { ...row } : (0, kysely_2.camelRow)(row));
|
|
199
|
+
for (const field of this.numbers) {
|
|
200
|
+
if (record[field] !== null && record[field] !== undefined)
|
|
201
|
+
record[field] = Number(record[field]);
|
|
202
|
+
}
|
|
203
|
+
for (const field of this.options.dates ?? []) {
|
|
204
|
+
if (record[field] instanceof Date)
|
|
205
|
+
record[field] = dateOnly(record[field]);
|
|
206
|
+
}
|
|
207
|
+
return record;
|
|
208
|
+
}
|
|
209
|
+
/** Колонки к правке: всё переданное, кроме ключа, плюс время правки. */
|
|
210
|
+
changes(row, keys) {
|
|
211
|
+
const set = Object.fromEntries(Object.entries(row).filter(([column]) => !keys.includes(column)));
|
|
212
|
+
if (this.options.updatedAt)
|
|
213
|
+
set[this.column(this.options.updatedAt)] = (0, kysely_1.sql) `now()`;
|
|
214
|
+
// Правка без единого поля — запись остаётся как есть: ключ переписывается сам в себя.
|
|
215
|
+
if (Object.keys(set).length === 0 && keys.length > 0)
|
|
216
|
+
set[keys[0]] = kysely_1.sql.ref(`excluded.${keys[0]}`);
|
|
217
|
+
return set;
|
|
218
|
+
}
|
|
219
|
+
filter(eb, where) {
|
|
220
|
+
const groups = Array.isArray(where) ? where : [where];
|
|
221
|
+
// Незаданное значение условия не даёт — отбор по остальным полям, как у прежней прослойки.
|
|
222
|
+
const clauses = (group) => Object.entries(group)
|
|
223
|
+
.filter(([, value]) => value !== undefined)
|
|
224
|
+
.map(([field, value]) => this.clause(eb, field, value));
|
|
225
|
+
return eb.or(groups.map((group) => eb.and(clauses(group))));
|
|
226
|
+
}
|
|
227
|
+
clause(eb, field, value) {
|
|
228
|
+
const column = this.column(field);
|
|
229
|
+
if (value === null)
|
|
230
|
+
return eb(column, 'is', null);
|
|
231
|
+
if (value !== undefined && typeof value === 'object' && CONDITION in value) {
|
|
232
|
+
const { operator, value: operand } = value;
|
|
233
|
+
if (operator === 'is null')
|
|
234
|
+
return eb(column, 'is', null);
|
|
235
|
+
if (operator === 'is not null')
|
|
236
|
+
return eb(column, 'is not', null);
|
|
237
|
+
if (operator === 'range') {
|
|
238
|
+
const [from, to] = operand;
|
|
239
|
+
const bounds = [];
|
|
240
|
+
if (from !== null && from !== undefined)
|
|
241
|
+
bounds.push(eb(column, '>=', from));
|
|
242
|
+
if (to !== null && to !== undefined)
|
|
243
|
+
bounds.push(eb(column, '<=', to));
|
|
244
|
+
return eb.and(bounds);
|
|
245
|
+
}
|
|
246
|
+
if (operator === 'contains')
|
|
247
|
+
return (0, kysely_1.sql) `${kysely_1.sql.ref(column)} @> ${JSON.stringify(operand)}::jsonb`;
|
|
248
|
+
if (operator === 'in')
|
|
249
|
+
return operand.length ? eb(column, 'in', operand) : (0, kysely_1.sql) `false`;
|
|
250
|
+
return eb(column, operator, operand);
|
|
251
|
+
}
|
|
252
|
+
return eb(column, '=', value);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
exports.TableStore = TableStore;
|
|
256
|
+
/** Дата без времени строкой `ГГГГ-ММ-ДД`: драйвер разбирает её в местную полночь, поэтому берутся местные части. */
|
|
257
|
+
function dateOnly(value) {
|
|
258
|
+
const pad = (part) => String(part).padStart(2, '0');
|
|
259
|
+
return `${value.getFullYear()}-${pad(value.getMonth() + 1)}-${pad(value.getDate())}`;
|
|
260
|
+
}
|