@coopenomics/extension-kit 2026.11.25 → 2026.12.1-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/dist/index.cjs +10 -56
- package/dist/index.d.cts +11 -89
- package/dist/index.d.mts +11 -89
- package/dist/index.d.ts +11 -89
- package/dist/index.mjs +7 -32
- package/dist/sync/index.cjs +9 -11
- package/dist/sync/index.d.cts +1 -1
- package/dist/sync/index.d.mts +1 -1
- package/dist/sync/index.d.ts +1 -1
- package/dist/sync/index.mjs +1 -3
- package/package.json +10 -7
- package/dist/shared/extension-kit.9c3dd9f1.d.cts +0 -196
- package/dist/shared/extension-kit.9c3dd9f1.d.mts +0 -196
- package/dist/shared/extension-kit.9c3dd9f1.d.ts +0 -196
- package/dist/shared/extension-kit.d5437cba.mjs +0 -398
- package/dist/shared/extension-kit.e25d0843.cjs +0 -424
|
@@ -1,196 +0,0 @@
|
|
|
1
|
-
import * as kysely from 'kysely';
|
|
2
|
-
import { Kysely } from 'kysely';
|
|
3
|
-
|
|
4
|
-
type Params = Record<string, unknown>;
|
|
5
|
-
interface BuilderHost<TRecord> {
|
|
6
|
-
kysely: Kysely<any>;
|
|
7
|
-
table: string;
|
|
8
|
-
primaryKey: string[];
|
|
9
|
-
records(rows: Array<Record<string, unknown>>): TRecord[];
|
|
10
|
-
}
|
|
11
|
-
/**
|
|
12
|
-
* Сборщик выборки из готовых фрагментов SQL с именованными параметрами — для
|
|
13
|
-
* запросов, которые яснее читать текстом: соединения таблиц, подзапросы,
|
|
14
|
-
* агрегаты. Значения передаются только параметрами (`:имя`, перечень —
|
|
15
|
-
* `:...имя`); в текст запроса данные вызывающего не подставляются. Исполняет
|
|
16
|
-
* запрос Kysely.
|
|
17
|
-
*
|
|
18
|
-
* ```ts
|
|
19
|
-
* store.sqlBuilder('p').where('p.coopname = :coopname', { coopname }).orderBy('p.created_at', 'DESC').getMany();
|
|
20
|
-
* ```
|
|
21
|
-
*/
|
|
22
|
-
declare class SqlBuilder<TRecord extends object> {
|
|
23
|
-
private readonly host;
|
|
24
|
-
private readonly alias;
|
|
25
|
-
private selections;
|
|
26
|
-
private distinctRows;
|
|
27
|
-
private joins;
|
|
28
|
-
private conditions;
|
|
29
|
-
private groups;
|
|
30
|
-
private orders;
|
|
31
|
-
private rowLimit?;
|
|
32
|
-
private rowOffset?;
|
|
33
|
-
private params;
|
|
34
|
-
constructor(host: BuilderHost<TRecord>, alias: string);
|
|
35
|
-
/** Выбираемое выражение; псевдоним таблицы целиком — все её колонки (так и по умолчанию). */
|
|
36
|
-
select(expression: string | string[], as?: string): this;
|
|
37
|
-
/**
|
|
38
|
-
* Колонка без своего имени (`te.issue_hash`) в сырой выборке называется
|
|
39
|
-
* `te_issue_hash` — по псевдониму таблицы и имени колонки.
|
|
40
|
-
*/
|
|
41
|
-
addSelect(expression: string | string[], as?: string): this;
|
|
42
|
-
distinct(enabled?: boolean): this;
|
|
43
|
-
innerJoin(table: string, alias: string, on: string, params?: Params): this;
|
|
44
|
-
leftJoin(table: string, alias: string, on: string, params?: Params): this;
|
|
45
|
-
where(condition: string, params?: Params): this;
|
|
46
|
-
andWhere(condition: string, params?: Params): this;
|
|
47
|
-
groupBy(expression: string): this;
|
|
48
|
-
addGroupBy(expression: string): this;
|
|
49
|
-
orderBy(expression: string, direction?: 'ASC' | 'DESC'): this;
|
|
50
|
-
addOrderBy(expression: string, direction?: 'ASC' | 'DESC'): this;
|
|
51
|
-
limit(count?: number): this;
|
|
52
|
-
offset(count?: number): this;
|
|
53
|
-
/** Записи таблицы сборщика. */
|
|
54
|
-
getMany(): Promise<TRecord[]>;
|
|
55
|
-
getOne(): Promise<TRecord | null>;
|
|
56
|
-
/** Число записей таблицы сборщика под условиями; соединения запись не размножают. */
|
|
57
|
-
getCount(): Promise<number>;
|
|
58
|
-
getManyAndCount(): Promise<[TRecord[], number]>;
|
|
59
|
-
/** Строки как есть — для выражений из `select`. */
|
|
60
|
-
getRawMany<TRow = any>(): Promise<TRow[]>;
|
|
61
|
-
getRawOne<TRow = any>(): Promise<TRow | undefined>;
|
|
62
|
-
private join;
|
|
63
|
-
private compile;
|
|
64
|
-
}
|
|
65
|
-
/**
|
|
66
|
-
* Именованные параметры (`:имя`, перечень — `:...имя`) в нумерованные.
|
|
67
|
-
* Приведение типа `::jsonb` параметром не считается.
|
|
68
|
-
*/
|
|
69
|
-
declare function bindNamed(text: string, params: Params): {
|
|
70
|
-
text: string;
|
|
71
|
-
values: unknown[];
|
|
72
|
-
};
|
|
73
|
-
|
|
74
|
-
/** Значение колонки пусто. */
|
|
75
|
-
declare const isNull: () => any;
|
|
76
|
-
/** Значение колонки задано. */
|
|
77
|
-
declare const notNull: () => any;
|
|
78
|
-
/** Значение колонки не равно заданному. */
|
|
79
|
-
declare const notEqual: <T>(value: T) => any;
|
|
80
|
-
/** Значение колонки меньше заданного. */
|
|
81
|
-
declare const lessThan: <T>(value: T) => any;
|
|
82
|
-
/** Значение колонки больше заданного. */
|
|
83
|
-
declare const moreThan: <T>(value: T) => any;
|
|
84
|
-
/** Значение колонки не больше заданного. */
|
|
85
|
-
declare const lessOrEqual: <T>(value: T) => any;
|
|
86
|
-
/** Значение колонки не меньше заданного. */
|
|
87
|
-
declare const moreOrEqual: <T>(value: T) => any;
|
|
88
|
-
/** Значение колонки подходит под шаблон LIKE без учёта регистра. */
|
|
89
|
-
declare const ilike: (pattern: string) => any;
|
|
90
|
-
/** Значение колонки — одно из перечня. */
|
|
91
|
-
declare const oneOf: <T>(values: readonly T[]) => any;
|
|
92
|
-
/** Значение колонки в границах (обе включительно); незаданная граница не ограничивает. */
|
|
93
|
-
declare const within: <T>(from?: T | null, to?: T | null) => any;
|
|
94
|
-
/** Json-колонка содержит заданный фрагмент (оператор `@>`). */
|
|
95
|
-
declare const contains: (fragment: unknown) => any;
|
|
96
|
-
/** Условие отбора: равенство по полям либо условие из помощников выше; массив — «или». */
|
|
97
|
-
type Where<TRecord> = {
|
|
98
|
-
[K in keyof TRecord]?: unknown;
|
|
99
|
-
};
|
|
100
|
-
type WhereInput<TRecord> = Where<TRecord> | Where<TRecord>[];
|
|
101
|
-
interface FindOptions<TRecord> {
|
|
102
|
-
order?: {
|
|
103
|
-
[K in keyof TRecord]?: 'ASC' | 'DESC';
|
|
104
|
-
};
|
|
105
|
-
limit?: number;
|
|
106
|
-
offset?: number;
|
|
107
|
-
}
|
|
108
|
-
interface TableStoreOptions<TRecord> {
|
|
109
|
-
table: string;
|
|
110
|
-
/** Поля первичного ключа записи. */
|
|
111
|
-
primaryKey: Array<keyof TRecord & string>;
|
|
112
|
-
/** Поля json/jsonb: при записи сериализуются. */
|
|
113
|
-
json?: Array<keyof TRecord & string>;
|
|
114
|
-
/** Поля numeric/bigint: база отдаёт их строкой, в записи они числа. */
|
|
115
|
-
numbers?: Array<keyof TRecord & string>;
|
|
116
|
-
/** Поля типа `date` (без времени): драйвер отдаёт дату объектом, в записи она строка `ГГГГ-ММ-ДД`. */
|
|
117
|
-
dates?: Array<keyof TRecord & string>;
|
|
118
|
-
/** Поле времени правки: при каждой правке ставится текущее время базы. */
|
|
119
|
-
updatedAt?: keyof TRecord & string;
|
|
120
|
-
/**
|
|
121
|
-
* Поля записи. Из перечня выбирается поле сортировки по запросу клиента, и
|
|
122
|
-
* только поля из него пишутся в базу — подгруженные связи и прочие
|
|
123
|
-
* добавленные к записи поля в запрос не попадают.
|
|
124
|
-
*/
|
|
125
|
-
columns?: Array<keyof TRecord & string>;
|
|
126
|
-
/** Имена колонок совпадают с именами полей (иначе поле `camelCase` — колонка `snake_case`). */
|
|
127
|
-
sameNames?: boolean;
|
|
128
|
-
}
|
|
129
|
-
/**
|
|
130
|
-
* Шлюз одной таблицы для кода, который работает с записями целиком: прочитал,
|
|
131
|
-
* поправил, сохранил (C28-81). Запросы — обычные запросы Kysely; отбор — по
|
|
132
|
-
* равенству полей и простым условиям. Всё сложнее (соединения, агрегаты,
|
|
133
|
-
* подзапросы) пишется в хранилище прямо на Kysely.
|
|
134
|
-
*/
|
|
135
|
-
declare class TableStore<TRecord extends object> {
|
|
136
|
-
private readonly db;
|
|
137
|
-
private readonly options;
|
|
138
|
-
private readonly json;
|
|
139
|
-
private readonly numbers;
|
|
140
|
-
constructor(db: Kysely<any>, options: TableStoreOptions<TRecord>);
|
|
141
|
-
/** Тот же шлюз на другом соединении — внутри транзакции `inTransaction`. */
|
|
142
|
-
on(db: Kysely<any>): TableStore<TRecord>;
|
|
143
|
-
/** Имя таблицы шлюза. */
|
|
144
|
-
get table(): string;
|
|
145
|
-
/**
|
|
146
|
-
* Поле сортировки по запросу клиента: только из перечня полей записи, иначе
|
|
147
|
-
* умолчание. Имя вне перечня до запроса не доходит.
|
|
148
|
-
*/
|
|
149
|
-
sortField(requested: string | undefined, fallback: keyof TRecord & string): keyof TRecord & string;
|
|
150
|
-
/** Сборщик выборки из фрагментов SQL с именованными параметрами: соединения, подзапросы, агрегаты. */
|
|
151
|
-
sqlBuilder(alias: string): SqlBuilder<TRecord>;
|
|
152
|
-
/** Kysely этого шлюза — для запросов сложнее отбора по равенству. */
|
|
153
|
-
get kysely(): Kysely<any>;
|
|
154
|
-
/** Начало выборки из таблицы шлюза: все колонки, условия дописывает вызывающий. */
|
|
155
|
-
select(): kysely.SelectQueryBuilder<any, string, {
|
|
156
|
-
[x: string]: any;
|
|
157
|
-
}>;
|
|
158
|
-
/** Строки базы, полученные своим запросом, в записи шлюза. */
|
|
159
|
-
records(rows: Array<Record<string, unknown>>): TRecord[];
|
|
160
|
-
/** Заготовка записи: обычный объект, в базу не пишется. */
|
|
161
|
-
create(fields: Partial<TRecord>): TRecord;
|
|
162
|
-
findOne(where: WhereInput<TRecord>, options?: FindOptions<TRecord>): Promise<TRecord | null>;
|
|
163
|
-
/** Запись по условию; нет такой — ошибка: вызывающий уверен, что она есть. */
|
|
164
|
-
findOneOrFail(where: WhereInput<TRecord>): Promise<TRecord>;
|
|
165
|
-
find(where?: WhereInput<TRecord>, options?: FindOptions<TRecord>): Promise<TRecord[]>;
|
|
166
|
-
/** Страница записей и общее число подходящих. */
|
|
167
|
-
findAndCount(where?: WhereInput<TRecord>, options?: FindOptions<TRecord>): Promise<[TRecord[], number]>;
|
|
168
|
-
exists(where: WhereInput<TRecord>): Promise<boolean>;
|
|
169
|
-
count(where?: WhereInput<TRecord>): Promise<number>;
|
|
170
|
-
/** Вставка новой записи; возвращает её с ключом и умолчаниями базы. */
|
|
171
|
-
insert(fields: Partial<TRecord>): Promise<TRecord>;
|
|
172
|
-
/**
|
|
173
|
-
* Сохранение записи: с заданным ключом — вставка либо правка существующей,
|
|
174
|
-
* без ключа — вставка. Переданный объект дополняется тем, что вернула база
|
|
175
|
-
* (ключ, даты, умолчания), и возвращается.
|
|
176
|
-
*/
|
|
177
|
-
save(record: Partial<TRecord>): Promise<TRecord>;
|
|
178
|
-
save(records: Array<Partial<TRecord>>): Promise<TRecord[]>;
|
|
179
|
-
/** Сохранение нескольких записей по очереди — каждая как в `save`. */
|
|
180
|
-
saveMany(records: Array<Partial<TRecord>>): Promise<TRecord[]>;
|
|
181
|
-
/** Правка записей по условию; возвращает число затронутых. */
|
|
182
|
-
update(where: WhereInput<TRecord>, patch: Partial<TRecord>): Promise<number>;
|
|
183
|
-
/** Удаление записей по условию; возвращает число удалённых. */
|
|
184
|
-
delete(where: WhereInput<TRecord>): Promise<number>;
|
|
185
|
-
private column;
|
|
186
|
-
/** Значения колонок из полей записи; незаданные поля и поля вне перечня пропускаются. */
|
|
187
|
-
private toRow;
|
|
188
|
-
private toRecord;
|
|
189
|
-
/** Колонки к правке: всё переданное, кроме ключа, плюс время правки. */
|
|
190
|
-
private changes;
|
|
191
|
-
private filter;
|
|
192
|
-
private clause;
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
export { SqlBuilder as S, TableStore as T, notEqual as a, lessOrEqual as b, moreOrEqual as c, ilike as d, contains as e, bindNamed as h, isNull as i, lessThan as l, moreThan as m, notNull as n, oneOf as o, within as w };
|
|
196
|
-
export type { FindOptions as F, Where as W, WhereInput as f, TableStoreOptions as g };
|
|
@@ -1,398 +0,0 @@
|
|
|
1
|
-
import { CompiledQuery, sql } from 'kysely';
|
|
2
|
-
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
3
|
-
|
|
4
|
-
const KYSELY = Symbol.for("Controller.Database.Kysely");
|
|
5
|
-
function sortColumn(allowed, requested, fallback) {
|
|
6
|
-
return allowed.includes(requested) ? requested : fallback;
|
|
7
|
-
}
|
|
8
|
-
function sortDirection(requested, fallback = "desc") {
|
|
9
|
-
const value = typeof requested === "string" ? requested.toUpperCase() : "";
|
|
10
|
-
if (value === "ASC")
|
|
11
|
-
return "asc";
|
|
12
|
-
if (value === "DESC")
|
|
13
|
-
return "desc";
|
|
14
|
-
return fallback;
|
|
15
|
-
}
|
|
16
|
-
async function rawQuery(db, text, parameters = []) {
|
|
17
|
-
const result = await db.executeQuery(CompiledQuery.raw(text, [...parameters]));
|
|
18
|
-
return result.rows;
|
|
19
|
-
}
|
|
20
|
-
const toCamel = (key) => key.replace(/_([a-z0-9])/g, (_, char) => char.toUpperCase());
|
|
21
|
-
const toSnake$1 = (key) => key.replace(/[A-Z]/g, (char) => `_${char.toLowerCase()}`);
|
|
22
|
-
function camelRow(row) {
|
|
23
|
-
return Object.fromEntries(Object.entries(row).map(([key, value]) => [toCamel(key), value]));
|
|
24
|
-
}
|
|
25
|
-
function snakeRow(fields) {
|
|
26
|
-
return Object.fromEntries(
|
|
27
|
-
Object.entries(fields).filter(([, value]) => value !== void 0).map(([key, value]) => [toSnake$1(key), value])
|
|
28
|
-
);
|
|
29
|
-
}
|
|
30
|
-
function affectedCount(results) {
|
|
31
|
-
const [first] = results;
|
|
32
|
-
const summary = first;
|
|
33
|
-
const counted = summary?.numDeletedRows ?? summary?.numUpdatedRows;
|
|
34
|
-
if (results.length === 1 && typeof counted === "bigint")
|
|
35
|
-
return Number(counted);
|
|
36
|
-
return results.length;
|
|
37
|
-
}
|
|
38
|
-
const MAIN_DATABASE = Symbol.for("Controller.Database.Main");
|
|
39
|
-
|
|
40
|
-
class SqlBuilder {
|
|
41
|
-
constructor(host, alias) {
|
|
42
|
-
this.host = host;
|
|
43
|
-
this.alias = alias;
|
|
44
|
-
this.selections = [];
|
|
45
|
-
this.distinctRows = false;
|
|
46
|
-
this.joins = [];
|
|
47
|
-
this.conditions = [];
|
|
48
|
-
this.groups = [];
|
|
49
|
-
this.orders = [];
|
|
50
|
-
this.params = {};
|
|
51
|
-
}
|
|
52
|
-
/** Выбираемое выражение; псевдоним таблицы целиком — все её колонки (так и по умолчанию). */
|
|
53
|
-
select(expression, as) {
|
|
54
|
-
this.selections = [];
|
|
55
|
-
return this.addSelect(expression, as);
|
|
56
|
-
}
|
|
57
|
-
/**
|
|
58
|
-
* Колонка без своего имени (`te.issue_hash`) в сырой выборке называется
|
|
59
|
-
* `te_issue_hash` — по псевдониму таблицы и имени колонки.
|
|
60
|
-
*/
|
|
61
|
-
addSelect(expression, as) {
|
|
62
|
-
for (const item of Array.isArray(expression) ? expression : [expression]) {
|
|
63
|
-
if (item === this.alias)
|
|
64
|
-
continue;
|
|
65
|
-
const column = /^(\w+)\.(\w+)$/.exec(item);
|
|
66
|
-
const name = as ?? (column ? `${column[1]}_${column[2]}` : void 0);
|
|
67
|
-
this.selections.push(name ? `${item} AS "${name}"` : item);
|
|
68
|
-
}
|
|
69
|
-
return this;
|
|
70
|
-
}
|
|
71
|
-
distinct(enabled = true) {
|
|
72
|
-
this.distinctRows = enabled;
|
|
73
|
-
return this;
|
|
74
|
-
}
|
|
75
|
-
innerJoin(table, alias, on, params = {}) {
|
|
76
|
-
return this.join("INNER", table, alias, on, params);
|
|
77
|
-
}
|
|
78
|
-
leftJoin(table, alias, on, params = {}) {
|
|
79
|
-
return this.join("LEFT", table, alias, on, params);
|
|
80
|
-
}
|
|
81
|
-
where(condition, params = {}) {
|
|
82
|
-
this.conditions = [];
|
|
83
|
-
return this.andWhere(condition, params);
|
|
84
|
-
}
|
|
85
|
-
andWhere(condition, params = {}) {
|
|
86
|
-
this.conditions.push(`(${condition})`);
|
|
87
|
-
Object.assign(this.params, params);
|
|
88
|
-
return this;
|
|
89
|
-
}
|
|
90
|
-
groupBy(expression) {
|
|
91
|
-
this.groups = [expression];
|
|
92
|
-
return this;
|
|
93
|
-
}
|
|
94
|
-
addGroupBy(expression) {
|
|
95
|
-
this.groups.push(expression);
|
|
96
|
-
return this;
|
|
97
|
-
}
|
|
98
|
-
orderBy(expression, direction = "ASC") {
|
|
99
|
-
this.orders = [];
|
|
100
|
-
return this.addOrderBy(expression, direction);
|
|
101
|
-
}
|
|
102
|
-
addOrderBy(expression, direction = "ASC") {
|
|
103
|
-
this.orders.push(`${expression} ${direction === "DESC" ? "DESC" : "ASC"}`);
|
|
104
|
-
return this;
|
|
105
|
-
}
|
|
106
|
-
limit(count) {
|
|
107
|
-
this.rowLimit = count;
|
|
108
|
-
return this;
|
|
109
|
-
}
|
|
110
|
-
offset(count) {
|
|
111
|
-
this.rowOffset = count;
|
|
112
|
-
return this;
|
|
113
|
-
}
|
|
114
|
-
/** Записи таблицы сборщика. */
|
|
115
|
-
async getMany() {
|
|
116
|
-
const { text, values } = this.compile(`${this.distinctRows ? "DISTINCT " : ""}${this.alias}.*`, true);
|
|
117
|
-
return this.host.records(await rawQuery(this.host.kysely, text, values));
|
|
118
|
-
}
|
|
119
|
-
async getOne() {
|
|
120
|
-
const saved = this.rowLimit;
|
|
121
|
-
this.rowLimit = 1;
|
|
122
|
-
const [record] = await this.getMany();
|
|
123
|
-
this.rowLimit = saved;
|
|
124
|
-
return record ?? null;
|
|
125
|
-
}
|
|
126
|
-
/** Число записей таблицы сборщика под условиями; соединения запись не размножают. */
|
|
127
|
-
async getCount() {
|
|
128
|
-
const key = this.host.primaryKey.map((column) => `${this.alias}."${column}"`).join(", ");
|
|
129
|
-
const { text, values } = this.compile(`COUNT(DISTINCT (${key})) AS count`, false);
|
|
130
|
-
const [row] = await rawQuery(this.host.kysely, text, values);
|
|
131
|
-
return Number(row?.count ?? 0);
|
|
132
|
-
}
|
|
133
|
-
async getManyAndCount() {
|
|
134
|
-
return [await this.getMany(), await this.getCount()];
|
|
135
|
-
}
|
|
136
|
-
/** Строки как есть — для выражений из `select`. */
|
|
137
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
138
|
-
async getRawMany() {
|
|
139
|
-
const selection = `${this.distinctRows ? "DISTINCT " : ""}${this.selections.length ? this.selections.join(", ") : `${this.alias}.*`}`;
|
|
140
|
-
const { text, values } = this.compile(selection, true);
|
|
141
|
-
return rawQuery(this.host.kysely, text, values);
|
|
142
|
-
}
|
|
143
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
144
|
-
async getRawOne() {
|
|
145
|
-
const [row] = await this.getRawMany();
|
|
146
|
-
return row;
|
|
147
|
-
}
|
|
148
|
-
join(kind, table, alias, on, params) {
|
|
149
|
-
this.joins.push(`${kind} JOIN ${table} ${alias} ON ${on}`);
|
|
150
|
-
Object.assign(this.params, params);
|
|
151
|
-
return this;
|
|
152
|
-
}
|
|
153
|
-
compile(selection, page) {
|
|
154
|
-
const parts = [`SELECT ${selection} FROM ${this.host.table} ${this.alias}`, ...this.joins];
|
|
155
|
-
if (this.conditions.length)
|
|
156
|
-
parts.push(`WHERE ${this.conditions.join(" AND ")}`);
|
|
157
|
-
if (this.groups.length)
|
|
158
|
-
parts.push(`GROUP BY ${this.groups.join(", ")}`);
|
|
159
|
-
if (page && this.orders.length)
|
|
160
|
-
parts.push(`ORDER BY ${this.orders.join(", ")}`);
|
|
161
|
-
if (page && this.rowLimit !== void 0)
|
|
162
|
-
parts.push(`LIMIT ${Number(this.rowLimit)}`);
|
|
163
|
-
if (page && this.rowOffset)
|
|
164
|
-
parts.push(`OFFSET ${Number(this.rowOffset)}`);
|
|
165
|
-
return bindNamed(parts.join(" "), this.params);
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
function bindNamed(text, params) {
|
|
169
|
-
const values = [];
|
|
170
|
-
const bound = text.replace(/(?<![:\w]):(\.\.\.)?([A-Za-z_]\w*)/g, (match, spread, name) => {
|
|
171
|
-
if (!(name in params))
|
|
172
|
-
throw new Error(`SQL parameter :${name} is not provided`);
|
|
173
|
-
const value = params[name];
|
|
174
|
-
if (!spread)
|
|
175
|
-
return `$${values.push(value)}`;
|
|
176
|
-
const list = value;
|
|
177
|
-
if (list.length === 0)
|
|
178
|
-
return "NULL";
|
|
179
|
-
return list.map((item) => `$${values.push(item)}`).join(", ");
|
|
180
|
-
});
|
|
181
|
-
return { text: bound, values };
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
const CONDITION = Symbol("TableStore.Condition");
|
|
185
|
-
const condition = (operator, value) => ({ [CONDITION]: true, operator, value });
|
|
186
|
-
const isNull = () => condition("is null");
|
|
187
|
-
const notNull = () => condition("is not null");
|
|
188
|
-
const notEqual = (value) => condition("<>", value);
|
|
189
|
-
const lessThan = (value) => condition("<", value);
|
|
190
|
-
const moreThan = (value) => condition(">", value);
|
|
191
|
-
const lessOrEqual = (value) => condition("<=", value);
|
|
192
|
-
const moreOrEqual = (value) => condition(">=", value);
|
|
193
|
-
const ilike = (pattern) => condition("ilike", pattern);
|
|
194
|
-
const oneOf = (values) => condition("in", values);
|
|
195
|
-
const within = (from, to) => condition("range", [from, to]);
|
|
196
|
-
const contains = (fragment) => condition("contains", fragment);
|
|
197
|
-
const toSnake = (key) => key.replace(/[A-Z]/g, (char) => `_${char.toLowerCase()}`);
|
|
198
|
-
class TableStore {
|
|
199
|
-
constructor(db, options) {
|
|
200
|
-
this.db = db;
|
|
201
|
-
this.options = options;
|
|
202
|
-
this.json = new Set(options.json ?? []);
|
|
203
|
-
this.numbers = options.numbers ?? [];
|
|
204
|
-
}
|
|
205
|
-
/** Тот же шлюз на другом соединении — внутри транзакции `inTransaction`. */
|
|
206
|
-
on(db) {
|
|
207
|
-
return new TableStore(db, this.options);
|
|
208
|
-
}
|
|
209
|
-
/** Имя таблицы шлюза. */
|
|
210
|
-
get table() {
|
|
211
|
-
return this.options.table;
|
|
212
|
-
}
|
|
213
|
-
/**
|
|
214
|
-
* Поле сортировки по запросу клиента: только из перечня полей записи, иначе
|
|
215
|
-
* умолчание. Имя вне перечня до запроса не доходит.
|
|
216
|
-
*/
|
|
217
|
-
sortField(requested, fallback) {
|
|
218
|
-
const known = this.options.columns ?? [];
|
|
219
|
-
return requested && known.includes(requested) ? requested : fallback;
|
|
220
|
-
}
|
|
221
|
-
/** Сборщик выборки из фрагментов SQL с именованными параметрами: соединения, подзапросы, агрегаты. */
|
|
222
|
-
sqlBuilder(alias) {
|
|
223
|
-
return new SqlBuilder(
|
|
224
|
-
{ kysely: this.db, table: this.options.table, primaryKey: this.options.primaryKey.map((field) => this.column(field)), records: (rows) => this.records(rows) },
|
|
225
|
-
alias
|
|
226
|
-
);
|
|
227
|
-
}
|
|
228
|
-
/** Kysely этого шлюза — для запросов сложнее отбора по равенству. */
|
|
229
|
-
get kysely() {
|
|
230
|
-
return this.db;
|
|
231
|
-
}
|
|
232
|
-
/** Начало выборки из таблицы шлюза: все колонки, условия дописывает вызывающий. */
|
|
233
|
-
select() {
|
|
234
|
-
return this.db.selectFrom(this.options.table).selectAll();
|
|
235
|
-
}
|
|
236
|
-
/** Строки базы, полученные своим запросом, в записи шлюза. */
|
|
237
|
-
records(rows) {
|
|
238
|
-
return rows.map((row) => this.toRecord(row));
|
|
239
|
-
}
|
|
240
|
-
/** Заготовка записи: обычный объект, в базу не пишется. */
|
|
241
|
-
create(fields) {
|
|
242
|
-
return { ...fields };
|
|
243
|
-
}
|
|
244
|
-
async findOne(where, options = {}) {
|
|
245
|
-
const [record] = await this.find(where, { ...options, limit: 1 });
|
|
246
|
-
return record ?? null;
|
|
247
|
-
}
|
|
248
|
-
/** Запись по условию; нет такой — ошибка: вызывающий уверен, что она есть. */
|
|
249
|
-
async findOneOrFail(where) {
|
|
250
|
-
const record = await this.findOne(where);
|
|
251
|
-
if (!record)
|
|
252
|
-
throw new Error(`No ${this.options.table} row matches the condition`);
|
|
253
|
-
return record;
|
|
254
|
-
}
|
|
255
|
-
async find(where = {}, options = {}) {
|
|
256
|
-
let query = this.db.selectFrom(this.options.table).selectAll().where((eb) => this.filter(eb, where));
|
|
257
|
-
for (const [field, direction] of Object.entries(options.order ?? {})) {
|
|
258
|
-
query = query.orderBy(this.column(field), direction === "DESC" ? "desc" : "asc");
|
|
259
|
-
}
|
|
260
|
-
if (options.offset)
|
|
261
|
-
query = query.offset(options.offset);
|
|
262
|
-
if (options.limit)
|
|
263
|
-
query = query.limit(options.limit);
|
|
264
|
-
return (await query.execute()).map((row) => this.toRecord(row));
|
|
265
|
-
}
|
|
266
|
-
/** Страница записей и общее число подходящих. */
|
|
267
|
-
async findAndCount(where = {}, options = {}) {
|
|
268
|
-
return [await this.find(where, options), await this.count(where)];
|
|
269
|
-
}
|
|
270
|
-
async exists(where) {
|
|
271
|
-
return await this.findOne(where) !== null;
|
|
272
|
-
}
|
|
273
|
-
async count(where = {}) {
|
|
274
|
-
const row = await this.db.selectFrom(this.options.table).select((eb) => eb.fn.countAll().as("count")).where((eb) => this.filter(eb, where)).executeTakeFirstOrThrow();
|
|
275
|
-
return Number(row.count);
|
|
276
|
-
}
|
|
277
|
-
/** Вставка новой записи; возвращает её с ключом и умолчаниями базы. */
|
|
278
|
-
async insert(fields) {
|
|
279
|
-
const row = await this.db.insertInto(this.options.table).values(this.toRow(fields)).returningAll().executeTakeFirstOrThrow();
|
|
280
|
-
return this.toRecord(row);
|
|
281
|
-
}
|
|
282
|
-
async save(record) {
|
|
283
|
-
if (Array.isArray(record))
|
|
284
|
-
return this.saveMany(record);
|
|
285
|
-
const row = this.toRow(record);
|
|
286
|
-
const keys = this.options.primaryKey.map((field) => this.column(field));
|
|
287
|
-
const hasKey = keys.every((key) => row[key] !== void 0 && row[key] !== null);
|
|
288
|
-
const insert = this.db.insertInto(this.options.table).values(row);
|
|
289
|
-
const saved = await (hasKey ? insert.onConflict((conflict) => conflict.columns(keys).doUpdateSet(this.changes(row, keys))) : insert).returningAll().executeTakeFirstOrThrow();
|
|
290
|
-
return Object.assign(record, this.toRecord(saved));
|
|
291
|
-
}
|
|
292
|
-
/** Сохранение нескольких записей по очереди — каждая как в `save`. */
|
|
293
|
-
async saveMany(records) {
|
|
294
|
-
const saved = [];
|
|
295
|
-
for (const record of records)
|
|
296
|
-
saved.push(await this.save(record));
|
|
297
|
-
return saved;
|
|
298
|
-
}
|
|
299
|
-
/** Правка записей по условию; возвращает число затронутых. */
|
|
300
|
-
async update(where, patch) {
|
|
301
|
-
const result = await this.db.updateTable(this.options.table).set(this.changes(this.toRow(patch), [])).where((eb) => this.filter(eb, where)).execute();
|
|
302
|
-
return affectedCount(result);
|
|
303
|
-
}
|
|
304
|
-
/** Удаление записей по условию; возвращает число удалённых. */
|
|
305
|
-
async delete(where) {
|
|
306
|
-
const result = await this.db.deleteFrom(this.options.table).where((eb) => this.filter(eb, where)).execute();
|
|
307
|
-
return affectedCount(result);
|
|
308
|
-
}
|
|
309
|
-
column(field) {
|
|
310
|
-
return this.options.sameNames ? field : toSnake(field);
|
|
311
|
-
}
|
|
312
|
-
/** Значения колонок из полей записи; незаданные поля и поля вне перечня пропускаются. */
|
|
313
|
-
toRow(fields) {
|
|
314
|
-
const row = {};
|
|
315
|
-
const known = this.options.columns;
|
|
316
|
-
for (const [field, value] of Object.entries(fields)) {
|
|
317
|
-
if (value === void 0)
|
|
318
|
-
continue;
|
|
319
|
-
if (known && !known.includes(field))
|
|
320
|
-
continue;
|
|
321
|
-
row[this.column(field)] = this.json.has(field) && value !== null ? JSON.stringify(value) : value;
|
|
322
|
-
}
|
|
323
|
-
return row;
|
|
324
|
-
}
|
|
325
|
-
toRecord(row) {
|
|
326
|
-
const record = this.options.sameNames ? { ...row } : camelRow(row);
|
|
327
|
-
for (const field of this.numbers) {
|
|
328
|
-
if (record[field] !== null && record[field] !== void 0)
|
|
329
|
-
record[field] = Number(record[field]);
|
|
330
|
-
}
|
|
331
|
-
for (const field of this.options.dates ?? []) {
|
|
332
|
-
if (record[field] instanceof Date)
|
|
333
|
-
record[field] = dateOnly(record[field]);
|
|
334
|
-
}
|
|
335
|
-
return record;
|
|
336
|
-
}
|
|
337
|
-
/** Колонки к правке: всё переданное, кроме ключа, плюс время правки. */
|
|
338
|
-
changes(row, keys) {
|
|
339
|
-
const set = Object.fromEntries(Object.entries(row).filter(([column]) => !keys.includes(column)));
|
|
340
|
-
if (this.options.updatedAt)
|
|
341
|
-
set[this.column(this.options.updatedAt)] = sql`now()`;
|
|
342
|
-
if (Object.keys(set).length === 0 && keys.length > 0)
|
|
343
|
-
set[keys[0]] = sql.ref(`excluded.${keys[0]}`);
|
|
344
|
-
return set;
|
|
345
|
-
}
|
|
346
|
-
filter(eb, where) {
|
|
347
|
-
const groups = Array.isArray(where) ? where : [where];
|
|
348
|
-
const clauses = (group) => Object.entries(group).filter(([, value]) => value !== void 0).map(([field, value]) => this.clause(eb, field, value));
|
|
349
|
-
return eb.or(groups.map((group) => eb.and(clauses(group))));
|
|
350
|
-
}
|
|
351
|
-
clause(eb, field, value) {
|
|
352
|
-
const column = this.column(field);
|
|
353
|
-
if (value === null)
|
|
354
|
-
return eb(column, "is", null);
|
|
355
|
-
if (value !== void 0 && typeof value === "object" && CONDITION in value) {
|
|
356
|
-
const { operator, value: operand } = value;
|
|
357
|
-
if (operator === "is null")
|
|
358
|
-
return eb(column, "is", null);
|
|
359
|
-
if (operator === "is not null")
|
|
360
|
-
return eb(column, "is not", null);
|
|
361
|
-
if (operator === "range") {
|
|
362
|
-
const [from, to] = operand;
|
|
363
|
-
const bounds = [];
|
|
364
|
-
if (from !== null && from !== void 0)
|
|
365
|
-
bounds.push(eb(column, ">=", from));
|
|
366
|
-
if (to !== null && to !== void 0)
|
|
367
|
-
bounds.push(eb(column, "<=", to));
|
|
368
|
-
return eb.and(bounds);
|
|
369
|
-
}
|
|
370
|
-
if (operator === "contains")
|
|
371
|
-
return sql`${sql.ref(column)} @> ${JSON.stringify(operand)}::jsonb`;
|
|
372
|
-
if (operator === "in")
|
|
373
|
-
return operand.length ? eb(column, "in", operand) : sql`false`;
|
|
374
|
-
return eb(column, operator, operand);
|
|
375
|
-
}
|
|
376
|
-
return eb(column, "=", value);
|
|
377
|
-
}
|
|
378
|
-
}
|
|
379
|
-
function dateOnly(value) {
|
|
380
|
-
const pad = (part) => String(part).padStart(2, "0");
|
|
381
|
-
return `${value.getFullYear()}-${pad(value.getMonth() + 1)}-${pad(value.getDate())}`;
|
|
382
|
-
}
|
|
383
|
-
|
|
384
|
-
const STATE_KEY = Symbol.for("Controller.Database.Transaction");
|
|
385
|
-
const globals = globalThis;
|
|
386
|
-
const state = globals[STATE_KEY] ??= { pending: new AsyncLocalStorage() };
|
|
387
|
-
const pendingLocalChanges = state.pending;
|
|
388
|
-
function configureLocalChangePublisher(publish) {
|
|
389
|
-
state.publish = publish;
|
|
390
|
-
}
|
|
391
|
-
async function inTransaction(db, work) {
|
|
392
|
-
const changes = [];
|
|
393
|
-
const result = await state.pending.run(changes, () => db.transaction().execute((trx) => work(trx)));
|
|
394
|
-
changes.forEach((change) => state.publish?.(change));
|
|
395
|
-
return result;
|
|
396
|
-
}
|
|
397
|
-
|
|
398
|
-
export { KYSELY as K, MAIN_DATABASE as M, SqlBuilder as S, TableStore as T, sortDirection as a, snakeRow as b, camelRow as c, affectedCount as d, notEqual as e, lessOrEqual as f, moreOrEqual as g, ilike as h, isNull as i, contains as j, configureLocalChangePublisher as k, lessThan as l, moreThan as m, notNull as n, oneOf as o, pendingLocalChanges as p, inTransaction as q, rawQuery as r, sortColumn as s, bindNamed as t, within as w };
|