Getting Started
Last updated
This page takes you from installation to a first query with the smallest working @pardnchiu/mysql-pool setup.
Prerequisites
| Item | Version |
|---|---|
| Node.js | 20 or higher (engines.node in package.json) |
| MySQL | 8.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
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.
export DB_READ_HOST=127.0.0.1
export DB_READ_USER=reader
export DB_READ_PASSWORD=secret
export DB_READ_DATABASE=app
export DB_WRITE_HOST=127.0.0.1
export DB_WRITE_USER=writer
export DB_WRITE_PASSWORD=secret
export DB_WRITE_DATABASE=app
You can also pass a config object to init(); see Configuration for every field.
First Query
import MySQLPool from "@pardnchiu/mysql-pool";
async function main() {
try {
// Create both pools and check out one connection from each
await MySQLPool.init();
// Uses the read pool by default
const users = await MySQLPool
.table("users")
.select("id", "name")
.where("status", "active")
.limit(10)
.get();
console.log(users);
} catch (err) {
console.error("query failed:", err);
} finally {
await MySQLPool.close();
}
}
main();
When init() cannot reach the database it prints MySQL initialization failed: through console.error and rethrows the original error (src/MySQLPool.ts:93).
First Write
const id = await MySQLPool
.table("users")
.insert({ name: "John Doe", email: "john@example.com" });
await MySQLPool
.table("users")
.where("id", id)
.update({ updated_at: "NOW()" });
insert(), update(), and upsert() always use the write pool regardless of the second argument to table().
Next Steps
- Builder State: why every chain starts with
table() - Select and Where: every form of
where() - Known Limitations: behaviors to know before production