Skip to content

Commit

Permalink
Merge pull request #1 from brokenhandsio/distance-sort
Browse files Browse the repository at this point in the history
Add support for sorting by distance
  • Loading branch information
0xTim authored Sep 17, 2019
2 parents ffcca3a + a4fa1d2 commit 93f82df
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions Sources/FluentPostGIS/Queries/QueryBuilder+Sort.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import FluentPostgreSQL

extension QueryBuilder where
Database: QuerySupporting,
Database.QuerySort: SQLOrderBy,
Database.QueryFilter: SQLExpression,
Database.QueryFilterValue == Database.QueryFilter
{
@discardableResult
public func sortByDistance<T,V>(between key: KeyPath<Result, T>, _ filter: V) -> Self
where T: GeometryConvertible, V: GeometryConvertible {
return self.sort(Database.distanceSort(between: Database.queryField(.keyPath(key)), Database.queryFilterValueGeographic(filter)))
}

}

extension QuerySupporting where
QuerySort: SQLOrderBy
{
public static func distanceSort(between field: QueryField, _ filter: QueryFilterValue) -> QuerySort {
let args: [QuerySort.Expression.Function.Argument] = [
GenericSQLFunctionArgument<PostgreSQLExpression>.expression(PostgreSQLExpression.column(field as! PostgreSQLColumnIdentifier)),
GenericSQLFunctionArgument<PostgreSQLExpression>.expression(filter as! PostgreSQLExpression),
] as! [QuerySort.Expression.Function.Argument]
return .orderBy(.function("ST_Distance", args), .ascending)
}
}


0 comments on commit 93f82df

Please sign in to comment.