Skip to content

Inconsistent and buggy default value parsing by queryInterface#describeTable #16787

Open

Description

@ghusse

Issue Creation Checklist

  • I understand that my issue will be automatically closed if I don't fill in the requested information
  • I have read the contribution guidelines

Bug Description

Different dialect are returning different format in the property defaultValue returned by queryInterface#describeTable:

  1. Postgresql (see this code):
    • Transforms true or false strings into booleans when the column is a boolean, but it does not transform other types (numbers, json values, etc)
    • Removes all simple quotes from the default value : it's buggy when the value actually contains simple quotes
    • If the default value contains ::, the returned value will be buggy as we don't parse the actual value to check if the content is some plain text or a casted value.
    • It's also not possible to distinguish constant values from function calls in the current defaultValue property returned by this function
  2. MSSQL (see this code):
  • Removes some characters (', ') or simple quotes without actually parsing, leading to invalid return values when default values are plain text containing these characters
  • Returns almost always raw values from MSSQL
    • (getdate()) when there is a function call
    • "(NULL)" instead of the null value
    • "((-99))" instead of the integer value
    • (Nvalue instead of the "value" string  

I did not test other providers, but I guess that the same problem will probably be also present.

I'm willing to work on a fix on this, because I'm planning to use queryInterface#describeTable and the returned defaultValue in a project, but I would need:

  1. To be able to distinguish constant values from function calls/special values (such as now(), getdate() or CURRENT_TIMESTAMP
  2. To return constant values either always as strings (except for null), or always parsed (for number, boolean, arrays, json, date etc).

I have the sentiment that it's not doable right now with the current interface of describeTable.

Do you think it would be OK to modify the current interface to match these requirements? My preference would be for something like:

export interface ColumnDescription {
  type: string;
  allowNull: boolean;
  defaultValue: string | boolean | number | null | Literal | unknown;
  primaryKey: boolean;
  autoIncrement: boolean;
  comment: string | null;
}

I'm interested in making these changes in v6 and v7.

Reproducible Example

I've started working on integration tests on current code, but almost all of them are breaking right now:

describe('default value parsing', () => {
        [
          'normal value',
          'with\'quote',
          'with"quote',
          'with\\backslash',
          'with\\\'backslash and quote',
          'with\\"backslash and quote',
          'with::double',
          null,
          'null',
          'NULL',
          'Test(\'containing function call in string\')',
        ].forEach(defaultValue => {
          [DataTypes.STRING, DataTypes.TEXT, DataTypes.STRING(50)].forEach(dataType => {
            it(`should return the right default value ${defaultValue} for fields of type ${dataType}`, async function () {
              await this.sequelize.getQueryInterface().createTable('with_string_default', {
                username: {
                  type: dataType,
                  defaultValue,
                },
              });

              const metadata = await this.queryInterface.describeTable('with_string_default');
              expect(metadata.username.defaultValue).to.eql(defaultValue);
            });
          });
        });

        [0, 99, -99, null].forEach(defaultValue => {
          it(`should return ${defaultValue} as the default value for numbers`, async function () {
            await this.sequelize.getQueryInterface().createTable('with_string_default', {
              age: {
                type: DataTypes.INTEGER,
                defaultValue,
              },
            });

            const metadata = await this.queryInterface.describeTable('_User');
            expect(metadata.age.defaultValue).to.eql(defaultValue === null ? null : `${defaultValue}`);
          });
        });

        it('should return the right default value for a function call', async function () {
          const now = dialect === 'sqlite' ? 'datetime(\'now\')'
            : dialect === 'mssql' ? 'getdate()'
            : 'now()';

          await this.sequelize.getQueryInterface().createTable('user_with_date', {
            date: {
              type: DataTypes.DATE,
              defaultValue: literal(now),
            },
          }, { freezeTableName: true });

          const metadata = await this.queryInterface.describeTable('user_with_date');
          expect(metadata.date.defaultValue).to.eql(now);
        });

        it('should return the right default value for autoincrement', async function () {
          await this.sequelize.getQueryInterface().createTable('user_autoincrement', {
            id: {
              type: DataTypes.INTEGER,
              autoIncrement: true,
              primaryKey: true,
            },
          });

          const metadata = await this.queryInterface.describeTable('user_autoincrement');
          expect(metadata.id.defaultValue).to.eql(dialect === 'postgres' ? `nextval('user_autoincrement_id_seq'::regclass)` : null);
        });

        if (Support.sequelize.dialect.supports.dataTypes.BOOLEAN) {
          [true, false, null].forEach(defaultValue => {
            it(`should return the right default value ${defaultValue} for booleans`, async function () {
              await this.sequelize.getQueryInterface().createTable('users_booleans', {
                active: {
                  type: DataTypes.BOOLEAN,
                  defaultValue,
                  allowNull: false,
                },
              });

              const metadata = await this.queryInterface.describeTable('users_booleans');
              expect(metadata.active.defaultValue).to.eql(defaultValue);
            });
          });
        }
      });

What do you expect to happen?

  1. Constant values should not be modified when returned by describeTable
  2. Parsing values (or not) should be consistent across dialects
  3. Ideally, I would like to be able to distinguish constant values from function calls when returned by describeTable

What is actually happening?

  1. Constant values are not always returned with the right value, depending on the provider and the characters it contains
  2. Postgresql parses boolean values, not other types of values (and other provider do not seem to parse anything)
  3. Function calls are returned as strings, as well as constant values so we cannot know if a given string contains literal SQL or a constant value.

Environment

Sequelize v7 on main, but also sequelize v6

Errors detected on PG & MSSQL, reproducible in tests.

Would you be willing to resolve this issue by submitting a Pull Request?

YES!

I just need guidance on how to make the current interface evolve in the good way.

  • Yes, I have the time and I know how to start.
  • Yes, I have the time but I will need guidance.
  • No, I don't have the time, but my company or I are supporting Sequelize through donations on OpenCollective.
  • No, I don't have the time, and I understand that I will need to wait until someone from the community or maintainers is interested in resolving my issue.

Indicate your interest in the resolution of this issue by adding the 👍 reaction. Comments such as "+1" will be removed.

Activity

  1. added
    pending-approval
    type: bug
    on Nov 20, 2023
  2. WikiRik commented on Nov 21, 2023

    @WikiRik
    Member

    Quick first thoughts:

    • We as maintainers already identified that describeTable needs to be improved, at least so that results are uniform across dialects. See this comment from last year; feat: add queryInterface.changeColumns, fix many bugs with changeColumn #14687 (comment) So I'll loop in @ephys in here as well, but I think we should be able to work together on this.
    • I am not so sure on if we want to have this in v6 though. The v7 alphas are quite stable and we'll have more flexibility to do it right on there. If we backport it to v6 we will have to think about breaking changes as well.

    I'll take a look at your actually suggested change at a later point

  3. ghusse commented on Nov 21, 2023

    @ghusse
    ContributorAuthor

    Thanks for your feedback.

    Let me know in which direction we should go in terms of interface.

    I'm very interested in having this ported to v6, even if it's through additional properties, because v7 is not released yet.

  4. ghusse commented on Nov 30, 2023

    @ghusse
    ContributorAuthor

    Any news on this?

  5. removed
    pending-approval
    on Feb 2, 2024
  6. ephys commented on Feb 2, 2024

    @ephys
    Member

    I'm very late to the party but yeah describeTable has many issues and has been blocking me for a long time too. Unfortunately it's rarely a priority given how much work needs to be put into it and how many other things need to be worked on. Any help unifying its behavior. Your preliminary research work is already a good help.

    Something tricky with parsing the default value is that sometimes it's SQL, and sometimes it's a value. If we try to parse it, how can the user know whether the defaultValue is a string or SQL code?

  7. added
    pending-approval
    and removed
    pending-approval
    on Feb 2, 2024
  8. ghusse commented on Feb 3, 2024

    @ghusse
    ContributorAuthor

    We just need to return an object with a property indicating if it's a value or some SQL, and another property for the value itself.

  9. ephys commented on Feb 4, 2024

    @ephys
    Member

    I'd propose to split "default value" into "rawDefaultValue", which contains the unparsed SQL and is always present, and "parsedDefaultValue", which contains the parsed version and can be undefined, as the raw one will be useful when automatically generating migrations

  10. ghusse commented on Feb 4, 2024

    @ghusse
    ContributorAuthor

    It seems perfect

  11. ghusse commented on Feb 5, 2024

    @ghusse
    ContributorAuthor

    Would you prefer 2 PRs (one introducing the new format, and the other fixing values in parsedValue), or only one PR doing both things at the same time?

    I suggest renaming defaultValue.rawDefaultValue and defaultValue.parsedDefaultValue to defaultValue.raw and defaultValue.parsed. WDYT?

  12. ephys commented on Feb 5, 2024

    @ephys
    Member

    A nested property like that works for me, the extra object isn't really going to have any noticeable perf impact considering what the goal of the method is

    I would personally prefer two PRs: one that splits the value (easy but already valuable), and another that works on improving its parsing (probably harder, but still very valuable)

  13. ghusse commented on Feb 26, 2024

    @ghusse
    ContributorAuthor

    I find it quite weird to have the mapping logic handled in the function PostgresQuery#run, by query type.

    Is it ok to move this logic inside a function describeTableon each dialect? It would simply return the expected format for this function, without having to navigate through 3 different functions for the same result:

    1. AbstractQueryInterface#describeTable
    2. PostgresQueryGenerator#describeTableQuery
    3. PostgresQuery#run
  14. WikiRik commented on Feb 26, 2024

    @WikiRik
    Member

    What I can remember from earlier discussions with the team is that we want to reduce the amount of logic in the QueryInterface so that QueryGenerator functions can be used to generate the SQL without being ran directly.

    As long as the result of the QueryGenerator function is the SQL executed in Query#run I am fine with some logic moved there, but preferably not towards QueryInterface#describeTable

  15. ghusse commented on Feb 27, 2024

    @ghusse
    ContributorAuthor

    I've made some progress on this topic, but digging it further I realize it's not really a good idea to have a defaultValue being a object with 2 properties:

    • describeTable is expected to return a ColumnDescription,
    • createTable and other structure-manipulation functions are expecting ColumnDescription objects as inputs.

    I think that the interface for these functions should not evolve in this direction, at least not because of the describeTable function.

    I guess that we need the function columnDescription to return literal values when parsing is not possible. What do you think?

  16. added theissue type on Mar 9, 2025
  17. removed
    type: bug
    on Mar 9, 2025
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

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions