diff --git a/Sources/SQLite/Query/SQLiteQuery+Select.swift b/Sources/SQLite/Query/SQLiteQuery+Select.swift index 5bd148b..745349d 100644 --- a/Sources/SQLite/Query/SQLiteQuery+Select.swift +++ b/Sources/SQLite/Query/SQLiteQuery+Select.swift @@ -29,23 +29,44 @@ extension SQLiteQuery { public var columns: [ResultColumn] public var tables: [TableOrSubquery] public var predicate: Expression? + public var orderBy: [OrderBy] public init( with: WithClause? = nil, distinct: Distinct? = nil, columns: [ResultColumn] = [], tables: [TableOrSubquery] = [], - predicate: Expression? = nil + predicate: Expression? = nil, + orderBy: [OrderBy] = [] ) { self.with = with self.distinct = distinct self.columns = columns self.tables = tables self.predicate = predicate + self.orderBy = orderBy + } + } +} + +extension SQLiteQuery { + public struct OrderBy { + public var expression: Expression + public var direction: Direction + + public init(expression: Expression, direction: Direction) { + self.expression = expression + self.direction = direction } } } +extension SQLiteSerializer { + func serialize(_ orderBy: SQLiteQuery.OrderBy, _ binds: inout [SQLiteData]) -> String { + return serialize(orderBy.expression, &binds) + " " + serialize(orderBy.direction) + } +} + extension SQLiteSerializer { func serialize(_ select: SQLiteQuery.Select, _ binds: inout [SQLiteData]) -> String { var sql: [String] = [] @@ -65,6 +86,10 @@ extension SQLiteSerializer { sql.append("WHERE") sql.append(serialize(predicate, &binds)) } + if !select.orderBy.isEmpty { + sql.append("ORDER BY") + sql.append(select.orderBy.map { serialize($0, &binds) }.joined(separator: ", ")) + } return sql.joined(separator: " ") }