diff --git a/src/index.js b/src/index.js index 0573e2bc..77fb36ce 100644 --- a/src/index.js +++ b/src/index.js @@ -98,7 +98,8 @@ function Postgres(a, b) { notify, array, json, - file + file, + addType }) return sql @@ -563,3 +564,12 @@ function osUsername() { return process.env.USERNAME || process.env.USER || process.env.LOGNAME // eslint-disable-line } } + +async function addType(name, { serializer, parser }) { + const [{ oid }] = await this` + select oid from pg_type where typname = ${name} + `; + this.typed[name] = (x) => this.typed(x, oid); + this.options.serializers[oid] = serializer; + this.options.parsers[oid] = parser; +} \ No newline at end of file diff --git a/tests/index.js b/tests/index.js index bf81b036..5400f655 100644 --- a/tests/index.js +++ b/tests/index.js @@ -2580,3 +2580,21 @@ t('arrays in reserved connection', async() => { x.join('') ] }) + +t('addType', async () => { + const sql = postgres(options) + await sql.addType('point', { + serializer: (v) => `(${v.x},${v.y})`, + parser: (v) => { + const [x, y] = v.slice(1, -1).split(',') + return { x: parseFloat(x), y: parseFloat(y) } + } + }) + await sql`create table test (p point)` + const data = { x: 1, y: 2 } + await sql`insert into test values(${sql.typed.point(data)})` + + const [{ p }] = await sql`select p from test` + const equal = p.x === data.x && p.y === data.y + return [equal, true, await sql`drop table test`] +}) diff --git a/types/index.d.ts b/types/index.d.ts index 8989ff47..d34b2a64 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -704,6 +704,8 @@ declare namespace postgres { json(value: JSONValue): Parameter; reserve(): Promise> + + addType(name: string, handler: { serializer: (x: T) => any, parser: (x: any) => T}): void; } interface UnsafeQueryOptions {