{"id":14969179,"url":"https://github.com/fastify/fastify-mysql","last_synced_at":"2025-05-16T14:05:03.100Z","repository":{"id":26894523,"uuid":"109702687","full_name":"fastify/fastify-mysql","owner":"fastify","description":"Fastify Mysql connection plugin","archived":false,"fork":false,"pushed_at":"2025-05-01T17:10:36.000Z","size":167,"stargazers_count":74,"open_issues_count":3,"forks_count":22,"subscribers_count":18,"default_branch":"main","last_synced_at":"2025-05-01T18:24:20.945Z","etag":null,"topics":["fastify","fastify-plugin","mysql"],"latest_commit_sha":null,"homepage":"https://npmjs.com/package/@fastify/mysql","language":"JavaScript","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/fastify.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,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"fastify","open_collective":"fastify"}},"created_at":"2017-11-06T14:02:24.000Z","updated_at":"2025-05-01T17:10:32.000Z","dependencies_parsed_at":"2023-02-10T05:01:17.702Z","dependency_job_id":"c16cc63d-bf76-45a7-801d-989738b26729","html_url":"https://github.com/fastify/fastify-mysql","commit_stats":{"total_commits":150,"total_committers":34,"mean_commits":4.411764705882353,"dds":0.6599999999999999,"last_synced_commit":"a0b668614003a0ffd2095be2422dd230c822df91"},"previous_names":[],"tags_count":16,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-mysql","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-mysql/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-mysql/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-mysql/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fastify","download_url":"https://codeload.github.com/fastify/fastify-mysql/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254544146,"owners_count":22088807,"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":["fastify","fastify-plugin","mysql"],"created_at":"2024-09-24T13:41:17.941Z","updated_at":"2025-05-16T14:05:03.094Z","avatar_url":"https://github.com/fastify.png","language":"JavaScript","readme":"# @fastify/mysql\n\n[![CI](https://github.com/fastify/fastify-mysql/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/fastify-mysql/actions/workflows/ci.yml)\n[![NPM version](https://img.shields.io/npm/v/@fastify/mysql.svg?style=flat)](https://www.npmjs.com/package/@fastify/mysql)\n[![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)\n\nFastify MySQL connection plugin; with this you can share the same MySQL connection pool in every part of your server.\nUnder the hood the [mysql2](https://github.com/sidorares/node-mysql2) is used. If you don't use the `connectionString` option, the options you pass to `register` will be passed to the MySQL pool builder.\n\n_Important:_ All MySQL2 options will be ignored when using `connectionString`, if you want to pass additional options to MySQL2 use `uri` instead of `connectionString`.\n\n## Install\n```\nnpm i @fastify/mysql\n```\n\n### Compatibility\n| Plugin version | Fastify version |\n| ---------------|-----------------|\n| `\u003e=5.x`        | `^5.x`          |\n| `^4.x`         | `^4.x`          |\n| `\u003e=2.x \u003c4.x`   | `^3.x`          |\n| `\u003e=0.x \u003c2.x`   | `^2.x`          |\n| `\u003e=0.x \u003c2.x`   | `^1.x`          |\n\n\nPlease note that if a Fastify version is out of support, then so are the corresponding versions of this plugin\nin the table above.\nSee [Fastify's LTS policy](https://github.com/fastify/fastify/blob/main/docs/Reference/LTS.md) for more details.\n\n\n\n## Usage\nAdd it to you project with `register` and you are done!\nThis plugin will add the `mysql` namespace in your Fastify instance, with the following properties:\n```\npool: the pool instance\nquery: an utility to perform a query without a transaction\nexecute: an utility to perform a prepared statement without a transaction\ngetConnection: get a connection from the pool\nformat: an utility to generate SQL string\nescape: an utility to escape query values\nescapeId: an utility to escape query identifiers\n```\n\nExample:\n```js\nconst fastify = require('fastify')()\n\nfastify.register(require('@fastify/mysql'), {\n  connectionString: 'mysql://root@localhost/mysql'\n})\n\nfastify.get('/user/:id', (req, reply) =\u003e {\n  fastify.mysql.getConnection(onConnect)\n\n  function onConnect (err, client) {\n    if (err) return reply.send(err)\n\n    client.query(\n      'SELECT id, username, hash, salt FROM users WHERE id=?', [req.params.id],\n      function onResult (err, result) {\n        client.release()\n        reply.send(err || result)\n      }\n    )\n  }\n})\n\nfastify.listen({ port: 3000 }, err =\u003e {\n  if (err) throw err\n  console.log(`server listening on ${fastify.server.address().port}`)\n})\n```\n\nUse of `mysql.query`\n```js\nconst fastify = require('fastify')()\n\nfastify.register(require('@fastify/mysql'), {\n  connectionString: 'mysql://root@localhost/mysql'\n})\n\nfastify.get('/user/:id', (req, reply) =\u003e {\n  fastify.mysql.query(\n    'SELECT id, username, hash, salt FROM users WHERE id=?', [req.params.id],\n    function onResult (err, result) {\n      reply.send(err || result)\n    }\n  )\n})\n\nfastify.listen({ port: 3000 }, err =\u003e {\n  if (err) throw err\n  console.log(`server listening on ${fastify.server.address().port}`)\n})\n```\nAs you can see there is no need to close the client, since it is done internally.\n\nAsync/await is supported, when register `promise` option is `true`:\n```js\nconst fastify = require('fastify')()\n\nfastify.register(require('@fastify/mysql'), {\n  promise: true,\n  connectionString: 'mysql://root@localhost/mysql'\n})\n\nfastify.get('/user/:id', async (req, reply) =\u003e {\n  const connection = await fastify.mysql.getConnection()\n  const [rows, fields] = await connection.query(\n    'SELECT id, username, hash, salt FROM users WHERE id=?', [req.params.id],\n  )\n  connection.release()\n  return rows[0]\n})\n\nfastify.listen({ port: 3000 }, err =\u003e {\n  if (err) throw err\n  console.log(`server listening on ${fastify.server.address().port}`)\n})\n```\n\n## TypeScript\nAs `mysql2` expose four different type of client, we do not specify the typing for you. You need to specify the type yourself following the example below.\n```ts\nimport { MySQLConnection, MySQLPool, MySQLPromiseConnection, MySQLPromisePool } from '@fastify/mysql'\n\n// if you only pass connectionString\ndeclare module 'fastify' {\n  interface FastifyInstance {\n    mysql: MySQLPool\n  }\n}\n\n// if you passed type = 'connection'\ndeclare module 'fastify' {\n  interface FastifyInstance {\n    mysql: MySQLConnection\n  }\n}\n\n// if you passed promise = true\ndeclare module 'fastify' {\n  interface FastifyInstance {\n    mysql: MySQLPromisePool\n  }\n}\n\n// if you passed promise = true, type = 'connection'\ndeclare module 'fastify' {\n  interface FastifyInstance {\n    mysql: MySQLPromiseConnection\n  }\n}\n```\n\n#### MySQLRowDataPacket\nAbility to add type for return data using mysql2 [RowDataPacket](https://sidorares.github.io/node-mysql2/docs/documentation/typescript-examples#rowdatapacket).\n\n```js\nconst fastifyMysql, { MySQLRowDataPacket } from '@fastify/mysql'\n\nconst app = fastify();\n\napp.register(fastifyMysql, {\n  connectionString: \"mysql://root@localhost/mysql\",\n});\n\napp.get(\"/\", async () =\u003e {\n  const connection = app.mysql;\n\n  // SELECT\n  const [rows, fields] = await connection.query\u003cMySQLRowDataPacket[]\u003e(\n    \"SELECT 1 + 1 AS `test`;\",\n  );\n\n  /**\n   * @rows: [ { test: 2 } ]\n   */\n  return rows[0];\n});\n```\n\n#### MySQLResultSetHeader\nAbility to add type for return data using mysql2 [ResultSetHeader](https://sidorares.github.io/node-mysql2/docs/documentation/typescript-examples#resultsetheader).\n\n```js\nconst fastifyMysql, { MySQLResultSetHeader } from '@fastify/mysql'\n\nconst app = fastify();\n\napp.register(fastifyMysql, {\n  connectionString: \"mysql://root@localhost/mysql\",\n});\n\napp.get(\"/\", async () =\u003e {\n  const connection = app.mysql;\n  const result = await connection.query\u003cMySQLResultSetHeader\u003e(\"SET @1 = 1\");\n\n  /**\n   * @result: ResultSetHeader {\n      fieldCount: 0,\n      affectedRows: 0,\n      insertId: 0,\n      info: '',\n      serverStatus: 2,\n      warningStatus: 0,\n      changedRows: 0\n    }\n   */\n  return result\n});\n```\n\n##### isMySQLPool\nMethod to check if fastify decorator, mysql is type of [MySQLPool](https://github.com/fastify/fastify-mysql/blob/main/types/index.d.ts#L32)\n\n```typescript\nconst app = fastify();\napp\n  .register(fastifyMysql, {\n    connectionString: \"mysql://root@localhost/mysql\",\n  })\n  .after(function (err) {\n    if (isMySQLPool(app.mysql)) {\n      const mysql = app.mysql\n      mysql.getConnection(function (err, con) {\n        con.release();\n      });\n      mysql.pool.end();\n    }\n  })\n```\n\n\n##### isMySQLPromisePool\nMethod to check if fastify decorator, mysql is type of [MySQLPromisePool](https://github.com/fastify/fastify-mysql/blob/main/types/index.d.ts#L43)\n\n```typescript\napp\n  .register(fastifyMysql, {\n    promise: true,\n    connectionString: \"mysql://root@localhost/mysql\",\n  })\n  .after(async function (err) {\n    if (isMySQLPromisePool(app.mysql)) {\n      const mysql = app.mysql\n      const con = await mysql.getConnection();\n      con.release();\n      mysql.pool.end();\n    }\n  });\n```\n\n\n##### isMySQLConnection\nMethod to check if fastify decorator, mysql is type of [MySQLConnection](https://github.com/fastify/fastify-mysql/blob/main/types/index.d.ts#L28)\n\n```typescript\napp\n  .register(fastifyMysql, {\n    type: \"connection\",\n    connectionString: \"mysql://root@localhost/mysql\",\n  })\n  .after(async function (err) {\n    if (isMySQLConnection(app.mysql)) {\n      const mysql = app.mysql\n      mysql.connection.end();\n    }\n  });\n```\n\n\n##### isMySQLPromiseConnection\nMethod to check if fastify decorator, mysql is type of [MySQLPromiseConnection](https://github.com/fastify/fastify-mysql/blob/main/types/index.d.ts#L36)\n\n```typescript\napp\n  .register(fastifyMysql, {\n    type: \"connection\",\n    promise: true,\n    connectionString: \"mysql://root@localhost/mysql\",\n  })\n  .after(async function (err) {\n    if (isMySQLPromiseConnection(app.mysql)) {\n      const mysql = app.mysql\n      mysql.connection.end();\n    }\n  });\n```\n\n## Acknowledgments\n\nThis project is kindly sponsored by:\n- [nearForm](https://nearform.com)\n- [LetzDoIt](https://www.letzdoitapp.com/)\n\n## License\n\nLicensed under [MIT](./LICENSE).\n","funding_links":["https://github.com/sponsors/fastify","https://opencollective.com/fastify"],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffastify%2Ffastify-mysql","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffastify%2Ffastify-mysql","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffastify%2Ffastify-mysql/lists"}