Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UNION Operator, or advice rewriting a query #587

Closed
Laptopmini opened this issue Jan 6, 2017 · 1 comment
Closed

UNION Operator, or advice rewriting a query #587

Laptopmini opened this issue Jan 6, 2017 · 1 comment

Comments

@Laptopmini
Copy link

Language: Swift 3
Target: iOS 10.0
Pod Version: 0.11.0
xCode: 8.2.1

Hello,

I have in my database a table of items. I am trying to write a query which will let me know if a particular item is in the first "page" of items.

To do so, I need to query the table with a limit to get the first "page", so lets say:

var query = itemsTable.limit(10, offset: 0)

Next, I need to check if the item I am looking for is in this first page, so my initial reflex was to apply the following:

query = query.filter(ItemsTableExpressions.id == targetID)

However, since the execution is lazy and I have been just building an Expression (so to speak, since query is actually of type Table), this query will be optimized and result in the following:

SELECT * FROM itemsTable WHERE id = targetID LIMIT 10;

Which is not what I want. This gets all items matching the targetID and THEN limits those results to 10. My intuition was then to use UNION and just make 2 different queries and find their common result domain. However, as you may know, this library does not offer a UNION operator.

Now, I can obviously use raw SQL, but I'd like to keep it swifty, so to speak. Does anyone have advice on how to meet the result I need using this library (and probably without the use of UNION)?

@Laptopmini
Copy link
Author

Laptopmini commented Jan 6, 2017

I figured out an alternative.

I declare my query, like I did:

var query = itemsTable.limit(10, offset: 0)

Then I execute it:

let results = try! db.prepare(query)

And I can then use first(where predicate: (Element) throws -> Bool) to find my target:

let target = results.first { row -> Bool in
    return row.get(ItemsTableExpressions.id) == targetID
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant