Skip to content

ENUM ARRAY types get parsed as single string #56

Closed

Description

@Mickael-van-der-Beek

Hi,

I found that currently there is an issue with the way pg-types parses ENUM ARRAY column types.
Currently the array is not parsed at all and a simple string is returned with the SQL array serialised as a string. e.g:

'{"bar", "baz"}'

will be returned as is, instead of the expected value:

['bar', 'baz']

Here is a piece of code that will reproduce this issue (pg is the only dependency):

'use strict';

const assert = require('assert');
const pg = require('pg');
const util = require('util');

const pool = new (pg.Pool)({
  user: 'postgres',
  password: 'postgres',
  host: 'postgresql',
  database: 'enum_test'
});

Promise
  .resolve()
  .then(() => pool.query(
    `
      CREATE TYPE
        MY_ENUM
      AS ENUM
        (
          'foo',
          'bar',
          'baz'
        );

      CREATE TABLE
        my_table
        (
          id             INTEGER        PRIMARY KEY,
          my_enum        MY_ENUM        NOT NULL,
          my_enum_array  MY_ENUM ARRAY  NOT NULL
        );

      INSERT INTO
        my_table
        (
          id,
          my_enum,
          my_enum_array
        )
      VALUES
        (
          1,
          'foo',
          '{"bar", "baz"}'
        );
    `
  ))
  .then(() => pool.query(
    `
      SELECT
        *
      FROM
        my_table
      WHERE
        id = 1;
    `
  ))
  .then(result => result.rows)
  .then(rows => {
    console.log(util.inspect(rows, { colors: true, depth: 100 }));
    assert.ok(util.isArray(rows));
    assert.strictEqual(rows.length, 1);
    assert.ok(util.isObject(rows[0]));
    assert.strictEqual(rows[0].id, 1);
    assert.strictEqual(rows[0].my_enum, 'foo');
    assert.ok(util.isArray(rows[0].my_enum_array));
    assert.strictEqual(rows[0].my_enum_array.length, 2);
    assert.strictEqual(rows[0].my_enum_array[0], 'bar');
    assert.strictEqual(rows[0].my_enum_array[1], 'baz');
  })
  .catch(error => console.log(error, error.stack));

This code will fail at line 68 with the following AssertionError:

{ AssertionError: false == true
    at Promise.resolve.then.then.then.then.rows (/opt/app/src/pg-enum-array-bug-poc.js:68:12)
    at process._tickCallback (internal/process/next_tick.js:103:7)
  name: 'AssertionError',
  actual: false,
  expected: true,
  operator: '==',
  message: 'false == true',
  generatedMessage: true } 'AssertionError: false == true\n    at Promise.resolve.then.then.then.then.rows (/opt/app/src/pg-enum-array-bug-poc.js:68:12)\n    at process._tickCallback (internal/process/next_tick.js:103:7)'

The value of rows will be:

[ anonymous { id: 1, my_enum: 'foo', my_enum_array: '{bar,baz}' } ]

A temporary fix for to this in user land is the following intermediary then() block:

  .then(rows => rows.map(row => {
    row.my_enum_array = pgArray.create(row.my_enum_array, String).parse();
    return row;
  }));

where pgArray is:

const pgArray = require('pg').types.arrayParser;

Activity

  1. Mickael-van-der-Beek commented on Aug 17, 2017

    @Mickael-van-der-Beek
    Author

    @brianc Would it be possible to know if this is considered a bug or expected behaviour?

  2. charmander commented on Aug 17, 2017

    @charmander
    Contributor

    @Mickael-van-der-Beek That’s expected; you can set its type parser.

    => SELECT typname, oid, typarray FROM pg_type WHERE typname = 'text';
     typname | oid | typarray 
    ---------+-----+----------
     text    |  25 |     1009
    (1 row)
    
    => SELECT typname, oid, typarray FROM pg_type WHERE typname = 'my_enum';
     typname |  oid   | typarray 
    ---------+--------+----------
     my_enum | 381744 |   381743
    (1 row)
    const OID_ARRAY_TEXT = 1009;
    const OID_ARRAY_MY_ENUM = 381743;
    
    pg.types.setTypeParser(OID_ARRAY_MY_ENUM, pg.types.getTypeParser(OID_ARRAY_TEXT));
  3. net commented on Apr 3, 2024

    @net

    For any poor souls that find their way here, this will set all existing enum types to be parsed as text:

    // node-postgres doesn't properly handle enum arrays out of the box,
    // so we have to manually set them up here to parse as text arrays.
    //
    // https://github.com/brianc/node-pg-types/issues/56
    
    const textArrayOID = (
      await pool.query("SELECT typarray FROM pg_type WHERE typname = 'text'")
    ).rows[0].typarray;
    
    const enumOIDs = (
      await pool.query("SELECT typname, typarray FROM pg_type WHERE typtype = 'e'")
    ).rows;
    
    const arrayTextParser = pg.types.getTypeParser(textArrayOID);
    
    enumOIDs.forEach(({ typname, typarray }) => {
      const parser =
        {
          // Parsers for specific types can be set up here, for example:
          // topic_tags: value => arrayTextParser(value).map(s => s.toLowerCase()),
        }[typname] || arrayTextParser;
    
      pg.types.setTypeParser(typarray, parser);
    });

    Obviously, based on the number of issues pointing here, this should just be the default behavior instead of each downstream library having to re-implement enum array parsing itself. @bendrucker could this be re-opened?

  4. Repository owner locked as resolved and limited conversation to collaborators on Apr 3, 2024
  5. bendrucker commented on Apr 3, 2024

    @bendrucker
    Collaborator

    Querying OID info and registering parsers as you have is clever

    this should just be the default behavior

    Definitely not. Changing parser registration from sync into async is a big (breaking) change. Coming in hot on a 7 year old issue is not the way to make that kind of change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions