question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Creating with associations as transactional

See original GitHub issue

Hi,

Is that possible creating with associations as transactional? When an error occurs on associated model creating, rollback entire transaction?

Models:

module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define("User", {
    username: DataTypes.STRING
  }, {
    classMethods: {
      associate: function(models) {
        User.hasMany(models.Task)
      }
    }
  });

  return User;
};

module.exports = function(sequelize, DataTypes) {
  var Task = sequelize.define("Task", {
    title: DataTypes.STRING(1)
  }, {
    classMethods: {
      associate: function(models) {
        Task.belongsTo(models.User, {
          onDelete: "CASCADE",
          foreignKey: {
            allowNull: false
          }
        });
      }
    }
  });

  return Task;
};

When called the create with association as below, throws SequelizeDatabaseError: ER_DATA_TOO_LONG: Data too long for column ‘title’ at row 1

  models.User.create({
    username: "username",
    Tasks: [{
      title: "Too long data for column"
    }]
  }, {
    include: [models.Task]
  }).then(function() {
    console.log('success');
  }).catch(function(err) {
   console.log(err);
  })

And then MySQL query results:

mysql> select * from users;
+----+----------+---------------------+---------------------+
| id | username | createdAt           | updatedAt           |
+----+----------+---------------------+---------------------+
|  1 | username   | 2016-08-04 13:35:41 | 2016-08-04 13:35:41 |
+----+----------+---------------------+---------------------+
1 row in set (0.00 sec)

mysql> select * from tasks;
Empty set (0.00 sec)

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:2
  • Comments:9 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
felixfbeckercommented, Aug 25, 2016

I don’t see any transaction() call in your code. Please try this:

sequelize.transaction(transaction =>
  models.User.create({
    username: "username",
    Tasks: [{
      title: "Too long data for column"
    }]
  }, {
    include: [models.Task],
    transaction
  }).then(function() {
    console.log('success');
  }).catch(function(err) {
   console.log(err);
  })
})
0reactions
ghostcommented, Aug 29, 2016
/*
 * Copy this file to ./sscce.js
 * Add code from issue
 * npm run sscce-{dialect}
 */
var Sequelize = require('./index');
var sequelize = require('./test/support').createSequelizeInstance();

var User = sequelize.define("User", {
    username: Sequelize.STRING
});
var Task = sequelize.define("Task", {
    title: Sequelize.STRING(1)
});

User.hasMany(Task);
Task.belongsTo(User);

sequelize.sync({
        force: true
    })
    .then(() => sequelize.transaction(transaction => User.create({
            username: "username",
            Tasks: [{
                title: "Too long data for column"
            }]
        }, {
            include: [Task],
            transaction
        })
    ))
.then(console.log)
.catch(console.log);

EDIT: @felixfbecker sorry my bad sscce. I changed it and it’s working correctly. I’ll close the issue.

output:

Executing (21f5cf99-8d5a-4a8a-986a-20399820e692): START TRANSACTION;
Executing (21f5cf99-8d5a-4a8a-986a-20399820e692): SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
Executing (21f5cf99-8d5a-4a8a-986a-20399820e692): SET autocommit = 1;
Executing (21f5cf99-8d5a-4a8a-986a-20399820e692): INSERT INTO `Users` (`id`,`username`,`createdAt`,`updatedAt`) VALUES (DEFAULT,'username','2016-08-29 08:53:29','2016-08-29 08:53:29');
Executing (21f5cf99-8d5a-4a8a-986a-20399820e692): INSERT INTO `Tasks` (`id`,`title`,`createdAt`,`updatedAt`,`UserId`) VALUES (DEFAULT,'Too long data for column','2016-08-29 08:53:29','2016-08-29 08:53:29',1);
Executing (21f5cf99-8d5a-4a8a-986a-20399820e692): ROLLBACK;
Read more comments on GitHub >

github_iconTop Results From Across the Web

Creating with Associations - Sequelize
Creating with Associations. An instance can be created with nested association in one step, provided all elements are new. In contrast, performing updates ......
Read more >
Use transaction in sequelize Bulk create with include ...
According to the official documentation bulkCreate doesn't support include option and supports transaction option. So if you want to create ...
Read more >
What are Association Rules in Data Mining ... - TechTarget
In transaction data, the AIS algorithm determines which large itemsets contained a transaction, and new candidate itemsets are created by extending the large ......
Read more >
Association rule analysis beyond transaction data
The outputs are association rules that explain the relationship (co-occurrence) between the items. A classic rule example is {Beer} ==> {Diapers} ...
Read more >
Hooks - Manual | Sequelize
update in the preceding code, no change would have occurred, since our newly created user does not exist in the database until the...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found