porsager / postgres

Postgres.js - The Fastest full featured PostgreSQL client for Node.js, Deno, Bun and CloudFlare

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Migrating from "brianc/node-postgres" to "porsager/postgres"

cesco69 opened this issue · comments

Hi, I have a huge application and I'm migrating the code from "brianc/node-postgres" to "porsager/postgres", I have some question.

FIRST QUESTION
I'm replace all query method of "brianc/node-postgres" (docs) with unsafe method of "porsager/postgres", eg.:

const sql = 'SELECT * FROM users WHERE id = $1'
const params = [10]
const name = 'user_id' // name of the query - used for prepared statements on brianc/node-postgres

// from brianc/node-postgres
import { Pool } from 'pg';
const client = new Pool(config)
client.query(sql, params, name)

// to porsager/postgres
import postgres from 'postgres';
const client = postgres(config)
client.unsafe(sql, params);

"porsager/postgres" has no argument for prepared statements. If a name is provided into "brianc/node-postgres" the query is auto-prepared before execution. What I do if i want the same into "porsager/postgres"

SECOND QUESTION
In "brianc/node-postgres" I can retrive a client from the pool and use the same connection for all the query instead of get a connection for each query, eg.:

import { Pool } from 'pg';
const pool = new Pool(config)
// In this way teach query use the same connection
const client = await pool.connect()
try {
    await client.query('SELECT * FROM users WHERE id = $1', [1])
    await client.query('SELECT * FROM users WHERE id = $1', [2])
} finally {
    client.release()
}

// ------

// In this way each query use a different connection
await pool.query('SELECT * FROM users WHERE id = $1', [1])
await pool.query('SELECT * FROM users WHERE id = $1', [2])

If I understand correctly "porsager/postgres" the correct replacement is:

import postgres from 'postgres';
const pool = postgres(config)

// In this way teach query use the same connection
const client = await pool.reserve()
try {
    await client.unsafe('SELECT * FROM users WHERE id = $1', [1])
    await client.unsafe('SELECT * FROM users WHERE id = $1', [2])
} finally {
    client.release()
}

// ------

// In this way each query use a different connection
await pool.unsafe('SELECT * FROM users WHERE id = $1', [1])
await pool.unsafe('SELECT * FROM users WHERE id = $1', [2])