tediousjs / node-mssql

Microsoft SQL Server client for Node.js
https://tediousjs.github.io/node-mssql
MIT License
2.23k stars 467 forks source link

How correctly use ConnectionPool with import and export? #1471

Closed Aaqu closed 1 year ago

Aaqu commented 1 year ago

How version ConnectionPool for mssql is better and why if not both uses are wrong? I don't want create redundant or new ConnectionPools each time.

I use close() only when I close applications, here understand documentation.

version A

// db.js
import sql from "mssql"
const config = {...}
export const mssqlPool = new sql.ConnectionPool(config).connect()
// n endpoint.js
import { mssqlPool } from "../lib/mssql/db"
try {
  const pool = await mssqlPool
  const result = await pool.request().query(`SELECT * FROM table`)
  console.log(result)
} catch (err) {
  console.log(err)
}

version B

// db.js
import sql from "mssql"
const config = {...}
export const mssqlPool = new sql.ConnectionPool(config)
// n endpoint.js
import { mssqlPool } from "../lib/mssql/db"
try {
  const pool = await mssqlPool.connect();
  const result = await pool.request().query(`SELECT * FROM table`)
  console.log(result)
} catch (err) {
  console.log(err)
}

Software versions

dhensby commented 1 year ago

I would say that version B is best because it means your application will not "cache" a bad connection pool if the initial connect rejected for some reason and it will also reconnect a pool that gets closed by accident.

The docs already provide some guidance on pool management; this has the benefit of removing the pool reference when it is closed.

Aaqu commented 1 year ago

Powiedziałbym, że wersja B jest najlepsza, ponieważ oznacza, że aplikacja nie będzie "buforować" złej puli połączeń, jeśli początkowe połączenie zostanie odrzucone z jakiegoś powodu, a także ponownie połączy pulę, która zostanie przypadkowo zamknięta.

Thank for clarifying that