Skip to content

Instantly share code, notes, and snippets.

@jamal
Created November 7, 2013 02:10
Show Gist options
  • Save jamal/7347777 to your computer and use it in GitHub Desktop.
Save jamal/7347777 to your computer and use it in GitHub Desktop.
Hack to support an atomic filter and update with RethinkDB. This is useful for supporting something like a locking message queue. The problem here is that return_vals only works for single-row modifications, and filter() and limit() always returns multiple rows. At least, this was the simplest solution I could come up with.
r.db("test").table("queue").filter({"available": true}).limit(1).forEach(function (row) {
return r.db("test").table("queue").get(row("id")).update({"available": false}, {return_vals: true})
})
@jamal
Copy link
Author

jamal commented Nov 7, 2013

And here is the version in Go using gorethink:

updateAvailable := func(row r.RqlTerm) r.RqlTerm {
    return r.Table("queue").Get(row.Field("id")).Update(
        map[string]interface{}{"available": false},
        "return_vals", true)
}

write, err := r.Table("queue").Filter(r.Row.Field("available").Eq(true)).Limit(1).ForEach(updateAvailable).RunWrite(session)
if err == nil {
    if val, ok := write.NewValue.(map[string]interface{}); ok {
        if id, ok := val["id"].(string); ok {
            // do something
        }
    }
}

@coffeemug
Copy link

Could you write an example query that you'd want to run but currently can't? We'll see if we can make it happen :)

@AtnNn
Copy link

AtnNn commented Nov 7, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment