SQLite.swift icon indicating copy to clipboard operation
SQLite.swift copied to clipboard

Support for returning

Open mfbx9da4 opened this issue 2 years ago • 1 comments

As far as I can tell there is no way to return anything other than the rowId inserted from an UPDATE or INSERT statement. That would be useful in my use case. eg

let alice = users.filter(id == 1)
let row = try db.run(alice.update(email <- "[email protected]").returning(users[*]))

mfbx9da4 avatar Jul 24 '23 10:07 mfbx9da4

FYI here's how it can be solved for a simple case:

extension Insert {
    func returning(_ columns: [Expression<Int64>]) -> Insert {
        var template = self.template
        let bindings = self.bindings
        
        template.append(" RETURNING ")
        template.append(columns.map { column in column.expression.template }.joined(separator: ", "))
        
        let insert = Insert(template, bindings)
        
        return insert
    }
}

...
let insert = table1.insert(...).returning([col1, col2])

if let results = try? db().prepareRowIterator(insert.template, bindings: insert.bindings) {
   // handle results as usual
}

dmitrygusev avatar Sep 24 '23 15:09 dmitrygusev