### Running Examples Source: https://github.com/ycforge/ydb-orm/blob/main/examples/README.md Commands to install dependencies, build the project, and execute a specific example. ```bash yarn install yarn build # собрать dist/ yarn examples:build # скомпилировать src + examples в dist-examples/ node dist-examples/examples/01-users/main.js ``` -------------------------------- ### Example Directory Structure Source: https://github.com/ycforge/ydb-orm/blob/main/examples/README.md Overview of the available example projects located in the examples directory. ```text examples/ ├── 01-users/ базовый пример: подключение, сохранение и чтение сущности ├── 02-crud/ полный CRUD: insertMany, updateBy, delete, deleteBy, count ├── 03-search/ поиск: find / findOneBy / findAll / findBy, пагинация ├── 04-relations/ связи: 1:N, N:1, 1:1, многие-ко-многим, eager/ленивая загрузка ├── 05-query-builder/ YdbQueryBuilder: AND/OR, сортировка, лимиты, проекция ├── 06-encryption/ шифрование полей, blind index, Security AAD, ленивая дешифровка ├── 07-transactions/ транзакции: runInTransaction, retry, ambient/reuse, таймауты ├── 08-schema-sync/ автосинхронизация схемы БД и проверка через YdbSchemaSyncer ├── 09-migrations/ миграции: runner, loader, пример конфига для CLI ├── 10-repository/ YdbRepository / YdbEntityManager без DI ├── 11-advanced/ продвинутые декораторы: enum, json, TTL, индексы, таймстампы, хуки └── nestjs/ примеры интеграции с NestJS (подпакет @ycforge/ydb-orm/nest) ├── 01-crud/ модуль, Active Record и инжектируемый репозиторий ├── 02-transactions/ транзакции через YdbTransactionManager из DI ├── 03-encryption/ шифрование через DI-провайдеры └── 04-schema-sync/ sync: true при старте и ручная проверка схемы ``` -------------------------------- ### Development Commands Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Standard commands for installing dependencies, building, testing, and linting the project. ```bash yarn install yarn build # tsc → dist/ (ESM + .d.ts) yarn test # jest (ESM), unit + NestJS-интеграционные тесты yarn lint # eslint --fix yarn format # prettier --write ``` -------------------------------- ### Install @ycforge/ydb-orm Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Commands to install the core package and optional peer dependencies for NestJS integration. ```bash # единственный устанавливаемый пакет (ядро + подпакет @ycforge/ydb-orm/nest): yarn add @ycforge/ydb-orm # опционально, для NestJS-интеграции — peer-зависимости: yarn add @nestjs/common @nestjs/core reflect-metadata rxjs ``` -------------------------------- ### Define YDB ORM Configuration Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Example configuration file structure for YDB ORM, supporting various JS/TS formats. ```ts import { createAuth, authKeyFromFile } from '@ycforge/auth'; import { UserEntity } from './src/user.entity.js'; export default { endpoint: process.env.YDB_ENDPOINT!, auth: createAuth(authKeyFromFile('./authorized_key.json')), entities: [UserEntity], // нужно для migration:generate migrationsDir: './migrations', // опционально }; ``` -------------------------------- ### WHERE Operators Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Example of using logical operators and comparison filters within a query. ```ts await UserEntity.findAll({ $or: [ { balance: { $gte: 100 } }, { is_admin: true }, ], is_banned: false, }); ``` -------------------------------- ### Standalone Transaction Execution Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Basic setup and execution of a transaction using YdbTransactionManager in a standalone environment. ```ts import { YdbTransactionManager, createExecutor, createDriver } from '@ycforge/ydb-orm'; import { createAuth } from '@ycforge/auth'; const driver = createDriver({ endpoint: '...', auth: createAuth({ type: 'anonymous' }), }); const executor = createExecutor(driver); const txManager = new YdbTransactionManager(executor); await txManager.runInTransaction(async (trx) => { const user = await UserEntity.find({ uuid: userId }, { trx }); await UserEntity.save(user, { trx }); }); ``` -------------------------------- ### QueryBuilder Usage Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Demonstrates basic query construction, execution methods, and YQL generation. ```ts const photos = await PhotoEntity.query() .where({ is_public: true }) .andWhere({ author_email: 'a@b.c' }) // encrypted + blind index — как в find .orderBy('rating', 'DESC') .addOrderBy('title') .limit(20) .offset(10) .getMany(); await PhotoEntity.query().where({ is_public: true }).getOne(); // первая или null await PhotoEntity.query().where({ is_public: true }).getCount(); // COUNT(*) const { sql, values } = await PhotoEntity.query().where({ is_public: true }).toYql(); // без выполнения ``` -------------------------------- ### Configure the YDB Executor Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Initialize the driver and executor with database credentials, then register entities to enable Active Record functionality. ```typescript const opts = { endpoint: 'grpcs://ydb.serverless.yandexcloud.net:2135/?database=/ru-central1/...', auth: createAuth(authKeyFromFile('./authorized_key.json')), }; const driver = await createDriver(opts); const executor = createExecutor(driver, opts); configureEntities([UserEntity], { executor }); // с этого момента Active Record-методы сущности работают ``` -------------------------------- ### Use the Repository Pattern Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Access data via a repository instance for more granular control, or use YdbEntityManager to manage multiple repositories. ```typescript import { getOrCreateRepository } from '@ycforge/ydb-orm'; // репозиторий создаётся автоматически после configureEntities const repo = getOrCreateRepository(UserEntity); const user = await repo.findOneBy({ uuid }); const users = await repo.findAll({ name: 'Ivan' }, { limit: 50 }); const count = await repo.count({ is_admin: true }); await repo.save(entity); await repo.insertMany([u1, u2]); await repo.updateBy({ status: 'old' }, { status: 'archived' }); await repo.deleteBy({ status: 'deprecated' }); ``` ```typescript import { YdbEntityManager } from '@ycforge/ydb-orm'; const manager = new YdbEntityManager(); const userRepo = manager.getRepository(UserEntity); const postRepo = manager.getRepository(PostEntity); // CRUD через репозиторий const user = await userRepo.findOneBy({ uuid }); const users = await userRepo.findAll({ is_admin: true }, { limit: 10 }); await userRepo.save(user); const posts = await postRepo.findBy({ author_uuid: user.uuid }); await postRepo.insertMany([post1, post2, post3]); await postRepo.updateBy({ status: 'draft' }, { status: 'published' }); await postRepo.deleteBy({ status: 'archived' }); // QueryBuilder const popular = await postRepo.query() .where({ is_public: true }) .orderBy('views', 'DESC') .limit(20) .getMany(); // Транзакции — передаём { trx } в любой метод const txManager = new YdbTransactionManager(executor); await txManager.runInTransaction(async (trx) => { await userRepo.save(user, { trx }); await postRepo.save(post, { trx }); }); ``` -------------------------------- ### Migration CLI Commands Source: https://github.com/ycforge/ydb-orm/blob/main/examples/README.md Commands for managing database migrations using the YDB ORM CLI. ```bash yarn build yarn ydb-orm migration:status yarn ydb-orm migration:run yarn ydb-orm migration:revert ``` -------------------------------- ### YDB-ORM CLI Commands Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Commonly used commands for migration management, entity creation, and metadata inspection. ```bash ydb-orm migration:create CreateUsers # пустая миграция ./migrations/-CreateUsers.ts ydb-orm migration:generate AddPhotos # миграция по diff сущностей и БД ydb-orm migration:run # применить все новые миграции ydb-orm migration:revert # откатить последнюю ydb-orm migration:show # статус миграций (алиас — migration:status) ydb-orm migration:check # проверка готовности для CI (exit != 0, если не готово) ydb-orm migration:repair 1755000000000-CreateUsers --as-applied # прерванная миграция дозаведена вручную ydb-orm entity:create UserProfile # сущность ./src/user-profile.entity.ts ydb-orm metadata:dump # метаданные сущностей в JSON (stdout, без БД) ydb-orm entity:diagram # Mermaid ER-диаграмма по метаданным (stdout/--output, без БД) ydb-orm completion bash # скрипт shell-автодополнения (bash|zsh|fish) ``` -------------------------------- ### Configure AuthManager strategies Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Initialize AuthManager with different authentication strategies provided by @ycforge/auth. ```ts import { createAuth, authKeyFromFile } from '@ycforge/auth'; // authorized key сервисного аккаунта const auth = createAuth(authKeyFromFile('./authorized_key.json')); // или другие стратегии: const auth = createAuth({ type: 'metadata' }); const auth = createAuth({ type: 'anonymous' }); const auth = createAuth({ type: 'iam_token', token: process.env.IAM_TOKEN! }); const auth = createAuth({ type: 'static', username: 'user', password: 'pass' }); ``` -------------------------------- ### Configure Shell Autocompletion Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Enable command and flag autocompletion for bash, zsh, and fish shells. ```bash # bash ydb-orm completion bash | sudo tee /etc/bash_completion.d/ydb-orm # zsh (путь из $fpath) ydb-orm completion zsh > ~/.zsh/completions/_ydb-orm # fish ydb-orm completion fish > ~/.config/fish/completions/ydb-orm.fish ``` -------------------------------- ### Configure Multiple YDB Scopes in Standalone Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Use createOrmScope to define named configurations and assign entities to specific executors. ```typescript import { createOrmScope, configureEntities, createDriver, createExecutor } from '@ycforge/ydb-orm'; import { createAuth } from '@ycforge/auth'; // Конфигурация 'default' (как обычно) const defaultExecutor = createExecutor( createDriver({ endpoint: 'grpcs://default...', auth: createAuth({ type: 'metadata' }) }), ); configureEntities([UserEntity], { executor: defaultExecutor }); // Именованная конфигурация 'reporting' с собственными executor и настройками const reportingScope = createOrmScope('reporting', { transactions: { ambient: true, warnOutsideTransaction: true }, }); const reportingExecutor = createExecutor( createDriver({ endpoint: 'grpcs://reporting...', auth: createAuth({ type: 'metadata' }) }), ); configureEntities([ReportEntity], { executor: reportingExecutor, scope: reportingScope }); ``` -------------------------------- ### Configure Encryption Providers Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Pass encryption and blind index providers into the module or standalone configuration. ```ts { encryptionProvider: myEncryptionProvider, // { encrypt(value, aad, ctx) → Uint8Array, decrypt(ciphertext, aad, ctx) → string } blindIndexProvider: myBlindIndexProvider, // { hash(value, ctx) → string } } ``` -------------------------------- ### createOrmScope Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Creates a standalone ORM configuration scope. ```APIDOC ## createOrmScope(name, { transactions }) ### Description Creates a scope for a configuration, which is then passed to configureEntities. ### Parameters - **name** (string) - Required - The name of the configuration. - **transactions** (Object) - Required - Transaction settings for the scope. ``` -------------------------------- ### Export Metadata Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Execute this command to dump entity metadata to stdout in JSON format without connecting to the database. ```bash ydb-orm metadata:dump ``` -------------------------------- ### Default Configuration Injection Tokens Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Standard injection tokens for the 'default' configuration remain backward compatible. ```typescript // эквивалентно: InjectRepository(UserEntity) и module.get(YdbTransactionManager) @InjectRepository(UserEntity) // → getRepositoryToken(UserEntity) @Inject(YdbTransactionManager) // → getTransactionManagerToken('default') ``` -------------------------------- ### Implement Custom CredentialsProvider Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Create a custom provider by extending CredentialsProvider and pass it to the driver or NestJS module. ```ts import { CredentialsProvider } from '@ycforge/ydb-orm'; import { createDriver } from '@ycforge/ydb-orm'; class OAuthTokenProvider extends CredentialsProvider { getToken(): Promise { return fetchOAuthToken(); // ваша реализация получения токена } } // standalone const driver = createDriver({ endpoint: process.env.YDB_ENDPOINT!, credentialsProvider: new OAuthTokenProvider(), }); ``` ```ts YdbCoreModule.forRootAsync({ useFactory: () => ({ endpoint: process.env.YDB_ENDPOINT!, credentialsProvider: new OAuthTokenProvider(), }), }); ``` -------------------------------- ### Implement a custom QueryLogger Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Define a custom logger to handle transaction warnings and query logs. ```ts const myLogger: QueryLogger = { log(entry) { // SQL, paramNames, maskedParams, durationMs, error }, warn(message) { // '[ydb-orm] UserEntity: query executed outside any transaction ...' }, }; ``` -------------------------------- ### Configure Standalone Query Logging Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Enable query logging in a standalone YDB ORM executor using the default ConsoleQueryLogger. ```ts import { createExecutor, createDriver, ConsoleQueryLogger } from '@ycforge/ydb-orm'; import { createAuth, authKeyFromFile } from '@ycforge/auth'; const driver = createDriver({ endpoint: '...', auth: createAuth(authKeyFromFile('./authorized_key.json')), }); const executor = createExecutor(driver, { logQueries: true, // ConsoleQueryLogger по умолчанию }); ``` -------------------------------- ### Generate Mermaid ER Diagrams Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Render entity metadata into a Mermaid ER diagram without requiring a database connection. ```bash ydb-orm entity:diagram # Mermaid-текст в stdout ydb-orm entity:diagram --output docs/schema.mmd # в файл (перезапись запрещена) ``` -------------------------------- ### createEntityFileFromSpec Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Programmatically generates an entity file based on a provided specification. ```APIDOC ## createEntityFileFromSpec ### Description Generates a new entity file in the specified directory based on the provided entity configuration object. ### Signature `createEntityFileFromSpec(directory: string, spec: EntitySpec): boolean` ### Parameters - **directory** (string) - Required - The target directory path for the generated file. - **spec** (object) - Required - The entity specification containing className, tableName, and columns definition. ### Example ```ts import { createEntityFileFromSpec } from '@ycforge/ydb-orm'; const created = createEntityFileFromSpec('./src', { className: 'OrderEntity', tableName: 'orders', columns: [ { name: 'uuid', type: 'Uuid', primary: true }, { name: 'status', type: 'Utf8', enumValues: ['active'], enumStorage: 'Utf8' }, { name: 'created_at', type: 'Timestamp', createDate: true }, ], }); ``` ``` -------------------------------- ### Configure NestJS Query Logging Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Enable query logging within the YdbCoreModule configuration for NestJS applications. ```ts YdbCoreModule.forRootAsync({ useFactory: () => ({ endpoint: '...', auth: createAuth(authKeyFromFile('./authorized_key.json')), logQueries: true, // logQueries: myLogger, // или свой экземпляр QueryLogger }), }); ``` -------------------------------- ### Initialize Driver with AuthManager Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Pass the AuthManager instance to the driver configuration for standalone or NestJS usage. ```ts const driver = createDriver({ endpoint: process.env.YDB_ENDPOINT!, auth, }); ``` ```ts YdbCoreModule.forRootAsync({ useFactory: () => ({ endpoint: process.env.YDB_ENDPOINT!, auth, }), }); ``` -------------------------------- ### buildMetadataDump Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Programmatically generates a deterministic JSON dump of entity metadata. ```APIDOC ## buildMetadataDump ### Description Generates a metadata dump object for a list of entities. This operation is read-only and does not require a database connection. ### Signature `buildMetadataDump(entities: any[]): MetadataDump` ### Parameters - **entities** (array) - Required - A list of entity classes or configurations to process. ### Returns - **MetadataDump** (object) - A deterministic JSON structure containing entity definitions, relations, indexes, and TTL settings. ``` -------------------------------- ### @InjectRepository Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Decorator for injecting a repository into a class constructor. ```APIDOC ## @InjectRepository(Entity, connectionName?) ### Description Decorator used to inject a repository for a specific entity and configuration into a class. ### Parameters - **Entity** (Class) - Required - The entity class. - **connectionName** (string) - Optional - The name of the configuration. ``` -------------------------------- ### Programmatic Entity Creation Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Use this API to generate entity files programmatically in scripts or tools. ```ts import { createEntityFileFromSpec } from '@ycforge/ydb-orm'; const created = createEntityFileFromSpec('./src', { className: 'OrderEntity', tableName: 'orders', columns: [ { name: 'uuid', type: 'Uuid', primary: true }, { name: 'status', type: 'Utf8', enumValues: ['active'], enumStorage: 'Utf8' }, { name: 'created_at', type: 'Timestamp', createDate: true }, ], }); ``` -------------------------------- ### Configure retry policy for executors Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Set up retry policies for standalone executors or wrap existing ones using withRetryPolicy. ```ts import { createAuth } from '@ycforge/auth'; import { createExecutor, createDriver } from '@ycforge/ydb-orm'; const driver = createDriver({ endpoint: '...', auth: createAuth({ type: 'anonymous' }) }); // standalone: const executor = createExecutor(driver, { retry: { maxAttempts: 5 } }); // Вручную поверх готового executor'а (оборачивать ОДИН раз): import { withRetryPolicy } from '@ycforge/ydb-orm'; const resilient = withRetryPolicy(executor, { maxAttempts: 5 }); ``` -------------------------------- ### YdbOrmModule.forFeature Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Registers entities for a specific YDB configuration. ```APIDOC ## YdbOrmModule.forFeature(entities, connectionName?) ### Description Registers entities into a specific YDB configuration. If connectionName is omitted, it defaults to 'default'. ### Parameters - **entities** (Array) - Required - List of entity classes to register. - **connectionName** (string) - Optional - The name of the configuration to register entities into. ``` -------------------------------- ### Transaction Execution Options Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Configuring transaction behavior with isolation levels, timeouts, and idempotency. ```ts await txManager.runInTransaction( async (trx, signal) => { await OrderEntity.save(order, { trx }); }, { isolation: 'snapshotReadWrite', // serializableReadWrite (по умолчанию) | snapshotReadOnly | snapshotReadWrite timeout: 5_000, // таймаут НА КАЖДУЮ ПОПЫТКУ (см. ниже) signal: controller.signal, // ГЛОБАЛЬНАЯ отмена: вся операция, все попытки idempotent: true, // см. «Retry-семантика» ниже }, ); ``` ```ts await txManager.runInTransaction(fn, { idempotent: true, signal: AbortSignal.timeout(30_000), // общий лимит на все попытки }); ``` -------------------------------- ### Execute Transaction with Retry Policy Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Demonstrates running a transaction with an idempotent retry policy, allowing the ORM to handle retries for transient errors. ```ts await txManager.runInTransaction( async (trx) => { await OrderEntity.save(order, { trx }); }, { idempotent: true, // семантика #98: колбэк обязан быть устойчивым к повтору retry: true, // или объект политики; нельзя совмещать с reuse maxAttempts: 5, }, ); ``` -------------------------------- ### Inject Repositories and Transaction Managers by Name Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Use configuration names to inject specific repositories and transaction managers in NestJS services. ```typescript @Injectable() export class ReportService { constructor( // репозиторий из конфигурации 'reporting' @InjectRepository(ReportEntity, 'reporting') private readonly reportRepo: YdbRepository, // менеджер транзакций из конфигурации 'reporting' (отдельный инстанс) @Inject(getTransactionManagerToken('reporting')) private readonly txManager: YdbTransactionManager, ) {} } ``` -------------------------------- ### Define a migration class Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Implement the YdbMigration interface to define schema changes. Use import type for YdbMigration and YdbExecutor to avoid runtime errors with native TypeScript stripping. ```ts import type { YdbMigration, YdbExecutor } from '@ycforge/ydb-orm'; import { executeSql } from '@ycforge/ydb-orm'; export class CreateUsers1755000000000 implements YdbMigration { readonly name = '1755000000000-CreateUsers'; async up(executor: YdbExecutor): Promise { await executeSql(executor, 'CREATE TABLE `users` (`uuid` Uuid, PRIMARY KEY (`uuid`))'); } async down(executor: YdbExecutor): Promise { await executeSql(executor, 'DROP TABLE `users`'); } } ``` -------------------------------- ### Define Lifecycle Hooks in YDB Entity Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Use decorators like @BeforeInsert and @AfterFind to attach logic to entity lifecycle events. These methods execute automatically during database operations. ```ts @YdbEntity('users') class User extends YdbBaseEntity { @YdbPrimaryColumn('Uuid') uuid: string; @YdbColumn('Utf8') name?: string; @BeforeInsert normalize() { this.name = this.name?.trim(); } @AfterFind touch() { // вызывается и для корневых сущностей, и для eager/lazy relations } } ``` -------------------------------- ### Standalone Schema Synchronization Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Use YdbSchemaSyncer to verify or synchronize database schemas manually. Verification checks for discrepancies without modifying the database, while sync applies necessary changes. ```ts import { YdbSchemaSyncer } from '@ycforge/ydb-orm'; const syncer = new YdbSchemaSyncer(executor); // verify — проверяет схему, ничего не меняет const issues = await syncer.verify([UserEntity, PostEntity]); // sync — подстраивает схему await syncer.sync([UserEntity, PostEntity]); ``` -------------------------------- ### Configure YDB ORM in NestJS Module Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Use YdbCoreModule.forRootAsync to configure the connection and YdbOrmModule.forFeature to register entities. The sync option should only be enabled for development environments. ```ts import { Module } from '@nestjs/common'; import { createAuth, authKeyFromFile } from '@ycforge/auth'; import { YdbCoreModule, YdbOrmModule, YdbBaseEntity, YdbEntity, YdbPrimaryColumn, YdbColumn, } from '@ycforge/ydb-orm/nest'; @YdbEntity('users') export class UserEntity extends YdbBaseEntity { @YdbPrimaryColumn('Uuid') uuid!: string; @YdbColumn('Utf8') name!: string; } @Module({ imports: [ YdbCoreModule.forRootAsync({ useFactory: () => ({ endpoint: 'grpcs://ydb.serverless.yandexcloud.net:2135/?database=/ru-central1/...', auth: createAuth(authKeyFromFile('./authorized_key.json')), sync: true, // как synchronize в TypeORM — только для dev! }), }), YdbOrmModule.forFeature([UserEntity]), ], }) export class AppModule {} ``` -------------------------------- ### Configure retry policy in NestJS Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Enable retry policies globally within a NestJS application using YdbCoreModule. ```ts YdbCoreModule.forRootAsync({ useFactory: () => ({ endpoint: '...', auth: createAuth({ type: 'anonymous' }), retry: true, // или объект YdbRetryPolicyOptions; false/undefined — выключено }), }); ``` -------------------------------- ### Ambient Transaction Context Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Configuring ambient transactions to automatically include repository operations in the active transaction. ```ts // NestJS: глобально при инициализации модуля YdbCoreModule.forRootAsync({ useFactory: () => ({ // ... transactions: { ambient: true }, }), }); // Standalone: через опции модуля (YdbModuleOptions) // или точечно, на один вызов: await txManager.runInTransaction(async () => { await OrderEntity.save(order); // уйдёт в транзакцию автоматически await OrderEntity.save(other, { trx }); // явный trx тоже работает }, { ambient: true }); ``` -------------------------------- ### getRepositoryToken Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Retrieves the DI token for a repository associated with a specific entity and configuration. ```APIDOC ## getRepositoryToken(Entity, connectionName?) ### Description Returns the DI token for the repository of the given entity. For the 'default' configuration, it returns the standard format; for named configurations, the token is suffixed with @. ### Parameters - **Entity** (Class) - Required - The entity class. - **connectionName** (string) - Optional - The name of the configuration. ``` -------------------------------- ### Enable transaction warnings Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Configure the ORM to issue warnings when queries are executed outside of a transaction. ```ts transactions: { warnOutsideTransaction: true } // предупреждение на каждый такой запрос ``` -------------------------------- ### Filtering by Related Entities Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Demonstrates filtering root entities based on conditions applied to their relationships. ```ts // Пользователи, у которых есть роль 'admin' (one-to-many) await UserEntity.findAll({ userRoles: { is_global: true } }); // Несколько related-предикатов + обычные условия корня (AND) await PhotoWithTagsEntity.findAll({ title: { $like: '%sunset%' }, tags: { name: 'nature' }, // many-to-many через join-таблицу author: { status: 'active' }, // many-to-one }); // Логические группы смешивают колонки корня и связи await UserEntity.findAll({ $or: [ { uuid: someUuid }, { userRoles: { role_uuid: adminRoleUuid } }, ], }); ``` -------------------------------- ### Synchronize Database Schema Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Use YdbSchemaSyncer to verify or apply schema changes to the database based on entity definitions. ```typescript import { YdbSchemaSyncer } from '@ycforge/ydb-orm'; const syncer = new YdbSchemaSyncer(executor); // проверка без изменений const issues = await syncer.verify([UserEntity]); console.log(issues); // применение (CREATE TABLE / ALTER TABLE ADD COLUMN) await syncer.sync([UserEntity]); ``` -------------------------------- ### Configure Multiple YDB Modules in NestJS Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Register multiple YdbCoreModule instances with unique names and bind entities to them via YdbOrmModule.forFeature. ```typescript @Module({ imports: [ // 'default' конфигурация YdbCoreModule.forRootAsync({ useFactory: () => ({ endpoint: 'grpcs://default...', auth: createAuth({ type: 'metadata' }), }), }), // 'reporting' конфигурация — отдельный executor, отдельные транзакции YdbCoreModule.forRootAsync({ name: 'reporting', useFactory: () => ({ endpoint: 'grpcs://reporting...', auth: createAuth({ type: 'metadata' }), transactions: { ambient: true, warnOutsideTransaction: true }, }), }), // Сущности привязываются к своей конфигурации: // forFeature без имени → 'default'; forFeature([...], 'reporting') → 'reporting' YdbOrmModule.forFeature([UserEntity]), YdbOrmModule.forFeature([ReportEntity], 'reporting'), ], }) export class AppModule {} ``` -------------------------------- ### Active Record CRUD and Query Operations Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Provides methods for interacting with entities, including finding records, counting, saving, and batch inserting. Note that save operations handle both insert and update based on the presence of a UUID. ```ts await UserEntity.find({ uuid }); // одна запись или null await UserEntity.findAll({ name: 'Ivan' }, { limit: 50, offset: 0 }); await UserEntity.count({ name: 'Ivan' }); await UserEntity.save(user); // insert (uuid генерируется, по умолчанию v7) или update по uuid await UserEntity.insertMany([u1, u2]); // батчи по 100 await user.loadRelations(['roles']); ``` -------------------------------- ### NestJS Schema Synchronization Configuration Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Enable automatic schema synchronization in NestJS by setting the sync option to true within YdbCoreModule. This should be restricted to development environments. ```ts YdbCoreModule.forRootAsync({ useFactory: () => ({ endpoint: '...', auth: createAuth(authKeyFromFile('./authorized_key.json')), sync: true, // только для dev! В проде — миграции. }), }); ``` -------------------------------- ### Nested Transaction Handling Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Managing nested transactions using the reuse option to join an existing transaction context. ```ts await txManager.runInTransaction(async () => { await txManager.runInTransaction(async (trx2) => { // Error: Nested runInTransaction() detected ... }); }); await txManager.runInTransaction(async () => { await txManager.runInTransaction(async (sameTrx) => { // та же транзакция, что и снаружи }, { reuse: true }); }); ``` -------------------------------- ### Integrate with @ycforge/auth/nestjs Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Inject an AuthManager instance from a NestJS module into the YdbCoreModule. ```ts import { Module } from '@nestjs/common'; import { YcAuthModule, InjectAuth } from '@ycforge/auth/nestjs'; import { YdbCoreModule } from '@ycforge/ydb-orm/nest'; @Module({ imports: [ YcAuthModule.forRoot({ config: authKeyFromFile('./authorized_key.json'), global: true, }), YdbCoreModule.forRootAsync({ useFactory: (@InjectAuth() auth) => ({ endpoint: process.env.YDB_ENDPOINT!, auth, }), inject: [YcAuthModule], // или токен YCFORGE_AUTH }), ], }) export class AppModule {} ``` -------------------------------- ### Define JSON Columns in Entity Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Use decorators to map JSON data to YDB columns, supporting native JSON types or stringified Utf8 storage. ```ts @YdbEntity('events') class EventEntity extends YdbBaseEntity { @YdbPrimaryColumn('Uuid') uuid: string; @YdbJson() @YdbColumn('Utf8') metadata: Record; @YdbColumn('Json') payload: any; } ``` -------------------------------- ### Execute Standalone Retry Wrapper Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Provides an explicit wrapper for retrying operations outside of a transaction context. ```ts import { runWithRetry } from '@ycforge/ydb-orm'; const result = await runWithRetry(async () => { const user = await UserEntity.find({ uuid }, {}); const orders = await OrderEntity.findBy({ userId: user.uuid }, { limit: 50 }); return buildReport(user, orders); }, { maxAttempts: 5 }); ``` -------------------------------- ### Query JSON Columns Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Perform JSON-specific queries using operators like andWhereJsonExists and andWhereJsonValue. ```ts await EventEntity.query() .andWhereJsonExists('metadata', '$.settings.theme') .andWhereJsonValue('metadata', '$.role', 'admin') .getMany(); ``` ```ts // metadata: $.settings.theme существует И $.role = 'admin' await EventEntity.query() .andWhereJsonExists('metadata', '$.settings.theme') .andWhereJsonValue('metadata', '$.role', 'admin') .getMany(); // WHERE (JSON_EXISTS(`metadata`, $metadata_0_jsonexists) // AND JSON_VALUE(`metadata`, $metadata_1_jsonvalue_path) = $metadata_1_jsonvalue_val) ``` -------------------------------- ### Пример использования связей ManyToMany Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Определение сущностей с использованием декораторов @EagerLoad и @ManyToMany для связи между фотографиями и тегами. ```ts @YdbEntity('photos') @EagerLoad(['tags']) class Photo extends YdbBaseEntity { @YdbPrimaryColumn('Uuid') uuid: string; @YdbColumn('Utf8') title: string; @ManyToMany(() => Tag, (tag) => tag.photos) @JoinTable('photo_tag') tags: Tag[]; } @YdbEntity('tags') class Tag extends YdbBaseEntity { @YdbPrimaryColumn('Uuid') uuid: string; @YdbColumn('Utf8') name: string; @ManyToMany(() => Photo, (photo) => photo.tags) photos: Photo[]; } ``` -------------------------------- ### Define a YDB Entity Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Use the @YdbEntity decorator to define a database table and @YdbPrimaryColumn or @YdbColumn to map class properties to YDB columns. ```typescript import { YdbBaseEntity, YdbEntity, YdbPrimaryColumn, YdbColumn, configureEntities, createDriver, createExecutor, YdbTransactionManager, } from '@ycforge/ydb-orm'; import { createAuth, authKeyFromFile } from '@ycforge/auth'; @YdbEntity('users') class UserEntity extends YdbBaseEntity { @YdbPrimaryColumn('Uuid') uuid!: string; @YdbColumn('Utf8') name!: string; } ``` -------------------------------- ### Пример наследования сущностей и конфликтов имен Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Демонстрация наследования колонок при создании новой таблицы и ошибка при дублировании имени таблицы. ```ts @YdbEntity('events') @YdbTtl({ interval: 'P30D', column: 'created_at' }) class EventEntity extends YdbBaseEntity { /* ... */ } // Своя таблица: колонки родителя наследуются, TTL/индексы — нет @YdbEntity('audit_events') class AuditEventEntity extends EventEntity { /* ... */ } // Ошибка: Duplicate table name "events" @YdbEntity('events') class BrokenChildEntity extends EventEntity { /* ... */ } ``` -------------------------------- ### Perform Active Record Operations Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Execute CRUD operations directly on the entity class using static methods like find, findAll, and save. ```typescript // одна запись по PK const user = await UserEntity.find({ uuid: '...' }); // выборка с условиями и лимитом const admins = await UserEntity.findAll({ is_admin: true }, { limit: 50 }); // INSERT/UPDATE const u = new UserEntity(); u.name = 'Ivan'; await UserEntity.save(u); // uuid генерируется автоматически (v7) // транзакции const txManager = new YdbTransactionManager(executor); await txManager.runInTransaction(async (trx) => { await UserEntity.save(user, { trx }); }); ``` -------------------------------- ### NestJS Transaction Injection Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Injecting YdbTransactionManager into a NestJS service for transaction management. ```ts @Injectable() export class OrderService { constructor(private readonly txManager: YdbTransactionManager) {} async transfer(fromId: string, toId: string) { await this.txManager.runInTransaction(async (trx) => { const from = await UserEntity.find({ uuid: fromId }, { trx }); await UserEntity.save(from, { trx }); }); } } ``` -------------------------------- ### releaseOrmScope Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Releases all entities associated with a specific scope. ```APIDOC ## releaseOrmScope(scope) ### Description Releases all entities of the provided scope. This is called automatically by app.close() in NestJS. ### Parameters - **scope** (Object) - Required - The scope to release. ``` -------------------------------- ### Mark operations as idempotent Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Explicitly mark queries as idempotent to allow the retry policy to safely re-execute them upon transient errors. ```ts // ❌ Не помечен (INSERT/UPSERT/UPDATE/DELETE по умолчанию): // выполнится РОВНО ОДИН раз даже при retry: true. await UserEntity.save(user); // ❌ Транзитная ошибка у незнакомой записи → повтор небезопасен: await OrderEntity.findBy({ status: 'new' }); // тоже один раз // ✅ Помечен идемпотентным: политика может повторить при // ABORTED / UNAVAILABLE / OVERLOADED. const users = await UserEntity.findAll({}, { idempotent: true }); await UserEntity.save(user, { idempotent: true }); // операция устойчива к повтору await executor`SELECT ...`.idempotent(true); // прямой executor ``` -------------------------------- ### getTransactionManagerToken Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Retrieves the DI token for the YdbTransactionManager. ```APIDOC ## getTransactionManagerToken(name) ### Description Returns the DI token for YdbTransactionManager. For 'default', it returns the class-token; for named configurations, it returns a symbol. ### Parameters - **name** (string) - Required - The name of the configuration. ``` -------------------------------- ### Inject YDB Repository in NestJS Service Source: https://github.com/ycforge/ydb-orm/blob/main/README.md Use the @InjectRepository decorator to access YdbRepository for CRUD operations within a service. ```ts import { Injectable } from '@nestjs/common'; import { InjectRepository, YdbRepository } from '@ycforge/ydb-orm/nest'; import { UserEntity } from './user.entity.js'; @Injectable() export class UserService { constructor( @InjectRepository(UserEntity) private readonly userRepo: YdbRepository, ) {} async getByUuid(uuid: string) { return this.userRepo.findOneBy({ uuid }); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.