Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions docs/manual/other-topics/upgrade-to-v7.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,68 @@ As a result, the manual typings that were formerly best-effort guesses on top of
have been removed and all typings are now directly retrieved from the actual TypeScript code.
You'll likely find many tiny differences which however should be easy to fix.

### Attributes cannot start and end with `$`, or include `.`

`$attribute$` & `$nested.attribute$` is a special syntax used to reference nested attributes in Queries.
The `.` character also has special meaning, being used to reference nested JSON object keys,
the `$nested.attribute$` syntax, and in output names of eager-loaded associations in SQL queries.

In Sequelize 6, it was possible to create an attribute that matched this special syntax, leading to subtle bugs.
Starting with Sequelize 7, this is now considered reserved syntax, and it is no longer possible to
use a string that both starts and ends with a `$` as the attribute name, or includes the `.` character.

This only affects the attribute name, it is still possible to do this for the column name.

Instead of doing this:

```typescript
import { DataTypes, Model } from 'sequelize';

class User extends Model {
$myAttribute$: string;
'another.attribute': string;
}

User.init({
// this key sets the JavaScript name.
// It's not allowed to start & end with $ anymore.
'$myAttribute$': {
type: DataTypes.STRING,
// 'field' sets the column name
field: '$myAttribute$'
},
// The JavaScript name is not allowed to include a dot anymore.
'another.attribute': {
type: DataTypes.STRING,
field: 'another.attribute'
}
}, { sequelize });
```

Do this:

```typescript
import { DataTypes, Model } from 'sequelize';

class User extends Model {
$myAttribute$: string;
'another.attribute': string;
}

User.init({
'myAttribute': {
type: DataTypes.STRING,
// Column names are still allowed to start & end with $
field: '$myAttribute$'
},
'anotherAttribute': {
type: DataTypes.STRING,
// Column names are still allowed to include dots
field: 'another.attribute' // this sets the column name
}
}, { sequelize });
```

### Changes to `ConnectionManager`

*This only impacts you if you used `ConnectionManager` directly.*
Expand Down
14 changes: 10 additions & 4 deletions src/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -1069,6 +1069,14 @@ class Model {
this.rawAttributes = _.mapValues(attributes, (attribute, name) => {
attribute = this.sequelize.normalizeAttribute(attribute);

if (Utils.isColString(name)) {
throw new Error(`Name of attribute "${name}" in model "${this.name}" cannot start and end with "$" as "$attribute$" is reserved syntax used to reference nested columns in queries.`);
}

if (name.includes('.')) {
throw new Error(`Name of attribute "${name}" in model "${this.name}" cannot include the character "." as it would be ambiguous with the syntax used to reference nested columns, and nested json keys, in queries.`);
}

if (attribute.type === undefined) {
throw new Error(`Unrecognized datatype for attribute "${this.name}.${name}"`);
}
Expand Down Expand Up @@ -1729,8 +1737,7 @@ class Model {
*
* # WHERE `Model`.`name` = 'a project' AND (`Model`.`id` IN (1, 2, 3) OR (`Model`.`id` > 10 AND `Model`.`id` < 100));
*
* @see
* {@link Operators} for possible operators
* @see {Sequelize.Op} for possible operators
* __Alias__: _all_
*
* The promise is resolved with an array of Model instances if the query succeeds._
Expand Down Expand Up @@ -1773,8 +1780,7 @@ class Model {
* @param {boolean|Error} [options.rejectOnEmpty=false] Throws an error when no records found
* @param {boolean} [options.dotNotation] Allows including tables having the same attribute/column names - which have a dot in them.
*
* @see
* {@link Sequelize#query}
* @see {Sequelize#query}
*
* @returns {Promise<Array<Model>>}
*/
Expand Down
10 changes: 10 additions & 0 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,16 @@ function mapValueFieldNames(dataValues, fields, Model) {

exports.mapValueFieldNames = mapValueFieldNames;

/**
* Returns whether `value` is using the nested syntax for attributes.
*
* @param {string} value The attribute reference to check.
*
* @example
* isColString('$id$'); // true
* isColString('$project.name$'); // true
* isColString('name'); // false
*/
function isColString(value) {
return typeof value === 'string' && value[0] === '$' && value[value.length - 1] === '$';
}
Expand Down
12 changes: 0 additions & 12 deletions test/integration/model/attributes.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,17 +127,5 @@ describe(Support.getTestDialectTeaser('Model'), () => {
expect(result[0].get('computers')[0].hostname).to.equal('laptop');
});
});

describe('quote', () => {
it('allows for an attribute with dots', async function () {
const User = this.sequelize.define('user', {
'foo.bar.baz': Sequelize.TEXT,
});

await this.sequelize.sync({ force: true });
const result = await User.findAll();
expect(result.length).to.equal(0);
});
});
});
});
16 changes: 16 additions & 0 deletions test/unit/model/define.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,22 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}).to.throw('A column called \'id\' was added to the attributes of \'bars\' but not marked with \'primaryKey: true\'');
});

it('should throw when the attribute name is ambiguous with $nested.attribute$ syntax', () => {
expect(() => {
current.define('foo', {
$id$: DataTypes.INTEGER,
});
}).to.throw('Name of attribute "$id$" in model "foo" cannot start and end with "$" as "$attribute$" is reserved syntax used to reference nested columns in queries.');
});

it('should throw when the attribute name is ambiguous with json.path syntax', () => {
expect(() => {
current.define('foo', {
'my.attribute': DataTypes.INTEGER,
});
}).to.throw('Name of attribute "my.attribute" in model "foo" cannot include the character "." as it would be ambiguous with the syntax used to reference nested columns, and nested json keys, in queries.');
});

it('should defend against null or undefined "unique" attributes', () => {
expect(() => {
current.define('baz', {
Expand Down
27 changes: 15 additions & 12 deletions test/unit/sql/select.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -875,39 +875,42 @@ describe(Support.getTestDialectTeaser('SQL'), () => {
const User = Support.sequelize.define('User', {
name: DataTypes.STRING,
age: DataTypes.INTEGER,
'status.label': DataTypes.STRING,
},
{
statuslabel: {
field: 'status.label',
type: DataTypes.STRING,
},
}, {
freezeTableName: true,
});
const Post = Support.sequelize.define('Post', {
title: DataTypes.STRING,
'status.label': DataTypes.STRING,
},
{
statuslabel: {
field: 'status.label',
type: DataTypes.STRING,
},
}, {
freezeTableName: true,
});

User.Posts = User.hasMany(Post, { foreignKey: 'user_id' });

expectsql(sql.selectQuery('User', {
attributes: ['name', 'age', 'status.label'],
attributes: ['name', 'age', ['status.label', 'statuslabel']],
include: Model._validateIncludedElements({
include: [{
attributes: ['title', 'status.label'],
attributes: ['title', ['status.label', 'statuslabel']],
association: User.Posts,
}],
model: User,
}).include,
model: User,
dotNotation: true,
}, User), {
default: 'SELECT [User].[name], [User].[age], [User].[status.label], [Posts].[id] AS [Posts.id], [Posts].[title] AS [Posts.title], [Posts].[status.label] AS [Posts.status.label] FROM [User] AS [User] LEFT OUTER JOIN [Post] AS [Posts] ON [User].[id] = [Posts].[user_id];',
postgres: 'SELECT "User".name, "User".age, "User"."status.label", Posts.id AS "Posts.id", Posts.title AS "Posts.title", Posts."status.label" AS "Posts.status.label" FROM "User" AS "User" LEFT OUTER JOIN Post AS Posts ON "User".id = Posts.user_id;',
snowflake: 'SELECT User.name, User.age, User."status.label", Posts.id AS "Posts.id", Posts.title AS "Posts.title", Posts."status.label" AS "Posts.status.label" FROM User AS User LEFT OUTER JOIN Post AS Posts ON User.id = Posts.user_id;',
default: 'SELECT [User].[name], [User].[age], [User].[status.label] AS [statuslabel], [Posts].[id] AS [Posts.id], [Posts].[title] AS [Posts.title], [Posts].[status.label] AS [Posts.statuslabel] FROM [User] AS [User] LEFT OUTER JOIN [Post] AS [Posts] ON [User].[id] = [Posts].[user_id];',
postgres: 'SELECT "User".name, "User".age, "User"."status.label" AS statuslabel, Posts.id AS "Posts.id", Posts.title AS "Posts.title", Posts."status.label" AS "Posts.statuslabel" FROM "User" AS "User" LEFT OUTER JOIN Post AS Posts ON "User".id = Posts.user_id;',
snowflake: 'SELECT User.name, User.age, User."status.label" AS statuslabel, Posts.id AS "Posts.id", Posts.title AS "Posts.title", Posts."status.label" AS "Posts.statuslabel" FROM User AS User LEFT OUTER JOIN Post AS Posts ON User.id = Posts.user_id;',
});
});

});

describe('raw query', () => {
Expand Down