Leentje
Leentje

Reputation: 134

sequelizejs saving an object when row was removed

I have the following code. The idea is that I update a database row in an interval, however if I remove the row manually from the database while this script runs, the save() still goes into success(), but the row is not actually put back into the database. (Because sequelize does an update query with a where clause and no rows match.) I expected a new row to be created or error() to be called. Any ideas to what I can do to make this behave like I want to?

var Sequelize = require("sequelize") 
, sequelize    = new Sequelize('test', 'test', 'test', {logging: false, host: 'localhost'})
, Server   = sequelize.import(__dirname + "/models/Servers")

sequelize.sync({force: true}).on('success', function() {
    Server
    .create({ hostname: 'Sequelize Server 1', ip: '127.0.0.1', port: 0})
        .on('success', function(server) {

            console.log('Server added to db, going to interval');

            setInterval(function() { console.log('timeout reached'); server.port = server.port + 1; server.save().success(function() { console.log('saved ' + server.port) }).error(function(error) { console.log(error); }); }, 1000);


    })
})

Upvotes: 0

Views: 389

Answers (1)

Jan Aagaard Meier
Jan Aagaard Meier

Reputation: 28798

I'm afraid what you are trying to do is not currently supported by sequelize.

Error callbacks are only ment for actual error situations, i.e. SQL syntax errors, stuff like that. Trying to update a non-existing row is not an error in SQL.

The import distinction here is, that you are modifying your database outside of your program. Sequelize has no way of knowing that! I have two possible solutions, only one of which is viable right now:

1 (works right now)

Use sequelize.query to include error handling in your query

IF EXISTS (SELELCT * FROM table WHERE id = 42)
    UPDATE table SET port = newport WHERE id = 42 
ELSE
    INSERT INTO table ... port = newport

Alternatively you could create a feature request on the sequelize github for INSERT ... ON DUPLICATE KEY UPDATE syntax to be implemented see and here

2 (will work when transactions are implemented

Use transactions to first check if the row exists, and insert it if it does not. Transactions are on the roadmap for sequelize, but not currently supported. If you are NOT using connection pooling, you might be able to acomplish transactions manually by calling sequelize.query('BEGIN / COMMIT TRANSACTION').

Upvotes: 1

Related Questions