pglue/mod.ts

80 lines
1.8 KiB
TypeScript
Raw Permalink Normal View History

2025-01-12 06:36:15 +11:00
import pg_conn_str from "npm:pg-connection-string@^2.7.0";
import type * as v from "./valita.ts";
2025-01-13 11:00:33 +11:00
import { Pool, PoolOptions, Wire, WireOptions } from "./wire.ts";
2025-01-07 22:12:30 +11:00
export {
WireError,
PostgresError,
type LogLevel,
type Transaction,
type Channel,
type Parameters,
} from "./wire.ts";
export {
type SqlFragment,
type SqlType,
type SqlTypeMap,
SqlTypeError,
2025-01-07 22:12:30 +11:00
sql,
is_sql,
Query,
type Result,
type Row,
type Rows,
type RowStream,
2025-01-07 22:12:30 +11:00
} from "./query.ts";
2025-01-12 06:36:15 +11:00
export default function postgres(s: string, options: Partial<Options> = {}) {
return new Postgres(Options.parse(parse_conn(s, options), { mode: "strip" }));
}
2025-01-07 22:12:30 +11:00
2025-01-12 06:36:15 +11:00
function parse_conn(s: string, options: Partial<WireOptions>) {
2025-01-07 22:12:30 +11:00
const {
host,
port,
user,
password,
database,
2025-01-12 06:36:15 +11:00
ssl: _ssl, // TODO: ssl support
2025-01-07 22:12:30 +11:00
...runtime_params
2025-01-12 06:36:15 +11:00
} = s ? pg_conn_str.parse(s) : {};
2025-01-07 22:12:30 +11:00
2025-01-12 06:36:15 +11:00
return {
...options,
host: options.host ?? host,
port: options.port ?? port,
user: options.user ?? user,
password: options.password ?? password,
database: options.database ?? database,
runtime_params: { ...runtime_params, ...options.runtime_params },
};
2025-01-07 22:12:30 +11:00
}
2025-01-12 06:36:15 +11:00
postgres.connect = connect;
export async function connect(s: string, options: Partial<WireOptions> = {}) {
return await new Wire(
WireOptions.parse(parse_conn(s, options), { mode: "strip" })
).connect();
2025-01-07 22:12:30 +11:00
}
2025-01-12 06:36:15 +11:00
export type Options = v.Infer<typeof Options>;
export const Options = PoolOptions;
2025-01-07 22:12:30 +11:00
export class Postgres extends Pool {
readonly #options;
2025-01-12 06:36:15 +11:00
constructor(options: Options) {
2025-01-07 22:12:30 +11:00
super(options);
this.#options = options;
}
2025-01-12 06:36:15 +11:00
async connect(options: Partial<WireOptions> = {}) {
return await new Wire(
WireOptions.parse({ ...this.#options, ...options }, { mode: "strip" })
)
.on("log", (l, c, s) => this.emit("log", l, c, s))
.connect();
}
2025-01-07 22:12:30 +11:00
}