{"id":16988466,"url":"https://github.com/speedphp/speedsql","last_synced_at":"2025-04-12T03:31:33.335Z","repository":{"id":50636921,"uuid":"405121287","full_name":"speedphp/speedsql","owner":"speedphp","description":"SQL Mapper annotations for NestJS, similar MyBatis.","archived":false,"fork":false,"pushed_at":"2024-05-07T03:24:04.000Z","size":41,"stargazers_count":3,"open_issues_count":0,"forks_count":2,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-03-25T23:24:43.359Z","etag":null,"topics":["decor","mybatis","nest","orm","sql","typescript"],"latest_commit_sha":null,"homepage":"","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/speedphp.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2021-09-10T15:09:39.000Z","updated_at":"2024-05-07T03:24:07.000Z","dependencies_parsed_at":"2022-08-23T19:30:32.436Z","dependency_job_id":null,"html_url":"https://github.com/speedphp/speedsql","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/speedphp%2Fspeedsql","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/speedphp%2Fspeedsql/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/speedphp%2Fspeedsql/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/speedphp%2Fspeedsql/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/speedphp","download_url":"https://codeload.github.com/speedphp/speedsql/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248512688,"owners_count":21116660,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","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":["decor","mybatis","nest","orm","sql","typescript"],"created_at":"2024-10-14T03:04:04.460Z","updated_at":"2025-04-12T03:31:32.971Z","avatar_url":"https://github.com/speedphp.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"## SpeedSQL \n\n[![typescript](https://badgen.net/badge/icon/TypeScript?icon=typescript\u0026label)](https://www.npmjs.com/package/speed)\n[![npm](https://badgen.net/npm/v/speed?color=cyan)](https://www.npmjs.com/package/speed)\n[![publis size](https://badgen.net/packagephobia/publish/speed?color=green)](https://www.npmjs.com/package/speed)\n[![downloads](https://badgen.net/npm/dt/speed?color=pink)](https://www.npmjs.com/package/speed)\n[![license](https://badgen.net/github/license/speedphp/speedsql)](https://github.com/SpeedPHP/speedsql/blob/main/LICENSE)\n\nSQL Mapper annotations for NestJS, similar MyBatis.\n\n### Introduction\n\n- Follow NestJS Module injection mode.\n- With the TypeScript Decorators, same as Java annotations.\n- Similar to MyBatis used in Java.\n- Support for the Prepared Statements.\n- Support for Entity Injection.\n- Support the Connection pools by mysql2 within.\n\n### Support Decorators\n\n`@Param`, `@ResultType`, `@Select`, `@Insert`, `@Update`, `@Delete`.\n\n### Install as a dependency\n\nSetup SpeedSQL as dependency in *package.json* file `dependencies`\n\n```\n\"dependencies\": {\n    \"speedsql\": \"latest\"\n}\n```\n\n### Quick Start\n\n- Prepare some entities and configurations.\n\n*db.provider.ts*\n```\nimport { createPool, Pool } from 'speedsql';\n\nexport const DbProviders = [\n  {\n    provide: 'SPEED_POOL',\n    useFactory: async (): Promise\u003cPool\u003e =\u003e {\n      return await createPool({\n        host: 'localhost',\n        user: 'root',\n        port: 3306,\n        password: 'qwer1234',\n        database: 'test',\n      });\n    },\n  },\n];\n```\n*entity/param.dto.ts*\n```\nexport class ParamDto {\n  constructor(public name: string, public age: number) {}\n}\n```\n*entity/user.dto.ts*\n```\nexport class UserDto {\n  constructor(public name: string, public age: number) {}\n}\n```\n\n* * *\n\n- Import into the Module of NestJS\n\n\n*app.mudule.ts*\n```\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { SpeedService } from 'speedsql';\nimport { DbProviders } from './db.provider';\n\n@Module({\n  imports: [],\n  controllers: [AppController],\n  providers: [AppService, SpeedService, ...DbProviders],\n})\nexport class AppModule {}\n```\n\n* * *\n\n- Define SpeedSQL within Services, use the Decorators as MyBatis.\n\n*app.service.ts*\n```\nimport { Injectable } from '@nestjs/common';\nimport { Delete, Update, Param, ResultType, Insert } from 'speedsql';\nimport { UserDto } from './entity/user.dto';\nimport { ParamDto } from './entity/param.dto';\n\n@Injectable()\nexport class AppService {\n  @Update('update user set age = #{age} where name = #{name}')\n  setUserAge(@Param('name') name: string, @Param('age') age: number): number {return;}\n\n  @Delete('delete from user where name = #{name}')\n  deleteUser(@Param('name') name: string): number {return;}\n\n  @ResultType(UserDto)\n  @Select('select `name`, `age` from `user` where `uid` = #{uid} and `name` = #{name}')\n  getRecords(paramDto: ParamDto): UserDto[] {return;}\n\n  @Insert('insert into user (name, age) value (#{name}, #{age})')\n  addUser(user: UserDto): number {return;}\n}\n```\n\n* * *\n\n- Use Your Services.\n\n*app.controller.ts*\n```\nimport { Controller, Get } from '@nestjs/common';\nimport { AppService } from './app.service';\nimport { ParamDto } from './entity/param.dto';\nimport { UserDto } from \"./entity/create-cat.dto\";\n\n@Controller()\nexport class AppController {\n  constructor(private readonly appService: AppService) {}\n\n  @Get()\n  async getHello() {\n    await this.appService.setUserAge(\"zzz\", 20);\n    return \"hello world\";\n  }\n}\n\n```\n\n### Configuration\n\nThe Connection pools configuration is exactly the same as mysql2's [createPool\\(\\)](https://github.com/sidorares/node-mysql2#using-promise-wrapper).\n\nThe usual format is as follows:\n\n```\n{\n    host: '127.0.0.1',\n    user: 'root',\n    port: 3306,\n    password: '123456',\n    database: 'test',\n}\n```\n\n* * *\nLike common NestJS Modules, SpeedSQL uses [Asynchronous providers](https://docs.nestjs.com/fundamentals/async-providers) to inject it's Connection Pool for startup.\n\n- Make file ```db.provider.ts```\n```\nimport { createPool, Pool } from 'speedsql';\n\nexport const DbProviders = [\n  {\n    provide: 'SPEED_POOL',\n    useFactory: async (): Promise\u003cPool\u003e =\u003e {\n      return await createPool({\n        host: 'localhost',\n        user: 'root',\n        port: 3306,\n        password: 'qwer1234',\n        database: 'test',\n      });\n    },\n  },\n];\n```\n- Put ```db.provider.ts``` in NestJS app src dir and set it as a provider.\n```\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { SpeedService } from 'speedsql';\nimport { DbProviders } from './db.providers';\n\n@Module({\n  imports: [],\n  controllers: [AppController],\n  providers: [AppService, SpeedService, ...DbProviders],\n})\nexport class AppModule {}\n```\n\n### Parameter with named (for Prepared Statements)\n\n`@Param` define the named parameters.\n\nAs with MyBatis, SpeedSQL is possible to pass a value to a bind parameter as a named parameter to ensure readability and prevent SQL Injection attacks.\n\nUnlike [Prepared Statements](https://github.com/sidorares/node-mysql2#using-prepared-statements) in mysql2, SpeedSQL can be pass param value with named to make SQL more clearer.\n\n**Parameter with named value can support ```@Select```, ```@Insert```, ```@Update```, ```@Delete``` all the CRUD operations.**\n\n* * *\n\nSpeedSQL has two Parameter with named modes.\n\n\u003e Note that you can only choose ONE of the modes at ONE statement.\n\n**Object as Parameters**\n\n- Creates a conditional entity class with the same attribute and parameter names.\n\n```\nexport class ParamDto {\n  constructor(public name: string, public age: number) {}\n}\n```\n\n- Inject values as parameter entities.\n\n```\nimport { ResultType, Select } from 'speedsql';\n\n\n@ResultType(UserDto)\n@Select('select `name`, `age` from `user` where `uid` = #{uid} and `name` = #{name}')\ngetRecords(paramDto: ParamDto): UserDto[]{return;}\n```\n- So we can start to use.\n```\nconst users: UserDto[] = await this.appService.getRecords(\n  new ParamDto(\"zzz\", 10)\n);\n```\n\n**Named Value as Parameters**\n\nAnnotate the parameter value name with the parameter annotation '@Param', which corresponds to the SQL value name.\n\n```\nimport { ResultType, Select, Param } from 'speedsql';\n\n@ResultType(UserDto)\n@Select(select `name`, `age` from `user` where `uid` = #{uid} and `name` = #{name}')\ngetRecords(@Param('uid') uid:number, @Param('name') name:string): UserDto[]{return;}\n```\nSo we can start to use.\n```\nconst users: UserDto[] = await this.appService.getRecords('zzz', 10);\n```\n\n### @Select\n\nSpeedSQL uses ```@ResultType``` to annotate the resulting entity.\n\n`@ResultType` define the data entity for @Selete returns.\n\nSelect returns an array of annotated entity (```@ResultType```).\n\n- Create a entity: \n\n```\nexport class UserDto {\n  constructor(public name: string, public age: number) {}\n}\n```\n- And Select.\n```\nimport { ResultType, Select, Param } from 'speedsql';\n\n\n@ResultType(UserDto)\n@Select('select `name`, `age` from user where uid = #{uid} and name = #{name} ')\ngetRecords(@Param('uid') uid:number, @Param('name') name:string): UserDto[] {return;}\n```\n- The return Array will contains entities, and field name will correspond to the attributes of the entity.\n\nIf the field name and attribute are not the same, the value of different name will be lost. The solution is to use SQL's ```AS``` to alias the field name to correspond to the attributes of the entity.\n\n\n```\nimport { ResultType, Select, Param } from 'speedsql';\n\n@ResultType(UserDto)\n@Select('select `realname` as `name`, `age` from user where uid = #{uid} and name = #{name} ')\ngetRecords(@Param('uid') uid:number, @Param('name') name:string): UserDto[] {return;}\n```\n\n\n### @Insert\n\nParameter with named is also supported in ```@Insert```.\n\nThe ```@Insert``` return value is \u003cu\u003ethe new inserted ID\u003c/u\u003e, which can also be ignored.\n\n```\nimport { Insert } from 'speedsql';\n\n@Insert('insert into user (name, age) value (#{name}, #{age})')\naddUser(user: UserDto): number {return;}\n```\n\n### @Update and @Delete\n\nParameter with named is also supported in ```@Update``` and ```@Delete```.\n\nThe ```@Update``` and ```@Delete``` returns number is \u003cu\u003ethe effected rows\u003c/u\u003e, which can also be ignored.\n\n```\nimport { Delete, Update, Param } from 'speedsql';\n\n@Update('update user set age = #{age} where name = #{name}')\nsetUserAge(@Param('name') name: string, @Param('age') age: number): number {return;}\n\n@Delete('delete from user where name = #{name}')\ndeleteUser(@Param('name') name: string): number {return;}\n```\n\n\n### About\n\nGithub：[https://github.com/speedphp/speedsql](https://github.com/speedphp/speedsql)\n\nThe SpeedSQL project follows the open source agreement of the ```MIT License```.\n\nThanks: [NestJS](https://nestjs.com/)，[mysql2](https://github.com/sidorares/node-mysql2)，[MyBatis](https://mybatis.org/).\n\nIssue: [https://github.com/SpeedPHP/speedsql/issues](https://github.com/SpeedPHP/speedsql/issues)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspeedphp%2Fspeedsql","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fspeedphp%2Fspeedsql","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspeedphp%2Fspeedsql/lists"}