Commit 682eb669 authored by Rene Saarsoo's avatar Rene Saarsoo
Browse files

Ensure Target#ensure works in concurrent environment.

parent 15f2a105
Loading
Loading
Loading
Loading
+1 −1
Original line number Diff line number Diff line
@@ -56,7 +56,7 @@ DbFacade.prototype = {
     */
    insert: function(table, fields, callback) {
        this.query("INSERT INTO "+table+" SET ?", [fields], function(err, result) {
            callback(err, result.insertId);
            callback(err, result && result.insertId);
        });
    },

+9 −4
Original line number Diff line number Diff line
@@ -25,12 +25,17 @@ Targets.prototype = {
     * @param {Number} callback.id The ID of the target
     */
    ensure: function(target, callback) {
        this.get(target, function(err, targetFound) {
            if (targetFound) {
                callback(err, targetFound.id);
        // first try to insert. If that fails, the target already
        // exists and we can instead look it up. If insert succeeds,
        // great also.
        this.add(target, function(err, target_id) {
            if (err) {
                this.get(target, function(err, t) {
                    callback(err, t.id);
                });
            }
            else {
                this.add(target, callback);
                callback(err, target_id);
            }
        }.bind(this));
    },