Getting Started

Last updated


This page takes you from installation to a first query with the smallest working @pardnchiu/mysql-pool setup.

Prerequisites


ItemVersion
Node.js20 or higher (engines.node in package.json)
MySQL8.0 or higher; only total() needs the COUNT(*) OVER() window function, so 5.7 works without it
mysql2^3.14.1, installed with the package

Installation


  1. npm install @pardnchiu/mysql-pool

Configure the Connection


The quickest route is environment variables. When only one side is set, the other side creates no pool; see Read-Write Pools.
  1. export DB_READ_HOST=127.0.0.1
  2. export DB_READ_USER=reader
  3. export DB_READ_PASSWORD=secret
  4. export DB_READ_DATABASE=app
  5. export DB_WRITE_HOST=127.0.0.1
  6. export DB_WRITE_USER=writer
  7. export DB_WRITE_PASSWORD=secret
  8. export DB_WRITE_DATABASE=app

You can also pass a config object to init(); see Configuration for every field.

First Query


  1. import MySQLPool from "@pardnchiu/mysql-pool";
  2. async function main() {
  3. try {
  4. // Create both pools and check out one connection from each
  5. await MySQLPool.init();
  6. // Uses the read pool by default
  7. const users = await MySQLPool
  8. .table("users")
  9. .select("id", "name")
  10. .where("status", "active")
  11. .limit(10)
  12. .get();
  13. console.log(users);
  14. } catch (err) {
  15. console.error("query failed:", err);
  16. } finally {
  17. await MySQLPool.close();
  18. }
  19. }
  20. main();

When init() cannot reach the database it prints MySQL initialization failed: through console.error and rethrows the original error (src/MySQLPool.ts:93-96).

First Write


  1. const id = await MySQLPool
  2. .table("users")
  3. .insert({ name: "John Doe", email: "john@example.com" });
  4. await MySQLPool
  5. .table("users")
  6. .where("id", id)
  7. .update({ updated_at: "NOW()" });

insert(), update(), and upsert() always use the write pool regardless of the second argument to table().

Next Steps


中文