Created
August 21, 2022 15:42
-
-
Save rdemorais/2e144ad9fc0612d88843124534ed8507 to your computer and use it in GitHub Desktop.
Redshift connection from NodeJS - from https://www.javaniceday.com/post/how-to-connect-to-a-redshift-database-from-node-js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pgp from "pg-promise"; | |
const connections = []; | |
export default class Redshift { | |
static async getConnection() { | |
const dbName = "myDb"; | |
if (!connections[dbName]) { | |
const dbUser = "dbUser"; | |
const dbPassword = "dbPassword"; | |
const dbHost = "myHost"; | |
const dbPort = "dbPort"; | |
const dbc = pgp({ capSQL: true }); | |
console.log(`Opening connection to: ${dbName}, host is: ${dbHost}`); | |
const connectionString = `postgres://${dbUser}:${dbPassword}@${dbHost}:${dbPort}/${dbName}`; | |
connections[dbName] = dbc(connectionString); | |
} | |
return connections[dbName]; | |
} | |
static async executeQuery(query) { | |
try { | |
const date1 = new Date().getTime(); | |
const connection = await this.getConnection(); | |
const result = await connection.query(query); | |
const date2 = new Date().getTime(); | |
const durationMs = date2 - date1; | |
const durationSeconds = Math.round(durationMs / 1000); | |
let dataLength = 0; | |
if (result && result.length) dataLength = result.length; | |
console.log( | |
`[Redshift] [${durationMs}ms] [${durationSeconds}s] [${dataLength.toLocaleString()} records] ${query}` | |
); | |
return result; | |
} catch (e) { | |
console.error(`Error executing query: ${query} Error: ${e.message}`); | |
throw e; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment