{"id":15288992,"url":"https://github.com/mcereal/nestjsdb2","last_synced_at":"2026-02-14T11:05:38.923Z","repository":{"id":257782428,"uuid":"846742728","full_name":"mcereal/nestjsdb2","owner":"mcereal","description":"NestJS DB2 implementation","archived":false,"fork":false,"pushed_at":"2025-02-15T08:47:31.000Z","size":1310,"stargazers_count":0,"open_issues_count":1,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-08-08T19:29:46.816Z","etag":null,"topics":["database","db2","ibm","migrations","nestjs","query-builder","sql","transactions"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/settings/mcereal/nestjsdb2","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mcereal.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2024-08-23T21:27:21.000Z","updated_at":"2024-12-09T14:40:38.000Z","dependencies_parsed_at":null,"dependency_job_id":"b82e132c-5238-4920-ab0a-a86ade9e2610","html_url":"https://github.com/mcereal/nestjsdb2","commit_stats":null,"previous_names":["mcereal/nestjsdb2"],"tags_count":69,"template":false,"template_full_name":null,"purl":"pkg:github/mcereal/nestjsdb2","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mcereal%2Fnestjsdb2","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mcereal%2Fnestjsdb2/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mcereal%2Fnestjsdb2/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mcereal%2Fnestjsdb2/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mcereal","download_url":"https://codeload.github.com/mcereal/nestjsdb2/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mcereal%2Fnestjsdb2/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29443447,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-14T10:51:12.367Z","status":"ssl_error","status_checked_at":"2026-02-14T10:50:52.088Z","response_time":53,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["database","db2","ibm","migrations","nestjs","query-builder","sql","transactions"],"created_at":"2024-09-30T15:55:31.008Z","updated_at":"2026-02-14T11:05:38.908Z","avatar_url":"https://github.com/mcereal.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# IBM DB2 Module for NestJS\n\n[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=mcereal_nestjsdb2\u0026metric=alert_status)](https://sonarcloud.io/summary/new_code?id=mcereal_nestjsdb2) [![Coverage](https://sonarcloud.io/api/project_badges/measure?project=mcereal_nestjsdb2\u0026metric=coverage)](https://sonarcloud.io/summary/new_code?id=mcereal_nestjsdb2) [![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=mcereal_nestjsdb2\u0026metric=sqale_rating)](https://sonarcloud.io/summary/new_code?id=mcereal_nestjsdb2) [![Reliability Rating](https://sonarcloud.io/api/project_badges/measure?project=mcereal_nestjsdb2\u0026metric=reliability_rating)](https://sonarcloud.io/summary/new_code?id=mcereal_nestjsdb2) [![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=mcereal_nestjsdb2\u0026metric=security_rating)](https://sonarcloud.io/summary/new_code?id=mcereal_nestjsdb2) [![npm version](https://badge.fury.io/js/@mcereal%2Fnestjsdb2.svg)](https://badge.fury.io/js/@mcereal%2Fnestjsdb2) [![CodeQL Advanced](https://github.com/mcereal/nestjsdb2/actions/workflows/codeql.yml/badge.svg)](https://github.com/mcereal/nestjsdb2/actions/workflows/codeql.yml) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![Build](https://github.com/mcereal/nestjsdb2/actions/workflows/build.yaml/badge.svg)](https://github.com/mcereal/nestjsdb2/actions/workflows/build.yaml)\n\nThe `@mcereal/nestjs` package is a powerful and flexible TypeScript library that integrates IBM DB2 database capabilities into NestJS applications. This package provides decorators, services, and utility functions to handle common database operations, connection management, caching, error handling, and transaction management, specifically tailored for IBM DB2 environments.\n\n**This package it under active development and is not yet ready for production use. Please use with caution and report any issues or bugs you encounter.**\n\n## Table of Contents\n\n- [Features](#features)\n- [Installation](#installation)\n- [Getting Started](#getting-started)\n- [Configuration](#configuration)\n- [Usage](#usage)\n  - [Importing Db2Module](#importing-db2module)\n  - [Database Operations](#database-operations)\n  - [Using Db2Module](#using-db2module)\n  - [Query Execution](#query-execution)\n    - [Basic Query Execution](#basic-query-execution)\n    - [Batch Operations](#batch-operations)\n    - [Transaction Management](#transaction-management)\n    - [ORM Support](#orm-support)\n    - [Query Builder](#query-builder)\n  - [Decorators](#decorators)\n  - [Error Handling](#error-handling)\n  - [Health Checks](#health-checks)\n- [Examples](#examples)\n- [Security](#security)\n- [Contributing](#contributing)\n- [License](#license)\n\n## Features\n\n- **Easy Integration**: Seamlessly integrate IBM DB2 databases into NestJS applications.\n- **Typed Configuration**: TypeScript-based configuration options for better type safety and IDE support.\n- **Connection Management**: Supports connection pooling, failover, and connection state monitoring.\n- **Query Builder**: A fluent API for building SQL queries with support for subqueries, parameterized queries, and more.\n- **Transaction Management**: Built-in support for transactions with `beginTransaction`, `commitTransaction`, and `rollbackTransaction`.\n- **Batch Operations**: Execute multiple queries in a single batch operation for improved performance.\n- **Decorators**: Custom decorators to enforce connection state checks and cache results.\n- **Health Checks**: Support for implementing health checks using NestJS Terminus.\n- **ORM Support**: Lightweight ORM-like interface for defining schemas and models.\n\n## Installation\n\n```bash\nnpm install @mcereal/nestjsdb2 --save\n```\n\n**Note**: The `@mcereal/nestjsdb2` package relies on the ibm_db package, which requires Rosetta 2 to run on Apple Silicon Macs. Please ensure Rosetta 2 is installed on your system. You can install Rosetta 2 by running:\n\n```bash\nsoftwareupdate --install-rosetta --agree-to-license\n```\n\n## Getting Started\n\nTo get started, import the Db2Module into your NestJS application and configure it using the provided options.\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { Db2Module } from '@mcereal/nestjsdb2';\n\n@Module({\n  imports: [\n    Db2Module.forRoot({\n      auth: {\n        authType: 'password',\n        username: 'db2user',\n        password: 'password',\n      },\n      host: 'localhost',\n      port: 50000,\n      database: 'sampledb',\n      useTls: false,\n      retry: {\n        maxReconnectAttempts: 5,\n        reconnectInterval: 3000,\n      },\n      queryTimeout: 10000, // in milliseconds\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n## Configuration\n\nThe Db2Module can be configured either synchronously or asynchronously:\n\n### Synchronous Configuration\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { Db2Module } from '@mcereal/nestjsdb2';\n\n@Module({\n  imports: [\n    Db2Module.forRoot({\n      auth: {\n        authType: 'password',\n        username: 'db2user',\n        password: 'password',\n      },\n      host: 'localhost',\n      port: 50000,\n      database: 'sampledb',\n      useTls: false,\n      cacheEnabled: true,\n      retry: {\n        maxReconnectAttempts: 5,\n        reconnectInterval: 3000,\n      },\n      queryTimeout: 10000,\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n### Asynchronous Configuration\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { ConfigModule, ConfigService } from '@nestjs/config';\nimport { Db2Module } from '@mcereal/nestjsdb2';\n\n@Module({\n  imports: [\n    ConfigModule.forRoot({\n      isGlobal: true,\n    }),\n    Db2Module.forRootAsync({\n      imports: [ConfigModule],\n      useFactory: async (configService: ConfigService) =\u003e ({\n        auth: {\n          authType: 'password',\n          username: configService.get\u003cstring\u003e('DB_USER'),\n          password: configService.get\u003cstring\u003e('DB_PASS'),\n        },\n        host: configService.get\u003cstring\u003e('DB_HOST'),\n        port: configService.get\u003cnumber\u003e('DB_PORT'),\n        useTls: configService.get\u003cboolean\u003e('DB2_SSL_CONNECTION'),\n        database: configService.get\u003cstring\u003e('DB_NAME'),\n        sslCertificatePath: configService.get\u003cstring\u003e('DB_SSL_CERT_PATH'),\n        retry: {\n          maxReconnectAttempts: configService.get\u003cnumber\u003e('DB_RETRY_MAX') || 5,\n          reconnectInterval:\n            configService.get\u003cnumber\u003e('DB_RETRY_INTERVAL') || 3000,\n        },\n        queryTimeout: configService.get\u003cnumber\u003e('DB_QUERY_TIMEOUT') || 10000,\n      }),\n      inject: [ConfigService],\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n## Usage\n\n### Importing Db2Module\n\nEnsure that the Db2Module is imported and configured in your root module (AppModule).\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { Db2Module } from '@mcereal/nestjsdb2';\n\n@Module({\n  imports: [\n    Db2Module.forRoot({\n      auth: {\n        authType: 'password',\n        username: 'db2user',\n        password: 'password',\n      },\n      host: 'localhost',\n      port: 50000,\n      database: 'sampledb',\n      useTls: false,\n      cacheEnabled: true,\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n### Database Operations\n\n### Basic Query Execution\n\nThe `query` method executes a SQL query and returns the result as an array of objects:\n\n```typescript\nconst result = await this.db2Service.query('SELECT * FROM users');\n```\n\n### Batch Operations\n\nThe `batch` method executes multiple queries in a single batch operation:\n\n```typescript\nconst queries = [\n  { sql: 'INSERT INTO users (name) VALUES (?)', params: ['Alice\n  { sql: 'INSERT INTO users (name) VALUES (?)', params: ['Bob'] },\n];\n\nconst results = await this.db2Service.batch(queries);\n```\n\n### Transaction Management\n\nThe `beginTransaction`, `commitTransaction`, and `rollbackTransaction` methods provide support for transactions:\n\n```typescript\nawait this.db2Service.beginTransaction();\nawait this.db2Service.query('INSERT INTO users (name) VALUES (?)', ['Alice']);\nawait this.db2Service.commitTransaction();\n```\n\n### Query Builder\n\nThe `QueryBuilder` class provides a fluent API for building SQL queries with support for subqueries, parameterized queries, and more.\n\nCreate a new Query builder by providing the table name and an instance of th Db2Client class.\n\n```typescript\nimport { QueryBuilder } from '@mcereal/nestjsdb2';\n\nconst queryBuilder = new QueryBuilder('users', this.db2Service);\n\nconst result = await queryBuilder\n  .select(['id', 'name'])\n  .where('name', '=', 'Alice')\n  .orderBy('created_at', 'DESC')\n  .limit(10)\n  .execute();\n\nconsole.log(result);\n```\n\n### Decorators\n\nThe `@Transaction`, `@Connection`, and `` decorators can be used to enforce connection state checks and cache results:\n\n```typescript\nimport { Transaction, Connection, Query, Param } from '@mcereal/nestjsdb2';\n\n@Injectable()\nexport class UserService {\n  @Transaction()\n  async createUser(name: string) {\n    await this.db2Service.query('INSERT INTO users (name) VALUES (?)', [name]);\n  }\n\n  @Connection()\n  async getUserData(userId: string) {\n    return this.db2Service.query('SELECT * FROM users WHERE id = ?', [userId]);\n  }\n\n  @Query('SELECT * FROM users WHERE id = ?')\n  async getUserData(@Param('id') userId: string) {\n    return this.db2Service.query('SELECT * FROM users WHERE id = ?', [userId]);\n\n}\n```\n\n#### ORM Support\n\nThe `@mcereal/nestjsdb2` package provides a lightweight ORM-like inrerface for working with DB2. You can define schemas using the `Schema` class and model classes using the `Model` class.\n\n1. First, define an entity class using the `@Entity` decorator, and define the schema using the `Schema` class:\n\n```typescript\nimport { Schema, Model } from '@mcereal/nestjsdb2';\nimport { Entity, Column, PrimaryKey } from '@mcereal/nestjsdb2';\n\n@Entity({\n  entityType: 'table',\n  name: 'users',\n})\nexport class User {\n  @PrimaryKey()\n  id!: string;\n\n  @Column()\n  name!: string;\n\n  @Column()\n  email!: string;\n}\n\nexport const UserSchema = new Schema([User]);\n\nconst UserModel = new Model('users', UserSchema);\n```\n\n2. Register the `Schema` and `Model` classes in the module configuration as providers:\n\n```typescript\nDb2Module.forRoot({\n  auth: {\n    authType: 'password',\n    host: 'localhost',\n    port: 50000,\n    database: 'sampledb',\n    useTls: false,\n  },\n  providers: [\n    {\n      provide: 'UserModel',\n      useValue: UserModel,\n    },\n  ],\n});\n```\n\n3. Use `Db2Module.forFeature` to register the `Schema` and `Model` classes in a feature module:\n\n```typescript\n\n@Module({\n  imports: [\n    Db2Module.forFeature({\n      auth: {\n        authType: 'password',\n        host: 'localhost',\n        port: 50000,\n        database: 'sampledb',\n        useTls: false,\n      },\n      providers: [\n        {\n          provide: 'UserModel',\n          useValue: UserModel,\n        },\n      ],\n    }),\n  ],\n})\n```\n\n4. Use the `UserModel` class to perform CRUD operations on the `users` table:\n\n```typescript\nimport { Injectable, Inject } from '@nestjs/common';\n\n@Injectable()\nexport class UserService {\n  constructor(@Inject('UserModel') private userModel: Model\u003cUserModel\u003e) {}\n\n  async createUser(name: string, email: string) {\n    return this.userModel.insert({ name, email });\n  }\n\n  async getUserById(id: string) {\n    return this.userModel.findOne({ id });\n  }\n\n  async updateUser(id: string, name: string, email: string) {\n    return this.userModel.update({ id }, { name, email });\n  }\n\n  async deleteUser(id: string) {\n    return this.userModel.delete({ id });\n  }\n}\n```\n\n## Error Handling\n\nThe `@mcereal/nestjsdb2` package provides detailed error messages and stack traces for common database errors. You can import multiple error types like `Db2Error`, `Db2ConnectionError`, `Db2QueryError`, and `Db2TransactionError` to handle specific error scenarios:\n\n```typescript\nimport {\n  Db2Error,\n  Db2ConnectionError,\n  Db2QueryError,\n  Db2TransactionError,\n} from '@mcereal/nestjsdb2';\n\ntry {\n  await this.db2Service.query('SELECT * FROM non_existent_table');\n} catch (error) {\n  if (error instanceof Db2QueryError) {\n    console.error('Query error:', error.message);\n  } else if (error instanceof Db2ConnectionError) {\n    console.error('Connection error:', error.message);\n  } else if (error instanceof Db2TransactionError) {\n    console.error('Transaction error:', error.message);\n  } else if (error instanceof Db2Error) {\n    console.error('DB2 error:', error.message);\n  } else {\n    console.error('Unknown error:', error.message);\n  }\n}\n```\n\n## Health Checks\n\nYou can implement health checks for your NestJS application using the `TerminusModule` and the `Db2HealthIndicator`:\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { TerminusModule } from '@nestjs/terminus';\nimport { Db2HealthIndicator } from '@mcereal/nestjsdb2';\n\n@Module({\n  imports: [\n    TerminusModule.forRoot({\n      healthChecks: {\n        db2: () =\u003e Db2HealthIndicator.pingCheck('db2'),\n      },\n    }),\n  ],\n})\nexport class HealthModule {}\n```\n\n## Examples\n\nYou can find examples of how to use the `@mcereal/nestjsdb2` package in the [examples](examples) directory. This directory contains sample applications that demonstrate various features of the package, including basic query execution, batch operations, transaction management, and ORM support. To run the examples, follow the instructions in the [examples/README.md](examples/README.md) file.\n\n## Security\n\nThe `@mcereal/nestjsdb2` package follows best practices for security, including:\n\n- **Secure Connections**: Supports TLS encryption for secure communication with the database.\n- **Parameterized Queries**: Encourages the use of parameterized queries to prevent SQL injection attacks.\n- **Error Handling**: Provides detailed error messages and stack traces for common database errors.\n- **Health Checks**: Supports implementing health checks to monitor the database connection status.\n\n## Contributing\n\nContributions are welcome! Please read our [contributing guidelines](CONTRIBUTING.md) to get started.\n\n## License\n\nThis project is licensed under the terms of the [MIT License](LICENSE.md).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmcereal%2Fnestjsdb2","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmcereal%2Fnestjsdb2","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmcereal%2Fnestjsdb2/lists"}