@my-nestjs-kit/sqlite 0.0.0-stage → 0.1.0-dev.20261129010337
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +63 -2
- package/dist/constants/sqlite-tokens.d.ts +8 -0
- package/dist/constants/sqlite-tokens.js +11 -0
- package/dist/data-source/helpers/match-like-pattern.d.ts +6 -0
- package/dist/data-source/helpers/match-like-pattern.js +34 -0
- package/dist/data-source/helpers/register-ts-like.d.ts +9 -0
- package/dist/data-source/helpers/register-ts-like.js +26 -0
- package/dist/data-source/sqlite-data-source.d.ts +31 -0
- package/dist/data-source/sqlite-data-source.js +94 -0
- package/dist/decorators/column.decorator.d.ts +4 -0
- package/dist/decorators/column.decorator.js +24 -0
- package/dist/decorators/create-date-column.decorator.d.ts +2 -0
- package/dist/decorators/create-date-column.decorator.js +8 -0
- package/dist/decorators/delete-date-column.decorator.d.ts +2 -0
- package/dist/decorators/delete-date-column.decorator.js +8 -0
- package/dist/decorators/entity-repository.decorator.d.ts +4 -0
- package/dist/decorators/entity-repository.decorator.js +19 -0
- package/dist/decorators/entity.decorator.d.ts +1 -0
- package/dist/decorators/entity.decorator.js +7 -0
- package/dist/decorators/index.decorator.d.ts +5 -0
- package/dist/decorators/index.decorator.js +8 -0
- package/dist/decorators/many-to-one.decorator.d.ts +7 -0
- package/dist/decorators/many-to-one.decorator.js +8 -0
- package/dist/decorators/one-to-many.decorator.d.ts +3 -0
- package/dist/decorators/one-to-many.decorator.js +8 -0
- package/dist/decorators/one-to-one.decorator.d.ts +9 -0
- package/dist/decorators/one-to-one.decorator.js +13 -0
- package/dist/decorators/primary-column.decorator.d.ts +3 -0
- package/dist/decorators/primary-column.decorator.js +8 -0
- package/dist/decorators/primary-generated-column.decorator.d.ts +2 -0
- package/dist/decorators/primary-generated-column.decorator.js +8 -0
- package/dist/decorators/state-date-column.decorator.d.ts +5 -0
- package/dist/decorators/state-date-column.decorator.js +15 -0
- package/dist/decorators/update-date-column.decorator.d.ts +2 -0
- package/dist/decorators/update-date-column.decorator.js +8 -0
- package/dist/helpers/assert-order-direction.d.ts +3 -0
- package/dist/helpers/assert-order-direction.js +11 -0
- package/dist/helpers/assert-pragma-value.d.ts +2 -0
- package/dist/helpers/assert-pragma-value.js +11 -0
- package/dist/helpers/assert-row-count.d.ts +2 -0
- package/dist/helpers/assert-row-count.js +11 -0
- package/dist/helpers/assert-sql-name.d.ts +2 -0
- package/dist/helpers/assert-sql-name.js +10 -0
- package/dist/index.d.ts +31 -0
- package/dist/index.js +69 -0
- package/dist/metadata/helpers/to-snake-case.d.ts +2 -0
- package/dist/metadata/helpers/to-snake-case.js +7 -0
- package/dist/metadata/metadata-storage.d.ts +6 -0
- package/dist/metadata/metadata-storage.js +42 -0
- package/dist/metadata/types/entity-meta.types.d.ts +49 -0
- package/dist/metadata/types/entity-meta.types.js +2 -0
- package/dist/migrations/decorators/migration.decorator.d.ts +8 -0
- package/dist/migrations/decorators/migration.decorator.js +20 -0
- package/dist/migrations/define-migration.d.ts +3 -0
- package/dist/migrations/define-migration.js +7 -0
- package/dist/migrations/helpers/resolve-migrations.d.ts +9 -0
- package/dist/migrations/helpers/resolve-migrations.js +34 -0
- package/dist/migrations/migration-context.d.ts +21 -0
- package/dist/migrations/migration-context.js +42 -0
- package/dist/migrations/migrations-runner.d.ts +21 -0
- package/dist/migrations/migrations-runner.js +80 -0
- package/dist/migrations/migrations.service.d.ts +10 -0
- package/dist/migrations/migrations.service.js +20 -0
- package/dist/migrations/types/migration.types.d.ts +31 -0
- package/dist/migrations/types/migration.types.js +2 -0
- package/dist/operators/and.d.ts +3 -0
- package/dist/operators/and.js +7 -0
- package/dist/operators/between.d.ts +3 -0
- package/dist/operators/between.js +7 -0
- package/dist/operators/equal.d.ts +2 -0
- package/dist/operators/equal.js +6 -0
- package/dist/operators/find-operator.d.ts +10 -0
- package/dist/operators/find-operator.js +15 -0
- package/dist/operators/i-like.d.ts +3 -0
- package/dist/operators/i-like.js +7 -0
- package/dist/operators/in.d.ts +3 -0
- package/dist/operators/in.js +7 -0
- package/dist/operators/index.d.ts +14 -0
- package/dist/operators/index.js +30 -0
- package/dist/operators/is-null.d.ts +2 -0
- package/dist/operators/is-null.js +6 -0
- package/dist/operators/less-than-or-equal.d.ts +2 -0
- package/dist/operators/less-than-or-equal.js +6 -0
- package/dist/operators/less-than.d.ts +2 -0
- package/dist/operators/less-than.js +6 -0
- package/dist/operators/like.d.ts +3 -0
- package/dist/operators/like.js +7 -0
- package/dist/operators/more-than-or-equal.d.ts +2 -0
- package/dist/operators/more-than-or-equal.js +6 -0
- package/dist/operators/more-than.d.ts +2 -0
- package/dist/operators/more-than.js +6 -0
- package/dist/operators/not.d.ts +3 -0
- package/dist/operators/not.js +7 -0
- package/dist/query/find-many-query.base.d.ts +6 -0
- package/dist/query/find-many-query.base.js +10 -0
- package/dist/query/id.query.d.ts +4 -0
- package/dist/query/id.query.js +8 -0
- package/dist/query/pagination.query.d.ts +8 -0
- package/dist/query/pagination.query.js +13 -0
- package/dist/query-builder/helpers/normalize-relations.d.ts +4 -0
- package/dist/query-builder/helpers/normalize-relations.js +20 -0
- package/dist/query-builder/sqlite-query-builder.d.ts +87 -0
- package/dist/query-builder/sqlite-query-builder.js +378 -0
- package/dist/query-builder/sqlite-where-builder.d.ts +17 -0
- package/dist/query-builder/sqlite-where-builder.js +47 -0
- package/dist/query-builder/types/query-builder.types.d.ts +17 -0
- package/dist/query-builder/types/query-builder.types.js +2 -0
- package/dist/repository/helpers/column-value.d.ts +6 -0
- package/dist/repository/helpers/column-value.js +32 -0
- package/dist/repository/helpers/compile-condition.d.ts +7 -0
- package/dist/repository/helpers/compile-condition.js +57 -0
- package/dist/repository/helpers/quote-identifier.d.ts +2 -0
- package/dist/repository/helpers/quote-identifier.js +6 -0
- package/dist/repository/helpers/relation-target.d.ts +9 -0
- package/dist/repository/helpers/relation-target.js +34 -0
- package/dist/repository/helpers/resolve-inverse-property.d.ts +2 -0
- package/dist/repository/helpers/resolve-inverse-property.js +12 -0
- package/dist/repository/sqlite-repository.d.ts +52 -0
- package/dist/repository/sqlite-repository.js +181 -0
- package/dist/repository/types/find-opts.types.d.ts +33 -0
- package/dist/repository/types/find-opts.types.js +2 -0
- package/dist/repository/types/sql-fragment.types.d.ts +6 -0
- package/dist/repository/types/sql-fragment.types.js +2 -0
- package/dist/sqlite.module.d.ts +14 -0
- package/dist/sqlite.module.js +68 -0
- package/dist/types/sqlite-module-options.types.d.ts +18 -0
- package/dist/types/sqlite-module-options.types.js +2 -0
- package/package.json +58 -3
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SqliteQueryBuilder = void 0;
|
|
4
|
+
const metadata_storage_1 = require("../metadata/metadata-storage");
|
|
5
|
+
const assert_order_direction_1 = require("../helpers/assert-order-direction");
|
|
6
|
+
const assert_row_count_1 = require("../helpers/assert-row-count");
|
|
7
|
+
const in_1 = require("../operators/in");
|
|
8
|
+
const column_value_1 = require("../repository/helpers/column-value");
|
|
9
|
+
const quote_identifier_1 = require("../repository/helpers/quote-identifier");
|
|
10
|
+
const relation_target_1 = require("../repository/helpers/relation-target");
|
|
11
|
+
const normalize_relations_1 = require("./helpers/normalize-relations");
|
|
12
|
+
const sqlite_where_builder_1 = require("./sqlite-where-builder");
|
|
13
|
+
/**
|
|
14
|
+
* «qb lite» для того, що не вкладається в параметри репозиторію: агрегати, групування, `json_each`, join за relation.
|
|
15
|
+
* Поля — імена властивостей entity (`'m.periodStart'`), SQL і параметри будує builder; тексту SQL зовні немає.
|
|
16
|
+
*/
|
|
17
|
+
class SqliteQueryBuilder {
|
|
18
|
+
_dataSource;
|
|
19
|
+
meta;
|
|
20
|
+
alias;
|
|
21
|
+
_applyQuery;
|
|
22
|
+
_sources = new Map();
|
|
23
|
+
/** Шлях relation (`device`, `device.owner`) → alias приєднаної таблиці. */
|
|
24
|
+
_joinAliases = new Map();
|
|
25
|
+
_joins = [];
|
|
26
|
+
_conditions = [];
|
|
27
|
+
_rawSelect = [];
|
|
28
|
+
_groupBy = [];
|
|
29
|
+
_order = [];
|
|
30
|
+
_rootSelect;
|
|
31
|
+
_relations = {};
|
|
32
|
+
_limit;
|
|
33
|
+
_offset;
|
|
34
|
+
_deleted = 'exclude';
|
|
35
|
+
constructor(_dataSource, meta, alias, _applyQuery) {
|
|
36
|
+
this._dataSource = _dataSource;
|
|
37
|
+
this.meta = meta;
|
|
38
|
+
this.alias = alias;
|
|
39
|
+
this._applyQuery = _applyQuery;
|
|
40
|
+
this._sources.set(alias, { alias, kind: 'root', meta });
|
|
41
|
+
}
|
|
42
|
+
// ── умови ──────────────────────────────────────────────
|
|
43
|
+
where(field, value) {
|
|
44
|
+
new sqlite_where_builder_1.SqliteWhereBuilder(this, this._conditions).field(field, value);
|
|
45
|
+
return this;
|
|
46
|
+
}
|
|
47
|
+
andWhere(field, value) {
|
|
48
|
+
return this.where(field, value);
|
|
49
|
+
}
|
|
50
|
+
orWhere(...groups) {
|
|
51
|
+
new sqlite_where_builder_1.SqliteWhereBuilder(this, this._conditions).or(...groups);
|
|
52
|
+
return this;
|
|
53
|
+
}
|
|
54
|
+
/** Query-клас репозиторію через його `_applyWhere` — ті самі правила, що в `findMany`. */
|
|
55
|
+
applyQuery(query) {
|
|
56
|
+
if (!this._applyQuery)
|
|
57
|
+
throw new Error('applyQuery needs a builder from a repository (_qb)');
|
|
58
|
+
this._applyQuery(new sqlite_where_builder_1.SqliteWhereBuilder(this, this._conditions), query);
|
|
59
|
+
return this;
|
|
60
|
+
}
|
|
61
|
+
withDeleted() {
|
|
62
|
+
this._deleted = 'with';
|
|
63
|
+
return this;
|
|
64
|
+
}
|
|
65
|
+
onlyDeleted() {
|
|
66
|
+
this._deleted = 'only';
|
|
67
|
+
return this;
|
|
68
|
+
}
|
|
69
|
+
// ── джерела ────────────────────────────────────────────
|
|
70
|
+
/** `json_each(<field>) AS alias` з колонками `key` / `value` (`'v.key'`, `'v.value'`). */
|
|
71
|
+
jsonEach(alias, field) {
|
|
72
|
+
const { expr } = this.resolveField(field);
|
|
73
|
+
this._addSource({ alias, kind: 'json' });
|
|
74
|
+
this._joins.push({ sql: `JOIN json_each(${expr}) AS ${(0, quote_identifier_1.quoteIdentifier)(alias)}`, params: [] });
|
|
75
|
+
return this;
|
|
76
|
+
}
|
|
77
|
+
innerJoin(relation, alias) {
|
|
78
|
+
this.ensureJoin(relation, 'INNER', alias);
|
|
79
|
+
return this;
|
|
80
|
+
}
|
|
81
|
+
leftJoin(relation, alias) {
|
|
82
|
+
this.ensureJoin(relation, 'LEFT', alias);
|
|
83
|
+
return this;
|
|
84
|
+
}
|
|
85
|
+
// ── вибірка ────────────────────────────────────────────
|
|
86
|
+
/** Поля кореня для `getMany` / `getOne`; первинний ключ додається завжди. */
|
|
87
|
+
selectFields(properties) {
|
|
88
|
+
this._rootSelect = properties;
|
|
89
|
+
return this;
|
|
90
|
+
}
|
|
91
|
+
/** Relations для `getMany` / `getOne`: to-one — LEFT JOIN, to-many — другий запит. */
|
|
92
|
+
relations(spec) {
|
|
93
|
+
this._relations = (0, normalize_relations_1.normalizeRelations)(spec);
|
|
94
|
+
return this;
|
|
95
|
+
}
|
|
96
|
+
/** Сирі поля для `getRawMany`: `{ periodStart: 'm.periodStart', value: 'v.key' }`. */
|
|
97
|
+
select(map) {
|
|
98
|
+
for (const [as, field] of Object.entries(map)) {
|
|
99
|
+
const { expr, column } = this.resolveField(field);
|
|
100
|
+
this._rawSelect.push({ sql: expr, as, column });
|
|
101
|
+
}
|
|
102
|
+
return this;
|
|
103
|
+
}
|
|
104
|
+
sum(field, as) {
|
|
105
|
+
return this._aggregate('SUM', field, as);
|
|
106
|
+
}
|
|
107
|
+
min(field, as) {
|
|
108
|
+
return this._aggregate('MIN', field, as);
|
|
109
|
+
}
|
|
110
|
+
max(field, as) {
|
|
111
|
+
return this._aggregate('MAX', field, as);
|
|
112
|
+
}
|
|
113
|
+
count(as) {
|
|
114
|
+
this._rawSelect.push({ sql: 'COUNT(*)', as });
|
|
115
|
+
return this;
|
|
116
|
+
}
|
|
117
|
+
groupBy(...fields) {
|
|
118
|
+
this._groupBy.push(...fields.map((field) => this.resolveField(field).expr));
|
|
119
|
+
return this;
|
|
120
|
+
}
|
|
121
|
+
/** Поле entity або alias сирої вибірки (`orderBy('count', 'DESC')`). */
|
|
122
|
+
orderBy(field, direction = 'ASC') {
|
|
123
|
+
const raw = this._rawSelect.find((select) => select.as === field);
|
|
124
|
+
this._order.push(`${raw ? (0, quote_identifier_1.quoteIdentifier)(raw.as) : this.resolveField(field).expr} ${(0, assert_order_direction_1.assertOrderDirection)(direction)}`);
|
|
125
|
+
return this;
|
|
126
|
+
}
|
|
127
|
+
limit(limit) {
|
|
128
|
+
this._limit = (0, assert_row_count_1.assertRowCount)('limit', limit);
|
|
129
|
+
return this;
|
|
130
|
+
}
|
|
131
|
+
offset(offset) {
|
|
132
|
+
this._offset = (0, assert_row_count_1.assertRowCount)('offset', offset);
|
|
133
|
+
return this;
|
|
134
|
+
}
|
|
135
|
+
// ── результати ─────────────────────────────────────────
|
|
136
|
+
getMany() {
|
|
137
|
+
const loaded = this._joinRelationTree(this._relations, '', this.alias, this.meta);
|
|
138
|
+
const columns = [...this._entityColumns(this.alias, this.meta, this._rootSelect), ...loaded.flatMap(({ alias, meta }) => this._entityColumns(alias, meta))];
|
|
139
|
+
const sql = `SELECT ${columns.map((column) => column.sql).join(', ')} ${this._fromWhere().sql}${this._tail()}`;
|
|
140
|
+
const rows = this._dataSource.query(sql, ...this._fromWhere().params);
|
|
141
|
+
const entities = rows.map((row) => this._mapRow(row, loaded));
|
|
142
|
+
this._loadToMany(entities, this.meta, this._relations);
|
|
143
|
+
return entities;
|
|
144
|
+
}
|
|
145
|
+
getOne() {
|
|
146
|
+
return this.limit(1).getMany()[0] ?? null;
|
|
147
|
+
}
|
|
148
|
+
getRawMany() {
|
|
149
|
+
if (!this._rawSelect.length)
|
|
150
|
+
throw new Error('getRawMany needs select() / sum() / count()');
|
|
151
|
+
const { sql, params } = this._fromWhere();
|
|
152
|
+
const select = this._rawSelect.map((raw) => `${raw.sql} AS ${(0, quote_identifier_1.quoteIdentifier)(raw.as)}`).join(', ');
|
|
153
|
+
const groupBy = this._groupBy.length ? ` GROUP BY ${this._groupBy.join(', ')}` : '';
|
|
154
|
+
const rows = this._dataSource.query(`SELECT ${select} ${sql}${groupBy}${this._tail()}`, ...params);
|
|
155
|
+
return rows.map((row) => {
|
|
156
|
+
const out = {};
|
|
157
|
+
for (const raw of this._rawSelect) {
|
|
158
|
+
const value = row[raw.as];
|
|
159
|
+
out[raw.as] = raw.column ? (0, column_value_1.fromDbValue)(raw.column, value) : typeof value === 'bigint' ? Number(value) : value;
|
|
160
|
+
}
|
|
161
|
+
return out;
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
getCount() {
|
|
165
|
+
const { sql, params } = this._fromWhere();
|
|
166
|
+
return Number(this._dataSource.query(`SELECT COUNT(*) AS n ${sql}`, ...params)[0].n);
|
|
167
|
+
}
|
|
168
|
+
exists() {
|
|
169
|
+
const { sql, params } = this._fromWhere();
|
|
170
|
+
return this._dataSource.query(`SELECT 1 ${sql} LIMIT 1`, ...params).length > 0;
|
|
171
|
+
}
|
|
172
|
+
// ── масові зміни на тих самих умовах ───────────────────
|
|
173
|
+
/** Оновлює рядки, що підпадають під умови. `UpdateDateColumn` ставиться сам. Повертає кількість змінених. */
|
|
174
|
+
update(dto) {
|
|
175
|
+
const assignments = this._assignments(dto);
|
|
176
|
+
const updated = this.meta.columns.find((column) => column.role === 'update-date');
|
|
177
|
+
if (updated && !assignments.some((assignment) => assignment.column === updated)) {
|
|
178
|
+
assignments.push({ column: updated, value: new Date().toISOString() });
|
|
179
|
+
}
|
|
180
|
+
if (!assignments.length)
|
|
181
|
+
return 0;
|
|
182
|
+
return this._mutate(`UPDATE ${(0, quote_identifier_1.quoteIdentifier)(this.meta.table)} SET ${assignments.map(({ column }) => `${(0, quote_identifier_1.quoteIdentifier)(column.name)} = ?`).join(', ')}`, assignments.map(({ column, value }) => (0, column_value_1.toDbValue)(column, value)));
|
|
183
|
+
}
|
|
184
|
+
/** Фізичне видалення. */
|
|
185
|
+
delete() {
|
|
186
|
+
return this._mutate(`DELETE FROM ${(0, quote_identifier_1.quoteIdentifier)(this.meta.table)}`, []);
|
|
187
|
+
}
|
|
188
|
+
softDelete() {
|
|
189
|
+
const column = this._deleteDateColumn();
|
|
190
|
+
return this._mutate(`UPDATE ${(0, quote_identifier_1.quoteIdentifier)(this.meta.table)} SET ${(0, quote_identifier_1.quoteIdentifier)(column.name)} = ?`, [new Date().toISOString()]);
|
|
191
|
+
}
|
|
192
|
+
restore() {
|
|
193
|
+
const column = this._deleteDateColumn();
|
|
194
|
+
this._deleted = 'only';
|
|
195
|
+
return this._mutate(`UPDATE ${(0, quote_identifier_1.quoteIdentifier)(this.meta.table)} SET ${(0, quote_identifier_1.quoteIdentifier)(column.name)} = NULL`, []);
|
|
196
|
+
}
|
|
197
|
+
// ── для SqliteWhereBuilder ─────────────────────────────
|
|
198
|
+
/** @internal `'startedAt'` → корінь; `'d.userAgent'` → джерело `d`; `'v.key'` → колонка `json_each`. */
|
|
199
|
+
resolveField(field) {
|
|
200
|
+
const dot = field.indexOf('.');
|
|
201
|
+
const source = dot > 0 ? this._sources.get(field.slice(0, dot)) : undefined;
|
|
202
|
+
const alias = source ? source.alias : this.alias;
|
|
203
|
+
const property = source ? field.slice(dot + 1) : field;
|
|
204
|
+
const resolved = source ?? this._sources.get(this.alias);
|
|
205
|
+
if (resolved.kind === 'json') {
|
|
206
|
+
if (property !== 'key' && property !== 'value')
|
|
207
|
+
throw new Error(`json_each ${alias} has only key / value, got ${property}`);
|
|
208
|
+
return { expr: `${(0, quote_identifier_1.quoteIdentifier)(alias)}.${property}` };
|
|
209
|
+
}
|
|
210
|
+
const column = (0, relation_target_1.findColumn)(resolved.meta, property);
|
|
211
|
+
return { expr: `${(0, quote_identifier_1.quoteIdentifier)(alias)}.${(0, quote_identifier_1.quoteIdentifier)(column.name)}`, column };
|
|
212
|
+
}
|
|
213
|
+
/** @internal Приєднує to-one relation за шляхом від кореня (`device`, `device.owner`); повертає alias. */
|
|
214
|
+
ensureJoin(path, type, alias) {
|
|
215
|
+
const existing = this._joinAliases.get(path);
|
|
216
|
+
if (existing)
|
|
217
|
+
return existing;
|
|
218
|
+
const dot = path.lastIndexOf('.');
|
|
219
|
+
const parentAlias = dot > 0 ? this.ensureJoin(path.slice(0, dot), type) : this.alias;
|
|
220
|
+
const parentMeta = this._sources.get(parentAlias).meta;
|
|
221
|
+
const property = dot > 0 ? path.slice(dot + 1) : path;
|
|
222
|
+
const relation = (0, relation_target_1.findRelation)(parentMeta, property);
|
|
223
|
+
if (relation.type === 'one-to-many')
|
|
224
|
+
throw new Error(`${parentMeta.target.name}.${property}: one-to-many is loaded by relations(), not joined`);
|
|
225
|
+
const childAlias = alias ?? path.replace(/\./g, '__');
|
|
226
|
+
let childMeta;
|
|
227
|
+
let on;
|
|
228
|
+
if (relation.joinColumn) {
|
|
229
|
+
childMeta = (0, metadata_storage_1.getEntityMeta)(relation.target());
|
|
230
|
+
on = `${(0, quote_identifier_1.quoteIdentifier)(childAlias)}.${(0, quote_identifier_1.quoteIdentifier)((0, relation_target_1.primaryColumn)(childMeta).name)} = ${(0, quote_identifier_1.quoteIdentifier)(parentAlias)}.${(0, quote_identifier_1.quoteIdentifier)((0, relation_target_1.findColumn)(parentMeta, relation.joinColumn).name)}`;
|
|
231
|
+
}
|
|
232
|
+
else {
|
|
233
|
+
const { meta, owner } = (0, relation_target_1.inverseOwner)(relation);
|
|
234
|
+
childMeta = meta;
|
|
235
|
+
on = `${(0, quote_identifier_1.quoteIdentifier)(childAlias)}.${(0, quote_identifier_1.quoteIdentifier)((0, relation_target_1.findColumn)(meta, owner.joinColumn).name)} = ${(0, quote_identifier_1.quoteIdentifier)(parentAlias)}.${(0, quote_identifier_1.quoteIdentifier)((0, relation_target_1.primaryColumn)(parentMeta).name)}`;
|
|
236
|
+
}
|
|
237
|
+
const deleted = childMeta.columns.find((column) => column.role === 'delete-date');
|
|
238
|
+
if (deleted && this._deleted !== 'with')
|
|
239
|
+
on += ` AND ${(0, quote_identifier_1.quoteIdentifier)(childAlias)}.${(0, quote_identifier_1.quoteIdentifier)(deleted.name)} IS NULL`;
|
|
240
|
+
this._addSource({ alias: childAlias, kind: 'join', meta: childMeta });
|
|
241
|
+
this._joins.push({ sql: `${type} JOIN ${(0, quote_identifier_1.quoteIdentifier)(childMeta.table)} AS ${(0, quote_identifier_1.quoteIdentifier)(childAlias)} ON ${on}`, params: [] });
|
|
242
|
+
this._joinAliases.set(path, childAlias);
|
|
243
|
+
return childAlias;
|
|
244
|
+
}
|
|
245
|
+
// ── внутрішнє ──────────────────────────────────────────
|
|
246
|
+
_addSource(source) {
|
|
247
|
+
if (this._sources.has(source.alias))
|
|
248
|
+
throw new Error(`alias ${source.alias} is already used in this query`);
|
|
249
|
+
this._sources.set(source.alias, source);
|
|
250
|
+
}
|
|
251
|
+
_aggregate(fn, field, as) {
|
|
252
|
+
this._rawSelect.push({ sql: `${fn}(${this.resolveField(field).expr})`, as });
|
|
253
|
+
return this;
|
|
254
|
+
}
|
|
255
|
+
_deleteDateColumn() {
|
|
256
|
+
const column = this.meta.columns.find((existing) => existing.role === 'delete-date');
|
|
257
|
+
if (!column)
|
|
258
|
+
throw new Error(`${this.meta.target.name} has no @DeleteDateColumn`);
|
|
259
|
+
return column;
|
|
260
|
+
}
|
|
261
|
+
_fromWhere() {
|
|
262
|
+
const conditions = [...this._conditions];
|
|
263
|
+
const deleted = this.meta.columns.find((column) => column.role === 'delete-date');
|
|
264
|
+
if (deleted && this._deleted !== 'with') {
|
|
265
|
+
conditions.push({ sql: `${(0, quote_identifier_1.quoteIdentifier)(this.alias)}.${(0, quote_identifier_1.quoteIdentifier)(deleted.name)} IS ${this._deleted === 'only' ? 'NOT ' : ''}NULL`, params: [] });
|
|
266
|
+
}
|
|
267
|
+
const joins = this._joins.map((join) => join.sql).join(' ');
|
|
268
|
+
const where = conditions.length ? ` WHERE ${conditions.map((condition) => `(${condition.sql})`).join(' AND ')}` : '';
|
|
269
|
+
return {
|
|
270
|
+
sql: `FROM ${(0, quote_identifier_1.quoteIdentifier)(this.meta.table)} AS ${(0, quote_identifier_1.quoteIdentifier)(this.alias)}${joins ? ` ${joins}` : ''}${where}`,
|
|
271
|
+
params: [...this._joins.flatMap((join) => join.params), ...conditions.flatMap((condition) => condition.params)],
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
_tail() {
|
|
275
|
+
let tail = this._order.length ? ` ORDER BY ${this._order.join(', ')}` : '';
|
|
276
|
+
if (this._limit !== undefined || this._offset !== undefined)
|
|
277
|
+
tail += ` LIMIT ${this._limit ?? -1}`;
|
|
278
|
+
if (this._offset !== undefined)
|
|
279
|
+
tail += ` OFFSET ${this._offset}`;
|
|
280
|
+
return tail;
|
|
281
|
+
}
|
|
282
|
+
/** UPDATE / DELETE за `rowid IN (SELECT ...)`: умови, join, ORDER / LIMIT працюють так само, як у вибірці. */
|
|
283
|
+
_mutate(head, headParams) {
|
|
284
|
+
if (!this._conditions.length && this._limit === undefined && this._offset === undefined) {
|
|
285
|
+
throw new Error(`${this.meta.target.name}: update / delete without conditions`);
|
|
286
|
+
}
|
|
287
|
+
const { sql, params } = this._fromWhere();
|
|
288
|
+
const subquery = `SELECT ${(0, quote_identifier_1.quoteIdentifier)(this.alias)}.rowid ${sql}${this._tail()}`;
|
|
289
|
+
return this._dataSource.run(`${head} WHERE rowid IN (${subquery})`, ...headParams, ...params).changes;
|
|
290
|
+
}
|
|
291
|
+
_assignments(dto) {
|
|
292
|
+
const assignments = [];
|
|
293
|
+
for (const [property, value] of Object.entries(dto)) {
|
|
294
|
+
if (value === undefined)
|
|
295
|
+
continue;
|
|
296
|
+
if (this.meta.relations.some((relation) => relation.property === property))
|
|
297
|
+
continue;
|
|
298
|
+
assignments.push({ column: (0, relation_target_1.findColumn)(this.meta, property), value });
|
|
299
|
+
}
|
|
300
|
+
return assignments;
|
|
301
|
+
}
|
|
302
|
+
_entityColumns(alias, meta, properties) {
|
|
303
|
+
const primary = meta.columns.filter((column) => column.primary).map((column) => column.property);
|
|
304
|
+
const wanted = properties ? new Set([...primary, ...properties]) : undefined;
|
|
305
|
+
return meta.columns
|
|
306
|
+
.filter((column) => !wanted || wanted.has(column.property))
|
|
307
|
+
.map((column) => ({ sql: `${(0, quote_identifier_1.quoteIdentifier)(alias)}.${(0, quote_identifier_1.quoteIdentifier)(column.name)} AS ${(0, quote_identifier_1.quoteIdentifier)(`${alias}::${column.property}`)}` }));
|
|
308
|
+
}
|
|
309
|
+
/** to-one з дерева relations → LEFT JOIN; повертає приєднані джерела для мапінгу. */
|
|
310
|
+
_joinRelationTree(tree, prefix, parentAlias, parentMeta) {
|
|
311
|
+
const loaded = [];
|
|
312
|
+
for (const [property, subtree] of Object.entries(tree)) {
|
|
313
|
+
const relation = (0, relation_target_1.findRelation)(parentMeta, property);
|
|
314
|
+
if (relation.type === 'one-to-many')
|
|
315
|
+
continue;
|
|
316
|
+
const path = prefix ? `${prefix}.${property}` : property;
|
|
317
|
+
const alias = this.ensureJoin(path, 'LEFT', `rel__${path.replace(/\./g, '__')}`);
|
|
318
|
+
const meta = this._sources.get(alias).meta;
|
|
319
|
+
loaded.push({ path, alias, meta }, ...this._joinRelationTree(subtree, path, alias, meta));
|
|
320
|
+
}
|
|
321
|
+
return loaded;
|
|
322
|
+
}
|
|
323
|
+
_buildEntity(row, alias, meta) {
|
|
324
|
+
const entity = Object.create(meta.target.prototype);
|
|
325
|
+
let present = false;
|
|
326
|
+
for (const column of meta.columns) {
|
|
327
|
+
const key = `${alias}::${column.property}`;
|
|
328
|
+
if (!(key in row))
|
|
329
|
+
continue;
|
|
330
|
+
entity[column.property] = (0, column_value_1.fromDbValue)(column, row[key]);
|
|
331
|
+
if (column.primary && row[key] !== null)
|
|
332
|
+
present = true;
|
|
333
|
+
}
|
|
334
|
+
return present ? entity : null;
|
|
335
|
+
}
|
|
336
|
+
_mapRow(row, loaded) {
|
|
337
|
+
const root = this._buildEntity(row, this.alias, this.meta);
|
|
338
|
+
const byPath = new Map([['', root]]);
|
|
339
|
+
for (const { path, alias, meta } of loaded) {
|
|
340
|
+
const dot = path.lastIndexOf('.');
|
|
341
|
+
const parent = byPath.get(dot > 0 ? path.slice(0, dot) : '');
|
|
342
|
+
const child = parent ? this._buildEntity(row, alias, meta) : null;
|
|
343
|
+
if (parent)
|
|
344
|
+
parent[dot > 0 ? path.slice(dot + 1) : path] = child;
|
|
345
|
+
byPath.set(path, child);
|
|
346
|
+
}
|
|
347
|
+
return root;
|
|
348
|
+
}
|
|
349
|
+
/** to-many другим запитом `WHERE fk IN (ids)`, рекурсивно і всередині вже приєднаних to-one. */
|
|
350
|
+
_loadToMany(entities, meta, tree) {
|
|
351
|
+
if (!entities.length)
|
|
352
|
+
return;
|
|
353
|
+
for (const [property, subtree] of Object.entries(tree)) {
|
|
354
|
+
const relation = (0, relation_target_1.findRelation)(meta, property);
|
|
355
|
+
if (relation.type !== 'one-to-many') {
|
|
356
|
+
const children = entities.map((entity) => entity[property]).filter(Boolean);
|
|
357
|
+
this._loadToMany(children, (0, metadata_storage_1.getEntityMeta)(relation.target()), subtree);
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
const { meta: childMeta, owner } = (0, relation_target_1.inverseOwner)(relation);
|
|
361
|
+
const parentKey = (0, relation_target_1.primaryColumn)(meta).property;
|
|
362
|
+
const ids = entities.map((entity) => entity[parentKey]);
|
|
363
|
+
const childBuilder = new SqliteQueryBuilder(this._dataSource, childMeta, 'c').where(owner.joinColumn, (0, in_1.In)(ids));
|
|
364
|
+
if (this._deleted === 'with')
|
|
365
|
+
childBuilder.withDeleted();
|
|
366
|
+
const nested = Object.fromEntries(Object.entries(subtree));
|
|
367
|
+
childBuilder._relations = nested;
|
|
368
|
+
const groups = new Map();
|
|
369
|
+
for (const child of childBuilder.getMany()) {
|
|
370
|
+
const key = child[owner.joinColumn];
|
|
371
|
+
groups.set(key, [...(groups.get(key) ?? []), child]);
|
|
372
|
+
}
|
|
373
|
+
for (const entity of entities)
|
|
374
|
+
entity[property] = groups.get(entity[parentKey]) ?? [];
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
exports.SqliteQueryBuilder = SqliteQueryBuilder;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { SqlFragment } from '../repository/types/sql-fragment.types';
|
|
2
|
+
import type { SqliteQueryBuilder } from './sqlite-query-builder';
|
|
3
|
+
/**
|
|
4
|
+
* Умови запиту по полях entity. Отримує його `_applyWhere` репозиторію; SQL-тексту зовні немає:
|
|
5
|
+
* лише поле і значення / find-оператор. `undefined` — умову пропущено.
|
|
6
|
+
*/
|
|
7
|
+
export declare class SqliteWhereBuilder<E> {
|
|
8
|
+
private readonly _qb;
|
|
9
|
+
private readonly _parts;
|
|
10
|
+
constructor(_qb: SqliteQueryBuilder<any>, _parts: SqlFragment[]);
|
|
11
|
+
/** Поле кореня (`'startedAt'`) або джерела запиту (`'d.userAgent'`). */
|
|
12
|
+
field(field: (keyof E & string) | `${string}.${string}`, value: unknown): this;
|
|
13
|
+
/** Поле to-one relation кореня: сам додає LEFT JOIN (`joined('device', 'userAgent', ILike('%mac%'))`). */
|
|
14
|
+
joined(relation: string, property: string, value: unknown): this;
|
|
15
|
+
/** `(група) OR (група)`; умови всередині групи — через AND. Порожні групи пропускаються. */
|
|
16
|
+
or(...groups: ((where: SqliteWhereBuilder<E>) => void)[]): this;
|
|
17
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SqliteWhereBuilder = void 0;
|
|
4
|
+
const compile_condition_1 = require("../repository/helpers/compile-condition");
|
|
5
|
+
/**
|
|
6
|
+
* Умови запиту по полях entity. Отримує його `_applyWhere` репозиторію; SQL-тексту зовні немає:
|
|
7
|
+
* лише поле і значення / find-оператор. `undefined` — умову пропущено.
|
|
8
|
+
*/
|
|
9
|
+
class SqliteWhereBuilder {
|
|
10
|
+
_qb;
|
|
11
|
+
_parts;
|
|
12
|
+
constructor(_qb, _parts) {
|
|
13
|
+
this._qb = _qb;
|
|
14
|
+
this._parts = _parts;
|
|
15
|
+
}
|
|
16
|
+
/** Поле кореня (`'startedAt'`) або джерела запиту (`'d.userAgent'`). */
|
|
17
|
+
field(field, value) {
|
|
18
|
+
if (value === undefined)
|
|
19
|
+
return this;
|
|
20
|
+
const { expr, column } = this._qb.resolveField(field);
|
|
21
|
+
this._parts.push((0, compile_condition_1.compileCondition)(expr, value, column));
|
|
22
|
+
return this;
|
|
23
|
+
}
|
|
24
|
+
/** Поле to-one relation кореня: сам додає LEFT JOIN (`joined('device', 'userAgent', ILike('%mac%'))`). */
|
|
25
|
+
joined(relation, property, value) {
|
|
26
|
+
if (value === undefined)
|
|
27
|
+
return this;
|
|
28
|
+
const alias = this._qb.ensureJoin(relation, 'LEFT');
|
|
29
|
+
return this.field(`${alias}.${property}`, value);
|
|
30
|
+
}
|
|
31
|
+
/** `(група) OR (група)`; умови всередині групи — через AND. Порожні групи пропускаються. */
|
|
32
|
+
or(...groups) {
|
|
33
|
+
const compiled = groups
|
|
34
|
+
.map((group) => {
|
|
35
|
+
const parts = [];
|
|
36
|
+
group(new SqliteWhereBuilder(this._qb, parts));
|
|
37
|
+
return parts;
|
|
38
|
+
})
|
|
39
|
+
.filter((parts) => parts.length)
|
|
40
|
+
.map((parts) => ({ sql: parts.map((part) => `(${part.sql})`).join(' AND '), params: parts.flatMap((part) => part.params) }));
|
|
41
|
+
if (compiled.length) {
|
|
42
|
+
this._parts.push({ sql: compiled.map((part) => `(${part.sql})`).join(' OR '), params: compiled.flatMap((part) => part.params) });
|
|
43
|
+
}
|
|
44
|
+
return this;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
exports.SqliteWhereBuilder = SqliteWhereBuilder;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { ColumnMeta, EntityMeta } from '../../metadata/types/entity-meta.types';
|
|
2
|
+
/** Джерело у FROM: корінь, приєднана relation або `json_each`. */
|
|
3
|
+
export interface QuerySource {
|
|
4
|
+
alias: string;
|
|
5
|
+
kind: 'root' | 'join' | 'json';
|
|
6
|
+
meta?: EntityMeta;
|
|
7
|
+
}
|
|
8
|
+
/** Вираз поля, готовий до SQL, і колонка, якщо це колонка entity (для перетворення значень). */
|
|
9
|
+
export interface ResolvedField {
|
|
10
|
+
expr: string;
|
|
11
|
+
column?: ColumnMeta;
|
|
12
|
+
}
|
|
13
|
+
/** Нормалізоване дерево relations: `{ device: { webSessions: {} } }`. */
|
|
14
|
+
export interface RelationTree {
|
|
15
|
+
[property: string]: RelationTree;
|
|
16
|
+
}
|
|
17
|
+
export type JoinType = 'LEFT' | 'INNER';
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { SQLInputValue } from 'node:sqlite';
|
|
2
|
+
import type { ColumnMeta } from '../../metadata/types/entity-meta.types';
|
|
3
|
+
/** Значення поля entity → параметр SQLite: boolean → 0/1, json → текст, Date → ISO, свій transformer. */
|
|
4
|
+
export declare function toDbValue(column: ColumnMeta | undefined, value: unknown): SQLInputValue;
|
|
5
|
+
/** Значення з SQLite → поле entity. */
|
|
6
|
+
export declare function fromDbValue(column: ColumnMeta, value: unknown): unknown;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.toDbValue = toDbValue;
|
|
4
|
+
exports.fromDbValue = fromDbValue;
|
|
5
|
+
/** Значення поля entity → параметр SQLite: boolean → 0/1, json → текст, Date → ISO, свій transformer. */
|
|
6
|
+
function toDbValue(column, value) {
|
|
7
|
+
if (value === undefined || value === null)
|
|
8
|
+
return null;
|
|
9
|
+
if (column?.transformer)
|
|
10
|
+
return column.transformer.to(value);
|
|
11
|
+
if (column?.type === 'json')
|
|
12
|
+
return JSON.stringify(value);
|
|
13
|
+
if (typeof value === 'boolean')
|
|
14
|
+
return value ? 1 : 0;
|
|
15
|
+
if (value instanceof Date)
|
|
16
|
+
return value.toISOString();
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
/** Значення з SQLite → поле entity. */
|
|
20
|
+
function fromDbValue(column, value) {
|
|
21
|
+
if (column.transformer)
|
|
22
|
+
return column.transformer.from(value);
|
|
23
|
+
if (value === null || value === undefined)
|
|
24
|
+
return null;
|
|
25
|
+
if (column.type === 'boolean')
|
|
26
|
+
return value === 1 || value === 1n;
|
|
27
|
+
if (column.type === 'json')
|
|
28
|
+
return JSON.parse(String(value));
|
|
29
|
+
if (typeof value === 'bigint')
|
|
30
|
+
return Number(value);
|
|
31
|
+
return value;
|
|
32
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { ColumnMeta } from '../../metadata/types/entity-meta.types';
|
|
2
|
+
import type { SqlFragment } from '../types/sql-fragment.types';
|
|
3
|
+
/**
|
|
4
|
+
* Одна умова на вираз колонки: голе значення → `=`, `null` → `IS NULL`, масив → `IN`, оператор → його SQL.
|
|
5
|
+
* Єдиний компілятор для query-класів, `_applyWhere` і query builder.
|
|
6
|
+
*/
|
|
7
|
+
export declare function compileCondition(expr: string, value: unknown, column?: ColumnMeta): SqlFragment;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.compileCondition = compileCondition;
|
|
4
|
+
const find_operator_1 = require("../../operators/find-operator");
|
|
5
|
+
const column_value_1 = require("./column-value");
|
|
6
|
+
const COMPARISON = { lessThan: '<', lessThanOrEqual: '<=', moreThan: '>', moreThanOrEqual: '>=' };
|
|
7
|
+
/**
|
|
8
|
+
* Одна умова на вираз колонки: голе значення → `=`, `null` → `IS NULL`, масив → `IN`, оператор → його SQL.
|
|
9
|
+
* Єдиний компілятор для query-класів, `_applyWhere` і query builder.
|
|
10
|
+
*/
|
|
11
|
+
function compileCondition(expr, value, column) {
|
|
12
|
+
const param = (v) => (0, column_value_1.toDbValue)(column, v);
|
|
13
|
+
if (value === null)
|
|
14
|
+
return { sql: `${expr} IS NULL`, params: [] };
|
|
15
|
+
if (Array.isArray(value))
|
|
16
|
+
return compileIn(expr, value.map(param));
|
|
17
|
+
if (!(0, find_operator_1.isFindOperator)(value))
|
|
18
|
+
return { sql: `${expr} = ?`, params: [param(value)] };
|
|
19
|
+
const op = value;
|
|
20
|
+
switch (op.type) {
|
|
21
|
+
case 'equal':
|
|
22
|
+
return compileCondition(expr, op.value ?? null, column);
|
|
23
|
+
case 'isNull':
|
|
24
|
+
return { sql: `${expr} IS NULL`, params: [] };
|
|
25
|
+
case 'in':
|
|
26
|
+
return compileIn(expr, op.value.map(param));
|
|
27
|
+
case 'between': {
|
|
28
|
+
const [from, to] = op.value;
|
|
29
|
+
return { sql: `${expr} >= ? AND ${expr} <= ?`, params: [param(from), param(to)] };
|
|
30
|
+
}
|
|
31
|
+
case 'lessThan':
|
|
32
|
+
case 'lessThanOrEqual':
|
|
33
|
+
case 'moreThan':
|
|
34
|
+
case 'moreThanOrEqual':
|
|
35
|
+
return { sql: `${expr} ${COMPARISON[op.type]} ?`, params: [param(op.value)] };
|
|
36
|
+
case 'like':
|
|
37
|
+
case 'ilike':
|
|
38
|
+
return { sql: `ts_like(?, ${expr}, ${op.type === 'ilike' ? 1 : 0}) = 1`, params: [String(op.value)] };
|
|
39
|
+
case 'not': {
|
|
40
|
+
if (op.value === null || op.value === undefined)
|
|
41
|
+
return { sql: `${expr} IS NOT NULL`, params: [] };
|
|
42
|
+
if (!(0, find_operator_1.isFindOperator)(op.value) && !Array.isArray(op.value))
|
|
43
|
+
return { sql: `${expr} != ?`, params: [param(op.value)] };
|
|
44
|
+
const inner = compileCondition(expr, op.value, column);
|
|
45
|
+
return { sql: `NOT (${inner.sql})`, params: inner.params };
|
|
46
|
+
}
|
|
47
|
+
case 'and': {
|
|
48
|
+
const parts = op.value.map((inner) => compileCondition(expr, inner, column));
|
|
49
|
+
return { sql: parts.map((part) => `(${part.sql})`).join(' AND '), params: parts.flatMap((part) => part.params) };
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
function compileIn(expr, params) {
|
|
54
|
+
if (!params.length)
|
|
55
|
+
return { sql: '0 = 1', params: [] };
|
|
56
|
+
return { sql: `${expr} IN (${params.map(() => '?').join(', ')})`, params };
|
|
57
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.quoteIdentifier = void 0;
|
|
4
|
+
/** `"name"` з подвоєними лапками всередині. Імена беруться з метаданих, але лапки ставимо завжди. */
|
|
5
|
+
const quoteIdentifier = (name) => `"${name.replace(/"/g, '""')}"`;
|
|
6
|
+
exports.quoteIdentifier = quoteIdentifier;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { ColumnMeta, EntityMeta, RelationMeta } from '../../metadata/types/entity-meta.types';
|
|
2
|
+
export declare function findRelation(meta: EntityMeta, property: string): RelationMeta;
|
|
3
|
+
export declare function findColumn(meta: EntityMeta, property: string): ColumnMeta;
|
|
4
|
+
export declare function primaryColumn(meta: EntityMeta): ColumnMeta;
|
|
5
|
+
/** Зворотна relation на дочірній entity, що тримає FK (`(session) => session.device` → її ManyToOne). */
|
|
6
|
+
export declare function inverseOwner(relation: RelationMeta): {
|
|
7
|
+
meta: EntityMeta;
|
|
8
|
+
owner: RelationMeta;
|
|
9
|
+
};
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.findRelation = findRelation;
|
|
4
|
+
exports.findColumn = findColumn;
|
|
5
|
+
exports.primaryColumn = primaryColumn;
|
|
6
|
+
exports.inverseOwner = inverseOwner;
|
|
7
|
+
const metadata_storage_1 = require("../../metadata/metadata-storage");
|
|
8
|
+
const resolve_inverse_property_1 = require("./resolve-inverse-property");
|
|
9
|
+
function findRelation(meta, property) {
|
|
10
|
+
const relation = meta.relations.find((existing) => existing.property === property);
|
|
11
|
+
if (!relation)
|
|
12
|
+
throw new Error(`${meta.target.name}.${property} is not a relation`);
|
|
13
|
+
return relation;
|
|
14
|
+
}
|
|
15
|
+
function findColumn(meta, property) {
|
|
16
|
+
const column = meta.columns.find((existing) => existing.property === property);
|
|
17
|
+
if (!column)
|
|
18
|
+
throw new Error(`${meta.target.name}.${property} is not a column`);
|
|
19
|
+
return column;
|
|
20
|
+
}
|
|
21
|
+
function primaryColumn(meta) {
|
|
22
|
+
const primary = meta.columns.filter((column) => column.primary);
|
|
23
|
+
if (primary.length !== 1)
|
|
24
|
+
throw new Error(`${meta.target.name}: relations need exactly one primary column`);
|
|
25
|
+
return primary[0];
|
|
26
|
+
}
|
|
27
|
+
/** Зворотна relation на дочірній entity, що тримає FK (`(session) => session.device` → її ManyToOne). */
|
|
28
|
+
function inverseOwner(relation) {
|
|
29
|
+
const meta = (0, metadata_storage_1.getEntityMeta)(relation.target());
|
|
30
|
+
const owner = findRelation(meta, (0, resolve_inverse_property_1.resolveInverseProperty)(relation.inverse));
|
|
31
|
+
if (!owner.joinColumn)
|
|
32
|
+
throw new Error(`${meta.target.name}.${owner.property}: inverse side must own the join column`);
|
|
33
|
+
return { meta, owner };
|
|
34
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.resolveInverseProperty = resolveInverseProperty;
|
|
4
|
+
/** `(session) => session.device` → `'device'`: викликає функцію на Proxy, що запам'ятовує, яке поле прочитали. */
|
|
5
|
+
function resolveInverseProperty(inverse) {
|
|
6
|
+
let property;
|
|
7
|
+
const probe = new Proxy({}, { get: (_target, key) => ((property ??= String(key)), undefined) });
|
|
8
|
+
inverse(probe);
|
|
9
|
+
if (!property)
|
|
10
|
+
throw new Error('Relation inverse must read a property: (child) => child.parent');
|
|
11
|
+
return property;
|
|
12
|
+
}
|