Skip to content

Instantly share code, notes, and snippets.

@zerbfra
Last active February 22, 2023 22:54
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
  • Save zerbfra/70b155fa00b4e0d6fd1d4e090a039ad4 to your computer and use it in GitHub Desktop.
Save zerbfra/70b155fa00b4e0d6fd1d4e090a039ad4 to your computer and use it in GitHub Desktop.
node-postgres connection and query with async/await
const pg = require('pg')
// create a config to configure both pooling behavior
// and client options
// note: all config is optional and the environment variables
// will be read if the config is not present
var config = {
user: '', // env var: PGUSER
database: '', // env var: PGDATABASE
password: '', // env var: PGPASSWORD
host: 'localhost', // Server hosting the postgres database
port: 5432, // env var: PGPORT
max: 10, // max number of clients in the pool
idleTimeoutMillis: 30000 // how long a client is allowed to remain idle before being closed
}
const pool = new pg.Pool(config)
async function query (q) {
const client = await pool.connect()
let res
try {
await client.query('BEGIN')
try {
res = await client.query(q)
await client.query('COMMIT')
} catch (err) {
await client.query('ROLLBACK')
throw err
}
} finally {
client.release()
}
return res
}
async function main () {
try {
const { rows } = await query('SELECT * FROM users')
console.log(JSON.stringify(rows))
} catch (err) {
console.log('Database ' + err)
}
}
main()
@talkingtab
Copy link

This was very helpful, but when you have a query with parameters, for example

('SELECT * FROM USERS where name = $1,"Nixon")

the code fails because the second argument is not passed along. The async function 'query' needs a second argument (p is for parameter)

async function query (q,p) {

which then needs to be passed to the client.query

await client.query(q,p);

@chrisalexander55
Copy link

@talkingtab. Try:

('SELECT * FROM USERS where name = $1, ["Nixon"]) // needs array of bindable values

@nehuenlabs
Copy link

This code it's like a beautyful girl dancing ballet.

@zzznavarrete
Copy link

Thanks buddy, it works for me

@shailendra-k1245
Copy link

Can try this hope this is helpful

const Pool = require("pg").Pool
const pool = new Pool({
    user: "",
    host: "",
    database: "",
    password: "", 
    port: 5432,
    ssl: true
})

const userWorkflow = async()=>{
await insertNewUser(userMobileNumber,workflow)
let user = await checkUser
console.log(user)
}

const insertNewUser = async (userMobileNumber, workflow) => {
    let query = "INSERT INTO userinfo (usermobilenumber,workflows) values" + "(" + "'" + userMobileNumber + "'" + "," + "'" + workflow + "'" + ")"
   
    await pool.query(query)
}

const checkUser = async (userMobileNumber) => {
    let query = "select * from userinfo where usermobilenumber =" + "'" + userMobileNumber + "'"

    let results = await pool.query(query)
    if (results.rows.length === 0) {
        return 1
    }
    return results.rows[0].workflows.idx

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment