Skip to content

Neon Serverless Connection #39

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jul 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
139 changes: 135 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,14 @@
"author": "Outerbase",
"license": "MIT",
"dependencies": {
"handlebars": "^4.7.8"
"@neondatabase/serverless": "^0.9.3",
"handlebars": "^4.7.8",
"ws": "^8.17.1"
},
"devDependencies": {
"@jest/globals": "^29.7.0",
"@types/node": "^20.12.12",
"@types/ws": "^8.5.10",
"husky": "^9.0.11",
"jest": "^29.7.0",
"lint-staged": "^15.2.4",
Expand Down
21 changes: 19 additions & 2 deletions playground/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,28 @@
import { CloudflareD1Connection, Outerbase, OuterbaseConnection, equalsNumber } from '../dist/index.js';
import { CloudflareD1Connection, Outerbase, NeonHttpConnection, OuterbaseConnection, equalsNumber } from '../dist/index.js';
import express from 'express';

const app = express();
const port = 4000;

app.get('/', async (req, res) => {
const data = {}
// Establish connection to your provider database
const d1 = new CloudflareD1Connection('API_KEY', 'ACCOUNT_ID', 'DATABASE_ID');
const neon = new NeonHttpConnection({
databaseUrl: 'postgresql://USER:[email protected]/neondb?sslmode=require'
});

// Create an Outerbase instance from the data connection
await neon.connect();
const db = Outerbase(neon);

// SELECT:
// let { data, query } = await db.selectFrom([
// { table: 'playing_with_neon', columns: ['id', 'name', 'value'] }
// ])
// .where(equalsNumber('id', 1))
// .query()

let { data } = await db.queryRaw('SELECT * FROM playing_with_neon WHERE id = $1', ['1']);
res.json(data);
});

Expand Down
86 changes: 86 additions & 0 deletions src/connections/neon-http.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { Client } from '@neondatabase/serverless';
import ws from 'ws';
import { Connection } from './index';
import { Query, constructRawQuery } from '../query';
import { QueryParamsPositional, QueryType } from '../query-params';

export type NeonConnectionDetails = {
databaseUrl: string
};

export class NeonHttpConnection implements Connection {
databaseUrl: string;
client: Client;

// Default query type to named for Outerbase
queryType = QueryType.positional

/**
* Creates a new NeonHttpConnection object with the provided API key,
* account ID, and database ID.
*
* @param databaseUrl - The URL to the database to be used for the connection.
*/
constructor(private _: NeonConnectionDetails) {
this.databaseUrl = _.databaseUrl;

this.client = new Client(this.databaseUrl);
this.client.neonConfig.webSocketConstructor = ws;
}

/**
* Performs a connect action on the current Connection object.
*
* @param details - Unused in the Neon scenario.
* @returns Promise<any>
*/
async connect(): Promise<any> {
return this.client.connect();
}

/**
* Performs a disconnect action on the current Connection object.
*
* @returns Promise<any>
*/
async disconnect(): Promise<any> {
return this.client.end();
}

/**
* Triggers a query action on the current Connection object. The query
* is a SQL query that will be executed on a Neon database. Neon's driver
* requires positional parameters to be used in the specific format of `$1`,
* `$2`, etc. The query is sent to the Neon database and the response is returned.
*
* @param query - The SQL query to be executed.
* @param parameters - An object containing the parameters to be used in the query.
* @returns Promise<{ data: any, error: Error | null }>
*/
async query(query: Query): Promise<{ data: any; error: Error | null; query: string }> {
let items = null
let error = null

// Replace all `?` with `$1`, `$2`, etc.
let index = 0;
const formattedQuery = query.query.replace(/\?/g, () => `$${++index}`);

try {
await this.client.query('BEGIN');
const { rows } = await this.client.query(formattedQuery, query.parameters as QueryParamsPositional);
items = rows;
await this.client.query('COMMIT');
} catch (error) {
await this.client.query('ROLLBACK');
throw error;
}

const rawSQL = constructRawQuery(query)

return {
data: items,
error: error,
query: rawSQL
};
}
};
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export * from './connections';
export * from './connections/outerbase';
export * from './connections/cloudflare';
export * from './connections/neon-http';
export * from './client';
export * from './models';
export * from './models/decorators';
20 changes: 20 additions & 0 deletions tests/connections/neon.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { describe, expect, test } from '@jest/globals'

import { NeonHttpConnection } from 'src/connections/neon-http'
import { QueryType } from 'src/query-params'

describe('NeonHttpConnection', () => {
describe('Query Type', () => {
const connection = new NeonHttpConnection({
databaseUrl: 'postgresql://USER:[email protected]/neondb?sslmode=require'
})

test('Query type is set to positional', () => {
expect(connection.queryType).toBe(QueryType.positional)
})

test('Query type is set not named', () => {
expect(connection.queryType).not.toBe(QueryType.named)
})
})
})
Loading