porsager / postgres

Postgres.js - The Fastest full featured PostgreSQL client for Node.js, Deno, Bun and CloudFlare
The Unlicense
7.04k stars 257 forks source link

Wrong inferred array types when invoking `sql.array()` for the first time. #789

Open c0per opened 5 months ago

c0per commented 5 months ago

When using sql.array() immediately after connection is made, the inferred data type if wrong.

import { postgres } from './deps.ts';

const sql = postgres(Deno.env.get('DATABASE_URL')!, {
    debug: (conn, query, params, types) => {
        console.log('conn:', conn);
        console.log('query:', query);
        console.log('params:', params);
        console.log('types:', types);
        console.log('-----\n');
    },
});

const r1 = await sql`SELECT ${sql.array(['text', 'array'])};`;
console.log('first:', r1);
console.log('=====\n');

const r2 = await sql`SELECT ${sql.array(['text', 'array'])};`;
console.log('second:', r2);
console.log('=====\n');

Code above gives following output:

conn: 2
query: 
      select b.oid, b.typarray
      from pg_catalog.pg_type a
      left join pg_catalog.pg_type b on b.oid = a.typelem
      where a.typcategory = 'A'
      group by b.oid, b.typarray
      order by b.oid

params: []
types: []
-----

conn: 2
query: SELECT $1;
params: [ [ "text", "array" ] ]
types: [ 25 ]
-----

first: Result(1) [ { "?column?": "text,array" } ]
=====

conn: 2
query: SELECT $1;
params: [ [ "text", "array" ] ]
types: [ 1009 ]
-----

second: Result(1) [ { "?column?": [ "text", "array" ] } ]
=====

It seems the first query failed to utilize type oids from the initial pg_type query, thus treating the array as 25 TEXT. The second (and so on) query does set the correct type to 1009 TEXT[].

The bug occurs both in deno and node, using latest postgres.js 3.4.3

Maybe there's a bug for the type query thing, or maybe we should always default type of arrays to 1009 TEXT[]?

zmeecer commented 3 months ago

I faced with the same issue