Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Bart Huijgen committed Jan 12, 2022
0 parents commit 56509c3
Show file tree
Hide file tree
Showing 13 changed files with 332 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"deno.enable": true
}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2022

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
1 change: 1 addition & 0 deletions mod.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./src/mod.ts";
18 changes: 18 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Kysely Deno Postgres driver

## usage

```ts
import { Kysely } from "https://cdn.jsdelivr.net/npm/kysely@0.16.5/dist/esm/index-nodeless.js";
import { PostgresDialect } from "[not hosted yet]";

const db = new Kysely<{}>({
dialect: new PostgresDialect({
// ...
}),
});
```

## Reference

Based on node driver for postgres https://github.com/koskimas/kysely/tree/master/src/dialect/postgres
1 change: 1 addition & 0 deletions src/deps/kysely.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "https://cdn.jsdelivr.net/npm/kysely@0.16.5/dist/esm/index-nodeless.js";
1 change: 1 addition & 0 deletions src/deps/postgres.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "https://deno.land/x/postgres@v0.14.3/mod.ts";
1 change: 1 addition & 0 deletions src/mod.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { PostgresDialect } from "./postgres/postgres-dialect.ts";
26 changes: 26 additions & 0 deletions src/postgres/postgres-adapter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { DialectAdapterBase } from "../deps/kysely.ts";
import type { Kysely } from "../deps/kysely.ts";

// Random id for our transaction lock.
const LOCK_ID = "3853314791062309107";

export class PostgresAdapter extends DialectAdapterBase {
get supportsTransactionalDdl(): boolean {
return true;
}

get supportsReturning(): boolean {
return true;
}

async acquireMigrationLock(db: Kysely<any>): Promise<void> {
// Acquire a transaction level advisory lock.
await db.raw(`select pg_advisory_xact_lock(${LOCK_ID})`).execute();
}

async releaseMigrationLock(): Promise<void> {
// Nothing to do here. `pg_advisory_xact_lock` is automatically released at the
// end of the transaction and since `supportsTransactionalDdl` true, we know
// the `db` instance passed to acquireMigrationLock is actually a transaction.
}
}
3 changes: 3 additions & 0 deletions src/postgres/postgres-dialect-config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import type { ClientOptions } from "../deps/postgres.ts";

export type PostgresDialectConfig = ClientOptions;
37 changes: 37 additions & 0 deletions src/postgres/postgres-dialect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { PostgresDriver } from "./postgres-driver.ts";
import { PostgresIntrospector } from "./postgres-introspector.ts";
import { PostgresQueryCompiler } from "./postgres-query-compiler.ts";
import { PostgresAdapter } from "./postgres-adapter.ts";
import type { PostgresDialectConfig } from "./postgres-dialect-config.ts";
import { Kysely } from "../deps/kysely.ts";
import type {
Driver,
DialectAdapter,
DatabaseIntrospector,
Dialect,
QueryCompiler,
} from "../deps/kysely.ts";

