{"name":"@eggjs/rds","version":"1.2.2","keywords":["rds","mysql","mysql2"],"author":{"url":"https://github.com/fengmk2","name":"fengmk2","email":"fengmk2@gmail.com"},"license":"MIT","_id":"@eggjs/rds@1.2.2","maintainers":[{"name":"gxkl","email":"gxkl203@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"},{"name":"gemwuu","email":"gemwuu@gmail.com"},{"name":"akitasummer","email":"644171127@qq.com"}],"homepage":"https://github.com/node-modules/rds","bugs":{"url":"https://github.com/node-modules/rds/issues"},"dist":{"shasum":"b5f0df84abfad05d29cd39397984124004015189","tarball":"http://registry-npm.ywwl.com/@eggjs/rds/download/@eggjs/rds-1.2.2.tgz","fileCount":23,"integrity":"sha512-Fy6hhKtO23wr0B4oTgZg1a3ncKoeccmNTahinL1SN9V99BuGJn+TClnJqOozvjQ5qtsk88U9M+7hTI38eMue0Q==","signatures":[{"sig":"MEUCIBuj0sCikGXjk0iYN7YYxSPCE33HcqGWp6TiWMZDUyE7AiEA18tP/uzXkoooz2KuNznh6vzNrU/UQBnxs4CcoNhVWuY=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/@eggjs%2frds@1.2.2","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"unpackedSize":98385,"size":23835,"noattachment":false,"key":"/@eggjs/rds/-/@eggjs/rds-1.2.2.tgz"},"main":"lib/client.js","types":"lib/client.d.ts","engines":{"node":">= 16.17.0"},"gitHead":"db72b8e26dca655fe511bb07cf504498bd01c8c0","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.8.2","description":"My RDS Client","directories":{},"_nodeVersion":"20.18.3","dependencies":{"mysql2":"^3.9.1","sqlstring":"^2.3.3"},"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","eslint-config-egg":"^12.1.0"},"_npmOperationalInternal":{"tmp":"tmp/rds_1.2.2_1741501187229_0.4839128102486663","host":"s3://npm-registry-packages-npm-production"},"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## For the local dev\n\nRun docker compose to start test mysql service\n\n```bash\ndocker compose -f docker-compose.yml up -d\n# if you run the first time, should wait for ~20s to let mysql service init started\n```\n\nRun the unit tests\n\n```bash\nnpm test\n```\n\nStop test mysql service\n\n```bash\ndocker compose -f docker-compose.yml down\n```\n\n## License\n\n[MIT](LICENSE)\n\n## Contributors\n\n[![Contributors](https://contrib.rocks/image?repo=node-modules/rds)](https://github.com/node-modules/rds/graphs/contributors)\n\nMade with [contributors-img](https://contrib.rocks).\n","publish_time":1741501187461,"_cnpm_publish_time":1741501187461,"dist-tags":{"latest":"1.5.0"}}