@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
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 sabationok
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,64 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @my-nestjs-kit/sqlite
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Small ORM for NestJS over `node:sqlite` (`DatabaseSync`, Node >= 22.5). No native addons, so it bundles into a single
|
|
4
|
+
file (esbuild) and does not depend on the Node ABI.
|
|
5
|
+
|
|
6
|
+
```sh
|
|
7
|
+
pnpm add @my-nestjs-kit/sqlite
|
|
8
|
+
# peers: @nestjs/common >= 10, reflect-metadata
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
- Entities on decorators: `@Entity`, `@Column`, `@PrimaryColumn`, `@PrimaryGeneratedColumn('increment' | 'uuid')`,
|
|
12
|
+
`@CreateDateColumn`, `@UpdateDateColumn`, `@StateDateColumn` (a state stored as a nullable time, a derived bool in
|
|
13
|
+
queries), `@DeleteDateColumn` (soft delete), `@Index`, `@ManyToOne` / `@OneToOne` / `@OneToMany`. Column types are
|
|
14
|
+
explicit (`text | integer | real | blob | boolean | json`), so `emitDecoratorMetadata` is not needed.
|
|
15
|
+
- `SqliteRepository<E, QForOne, QForMany>` + `@EntityRepository`: `findOne`, `findMany`, `count`, `exists`, `create`,
|
|
16
|
+
`createMany`, `update`, `upsert`, `delete` / `restore` / `hardDelete`; find opts `select`, `relations`, `order`,
|
|
17
|
+
`withDeleted`, `onlyDeleted`.
|
|
18
|
+
- Find operators: `Equal`, `Not`, `IsNull`, `In`, `Between`, `LessThan(OrEqual)`, `MoreThan(OrEqual)`, `Like`, `ILike`
|
|
19
|
+
(Unicode-aware, Cyrillic included), `And`.
|
|
20
|
+
- `SqliteQueryBuilder` ("qb lite"): join by relation, `jsonEach`, aggregates, `groupBy`, conditional mutations.
|
|
21
|
+
- Migrations as classes `@Migration(name)` (with DI) and objects `defineMigration`, table `_migrations`,
|
|
22
|
+
`MigrationsService.revert`.
|
|
23
|
+
- Guards: values only as parameters, identifiers only from metadata, runtime checks of order direction / `limit` /
|
|
24
|
+
`offset` / names, `ts_like` without ReDoS.
|
|
25
|
+
|
|
26
|
+
App modules write no SQL: only repository methods, operators or `_qb()`. SQL lives in this package and in migrations.
|
|
27
|
+
|
|
28
|
+
## Use
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
SqliteModule.forRootAsync({
|
|
32
|
+
inject: [APP_CONFIG],
|
|
33
|
+
useFactory: (config: AppConfig) => ({ path: config.dbPath, pragmas: { journal_mode: 'WAL', foreign_keys: 'ON' } }),
|
|
34
|
+
migrations: DATABASE_MIGRATIONS, // classes and defineMigration objects, run in `name` order before any provider
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
@Entity('sessions')
|
|
38
|
+
@Index(['startedAt'])
|
|
39
|
+
export class SessionEntity {
|
|
40
|
+
@PrimaryGeneratedColumn() id!: number;
|
|
41
|
+
@Column({ type: 'text' }) startedAt!: string;
|
|
42
|
+
@Column({ type: 'text', nullable: true }) endedAt!: string | null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
@EntityRepository(SessionEntity)
|
|
46
|
+
export class SessionsRepository extends SqliteRepository<SessionEntity, FindOneSessionQuery, FindManySessionsQuery> {}
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
`SqliteModule` is global and owns one connection per app; it closes it in `onApplicationShutdown`. The API is
|
|
50
|
+
synchronous: `transaction(fn)` throws when `fn` returns a `Promise`.
|
|
51
|
+
|
|
52
|
+
Design notes, the full API and the guards: [`docs/spec.md`](https://github.com/sabationok/my-nestjs-kit/blob/dev/packages/sqlite/docs/spec.md)
|
|
53
|
+
(in the repo, not shipped in the npm package).
|
|
54
|
+
|
|
55
|
+
## Develop
|
|
56
|
+
|
|
57
|
+
From the workspace root: `pnpm install`, `pnpm --filter @my-nestjs-kit/sqlite build` / `typecheck`. The package has no
|
|
58
|
+
automated tests yet. Every change a consumer can notice (behaviour, the public API in `src/index.ts`, schema or
|
|
59
|
+
`_migrations`, guards) carries a changeset (`pnpm changeset`); `major` when an export is removed or renamed, a signature,
|
|
60
|
+
default behaviour or storage format changes, or a guard rejects a call that used to pass, with migration steps.
|
|
61
|
+
|
|
62
|
+
## License
|
|
63
|
+
|
|
64
|
+
MIT
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** Опції `SqliteModule.forRootAsync` після `useFactory`. */
|
|
2
|
+
export declare const SQLITE_MODULE_OPTIONS: unique symbol;
|
|
3
|
+
/** Міграції з опцій модуля, уже з іменами й інстансами класів. */
|
|
4
|
+
export declare const SQLITE_MIGRATIONS: unique symbol;
|
|
5
|
+
/** Ключ метаданих `@Migration(name)` на класі міграції. */
|
|
6
|
+
export declare const SQLITE_MIGRATION_NAME: unique symbol;
|
|
7
|
+
/** Таблиця виконаних міграцій. */
|
|
8
|
+
export declare const SQLITE_MIGRATIONS_TABLE = "_migrations";
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SQLITE_MIGRATIONS_TABLE = exports.SQLITE_MIGRATION_NAME = exports.SQLITE_MIGRATIONS = exports.SQLITE_MODULE_OPTIONS = void 0;
|
|
4
|
+
/** Опції `SqliteModule.forRootAsync` після `useFactory`. */
|
|
5
|
+
exports.SQLITE_MODULE_OPTIONS = Symbol('SQLITE_MODULE_OPTIONS');
|
|
6
|
+
/** Міграції з опцій модуля, уже з іменами й інстансами класів. */
|
|
7
|
+
exports.SQLITE_MIGRATIONS = Symbol('SQLITE_MIGRATIONS');
|
|
8
|
+
/** Ключ метаданих `@Migration(name)` на класі міграції. */
|
|
9
|
+
exports.SQLITE_MIGRATION_NAME = Symbol('SQLITE_MIGRATION_NAME');
|
|
10
|
+
/** Таблиця виконаних міграцій. */
|
|
11
|
+
exports.SQLITE_MIGRATIONS_TABLE = '_migrations';
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* LIKE-шаблон (`%` — будь-скільки символів, `_` — один) по кодових точках, без RegExp.
|
|
3
|
+
* Жадібний алгоритм з одним поверненням до останнього `%`: O(шаблон × значення) у найгіршому разі,
|
|
4
|
+
* без експоненційного backtracking (ReDoS) на шаблонах на кшталт `%a%a%a…%b`.
|
|
5
|
+
*/
|
|
6
|
+
export declare function matchLikePattern(pattern: readonly string[], value: readonly string[]): boolean;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.matchLikePattern = matchLikePattern;
|
|
4
|
+
/**
|
|
5
|
+
* LIKE-шаблон (`%` — будь-скільки символів, `_` — один) по кодових точках, без RegExp.
|
|
6
|
+
* Жадібний алгоритм з одним поверненням до останнього `%`: O(шаблон × значення) у найгіршому разі,
|
|
7
|
+
* без експоненційного backtracking (ReDoS) на шаблонах на кшталт `%a%a%a…%b`.
|
|
8
|
+
*/
|
|
9
|
+
function matchLikePattern(pattern, value) {
|
|
10
|
+
let p = 0;
|
|
11
|
+
let v = 0;
|
|
12
|
+
let star = -1;
|
|
13
|
+
let mark = 0;
|
|
14
|
+
while (v < value.length) {
|
|
15
|
+
if (p < pattern.length && pattern[p] === '%') {
|
|
16
|
+
star = p++;
|
|
17
|
+
mark = v;
|
|
18
|
+
}
|
|
19
|
+
else if (p < pattern.length && (pattern[p] === '_' || pattern[p] === value[v])) {
|
|
20
|
+
p++;
|
|
21
|
+
v++;
|
|
22
|
+
}
|
|
23
|
+
else if (star !== -1) {
|
|
24
|
+
p = star + 1;
|
|
25
|
+
v = ++mark;
|
|
26
|
+
}
|
|
27
|
+
else {
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
while (p < pattern.length && pattern[p] === '%')
|
|
32
|
+
p++;
|
|
33
|
+
return p === pattern.length;
|
|
34
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { DatabaseSync } from 'node:sqlite';
|
|
2
|
+
/** Довший шаблон — помилка запиту: пошук по вводу з HTTP не має тягнути O(шаблон × значення) без меж. */
|
|
3
|
+
export declare const TS_LIKE_MAX_PATTERN = 500;
|
|
4
|
+
/**
|
|
5
|
+
* `ts_like(pattern, value, ci)` для `Like` / `ILike`. Вбудований LIKE у SQLite для ASCII завжди без регістру,
|
|
6
|
+
* а `lower()` / NOCASE не знають кирилиці, тож шаблон перевіряє JS (`toLowerCase` знає Unicode) лінійним
|
|
7
|
+
* matcher-ом, не RegExp: шаблон приходить з даних, а RegExp з багатьма `%` дає катастрофічний backtracking.
|
|
8
|
+
*/
|
|
9
|
+
export declare function registerTsLike(db: DatabaseSync): void;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TS_LIKE_MAX_PATTERN = void 0;
|
|
4
|
+
exports.registerTsLike = registerTsLike;
|
|
5
|
+
const match_like_pattern_1 = require("./match-like-pattern");
|
|
6
|
+
/** Довший шаблон — помилка запиту: пошук по вводу з HTTP не має тягнути O(шаблон × значення) без меж. */
|
|
7
|
+
exports.TS_LIKE_MAX_PATTERN = 500;
|
|
8
|
+
function toChars(text, caseInsensitive) {
|
|
9
|
+
return Array.from(caseInsensitive ? text.toLowerCase() : text);
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* `ts_like(pattern, value, ci)` для `Like` / `ILike`. Вбудований LIKE у SQLite для ASCII завжди без регістру,
|
|
13
|
+
* а `lower()` / NOCASE не знають кирилиці, тож шаблон перевіряє JS (`toLowerCase` знає Unicode) лінійним
|
|
14
|
+
* matcher-ом, не RegExp: шаблон приходить з даних, а RegExp з багатьма `%` дає катастрофічний backtracking.
|
|
15
|
+
*/
|
|
16
|
+
function registerTsLike(db) {
|
|
17
|
+
db.function('ts_like', { deterministic: true }, (pattern, value, caseInsensitive) => {
|
|
18
|
+
if (value === null || pattern === null)
|
|
19
|
+
return null;
|
|
20
|
+
const ci = caseInsensitive === 1;
|
|
21
|
+
const chars = toChars(String(pattern), ci).filter((char, index, all) => char !== '%' || all[index - 1] !== '%');
|
|
22
|
+
if (chars.length > exports.TS_LIKE_MAX_PATTERN)
|
|
23
|
+
throw new Error(`ts_like: pattern longer than ${exports.TS_LIKE_MAX_PATTERN} characters`);
|
|
24
|
+
return (0, match_like_pattern_1.matchLikePattern)(chars, toChars(String(value), ci)) ? 1 : 0;
|
|
25
|
+
});
|
|
26
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { DatabaseSync, type SQLInputValue, type StatementSync } from 'node:sqlite';
|
|
2
|
+
import type { SqliteModuleOptions } from '../types/sqlite-module-options.types';
|
|
3
|
+
/** Одне з'єднання `node:sqlite` на процес: кеш statements і синхронні транзакції з savepoint для вкладених. */
|
|
4
|
+
export declare class SqliteDataSource {
|
|
5
|
+
readonly db: DatabaseSync;
|
|
6
|
+
private readonly _statements;
|
|
7
|
+
private _txDepth;
|
|
8
|
+
constructor(options: SqliteModuleOptions);
|
|
9
|
+
get isOpen(): boolean;
|
|
10
|
+
get inTransaction(): boolean;
|
|
11
|
+
/**
|
|
12
|
+
* Statement з кешу за текстом SQL. SQLite сам перепідготує його після зміни схеми.
|
|
13
|
+
* Кеш обмежений: `In([...])` різної довжини дає різний текст.
|
|
14
|
+
*/
|
|
15
|
+
prepare(sql: string): StatementSync;
|
|
16
|
+
run(sql: string, ...params: SQLInputValue[]): {
|
|
17
|
+
changes: number;
|
|
18
|
+
lastInsertRowid: number;
|
|
19
|
+
};
|
|
20
|
+
exec(sql: string): void;
|
|
21
|
+
query<R = Record<string, unknown>>(sql: string, ...params: SQLInputValue[]): R[];
|
|
22
|
+
/**
|
|
23
|
+
* `fn` має бути синхронною: API `node:sqlite` синхронний, і `await` усередині віддав би чергу коду,
|
|
24
|
+
* який виконався б у цій самій транзакції. Promise у результаті — rollback і помилка.
|
|
25
|
+
* Вкладений виклик — SAVEPOINT: його помилка відкочує лише його частину, якщо зовнішній код її перехопив.
|
|
26
|
+
*/
|
|
27
|
+
transaction<T>(fn: () => T): T;
|
|
28
|
+
hasTable(name: string): boolean;
|
|
29
|
+
hasColumn(table: string, column: string): boolean;
|
|
30
|
+
close(): void;
|
|
31
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SqliteDataSource = void 0;
|
|
4
|
+
const node_fs_1 = require("node:fs");
|
|
5
|
+
const node_path_1 = require("node:path");
|
|
6
|
+
const node_sqlite_1 = require("node:sqlite");
|
|
7
|
+
const assert_pragma_value_1 = require("../helpers/assert-pragma-value");
|
|
8
|
+
const assert_sql_name_1 = require("../helpers/assert-sql-name");
|
|
9
|
+
const register_ts_like_1 = require("./helpers/register-ts-like");
|
|
10
|
+
const STATEMENT_CACHE_LIMIT = 300;
|
|
11
|
+
const isThenable = (value) => typeof value?.then === 'function';
|
|
12
|
+
/** Одне з'єднання `node:sqlite` на процес: кеш statements і синхронні транзакції з savepoint для вкладених. */
|
|
13
|
+
class SqliteDataSource {
|
|
14
|
+
db;
|
|
15
|
+
_statements = new Map();
|
|
16
|
+
_txDepth = 0;
|
|
17
|
+
constructor(options) {
|
|
18
|
+
if (options.path !== ':memory:')
|
|
19
|
+
(0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(options.path), { recursive: true });
|
|
20
|
+
this.db = new node_sqlite_1.DatabaseSync(options.path);
|
|
21
|
+
for (const [key, value] of Object.entries(options.pragmas ?? {}))
|
|
22
|
+
this.db.exec(`PRAGMA ${(0, assert_sql_name_1.assertSqlName)('pragma', key)} = ${(0, assert_pragma_value_1.assertPragmaValue)(key, value)}`);
|
|
23
|
+
(0, register_ts_like_1.registerTsLike)(this.db);
|
|
24
|
+
}
|
|
25
|
+
get isOpen() {
|
|
26
|
+
return this.db.isOpen;
|
|
27
|
+
}
|
|
28
|
+
get inTransaction() {
|
|
29
|
+
return this._txDepth > 0;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Statement з кешу за текстом SQL. SQLite сам перепідготує його після зміни схеми.
|
|
33
|
+
* Кеш обмежений: `In([...])` різної довжини дає різний текст.
|
|
34
|
+
*/
|
|
35
|
+
prepare(sql) {
|
|
36
|
+
let statement = this._statements.get(sql);
|
|
37
|
+
if (!statement) {
|
|
38
|
+
statement = this.db.prepare(sql);
|
|
39
|
+
if (this._statements.size >= STATEMENT_CACHE_LIMIT)
|
|
40
|
+
this._statements.delete(this._statements.keys().next().value);
|
|
41
|
+
this._statements.set(sql, statement);
|
|
42
|
+
}
|
|
43
|
+
return statement;
|
|
44
|
+
}
|
|
45
|
+
run(sql, ...params) {
|
|
46
|
+
const result = this.prepare(sql).run(...params);
|
|
47
|
+
return { changes: Number(result.changes), lastInsertRowid: Number(result.lastInsertRowid) };
|
|
48
|
+
}
|
|
49
|
+
exec(sql) {
|
|
50
|
+
this.db.exec(sql);
|
|
51
|
+
}
|
|
52
|
+
query(sql, ...params) {
|
|
53
|
+
return this.prepare(sql).all(...params);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* `fn` має бути синхронною: API `node:sqlite` синхронний, і `await` усередині віддав би чергу коду,
|
|
57
|
+
* який виконався б у цій самій транзакції. Promise у результаті — rollback і помилка.
|
|
58
|
+
* Вкладений виклик — SAVEPOINT: його помилка відкочує лише його частину, якщо зовнішній код її перехопив.
|
|
59
|
+
*/
|
|
60
|
+
transaction(fn) {
|
|
61
|
+
const depth = this._txDepth;
|
|
62
|
+
const savepoint = `sp_${depth}`;
|
|
63
|
+
this.db.exec(depth === 0 ? 'BEGIN' : `SAVEPOINT ${savepoint}`);
|
|
64
|
+
this._txDepth++;
|
|
65
|
+
try {
|
|
66
|
+
const result = fn();
|
|
67
|
+
if (isThenable(result)) {
|
|
68
|
+
Promise.resolve(result).catch(() => undefined);
|
|
69
|
+
throw new Error('SqliteDataSource.transaction: fn returned a Promise; transactions over node:sqlite must be synchronous');
|
|
70
|
+
}
|
|
71
|
+
this.db.exec(depth === 0 ? 'COMMIT' : `RELEASE ${savepoint}`);
|
|
72
|
+
return result;
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
this.db.exec(depth === 0 ? 'ROLLBACK' : `ROLLBACK TO ${savepoint}; RELEASE ${savepoint}`);
|
|
76
|
+
throw error;
|
|
77
|
+
}
|
|
78
|
+
finally {
|
|
79
|
+
this._txDepth--;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
hasTable(name) {
|
|
83
|
+
return this.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?", name).length > 0;
|
|
84
|
+
}
|
|
85
|
+
hasColumn(table, column) {
|
|
86
|
+
return this.query('SELECT name FROM pragma_table_info(?)', table).some((existing) => existing.name === column);
|
|
87
|
+
}
|
|
88
|
+
close() {
|
|
89
|
+
this._statements.clear();
|
|
90
|
+
if (this.db.isOpen)
|
|
91
|
+
this.db.close();
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
exports.SqliteDataSource = SqliteDataSource;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { ColumnMeta, ColumnOptions } from '../metadata/types/entity-meta.types';
|
|
2
|
+
/** Спільна частина декораторів колонок. Тип задається явно: без `emitDecoratorMetadata`. */
|
|
3
|
+
export declare function defineColumn(options: ColumnOptions, extra?: Partial<Pick<ColumnMeta, 'primary' | 'generated' | 'role'>>): PropertyDecorator;
|
|
4
|
+
export declare function Column(options: ColumnOptions): PropertyDecorator;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.defineColumn = defineColumn;
|
|
4
|
+
exports.Column = Column;
|
|
5
|
+
const metadata_storage_1 = require("../metadata/metadata-storage");
|
|
6
|
+
const to_snake_case_1 = require("../metadata/helpers/to-snake-case");
|
|
7
|
+
/** Спільна частина декораторів колонок. Тип задається явно: без `emitDecoratorMetadata`. */
|
|
8
|
+
function defineColumn(options, extra = {}) {
|
|
9
|
+
return (target, property) => {
|
|
10
|
+
(0, metadata_storage_1.addColumnMeta)(target.constructor, {
|
|
11
|
+
property: String(property),
|
|
12
|
+
name: options.name ?? (0, to_snake_case_1.toSnakeCase)(String(property)),
|
|
13
|
+
type: options.type,
|
|
14
|
+
nullable: options.nullable ?? false,
|
|
15
|
+
transformer: options.transformer,
|
|
16
|
+
primary: extra.primary ?? false,
|
|
17
|
+
generated: extra.generated,
|
|
18
|
+
role: extra.role ?? 'regular',
|
|
19
|
+
});
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
function Column(options) {
|
|
23
|
+
return defineColumn(options);
|
|
24
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.CreateDateColumn = CreateDateColumn;
|
|
4
|
+
const column_decorator_1 = require("./column.decorator");
|
|
5
|
+
/** ISO-час створення; база ставить його в `create`, якщо DTO його не дав. */
|
|
6
|
+
function CreateDateColumn(name) {
|
|
7
|
+
return (0, column_decorator_1.defineColumn)({ type: 'text', name }, { role: 'create-date' });
|
|
8
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DeleteDateColumn = DeleteDateColumn;
|
|
4
|
+
const column_decorator_1 = require("./column.decorator");
|
|
5
|
+
/** Soft delete: `delete` ставить час, пошук виключає такі рядки, поки не попросили `withDeleted`. */
|
|
6
|
+
function DeleteDateColumn(name) {
|
|
7
|
+
return (0, column_decorator_1.defineColumn)({ type: 'text', name, nullable: true }, { role: 'delete-date' });
|
|
8
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { type Type } from '@nestjs/common';
|
|
2
|
+
/** Репозиторій entity: `class XRepository extends SqliteRepository<...>`. Реєструється у providers модуля як звичайний провайдер. */
|
|
3
|
+
export declare function EntityRepository(entity: Type<unknown>): ClassDecorator;
|
|
4
|
+
export declare function getRepositoryEntity(target: Function): Type<unknown>;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.EntityRepository = EntityRepository;
|
|
4
|
+
exports.getRepositoryEntity = getRepositoryEntity;
|
|
5
|
+
const common_1 = require("@nestjs/common");
|
|
6
|
+
const ENTITY_REPOSITORY = Symbol('SQLITE_ENTITY_REPOSITORY');
|
|
7
|
+
/** Репозиторій entity: `class XRepository extends SqliteRepository<...>`. Реєструється у providers модуля як звичайний провайдер. */
|
|
8
|
+
function EntityRepository(entity) {
|
|
9
|
+
return (target) => {
|
|
10
|
+
Reflect.defineMetadata(ENTITY_REPOSITORY, entity, target);
|
|
11
|
+
(0, common_1.Injectable)()(target);
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
function getRepositoryEntity(target) {
|
|
15
|
+
const entity = Reflect.getMetadata(ENTITY_REPOSITORY, target);
|
|
16
|
+
if (!entity)
|
|
17
|
+
throw new Error(`${target.name} has no @EntityRepository(Entity)`);
|
|
18
|
+
return entity;
|
|
19
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function Entity(table: string): ClassDecorator;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Entity = Entity;
|
|
4
|
+
const metadata_storage_1 = require("../metadata/metadata-storage");
|
|
5
|
+
function Entity(table) {
|
|
6
|
+
return (target) => (0, metadata_storage_1.setEntityTable)(target, table);
|
|
7
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Index = Index;
|
|
4
|
+
const metadata_storage_1 = require("../metadata/metadata-storage");
|
|
5
|
+
/** Індекс для `schema:sql` і перевірки дрейфу; створює його міграція. */
|
|
6
|
+
function Index(fields, options = {}) {
|
|
7
|
+
return (target) => (0, metadata_storage_1.addIndexMeta)(target, { fields, unique: options.unique ?? false, name: options.name });
|
|
8
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Type } from '@nestjs/common';
|
|
2
|
+
import type { RelationMeta } from '../metadata/types/entity-meta.types';
|
|
3
|
+
/** Власник зв'язку: `joinColumn` — поле цієї entity з FK (`deviceId`). Завантажується LEFT JOIN. */
|
|
4
|
+
export declare function ManyToOne<T>(target: () => Type<T>, options: {
|
|
5
|
+
joinColumn: string;
|
|
6
|
+
onDelete?: RelationMeta['onDelete'];
|
|
7
|
+
}): PropertyDecorator;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ManyToOne = ManyToOne;
|
|
4
|
+
const metadata_storage_1 = require("../metadata/metadata-storage");
|
|
5
|
+
/** Власник зв'язку: `joinColumn` — поле цієї entity з FK (`deviceId`). Завантажується LEFT JOIN. */
|
|
6
|
+
function ManyToOne(target, options) {
|
|
7
|
+
return (entity, property) => (0, metadata_storage_1.addRelationMeta)(entity.constructor, { property: String(property), type: 'many-to-one', target, joinColumn: options.joinColumn, onDelete: options.onDelete });
|
|
8
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.OneToMany = OneToMany;
|
|
4
|
+
const metadata_storage_1 = require("../metadata/metadata-storage");
|
|
5
|
+
/** Зворотна сторона `ManyToOne`. Завантажується другим запитом `WHERE fk IN (...)`, не JOIN. */
|
|
6
|
+
function OneToMany(target, inverse) {
|
|
7
|
+
return (entity, property) => (0, metadata_storage_1.addRelationMeta)(entity.constructor, { property: String(property), type: 'one-to-many', target, inverse });
|
|
8
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Type } from '@nestjs/common';
|
|
2
|
+
import type { RelationMeta } from '../metadata/types/entity-meta.types';
|
|
3
|
+
/** З `joinColumn` — власник (FK тут); без нього — зворотна сторона, `inverse` вказує на relation-власника. */
|
|
4
|
+
export declare function OneToOne<T>(target: () => Type<T>, options: {
|
|
5
|
+
joinColumn: string;
|
|
6
|
+
onDelete?: RelationMeta['onDelete'];
|
|
7
|
+
} | {
|
|
8
|
+
inverse: (entity: T) => unknown;
|
|
9
|
+
}): PropertyDecorator;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.OneToOne = OneToOne;
|
|
4
|
+
const metadata_storage_1 = require("../metadata/metadata-storage");
|
|
5
|
+
/** З `joinColumn` — власник (FK тут); без нього — зворотна сторона, `inverse` вказує на relation-власника. */
|
|
6
|
+
function OneToOne(target, options) {
|
|
7
|
+
return (entity, property) => (0, metadata_storage_1.addRelationMeta)(entity.constructor, {
|
|
8
|
+
property: String(property),
|
|
9
|
+
type: 'one-to-one',
|
|
10
|
+
target,
|
|
11
|
+
...('joinColumn' in options ? { joinColumn: options.joinColumn, onDelete: options.onDelete } : { inverse: options.inverse }),
|
|
12
|
+
});
|
|
13
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.PrimaryColumn = PrimaryColumn;
|
|
4
|
+
const column_decorator_1 = require("./column.decorator");
|
|
5
|
+
/** Природний ключ (`ssid`). Кілька полів з ним — складений ключ. */
|
|
6
|
+
function PrimaryColumn(options = { type: 'text' }) {
|
|
7
|
+
return (0, column_decorator_1.defineColumn)(options, { primary: true });
|
|
8
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.PrimaryGeneratedColumn = PrimaryGeneratedColumn;
|
|
4
|
+
const column_decorator_1 = require("./column.decorator");
|
|
5
|
+
/** `increment` — INTEGER AUTOINCREMENT, id з lastInsertRowid; `uuid` — TEXT, `randomUUID()` при create. */
|
|
6
|
+
function PrimaryGeneratedColumn(strategy = 'increment', name) {
|
|
7
|
+
return (0, column_decorator_1.defineColumn)({ type: strategy === 'uuid' ? 'text' : 'integer', name }, { primary: true, generated: strategy });
|
|
8
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.StateDateColumn = StateDateColumn;
|
|
4
|
+
const column_decorator_1 = require("./column.decorator");
|
|
5
|
+
/**
|
|
6
|
+
* Стан рядка як час події (`disabledAt`, `revokedAt`, `endedAt`), не bool. Поле — `<participle>At`;
|
|
7
|
+
* query може фільтрувати похідним `<participle>?: boolean` → `IS [NOT] NULL`.
|
|
8
|
+
*/
|
|
9
|
+
function StateDateColumn(name) {
|
|
10
|
+
return (target, property) => {
|
|
11
|
+
if (!String(property).endsWith('At'))
|
|
12
|
+
throw new Error(`${target.constructor.name}.${String(property)}: state column must be named <participle>At`);
|
|
13
|
+
(0, column_decorator_1.defineColumn)({ type: 'text', name, nullable: true }, { role: 'state-date' })(target, property);
|
|
14
|
+
};
|
|
15
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.UpdateDateColumn = UpdateDateColumn;
|
|
4
|
+
const column_decorator_1 = require("./column.decorator");
|
|
5
|
+
/** ISO-час останньої зміни; NULL після create, база ставить його в кожному `update`. */
|
|
6
|
+
function UpdateDateColumn(name) {
|
|
7
|
+
return (0, column_decorator_1.defineColumn)({ type: 'text', name, nullable: true }, { role: 'update-date' });
|
|
8
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.assertOrderDirection = assertOrderDirection;
|
|
4
|
+
const DIRECTIONS = ['ASC', 'DESC'];
|
|
5
|
+
/** Напрямок іде в текст SQL, тож у рантаймі — лише `ASC` / `DESC` (тип TS не захищає від даних з HTTP). */
|
|
6
|
+
function assertOrderDirection(direction) {
|
|
7
|
+
const upper = typeof direction === 'string' ? direction.toUpperCase() : direction;
|
|
8
|
+
if (typeof upper !== 'string' || !DIRECTIONS.includes(upper))
|
|
9
|
+
throw new Error(`Invalid order direction: ${String(direction)}`);
|
|
10
|
+
return upper;
|
|
11
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.assertPragmaValue = assertPragmaValue;
|
|
4
|
+
const PRAGMA_VALUE = /^(?:-?\d+|[A-Za-z_][A-Za-z0-9_]*)$/;
|
|
5
|
+
/** Значення pragma — число або слово (`WAL`, `ON`, `-2000`); більше нічого в `PRAGMA x = …` не йде. */
|
|
6
|
+
function assertPragmaValue(name, value) {
|
|
7
|
+
const text = String(value);
|
|
8
|
+
if (!PRAGMA_VALUE.test(text))
|
|
9
|
+
throw new Error(`Invalid value for pragma ${name}: ${text}`);
|
|
10
|
+
return text;
|
|
11
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.assertRowCount = assertRowCount;
|
|
4
|
+
/** `LIMIT` / `OFFSET` ідуть у текст SQL: лише ціле невід'ємне число в межах safe integer. */
|
|
5
|
+
function assertRowCount(name, value) {
|
|
6
|
+
if (value === undefined)
|
|
7
|
+
return undefined;
|
|
8
|
+
if (!Number.isSafeInteger(value) || value < 0)
|
|
9
|
+
throw new Error(`Invalid ${name}: ${String(value)}`);
|
|
10
|
+
return value;
|
|
11
|
+
}
|