export class PostgresDialect implements Dialect {
readonly #config: PostgresDialectConfig;

constructor(config: PostgresDialectConfig) {
this.#config = config;
}

createDriver(): Driver {
return new PostgresDriver(this.#config);
}

createQueryCompiler(): QueryCompiler {
return new PostgresQueryCompiler();
}

createAdapter(): DialectAdapter {
return new PostgresAdapter();
}

createIntrospector(db: Kysely<any>): DatabaseIntrospector {
return new PostgresIntrospector(db);
}
}
113 changes: 113 additions & 0 deletions src/postgres/postgres-driver.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import { Pool } from "../deps/postgres.ts";
import type { PoolClient, ClientOptions } from "../deps/postgres.ts";
import { CompiledQuery } from "../deps/kysely.ts";
import type {
DatabaseConnection,
QueryResult,
Driver,
TransactionSettings,
} from "../deps/kysely.ts";

const PRIVATE_RELEASE_METHOD = Symbol();

export class PostgresDriver implements Driver {
readonly #config: ClientOptions;
readonly #connections = new WeakMap<PoolClient, DatabaseConnection>();
#pool: Pool | null = null;

constructor(config: ClientOptions) {
this.#config = config;
}

async init(): Promise<void> {
// TODO: size is required unlike the node `pg` module.
// Need to figure out what is a good value to use here
this.#pool = new Pool(this.#config, 1);
}

async acquireConnection(): Promise<DatabaseConnection> {
const client = await this.#pool!.connect();
let connection = this.#connections.get(client);

if (!connection) {
connection = new PostgresConnection(client);
this.#connections.set(client, connection);

// The driver must take care of calling `onCreateConnection` when a new
// connection is created. The `pg` module doesn't provide an async hook
// for the connection creation. We need to call the method explicitly.
// if (this.#config.onCreateConnection) {
// await this.#config.onCreateConnection(connection);
// }
}

return connection;
}

async beginTransaction(
connection: DatabaseConnection,
settings: TransactionSettings
): Promise<void> {
if (settings.isolationLevel) {
await connection.executeQuery(
CompiledQuery.raw(
`start transaction isolation level ${settings.isolationLevel}`
)
);
} else {
await connection.executeQuery(CompiledQuery.raw("begin"));
}
}

async commitTransaction(connection: DatabaseConnection): Promise<void> {
await connection.executeQuery(CompiledQuery.raw("commit"));
}

async rollbackTransaction(connection: DatabaseConnection): Promise<void> {
await connection.executeQuery(CompiledQuery.raw("rollback"));
}

// deno-lint-ignore require-await
async releaseConnection(connection: DatabaseConnection): Promise<void> {
const pgConnection = connection as PostgresConnection;
pgConnection[PRIVATE_RELEASE_METHOD]();
}

async destroy(): Promise<void> {
if (this.#pool) {
const pool = this.#pool;
this.#pool = null;
await pool.end();
}
}
}

class PostgresConnection implements DatabaseConnection {
#client: PoolClient;

constructor(client: PoolClient) {
this.#client = client;
}

async executeQuery<O>(compiledQuery: CompiledQuery): Promise<QueryResult<O>> {
const result = await this.#client.queryObject<O>(
compiledQuery.sql,
...compiledQuery.parameters
);

if (result.command === "UPDATE" || result.command === "DELETE") {
return {
numUpdatedOrDeletedRows: BigInt(result.rowCount!),
rows: result.rows ?? [],
};
}

return {
rows: result.rows ?? [],
};
}

[PRIVATE_RELEASE_METHOD](): void {
this.#client.release();
}
}
92 changes: 92 additions & 0 deletions src/postgres/postgres-introspector.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import {
Kysely,
MIGRATION_TABLE,
MIGRATION_LOCK_TABLE,
} from "../deps/kysely.ts";
import type {
ColumnDataType,
DatabaseIntrospector,
DatabaseMetadata,
DatabaseMetadataOptions,
TableMetadata,
} from "../deps/kysely.ts";

const freeze = Object.freeze;

export class PostgresIntrospector implements DatabaseIntrospector {
readonly #db: Kysely<any>;

constructor(db: Kysely<any>) {
this.#db = db;
}

async getMetadata(
options: DatabaseMetadataOptions = { withInternalKyselyTables: false }
): Promise<DatabaseMetadata> {
let query = this.#db
.selectFrom("pg_catalog.pg_attribute as a")
.innerJoin("pg_catalog.pg_class as c", "a.attrelid", "c.oid")
.innerJoin("pg_catalog.pg_tables as t", "t.tablename", "c.relname")
.innerJoin("pg_catalog.pg_type as typ", "a.atttypid", "typ.oid")
.select([
"a.attname as column",
"a.attnotnull as not_null",
"t.tablename as table",
"t.schemaname as schema",
"typ.typname as type",
])
.where("t.schemaname", "!~", "^pg_")
.where("t.schemaname", "!=", "information_schema")
.where("a.attnum", ">=", 0) // No system columns
.where("a.attisdropped", "!=", true)
.castTo<RawColumnMetadata>();

if (!options.withInternalKyselyTables) {
query = query
.where("t.tablename", "!=", MIGRATION_TABLE)
.where("t.tablename", "!=", MIGRATION_LOCK_TABLE);
}

const rawColumns = await query.execute();

return {
tables: this.#parseTableMetadata(rawColumns),
};
}

#parseTableMetadata(columns: RawColumnMetadata[]): TableMetadata[] {
return columns.reduce<TableMetadata[]>((tables, it) => {
let table = tables.find(
(tbl) => tbl.name === it.table && tbl.schema === it.schema
);

if (!table) {
table = freeze({
name: it.table,
schema: it.schema,
columns: [],
});

tables.push(table);
}

table.columns.push(
freeze({
name: it.column,
dataType: it.type,
isNullable: !it.not_null,
})
);

return tables;
}, []);
}
}

interface RawColumnMetadata {
column: string;
table: string;
schema: string;
not_null: boolean;
type: ColumnDataType;
}
15 changes: 15 additions & 0 deletions src/postgres/postgres-query-compiler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { DefaultQueryCompiler } from "../deps/kysely.ts";

export class PostgresQueryCompiler extends DefaultQueryCompiler {
protected getCurrentParameterPlaceholder(): string {
return "$" + this.numParameters;
}

protected override getLeftIdentifierWrapper(): string {
return '"';
}

protected override getRightIdentifierWrapper(): string {
return '"';
}
}

0 comments on commit 56509c3

Please sign in to comment.