forked from plarson/fluent-postgis
-
-
Notifications
You must be signed in to change notification settings - Fork 11
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1 from brokenhandsio/distance-sort
Add support for sorting by distance
- Loading branch information
Showing
1 changed file
with
29 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} | ||
|
||
|