{"name":"@eggjs/rds","version":"1.2.0","keywords":["rds","mysql","mysql2"],"author":{"url":"https://github.com/fengmk2","name":"fengmk2","email":"fengmk2@gmail.com"},"license":"MIT","_id":"@eggjs/rds@1.2.0","homepage":"https://github.com/node-modules/rds","bugs":{"url":"https://github.com/node-modules/rds/issues"},"dist":{"shasum":"a1f8f1dc985962c38f630ce0d488c1ddd2e9078b","tarball":"http://registry-npm.ywwl.com/@eggjs/rds/download/@eggjs/rds-1.2.0.tgz","fileCount":23,"integrity":"sha512-n1jCyBC7zrPOjZ5gLEimNN/V8NFMnr7/7kUO9gGgMRTmF5MSVVR1OAJyK3mN+BNSNfPoEIhyWUUDyERKAVug6g==","signatures":[{"sig":"MEQCIQDai7OKKNoip5SvytBjEurRfqz5JQjgzVPHjOjJv3NwewIfF1vXMbk5FzW3rs/M/9YLfJWHe3M5FwRo5ZHKhKtxmA==","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/@eggjs%2frds@1.2.0","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"unpackedSize":100001,"size":24042,"noattachment":false,"key":"/@eggjs/rds/-/@eggjs/rds-1.2.0.tgz"},"main":"lib/client.js","types":"lib/client.d.ts","engines":{"node":">= 16.17.0"},"gitHead":"b359064c67476c6c9423da8d8d0a41bc315f82fc","scripts":{"ci":"npm run lint && egg-bin cov && npm run prepublishOnly","lint":"eslint src test --cache","test":"egg-bin test","build":"tsc -p ./tsconfig.json","clean":"tsc --build --clean","contributor":"git-contributor","prepublishOnly":"npm run clean && npm run build"},"_npmUser":{"name":"fengmk2","email":"fengmk2@gmail.com"},"repository":{"url":"git://github.com/node-modules/rds.git","type":"git"},"_npmVersion":"10.7.0","description":"My RDS Client","directories":{},"_nodeVersion":"18.20.4","dependencies":{"mysql2":"^3.9.1"},"publishConfig":{"access":"public"},"_hasShrinkwrap":false,"devDependencies":{"mm":"^3.3.0","eslint":"^8.29.0","egg-bin":"^6.1.2","typescript":"^5.1.3","@types/node":"^20.2.5","@types/mocha":"^10.0.1","@eggjs/tsconfig":"^1.3.2","git-contributor":"^2.0.0","eslint-config-egg":"^12.1.0"},"_npmOperationalInternal":{"tmp":"tmp/rds_1.2.0_1723441361155_0.5981393584688441","host":"s3://npm-registry-packages"},"readme":"# @eggjs/rds\n\n[![NPM version][npm-image]][npm-url]\n[![Node.js CI](https://github.com/node-modules/rds/actions/workflows/nodejs.yml/badge.svg)](https://github.com/node-modules/rds/actions/workflows/nodejs.yml)\n[![Test coverage][codecov-image]][codecov-url]\n[![npm download][download-image]][download-url]\n\n[npm-image]: https://img.shields.io/npm/v/@eggjs/rds.svg?style=flat-square\n[npm-url]: https://npmjs.org/package/@eggjs/rds\n[codecov-image]: https://codecov.io/github/node-modules/rds/coverage.svg?branch=master\n[codecov-url]: https://codecov.io/github/node-modules/rds?branch=master\n[download-image]: https://img.shields.io/npm/dm/@eggjs/rds.svg?style=flat-square\n[download-url]: https://npmjs.org/package/@eggjs/rds\n\nA RDS client.\nRDS, Relational Database Service. Equal to well know Amazon [RDS](http://aws.amazon.com/rds/).\n\nSupport `MySQL` protocol only.\n\n## Usage\n\n### Create RDS instance\n\n```ts\nimport { RDSClient } from '@eggjs/rds';\n\nconst db = new RDSClient({\n  host: 'your-rds-address.mysql.rds.aliyuncs.com',\n  port: 3306,\n  user: 'your-username',\n  password: 'your-password',\n  database: 'your-database-name',\n  // optional params\n  // The charset for the connection.\n  // This is called \"collation\" in the SQL-level of MySQL (like utf8_general_ci).\n  // If a SQL-level charset is specified (like utf8mb4)\n  // then the default collation for that charset is used. (Default: 'UTF8_GENERAL_CI')\n  // charset: 'utf8_general_ci',\n  //\n  // The maximum number of connections to create at once. (Default: 10)\n  // connectionLimit: 10,\n  //\n  // The maximum number of connection requests the pool will queue\n  // before returning an error from getConnection.\n  // If set to 0, there is no limit to the number of queued connection requests. (Default: 0)\n  // queueLimit: 0,\n  // Set asyncLocalStorage manually for transaction\n  // connectionStorage: new AsyncLocalStorage(),\n  // If create multiple RDSClient instances with the same connectionStorage, use this key to distinguish between the instances\n  // connectionStorageKey: 'datasource',\n  \n  // The timeout for connecting to the MySQL server. (Default: 500 milliseconds)\n  // connectTimeout: 500,\n\n  // The timeout for waiting for a connection from the connection pool. (Default: 500 milliseconds)\n  // So max timeout for get a connection is (connectTimeout + poolWaitTimeout)\n  // poolWaitTimeout: 500,\n});\n```\n\n### Insert\n\n- Insert one row\n\n```js\nconst row = {\n  name: 'fengmk2',\n  otherField: 'other field value',\n  createdAt: db.literals.now, // `now()` on db server\n  // ...\n};\nconst result = await db.insert('table-name', row);\nconsole.log(result);\n{ fieldCount: 0,\n  affectedRows: 1,\n  insertId: 3710,\n  serverStatus: 2,\n  warningCount: 2,\n  message: '',\n  protocol41: true,\n  changedRows: 0 }\n```\n\n- Insert multi rows\n\nWill execute under a transaction and auto commit.\n\n```js\nconst rows = [\n  {\n    name: 'fengmk1',\n    otherField: 'other field value',\n    createdAt: db.literals.now, // `now()` on db server\n    // ...\n  },\n  {\n    name: 'fengmk2',\n    otherField: 'other field value',\n    createdAt: db.literals.now, // `now()` on db server\n    // ...\n  },\n  // ...\n];\n\nconst results = await db.insert('table-name', rows);\nconsole.log(result);\n{ fieldCount: 0,\n  affectedRows: 2,\n  insertId: 3840,\n  serverStatus: 2,\n  warningCount: 2,\n  message: '&Records: 2  Duplicates: 0  Warnings: 0',\n  protocol41: true,\n  changedRows: 0 }\n```\n\n### Update\n\n- Update a row with primary key: `id`\n\n```js\nconst row = {\n  id: 123,\n  name: 'fengmk2',\n  otherField: 'other field value',\n  modifiedAt: db.literals.now, // `now()` on db server\n};\nconst result = await db.update('table-name', row);\nconsole.log(result);\n{ fieldCount: 0,\n  affectedRows: 1,\n  insertId: 0,\n  serverStatus: 2,\n  warningCount: 0,\n  message: '(Rows matched: 1  Changed: 1  Warnings: 0',\n  protocol41: true,\n  changedRows: 1 }\n```\n\n- Update a row with `options.where` and `options.columns`\n\n```js\nconst row = {\n  name: 'fengmk2',\n  otherField: 'other field value',\n  modifiedAt: db.literals.now, // `now()` on db server\n};\nconst result = await db.update('table-name', row, {\n  where: { name: row.name },\n  columns: [ 'otherField', 'modifiedAt' ]\n});\nconsole.log(result);\n{ fieldCount: 0,\n  affectedRows: 1,\n  insertId: 0,\n  serverStatus: 2,\n  warningCount: 0,\n  message: '(Rows matched: 1  Changed: 1  Warnings: 0',\n  protocol41: true,\n  changedRows: 1 }\n```\n\n### Update multiple rows\n\n- Update multiple rows with primary key: `id`\n\n```js\nconst options = [{\n  id: 123,\n  name: 'fengmk2',\n  email: 'm@fengmk2.com',\n  otherField: 'other field value',\n  modifiedAt: db.literals.now, // `now()` on db server\n}, {\n   id: 124,\n  name: 'fengmk2_2',\n  email: 'm@fengmk2_2.com',\n  otherField: 'other field value 2',\n  modifiedAt: db.literals.now, // `now()` on db server\n}]\nconst result = await db.updateRows('table-name', options);\nconsole.log(result);\n{ fieldCount: 0,\n  affectedRows: 2,\n  insertId: 0,\n  serverStatus: 2,\n  warningCount: 0,\n  message: '(Rows matched: 2  Changed: 2  Warnings: 0',\n  protocol41: true,\n  changedRows: 2 }\n```\n\n- Update multiple rows with `row` and `where` properties\n\n```js\nconst options = [{\n  row: {\n    email: 'm@fengmk2.com',\n    otherField: 'other field value',\n    modifiedAt: db.literals.now, // `now()` on db server\n  },\n  where: {\n    id: 123,\n    name: 'fengmk2',\n  }\n}, {\n  row: {\n    email: 'm@fengmk2_2.com',\n    otherField: 'other field value2',\n    modifiedAt: db.literals.now, // `now()` on db server\n  }, \n  where: {\n    id: 124,\n    name: 'fengmk2_2',\n  }\n}]\nconst result = await db.updateRows('table-name', options);\nconsole.log(result);\n{ fieldCount: 0,\n  affectedRows: 2,\n  insertId: 0,\n  serverStatus: 2,\n  warningCount: 0,\n  message: '(Rows matched: 2  Changed: 2  Warnings: 0',\n  protocol41: true,\n  changedRows: 2 }\n```\n\n### Get\n\n- Get a row\n\n```js\nconst row = await db.get('table-name', { name: 'fengmk2' });\n\n=> SELECT * FROM `table-name` WHERE `name` = 'fengmk2'\n```\n\n### Select\n\n- Select all rows\n\n```js\nconst rows = await db.select('table-name');\n\n=> SELECT * FROM `table-name`\n```\n\n- Select rows with condition\n\n```js\nconst rows = await db.select('table-name', {\n  where: {\n    type: 'javascript'\n  },\n  columns: ['author', 'title'],\n  orders: [['id', 'desc']]\n});\n\n=> SELECT `author`, `title` FROM `table-name`\n WHERE `type` = 'javascript' ORDER BY `id` DESC\n```\n\n### Delete\n\n- Delete with condition\n\n```js\nconst result = await db.delete('table-name', {\n  name: 'fengmk2'\n});\n\n=> DELETE FROM `table-name` WHERE `name` = 'fengmk2'\n```\n\n### Count\n\n- Get count from a table with condition\n\n```js\nconst count = await db.count('table-name', {\n  type: 'javascript'\n});\n\n=> SELECT COUNT(*) AS count FROM `table-name` WHERE `type` = 'javascript';\n```\n\n### Transactions\n\nbeginTransaction, commit or rollback\n\n```js\nconst tran = await db.beginTransaction();\n\ntry {\n  await tran.insert(table, row1);\n  await tran.update(table, row2);\n  await tran.commit();\n} catch (err) {\n  // error, rollback\n  await tran.rollback(); // rollback call won't throw err\n  throw err;\n}\n```\n\n#### Transaction with scope\n\nAPI: `async beginTransactionScope(scope)`\n\nAll query run in scope will under a same transaction.\nWe will auto commit or rollback for you.\n\n```js\nconst result = await db.beginTransactionScope(async conn => {\n  // don't commit or rollback by yourself\n  await conn.insert(table, row1);\n  await conn.update(table, row2);\n  return { success: true };\n});\n// if error throw on scope, will auto rollback\n```\n\nIn `Promise.all` case, Parallel beginTransactionScope will create isolated transactions.\n\n```js\nconst result = await Promise.all([\n  db.beginTransactionScope(async conn => {\n    // commit and success\n  }),\n  db.beginTransactionScope(async conn => {\n    // throw err and rollback\n  }),\n])\n```\n\n### Raw Queries\n\n- Query without arguments\n\n```js\nconst rows = await db.query('SELECT * FROM your_table LIMIT 100');\nconsole.log(rows);\n```\n\n- Query with array arguments\n\n```js\nconst rows = await db.query('SELECT * FROM your_table WHERE id=?', [ 123 ]);\nconsole.log(rows);\n```\n\n- Query with object arguments\n\n```js\nconst rows = await db.query('SELECT * FROM your_table WHERE id=:id', { id: 123 });\nconsole.log(rows);\n```\n\n### Custom query lifecircle\n\n```ts\ndb.beforeQuery((sql: string) => {\n  // change sql string\n  return `/* add custom format here */ ${sql}`;\n});\n\ndb.afterQuery((sql: string, result: any, execDuration: number, err?: Error) => {\n  // handle logger here\n});\n```\n\n## APIs\n\n- `*` Meaning this function is yieldable.\n\n### IO queries\n\n- async query(sql[, values)\n- async queryOne(sql[, values)\n- async select(table, options)\n- async get(table, where, options)\n- async insert(table, row[s], options)\n- async update(table, row, options)\n- async updateRows(table, options)\n- async delete(table, where)\n- async count(table, where)\n\n### Transactions Helpers\n\n- async beginTransaction()\n- async beginTransactionScope(scope)\n\n### Utils\n\n- escape(value, stringifyObjects, timeZone)\n- escapeId(value, forbidQualified)\n- format(sql, values, stringifyObjects, timeZone)\n\n### Literals\n\n```js\nawait db.insert('user', {\n  name: 'fengmk2',\n  createdAt: db.literals.now,\n});\n\n=>\n\nINSERT INTO `user` SET `name` = 'fengmk2', `createdAt` = now()\n```\n\n#### Custom Literal\n\n```js\nconst session = new db.literals.Literal('session()');\n```\n\n## Class Relation\n\n```txt\n+-----------+                          +----------------+\n| RDSClient +-- beginTransaction() --> + RDSTransaction |\n+--+----+---+                          +----+----+------+\n   |    | getConnection()            .conn  |    |\n   |    |         +---------------+         |    |\n   |    +-------->+ RDSConnection +<--------+    |\n   |              +-------+-------+              |\n   |                      | extends              |\n   |                      v                      |\n   |   extends    +-------+-------+    extends   |\n   +------------->+   Operator    +<-------------+\n                  |    query()    |\n                  +---------------+\n```\n\n## License\n\n[MIT](LICENSE)\n\n<!-- GITCONTRIBUTOR_START -->\n\n## Contributors\n\n|[<img src=\"https://avatars.githubusercontent.com/u/156269?v=4\" width=\"100px;\"/><br/><sub><b>fengmk2</b></sub>](https://github.com/fengmk2)<br/>|[<img src=\"https://avatars.githubusercontent.com/u/32174276?v=4\" width=\"100px;\"/><br/><sub><b>semantic-release-bot</b></sub>](https://github.com/semantic-release-bot)<br/>|[<img src=\"https://avatars.githubusercontent.com/u/985607?v=4\" width=\"100px;\"/><br/><sub><b>dead-horse</b></sub>](https://github.com/dead-horse)<br/>|[<img src=\"https://avatars.githubusercontent.com/u/6587734?v=4\" width=\"100px;\"/><br/><sub><b>AntiMoron</b></sub>](https://github.com/AntiMoron)<br/>|[<img src=\"https://avatars.githubusercontent.com/u/9213756?v=4\" width=\"100px;\"/><br/><sub><b>gxkl</b></sub>](https://github.com/gxkl)<br/>|[<img src=\"https://avatars.githubusercontent.com/u/10287125?v=4\" width=\"100px;\"/><br/><sub><b>nodejh</b></sub>](https://github.com/nodejh)<br/>|\n| :---: | :---: | :---: | :---: | :---: | :---: |\n|[<img src=\"https://avatars.githubusercontent.com/u/4192962?v=4\" width=\"100px;\"/><br/><sub><b>fangk</b></sub>](https://github.com/fangk)<br/>|[<img src=\"https://avatars.githubusercontent.com/u/1619030?v=4\" width=\"100px;\"/><br/><sub><b>xujihui1985</b></sub>](https://github.com/xujihui1985)<br/>|[<img src=\"https://avatars.githubusercontent.com/u/1468366?v=4\" width=\"100px;\"/><br/><sub><b>csbun</b></sub>](https://github.com/csbun)<br/>|[<img src=\"https://avatars.githubusercontent.com/u/360661?v=4\" width=\"100px;\"/><br/><sub><b>popomore</b></sub>](https://github.com/popomore)<br/>|[<img src=\"https://avatars.githubusercontent.com/u/12378108?v=4\" width=\"100px;\"/><br/><sub><b>hoythan</b></sub>](https://github.com/hoythan)<br/>|[<img src=\"https://avatars.githubusercontent.com/u/35927028?v=4\" width=\"100px;\"/><br/><sub><b>deadhorse123</b></sub>](https://github.com/deadhorse123)<br/>|\n[<img src=\"https://avatars.githubusercontent.com/u/6897780?v=4\" width=\"100px;\"/><br/><sub><b>killagu</b></sub>](https://github.com/killagu)<br/>|[<img src=\"https://avatars.githubusercontent.com/u/3438038?v=4\" width=\"100px;\"/><br/><sub><b>qile222</b></sub>](https://github.com/qile222)<br/>|[<img src=\"https://avatars.githubusercontent.com/u/566097?v=4\" width=\"100px;\"/><br/><sub><b>RaoHai</b></sub>](https://github.com/RaoHai)<br/>\n\nThis project follows the git-contributor [spec](https://github.com/xudafeng/git-contributor), auto updated at `Tue Jan 30 2024 21:16:24 GMT+0800`.\n\n<!-- GITCONTRIBUTOR_END -->\n","publish_time":1723441361306,"maintainers":[{"name":"akitasummer","email":"644171127@qq.com"},{"name":"gxkl","email":"gxkl203@gmail.com"},{"name":"gemwuu","email":"gemwuu@gmail.com"},{"name":"eggjs-admin","email":"fengmk2+eggjs@gmail.com"},{"name":"fengmk2","email":"fengmk2@gmail.com"},{"name":"atian25","email":"atian25@qq.com"},{"name":"dead_horse","email":"dead_horse@qq.com"},{"name":"wanghx","email":"whxaxes@gmail.com"},{"name":"hyj1991","email":"yeekwanvong@gmail.com"},{"name":"killagu","email":"killa07071201@gmail.com"},{"name":"coolme200","email":"2001-wms@163.com"},{"name":"mansonchor.zzw","email":"mansonchor1987@gmail.com"},{"name":"hubcarl","email":"hubcarl@126.com"}],"_cnpm_publish_time":1723441361306,"dist-tags":{"latest":"1.5.0"}}