Skip to content

Instantly share code, notes, and snippets.

@evanshortiss
Created May 17, 2024 21:04
Show Gist options
  • Save evanshortiss/23c679dbd13a2cb0d0198a9d8b79d211 to your computer and use it in GitHub Desktop.
Save evanshortiss/23c679dbd13a2cb0d0198a9d8b79d211 to your computer and use it in GitHub Desktop.
Using knex@3.x with Neon's HTTP Driver
import { Client, knex } from 'knex';
import { NeonQueryFunction, neon } from '@neondatabase/serverless';
class KnexNeonHTTP extends Client{
connection: NeonQueryFunction<false, false>;
constructor(config) {
super(config);
this.driverName = 'neon';
}
acquireRawConnection(): Promise<NeonQueryFunction<false, false>> {
return this.acquireConnection();
}
releaseConnection(connection: any) {
// noop
}
processResponse(res) {
return { rows: res }
}
_query(connection, obj) {
return connection(obj.sql, obj.bindings);
}
query(connection: any, obj: any) {
return this._query(connection, obj);
}
async acquireConnection () {
if (!this.config.connection) {
throw new Error('No connection string provided');
} else if (!this.connection) {
const cfg = this.config.connection as {
host: string;
user: string;
password: string;
database: string;
sslmode: string;
};
const url = `postgres://${cfg.user}:${cfg.password}@${cfg.host}/${cfg.database}?sslmode=${cfg.sslmode}`;
const connection = this.connection = neon(url, {
arrayMode: false
})
return this.connection = connection;
} else {
return this.connection;
}
}
}
const pg = knex({
client: KnexNeonHTTP,
connection: process.env.DATABASE_URL
})
pg.raw('SELECT version()').then(({rows}) => {
console.log('Connected to PostgreSQL', rows[0]);
process.exit(0)
}).catch((error) => {
console.error('Error connecting to PostgreSQL', error);
process.exit(1)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment