Return row value direct in .first() and .first_or(x)

This commit is contained in:
luaneko 2025-01-12 01:25:55 +11:00
parent 00002525e4
commit a4c0055c79
Signed by: luaneko
GPG Key ID: 406809B8763FF07A
6 changed files with 46 additions and 59 deletions

View File

@ -14,9 +14,9 @@ The glue for TypeScript to PostgreSQL.
## Installation ## Installation
```ts ```ts
import pglue from "https://git.lua.re/luaneko/pglue/raw/tag/v0.2.0/mod.ts"; import pglue from "https://git.lua.re/luaneko/pglue/raw/tag/v0.3.0/mod.ts";
// ...or from github: // ...or from github:
import pglue from "https://raw.githubusercontent.com/luaneko/pglue/refs/tags/v0.2.0/mod.ts"; import pglue from "https://raw.githubusercontent.com/luaneko/pglue/refs/tags/v0.3.0/mod.ts";
``` ```
## Documentation ## Documentation

View File

@ -1,5 +1,5 @@
{ {
"name": "@luaneko/pglue", "name": "@luaneko/pglue",
"version": "0.2.0", "version": "0.3.0",
"exports": "./mod.ts" "exports": "./mod.ts"
} }

7
mod.ts
View File

@ -27,11 +27,10 @@ export {
sql, sql,
is_sql, is_sql,
Query, Query,
type Row,
type CommandResult,
type Result, type Result,
type Results, type Row,
type ResultStream, type Rows,
type RowStream,
} from "./query.ts"; } from "./query.ts";
export type Options = { export type Options = {

View File

@ -323,22 +323,15 @@ export const sql_types: SqlTypeMap = {
sql.types = sql_types; sql.types = sql_types;
type ReadonlyTuple<T extends readonly unknown[]> = readonly [...T]; export interface Result {
export interface CommandResult {
readonly tag: string; readonly tag: string;
} }
export interface Result<T> extends CommandResult, ReadonlyTuple<[T]> { export interface Rows<T> extends Result, ReadonlyArray<T> {
readonly row: T;
}
export interface Results<T> extends CommandResult, ReadonlyArray<T> {
readonly rows: ReadonlyArray<T>; readonly rows: ReadonlyArray<T>;
} }
export interface ResultStream<T> export interface RowStream<T> extends AsyncIterable<T[], Result, void> {}
extends AsyncIterable<T[], CommandResult, void> {}
export interface Row extends Iterable<unknown, void, void> { export interface Row extends Iterable<unknown, void, void> {
[column: string]: unknown; [column: string]: unknown;
@ -351,12 +344,10 @@ export interface QueryOptions {
readonly stdout: WritableStream<Uint8Array> | null; readonly stdout: WritableStream<Uint8Array> | null;
} }
export class Query<T = Row> export class Query<T = Row> implements PromiseLike<Rows<T>>, RowStream<T> {
implements PromiseLike<Results<T>>, ResultStream<T>
{
readonly #f; readonly #f;
constructor(f: (options: Partial<QueryOptions>) => ResultStream<T>) { constructor(f: (options: Partial<QueryOptions>) => RowStream<T>) {
this.#f = f; this.#f = f;
} }
@ -431,20 +422,18 @@ export class Query<T = Row>
return this.#f(options); return this.#f(options);
} }
async first(): Promise<Result<T>> { async first(): Promise<T> {
const { rows, tag } = await this.collect(1); const rows = await this.collect(1);
if (!rows.length) throw new TypeError(`expected one row, got none instead`); if (rows.length !== 0) return rows[0];
const row = rows[0]; else throw new TypeError(`expected one row, got none instead`);
return Object.assign([row] as const, { row: rows[0], tag });
} }
async first_or<S>(value: S): Promise<Result<T | S>> { async first_or<S>(value: S): Promise<T | S> {
const { rows, tag } = await this.collect(1); const rows = await this.collect(1);
const row = rows.length ? rows[0] : value; return rows.length !== 0 ? rows[0] : value;
return Object.assign([row] as const, { row: rows[0], tag });
} }
async collect(count = Number.POSITIVE_INFINITY): Promise<Results<T>> { async collect(count = Number.POSITIVE_INFINITY): Promise<Rows<T>> {
const iter = this[Symbol.asyncIterator](); const iter = this[Symbol.asyncIterator]();
let next; let next;
const rows = []; const rows = [];
@ -470,8 +459,8 @@ export class Query<T = Row>
return n; return n;
} }
then<S = Results<T>, U = never>( then<S = Rows<T>, U = never>(
f?: ((rows: Results<T>) => S | PromiseLike<S>) | null, f?: ((rows: Rows<T>) => S | PromiseLike<S>) | null,
g?: ((reason?: unknown) => U | PromiseLike<U>) | null g?: ((reason?: unknown) => U | PromiseLike<U>) | null
) { ) {
return this.collect().then(f, g); return this.collect().then(f, g);

12
test.ts
View File

@ -16,7 +16,7 @@ Deno.test(`integers`, async () => {
await using pg = await connect(); await using pg = await connect();
await using _tx = await pg.begin(); await using _tx = await pg.begin();
const [{ a, b, c }] = await pg.query` const { a, b, c } = await pg.query`
select select
${"0x100"}::int2 as a, ${"0x100"}::int2 as a,
${777}::int4 as b, ${777}::int4 as b,
@ -32,7 +32,7 @@ Deno.test(`integers`, async () => {
expect(b).toBe(777); expect(b).toBe(777);
expect(c).toBe(1234); expect(c).toBe(1234);
const [{ large }] = const { large } =
await pg.query`select ${"10000000000000000"}::int8 as large`.first(); await pg.query`select ${"10000000000000000"}::int8 as large`.first();
expect(large).toBe(10000000000000000n); expect(large).toBe(10000000000000000n);
@ -47,7 +47,7 @@ Deno.test(`boolean`, async () => {
await using pg = await connect(); await using pg = await connect();
await using _tx = await pg.begin(); await using _tx = await pg.begin();
const [{ a, b, c }] = await pg.query` const { a, b, c } = await pg.query`
select select
${true}::bool as a, ${true}::bool as a,
${"n"}::bool as b, ${"n"}::bool as b,
@ -63,7 +63,7 @@ Deno.test(`bytea`, async () => {
await using pg = await connect(); await using pg = await connect();
await using _tx = await pg.begin(); await using _tx = await pg.begin();
const [{ string, array, buffer }] = await pg.query` const { string, array, buffer } = await pg.query`
select select
${"hello, world"}::bytea as string, ${"hello, world"}::bytea as string,
${[1, 2, 3, 4, 5]}::bytea as array, ${[1, 2, 3, 4, 5]}::bytea as array,
@ -93,7 +93,7 @@ Deno.test(`row`, async () => {
).tag ).tag
).toBe(`COPY 1`); ).toBe(`COPY 1`);
const [row] = await pg.query`select * from my_table`.first(); const row = await pg.query`select * from my_table`.first();
{ {
// columns by name // columns by name
const { a, b, c } = row; const { a, b, c } = row;
@ -132,7 +132,7 @@ Deno.test(`sql injection`, async () => {
`INSERT 0 1` `INSERT 0 1`
); );
const [{ name }] = await pg.query<{ name: string }>` const { name } = await pg.query<{ name: string }>`
select name from users select name from users
`.first(); `.first();

37
wire.ts
View File

@ -35,11 +35,11 @@ import {
type EncoderType, type EncoderType,
} from "./ser.ts"; } from "./ser.ts";
import { import {
type CommandResult,
format, format,
is_sql, is_sql,
Query, Query,
type ResultStream, type Result,
type RowStream,
type Row, type Row,
sql, sql,
type SqlFragment, type SqlFragment,
@ -460,22 +460,22 @@ export type WireEvents = {
close(reason?: unknown): void; close(reason?: unknown): void;
}; };
export interface Transaction extends CommandResult, AsyncDisposable { export interface Transaction extends Result, AsyncDisposable {
readonly open: boolean; readonly open: boolean;
commit(): Promise<CommandResult>; commit(): Promise<Result>;
rollback(): Promise<CommandResult>; rollback(): Promise<Result>;
} }
export type ChannelEvents = { notify: NotificationHandler }; export type ChannelEvents = { notify: NotificationHandler };
export type NotificationHandler = (payload: string, process_id: number) => void; export type NotificationHandler = (payload: string, process_id: number) => void;
export interface Channel export interface Channel
extends TypedEmitter<ChannelEvents>, extends TypedEmitter<ChannelEvents>,
CommandResult, Result,
AsyncDisposable { AsyncDisposable {
readonly name: string; readonly name: string;
readonly open: boolean; readonly open: boolean;
notify(payload: string): Promise<CommandResult>; notify(payload: string): Promise<Result>;
unlisten(): Promise<CommandResult>; unlisten(): Promise<Result>;
} }
export async function wire_connect(options: WireOptions) { export async function wire_connect(options: WireOptions) {
@ -546,16 +546,15 @@ export class Wire<V extends WireEvents = WireEvents>
} }
async get(param: string) { async get(param: string) {
return ( return await this.query`select current_setting(${param}, true)`
await this.query`select current_setting(${param}, true)`
.map(([s]) => String(s)) .map(([s]) => String(s))
.first_or(null) .first_or(null);
)[0];
} }
async set(param: string, value: string, local = false) { async set(param: string, value: string, local = false) {
return await this return await this.query`select set_config(${param}, ${value}, ${local})`
.query`select set_config(${param}, ${value}, ${local})`.execute(); .map(([s]) => String(s))
.first();
} }
close(reason?: unknown) { close(reason?: unknown) {
@ -1143,7 +1142,7 @@ function wire_impl(
query: string, query: string,
stdin: ReadableStream<Uint8Array> | null, stdin: ReadableStream<Uint8Array> | null,
stdout: WritableStream<Uint8Array> | null stdout: WritableStream<Uint8Array> | null
): ResultStream<Row> { ): RowStream<Row> {
yield* await pipeline( yield* await pipeline(
() => { () => {
log("debug", { query }, `executing simple query`); log("debug", { query }, `executing simple query`);
@ -1189,7 +1188,7 @@ function wire_impl(
params: unknown[], params: unknown[],
stdin: ReadableStream<Uint8Array> | null, stdin: ReadableStream<Uint8Array> | null,
stdout: WritableStream<Uint8Array> | null stdout: WritableStream<Uint8Array> | null
): ResultStream<Row> { ): RowStream<Row> {
const { query, name: statement } = st; const { query, name: statement } = st;
const { ser_params, Row } = await st.parse(); const { ser_params, Row } = await st.parse();
const param_values = ser_params(params); const param_values = ser_params(params);
@ -1238,7 +1237,7 @@ function wire_impl(
chunk_size: number, chunk_size: number,
stdin: ReadableStream<Uint8Array> | null, stdin: ReadableStream<Uint8Array> | null,
stdout: WritableStream<Uint8Array> | null stdout: WritableStream<Uint8Array> | null
): ResultStream<Row> { ): RowStream<Row> {
const { query, name: statement } = st; const { query, name: statement } = st;
const { ser_params, Row } = await st.parse(); const { ser_params, Row } = await st.parse();
const param_values = ser_params(params); const param_values = ser_params(params);
@ -1326,7 +1325,7 @@ function wire_impl(
return tx_stack.indexOf(this) !== -1; return tx_stack.indexOf(this) !== -1;
} }
constructor(begin: CommandResult) { constructor(begin: Result) {
Object.assign(this, begin); Object.assign(this, begin);
} }
@ -1384,7 +1383,7 @@ function wire_impl(
return channels.get(this.#name) === this; return channels.get(this.#name) === this;
} }
constructor(name: string, listen: CommandResult) { constructor(name: string, listen: Result) {
super(); super();
Object.assign(this, listen); Object.assign(this, listen);
this.#name = name; this.#name = name;