Skip to content

Can't change default parser for Postgresql using setTypeParser after version 4.32.3 #9074

Closed as not planned

Description

@olmo

What are you doing?

I'm trying to change the default parser for decimal type (numeric in postgresql) from string to float using the following code:

var pg = require('pg');
pg.types.setTypeParser(1700, 'text', parseFloat);

This was working until version 4.32.4

What do you expect to happen?

The same behavior prior to version 4.32.4

What is actually happening?

The parser doesn't change.

Dialect: postgres
Dialect version: 7.4.1
Database version: 9.6
Sequelize version: 4.33.4

Note : Your issue may be ignored OR closed by maintainers if it's not tested against latest version OR does not follow issue template.

Activity

  1. changed the title [-]Can't change default parser for Postgresql using setTypeParser after version 4.32.4[/-] [+]Can't change default parser for Postgresql using setTypeParser after version 4.32.3[/+] on Feb 20, 2018
  2. Vovka19 commented on Feb 20, 2018

    @Vovka19

    Thank you!

  3. tfazekas commented on Mar 7, 2018

    @tfazekas

    Hi olmo,

    Same issue here.
    Just upgraded to 4.32.4

    Did you find any solution?

  4. kingjerod commented on May 23, 2018

    @kingjerod

    After digging through the code, I was able to get it to work with this

    sequelize.Sequelize.DataTypes.postgres.DECIMAL.parse = parseFloat;
    

    Wonder how long this hack will last...

    Edit: The old pg.types.setTypeParser method still works for other DataTypes, like DATEONLY (1082). I'm a bit confused on what is going on in the code...

  5. stale commented on Aug 21, 2018

    @stale
  6. added
    type: bug
    and removed on Aug 21, 2018
  7. psotres commented on Sep 20, 2018

    @psotres

    I've also been digging though the code and problem seems to have been introduced with #9025 and #9026.

    The way the parser is stored for future usage in the connectionManager (via a function that will call dataType.parse method when needed instead of storing its current reference) makes adding custom parser logic quite obscure if you don't clone the dataType object, as a subsequent modification of Sequelize.DataTypes.postgres.*.parse value in another sequelize instance will impact all instances.

    My current workaround to solve the problem without having to use the hack provided by @kingjerod (which is a valid solution but it impacts all sequelize instances) is this:

    const types = {
      DECIMAL: { ...sequelize.Sequelize.DataTypes.postgres.DECIMAL },
    };
    types.DECIMAL.parse = parseFloat;
    sequelize.connectionManager.refreshTypeParser(types);

    Nevertheless, as a getTypeParser(oid) method is already there, I would say the more elegant way to provide the functionality is via a new setTypeParser(oid, parser) method.

    Edit: I ended up using an afterConnect hook to configure it because

    return this._refreshDynamicOIDs(connection);
    overwrites the parsers a single time after the first connection is made:

    hooks: {
      afterConnect: [
        once(function setParsers() {
          const types = {
            DECIMAL: { ...this.Sequelize.DataTypes.postgres.DECIMAL },
          };
          types.DECIMAL.parse = parseFloat;
          this.connectionManager.refreshTypeParser(types);
        }),
      ],
    },

    Note: it uses once to avoid a refresh every time db is reconnected, but it can be easily done without the dependency.

  8. EyePulp commented on Mar 12, 2019

    @EyePulp

    @psotres Your fix did the trick for me. But wow, what a frustrating red-herring with all the articles pointing to the setTypeParser(oid, parser) methods, but having DECIMAL (or NUMERIC in postgres' case) not work the same or be overwritten during instantiation.

    Thanks again for figuring this out.

  9. EyePulp commented on Aug 26, 2019

    @EyePulp

    @psotres This seemed to rear its head again under v5.x. The final call to

    this.connectionManager.refreshTypeParser(types);

    would fail -- it seems like the duped type { ...this.Sequelize.DataTypes.postgres.DECIMAL } wasn't pulling all the properties -- .DECIMAL is a Function with additional properties hung on it, such as key, types, parse etc...

    Also under v5 there doesn't seem to be a this.Sequelize in scope when afterConnect runs setParsers() -- there is a this.sequelize (note the lower case), but it doesn't have the .DataTypes property. I instead used the Sequelize from my upper scoped initial import of the library.

    I couldn't seem to clone it in a one-liner and keep those properties, so I wrote a cloning function to grab some things both manually and via Object.getOwnPropertyNames()

    This is starting to feel pretty hacky, but tests are passing. 🤷‍♂

    const Sequelize = require('sequelize');
    
    
    // other sequelize setup code
    
    
    
    hooks: {
        afterConnect: [
            // sequelize defaults some numeric fields to strings to avoid overflows in parsing,
            // but our numeric/int values remain small enough that it's (probably) a safe override
            // so we adjust to to use appropriate parsers:
            // https://github.com/sequelize/sequelize/issues/9074#issuecomment-423271834
    
            function setParsers() {
                const cloneType = function(t, parseFn) {
                    const clone = {};
                    for (const name of Object.getOwnPropertyNames(t)) {
                        clone[name] = t[name];
                    }
                    (clone.key = t.key), (clone.types = t.types), (clone.parse = parseFn);
    
                    return clone;
                };
    
                const dTypes = {
                    DECIMAL: cloneType(Sequelize.DataTypes.postgres.DECIMAL, parseFloat),
                    INTEGER: cloneType(Sequelize.DataTypes.postgres.INTEGER, v => parseInt(v, 10)),
                    BIGINT: cloneType(Sequelize.DataTypes.postgres.BIGINT, v => parseInt(v, 10)),
                };
                this.connectionManager.refreshTypeParser(dTypes);
            },
        ],
    },

    Happy to use a different approach if a better one exists!

  10. papb commented on Aug 26, 2019

    @papb
    Member

    Related: #8019

    @EyePulp Can you take a look on the suggested workaround I gave there? Let me know, thanks

  11. added
    status: awaiting response
    and removed
    status: awaiting response
    on Aug 26, 2019
  12. 1 remaining item

  13. guillaumeduliscouet commented on Apr 7, 2020

    @guillaumeduliscouet

    For anyone facing the same problem as @k98kumar, refer to https://sequelize.org/master/manual/hooks.html. It seems like @EyePulp is referring to Permanent Hooks, they can be added this way for example:

    new Sequelize(..., {
      hooks: {
        afterConnect() {
          // do stuff
        }
      }
    });
    

    Anyway, @EyePulp's workaround works for me, thanks

  14. Leithal3 commented on May 6, 2020

    @Leithal3
    Contributor

    @EyePulp @psotres

    I would like to start by thanking you, your help was invaluable.

    Having a look it seems we can get the workaround to look a little cleaner by extending the class instead of trying to clone the entire object.

    Defining our CustomDecimal as follows alllows us to override the parse function and keep all of the other information associated.

    class CustomDecimal extends (Sequelize.DataTypes.DECIMAL as Sequelize.DataTypes.NumberDataTypeConstructor) {
      static parse (value: string): number {
        return parseFloat(value)
      }
    }

    This enables us to make the hook itself a bit cleaner.

    hooks: {
        afterConnect (): Promise<void> | void {
          const dTypes = {
            DECIMAL: CustomDecimal
          };
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          (this as any as Sequelize.Sequelize).connectionManager.refreshTypeParser(dTypes)
        }
      }

    May be important to mention that I am using TypeScript.
    Hopefully this helps!

  15. EyePulp commented on Jun 18, 2020

    @EyePulp

    @Leithal3 Thanks for the more succinct implementation! I'll admit I'm not entirely sure how this would look as standard ES6, as my familiarity with TypeScript is pretty limited =)

    If you're feeling generous, I'd love a translated version, but regardless I appreciate your effort - thanks again.

  16. Leithal3 commented on Jun 19, 2020

    @Leithal3
    Contributor

    @EyePulp - I'm happy to give it a go - but have no way to verify right now.

    Removing Typescript related code gives the following:

    class CustomDecimal extends Sequelize.DataTypes.DECIMAL {
      static parse (value) {
        return parseFloat(value)
      }
    }
    
    hooks: {
      afterConnect: function () {
        const dTypes = {
          DECIMAL: CustomDecimal
        };
        this.connectionManager.refreshTypeParser(dTypes)
      }
    }

    Good luck!

  17. EyePulp commented on Jun 19, 2020

    @EyePulp

    @Leithal3 That works, thanks so much. That's pretty much identical to where I ended up. Clearly the best solution is for us to start using TS more often. =)

  18. jobelenus commented on Jan 8, 2021

    @jobelenus

    I am on node12 and seq6.3.5. I have all my INTEGERs (even FKs) and BIGINT fields displaying as strings in JSON/get({plain}).

    I tried @Leithal3 approach and confirmed that I was parsing ints with my custom parser type. However, the values were still strings in my JSON output.

    In order to get them to be integers in a JSON representation, I had to add getters and return the parseInt value from there.

    In short, this hook approach did not work for me.

  19. ephys commented on Dec 21, 2022

    @ephys
    Member

    The workaround mentioned in this thread are going to break again in v7, but we have worked on a stable solution for this:

    Starting with the next v7 alpha release, Data Types are a lot more powerful. Take a look at our updated documentation to see how you can customize an existing Data Type. This feature request should also cover this use case without needing to use internal APIs.

  20. added
    pending-approval
    and removed on Dec 21, 2022
  21. github-actions commented on Jan 5, 2023

    @github-actions
    Contributor

    This bug report has not been verified by maintainers yet, and has been open for 14 days without activity. It will be closed if no further activity occurs within the next 14 days. If this is still an issue, consider commenting with more information to help us verify it.

  22. jvalerodev commented on May 31, 2023

    @jvalerodev

    @EyePulp @psotres

    I would like to start by thanking you, your help was invaluable.

    Having a look it seems we can get the workaround to look a little cleaner by extending the class instead of trying to clone the entire object.

    Defining our CustomDecimal as follows alllows us to override the parse function and keep all of the other information associated.

    class CustomDecimal extends (Sequelize.DataTypes.DECIMAL as Sequelize.DataTypes.NumberDataTypeConstructor) {
      static parse (value: string): number {
        return parseFloat(value)
      }
    }

    This enables us to make the hook itself a bit cleaner.

    hooks: {
        afterConnect (): Promise<void> | void {
          const dTypes = {
            DECIMAL: CustomDecimal
          };
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          (this as any as Sequelize.Sequelize).connectionManager.refreshTypeParser(dTypes)
        }
      }

    May be important to mention that I am using TypeScript. Hopefully this helps!

    I get the following error: "Base constructors must all have the same return type."

    Could you tell me how can I fix it?

  23. Chewbye commented on Oct 16, 2023

    @Chewbye

    @EyePulp - I'm happy to give it a go - but have no way to verify right now.

    Removing Typescript related code gives the following:

    class CustomDecimal extends Sequelize.DataTypes.DECIMAL {
      static parse (value) {
        return parseFloat(value)
      }
    }
    
    hooks: {
      afterConnect: function () {
        const dTypes = {
          DECIMAL: CustomDecimal
        };
        this.connectionManager.refreshTypeParser(dTypes)
      }
    }

    Good luck!

    This workaround worked with version 6.33, thank you

  24. nikolaydyankov commented on Mar 18, 2024

    @nikolaydyankov

    @EyePulp - I'm happy to give it a go - but have no way to verify right now.
    Removing Typescript related code gives the following:

    class CustomDecimal extends Sequelize.DataTypes.DECIMAL {
      static parse (value) {
        return parseFloat(value)
      }
    }
    
    hooks: {
      afterConnect: function () {
        const dTypes = {
          DECIMAL: CustomDecimal
        };
        this.connectionManager.refreshTypeParser(dTypes)
      }
    }

    Good luck!

    This workaround worked with version 6.33, thank you

    Thank you for the fix, it works. The only thing is that TS complains:

    Property 'DataTypes' does not exist on type 'typeof Sequelize'.ts(2339)
    
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

    pending-approvalstaletype: bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions