We now have the basics of a query builder library implemented, and it already is more powerful than probably any Swift SQL library out there. It is capable of expressing complex selections from a table, including columns, aggregates, and even subqueries. And best of all, we are able to leverage some of Swift’s most advanced features, such as key paths, macros and variadic generics, to provide a lot of type safety and static checks that give us a lot of confidence we are writing valid SQL statements.
But there is still a lot more functionality in a SQL SELECT
statement that we need to support. You can filter rows from a SELECT
by using a WHERE
clause with complex predicate logic. You can join multiple tables together so that you can cross reference data between tables. You can group aggregate results together, like if you wanted to select all tags along with a count of the number of reminders assigned to each tag. And a lot more.
But for right now we are going to concentrate on ordering. Once you have performed a select you will typically have a big list of rows, and you often want to order those rows in particular manner. SQL has great support for sorting, allowing you to sort by any number of fields in any direction, and you can even perform computations in the ordering, such as sorting a text column by ignoring the case of characters.
Let’s first see what SQL has to offer when it comes to ordering, and then see how we can recreate all of it in our query builder.