Repository navigation
Description
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:
- Postgresql (see this code):
- Transforms
trueorfalsestrings 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
defaultValueproperty returned by this function
- Transforms
- 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 thenullvalue"((-99))"instead of the integer value(Nvalueinstead 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:
- To be able to distinguish constant values from function calls/special values (such as
now(),getdate()orCURRENT_TIMESTAMP - To return constant values either always as strings (except for null), or always parsed (for
number,boolean,arrays,json,dateetc).
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?
- Constant values should not be modified when returned by
describeTable - Parsing values (or not) should be consistent across dialects
- Ideally, I would like to be able to distinguish constant values from function calls when returned by
describeTable
What is actually happening?
- Constant values are not always returned with the right value, depending on the provider and the characters it contains
- Postgresql parses boolean values, not other types of values (and other provider do not seem to parse anything)
- 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
WikiRik commentedon Nov 21, 2023
Quick first thoughts:
describeTableneeds to be improved, at least so that results are uniform across dialects. See this comment from last year; feat: addqueryInterface.changeColumns, fix many bugs withchangeColumn#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'll take a look at your actually suggested change at a later point
ghusse commentedon Nov 21, 2023
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.
ghusse commentedon Nov 30, 2023
Any news on this?
ephys commentedon Feb 2, 2024
I'm very late to the party but yeah
describeTablehas 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?
ghusse commentedon Feb 3, 2024
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.
ephys commentedon Feb 4, 2024
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
ghusse commentedon Feb 4, 2024
It seems perfect
ghusse commentedon Feb 5, 2024
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.rawDefaultValueanddefaultValue.parsedDefaultValuetodefaultValue.rawanddefaultValue.parsed. WDYT?ephys commentedon Feb 5, 2024
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)
ghusse commentedon Feb 26, 2024
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:WikiRik commentedon Feb 26, 2024
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
ghusse commentedon Feb 27, 2024
I've made some progress on this topic, but digging it further I realize it's not really a good idea to have a
defaultValuebeing a object with 2 properties:describeTableis expected to return aColumnDescription,createTableand other structure-manipulation functions are expectingColumnDescriptionobjects as inputs.I think that the interface for these functions should not evolve in this direction, at least not because of the
describeTablefunction.I guess that we need the function
columnDescriptionto return literal values when parsing is not possible. What do you think?