-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Bart Huijgen
committed
Jan 12, 2022
0 parents
commit 56509c3
Showing
13 changed files
with
332 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
{ | ||
"deno.enable": true | ||
} |
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
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. |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export * from "./src/mod.ts"; |
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
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 |
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
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"; |
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
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"; |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export { PostgresDialect } from "./postgres/postgres-dialect.ts"; |
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
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. | ||
} | ||
} |
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
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; |
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
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); | ||
} | ||
} |
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
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(); | ||
} | ||
} |
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
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; | ||
} |
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
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 '"'; | ||
} | ||
} |