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

Add support for sorting joined tables #53

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 2 additions & 8 deletions Sources/FluentMongoDriver/DatabaseQuery+Mongo.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,11 @@ import FluentKit
import MongoKitten

extension DatabaseQuery {
internal func makeMongoDBSort() throws -> MongoKitten.Sort? {
internal func makeMongoDBSort(aggregate: Bool) throws -> MongoKitten.Sort? {
var sortSpec = [(String, SortOrder)]()

for sort in sorts {
switch sort {
case .sort(let field, let direction):
let path = try field.makeMongoPath()
try sortSpec.append((path, direction.makeMongoDirection()))
case .custom:
throw FluentMongoError.unsupportedCustomSort
}
sortSpec.append(try sort.makeMongoDBSort(aggregate: aggregate))
}

if sortSpec.isEmpty {
Expand Down
4 changes: 4 additions & 0 deletions Sources/FluentMongoDriver/MongoDB+Join.swift
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,10 @@ extension DatabaseQuery {
stages.append(match(filter))
}

if let mongoDBSort = try makeMongoDBSort(aggregate: true) {
stages.append(sort(mongoDBSort))
}

switch offsets.first {
case .count(let offset):
stages.append(skip(offset))
Expand Down
2 changes: 1 addition & 1 deletion Sources/FluentMongoDriver/MongoDB+Read.swift
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ extension FluentMongoDatabase {
}
find.command.projection = projection.document

find.command.sort = try query.makeMongoDBSort()?.document
find.command.sort = try query.makeMongoDBSort(aggregate: false)?.document

logger.debug("fluent-mongo find command=\(find.command)")
let decoder = BSONDecoder()
Expand Down
19 changes: 19 additions & 0 deletions Sources/FluentMongoDriver/Sort.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,22 @@ extension DatabaseQuery.Sort.Direction {
}
}
}

extension DatabaseQuery.Sort {
internal func makeMongoDBSort(aggregate: Bool) throws -> (String, SortOrder) {
switch self {
case .sort(let field, let direction):
let path: String

if aggregate {
path = try field.makeProjectedMongoPath()
} else {
path = try field.makeMongoPath()
}

return try (path, direction.makeMongoDirection())
case .custom:
throw FluentMongoError.unsupportedCustomSort
}
}
}