vapor / sql-kit

*️⃣ Build SQL queries in Swift. Extensible, protocol-based design that supports DQL, DML, and DDL.
MIT License
248 stars 58 forks source link

UNION handles single entry #148

Closed NeedleInAJayStack closed 2 years ago

NeedleInAJayStack commented 2 years ago

This PR simplifies dynamically building UNION statements.

To be specific, it loosens the restriction that a SQLUnion must contain multiple select statements. While this is common usage, it makes building up UNIONs in client code difficult. For example, building up a UNION in a for loop is awkward right now:

let ids = [1, 2, 3, ...]
guard let firstId = ids.first else { ... }

// Must manually short-circuit as a SQLSelectBuilder
guard ids.count > 1 else {
    return sql.select.column("id").from("t1").where("id", .equals, firstId).all()
}
let unionBuilder = sql.union { select in
    select.column("id").from("t1").where("id", .equals, firstId)
}
for id in ids[1..<ids.count] {
    unionBuilder.union(all: { select in
        select.column("id").from("t1").where("id", .equals, id)
    })
}
return unionBuilder.all()

This PR removes the need for the commented guard in the code above. It also improves code safety by removing a runtime fatal error condition.

VaporBot commented 2 years ago

These changes are now available in 3.19.1