Skip to content

Commit

Permalink
fix build after #4201
Browse files Browse the repository at this point in the history
  • Loading branch information
tomhoule committed Sep 8, 2023
1 parent 3430e03 commit 6c92736
Show file tree
Hide file tree
Showing 5 changed files with 104 additions and 104 deletions.
166 changes: 85 additions & 81 deletions query-engine/driver-adapters/js/adapter-pg/src/pg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,100 +9,104 @@ type StdClient = pg.Pool
type TransactionClient = pg.PoolClient

class PgQueryable<ClientT extends StdClient | TransactionClient>
implements Queryable {
readonly flavour = 'postgres'

constructor(protected readonly client: ClientT) {
implements Queryable {
readonly flavour = 'postgres'

constructor(protected readonly client: ClientT) {
}

/**
* Execute a query given as SQL, interpolating the given parameters.
*/
async queryRaw(query: Query): Promise<Result<ResultSet>> {
const tag = '[js::query_raw]'
debug(`${tag} %O`, query)

const { fields, rows: results } = await this.performIO(query)

const columns = fields.map((field) => field.name)
const resultSet: ResultSet = {
columnNames: columns,
columnTypes: fields.map((field) => fieldToColumnType(field.dataTypeID)),
rows: results.map((result) => columns.map((column) => result[column])),
}

/**
* Execute a query given as SQL, interpolating the given parameters.
*/
async queryRaw(query: Query): Promise<Result<ResultSet>> {
const tag = '[js::query_raw]'
debug(`${tag} %O`, query)

const { fields, rows: results } = await this.performIO(query)

const columns = fields.map((field) => field.name)
const resultSet: ResultSet = {
columnNames: columns,
columnTypes: fields.map((field) => fieldToColumnType(field.dataTypeID)),
rows: results.map((result) => columns.map((column) => result[column])),
}

return { ok: true, value: resultSet }
}

/**
* Execute a query given as SQL, interpolating the given parameters and
* returning the number of affected rows.
* Note: Queryable expects a u64, but napi.rs only supports u32.
*/
async executeRaw(query: Query): Promise<Result<number>> {
const tag = '[js::execute_raw]'
debug(`${tag} %O`, query)

const { rowCount: rowsAffected } = await this.performIO(query)

// Note: `rowsAffected` can sometimes be null (e.g., when executing `"BEGIN"`)
return { ok: true, value: rowsAffected ?? 0 }
}

/**
* Run a query against the database, returning the result set.
* Should the query fail due to a connection error, the connection is
* marked as unhealthy.
*/
private async performIO(query: Query) {
const { sql, args: values } = query

try {
const result = await this.client.query(sql, values)
return result
} catch (e) {
const error = e as Error
debug('Error in performIO: %O', error)
throw error
}
return { ok: true, value: resultSet }
}

/**
* Execute a query given as SQL, interpolating the given parameters and
* returning the number of affected rows.
* Note: Queryable expects a u64, but napi.rs only supports u32.
*/
async executeRaw(query: Query): Promise<Result<number>> {
const tag = '[js::execute_raw]'
debug(`${tag} %O`, query)

const { rowCount: rowsAffected } = await this.performIO(query)

// Note: `rowsAffected` can sometimes be null (e.g., when executing `"BEGIN"`)
return { ok: true, value: rowsAffected ?? 0 }
}

/**
* Run a query against the database, returning the result set.
* Should the query fail due to a connection error, the connection is
* marked as unhealthy.
*/
private async performIO(query: Query) {
const { sql, args: values } = query

try {
const result = await this.client.query(sql, values)
return result
} catch (e) {
const error = e as Error
debug('Error in performIO: %O', error)
throw error
}
}
}

class PgTransaction extends PgQueryable<TransactionClient>
implements Transaction {
constructor(client: pg.PoolClient, readonly options: TransactionOptions) {
super(client)
}
implements Transaction {
constructor(client: pg.PoolClient, readonly options: TransactionOptions) {
super(client)
}

async commit(): Promise<Result<void>> {
debug(`[js::commit]`)
async commit(): Promise<Result<void>> {
debug(`[js::commit]`)

this.client.release()
return Promise.resolve({ ok: true, value: undefined })
}
this.client.release()
return Promise.resolve({ ok: true, value: undefined })
}

async rollback(): Promise<Result<void>> {
debug(`[js::rollback]`)
async rollback(): Promise<Result<void>> {
debug(`[js::rollback]`)

this.client.release()
return Promise.resolve({ ok: true, value: undefined })
}
this.client.release()
return Promise.resolve({ ok: true, value: undefined })
}
}

export class PrismaPg extends PgQueryable<StdClient> implements Connector {
async startTransaction(): Promise<Result<Transaction>> {
const options: TransactionOptions = {
usePhantomQuery: false,
}
export class PrismaPg extends PgQueryable<StdClient> implements DriverAdapter {
constructor(client: pg.Pool) {
super(client)
}

const tag = '[js::startTransaction]'
debug(`${tag} options: %O`, options)

const connection = await this.client.connect()
return { ok: true, value: new PgTransaction(connection, options) }
async startTransaction(): Promise<Result<Transaction>> {
const options: TransactionOptions = {
usePhantomQuery: false,
}

async close() {
return { ok: true as const, value: undefined }
}
const tag = '[js::startTransaction]'
debug(`${tag} options: %O`, options)

const connection = await this.client.connect()
return { ok: true, value: new PgTransaction(connection, options) }
}

async close() {
return { ok: true as const, value: undefined }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,9 @@
"author": "",
"sideEffects": false,
"license": "Apache-2.0",
"dependencies": { "@jkomyno/prisma-adapter-pg": "workspace:*" }
"dependencies": {
"@jkomyno/prisma-adapter-pg": "workspace:*",
"pg": "^8.11.3",
"@types/pg": "^8.10.2"
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import * as pg from '@jkomyno/prisma-pg-js-connector'
import * as pgDriver from 'pg'
import * as pg from '@jkomyno/prisma-adapter-pg'
import * as qe from './qe'
import * as engines from './engines/Library'
import * as readline from 'node:readline'
import * as jsonRpc from './jsonRpc'
import * as tempy from 'tempy'

async function main(): Promise<void> {
const iface = readline.createInterface({
Expand Down Expand Up @@ -97,11 +97,9 @@ function respondOk(requestId: number, payload: unknown) {
}

async function initQe(url: string, prismaSchema: string): Promise<engines.QueryEngineInstance> {
const connector = pg.createPgConnector({
url,
});
const schemaPath: string = await tempy.temporaryWrite(prismaSchema);
return qe.initQueryEngine(connector, schemaPath)
const pool = new pgDriver.Pool({ connectionString: url })
const adapter = new pg.PrismaPg(pool)
return qe.initQueryEngine(adapter, prismaSchema)
}

main().catch(console.error)
Original file line number Diff line number Diff line change
@@ -1,26 +1,23 @@
import * as pg from '@jkomyno/prisma-pg-js-connector'
import * as pg from '@jkomyno/prisma-adapter-pg'
import * as lib from './engines/Library'
import * as os from 'node:os'
import * as path from 'node:path'
import * as fs from 'node:fs'

export function initQueryEngine(driver: pg.Connector, schemaPath: string): lib.QueryEngineInstance {
export function initQueryEngine(driver: pg.PrismaPg, datamodel: string): lib.QueryEngineInstance {
// I assume nobody will run this on Windows ¯\_(ツ)_/¯
const libExt = os.platform() === 'darwin' ? 'dylib' : 'so'
const dirname = path.dirname(new URL(import.meta.url).pathname)

const libQueryEnginePath = path.join(dirname, `../../../../../target/debug/libquery_engine.${libExt}`)

console.log('[nodejs] read Prisma schema from', schemaPath)

const libqueryEngine = { exports: {} as unknown as lib.Library }
// @ts-ignore
process.dlopen(libqueryEngine, libQueryEnginePath)

const QueryEngine = libqueryEngine.exports.QueryEngine

const queryEngineOptions = {
datamodel: fs.readFileSync(schemaPath, 'utf-8'),
datamodel,
configDir: '.',
engineProtocol: 'json' as const,
logLevel: 'info' as const,
Expand Down
15 changes: 6 additions & 9 deletions query-engine/driver-adapters/js/pnpm-lock.yaml

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

0 comments on commit 6c92736

Please sign in to comment.