Lifecycle and Shutdown

Last updated

This page covers the full pool lifecycle, from creation in init() to shutdown through close() or a process signal.

init()

  1. Resolves the read and write configs by priority (see Configuration)
  2. Creates a pool with createPool() for each side whose database is non-empty
  3. Checks out one connection from each pool and releases it to verify credentials and network
  4. On any failure, calls console.error("MySQL initialization failed:", err) and rethrows the original error

Calling init() again creates new pools and overwrites the references without closing the old ones; call close() first when you need to reinitialize.

close()

Calls end() on the read pool and then the write pool and sets both references to null (src/MySQLPool.ts:99-115). Later queries throw ... connection is not available., and you can call init() again to recreate the pools. On failure it prints Failed to close MySQL connections: and rethrows the original error.

import MySQLPool from "@pardnchiu/mysql-pool";

await MySQLPool.init();
try {
  await MySQLPool.table("jobs", "write").where("status", "pending").get();
} finally {
  await MySQLPool.close();
}

Signal Handlers

Importing the package registers two process-level handlers (src/MySQLPool.ts:409-417):

Signal Behavior
SIGINT await MySQLPool.close(), then process.exit(0)
SIGTERM Same as above
Effect Detail
Exit code is always 0 Overrides an application that wants to exit with a non-zero code
Runs alongside your own handlers Node.js calls every handler in registration order; once this handler calls process.exit(0), pending async cleanup (such as an HTTP server's close()) is not awaited
close() fails The exception inside the handler is not caught, so process.exit(0) is never reached

Keep these behaviors in mind when your application needs its own shutdown order; see Known Limitations.

States

stateDiagram-v2
    [*] --> Uninitialized
    Uninitialized --> Ready: init() succeeds
    Uninitialized --> Uninitialized: init() fails and throws
    Ready --> Closed: close()
    Ready --> Closed: SIGINT / SIGTERM
    Closed --> Ready: init()
中文