Skip to content
Merged
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
62 changes: 34 additions & 28 deletions modules/sql-core/src/main/scala/SqlMapping.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2832,7 +2832,9 @@ trait SqlMappingLike[F[_]] extends CirceMappingLike[F] with SqlModule[F] { self
else Nil) ++ pred

val (oss, orderJoins) =
orderBy.map { case (oss, joins) => (oss, joins) }.getOrElse((Nil, Nil))
orderBy
.map { case (oss, joins) => (oss.distinctBy(_.term), joins) }
.getOrElse((Nil, Nil))

// Columns inside a nested select that `SqlSelect.nest` could not flatten are out of scope
// here. `viaSubquery` gives the column of the joined subquery that projects such a
Expand Down Expand Up @@ -3328,29 +3330,35 @@ trait SqlMappingLike[F[_]] extends CirceMappingLike[F] with SqlModule[F] { self
if (orderBy.isEmpty || initialKeyOrder) {
// Case 2) No order, or key columns at the start of the order

contextualiseWheres(baseRef, predJoins, pred0).flatMap { pred1 =>
contextualiseOrders(baseRef, predJoins, oss).flatMap { oss0 =>
val orders = oss0 ++ keyCols
.diff(orderCols)
.map(col => OrderSelection(col.derive(baseRef).toTerm, true, nullsHigh))
contextualiseWheres(baseRef, predJoins, pred0).map { pred1 =>
val orders =
(orderCols.take(keyCols.size) ++ keyCols.diff(orderCols)).map { col =>
Comment thread
hugo-vrijswijk marked this conversation as resolved.
Resolved
val ascending = orderCols
.zip(oss)
.collectFirst { case (c, os) if c == col => os.ascending }
.getOrElse(true)
OrderSelection(
col.derive(baseRef).toTerm,
ascending,
ascending == nullsHigh)
}

val predQuery = SqlSelect(
context = context,
withs = Nil,
table = baseRef,
cols = predCols,
joins = predJoins,
wheres = (pred1 ++ nonNullKeys).distinct,
orders = orders,
offset = offset0,
limit = limit0,
distinct = predCols,
oneToOne = true,
predicate = true
)
val predQuery = SqlSelect(
context = context,
withs = Nil,
table = baseRef,
cols = predCols,
joins = predJoins,
wheres = (pred1 ++ nonNullKeys).distinct,
orders = orders,
offset = offset0,
limit = limit0,
distinct = predCols,
oneToOne = true,
predicate = true
)

mkPredSubquery(base0, predQuery).success
}
mkPredSubquery(base0, predQuery)
}
} else {
// Case 3) There is an order orthogonal to the key
Comment thread
hugo-vrijswijk marked this conversation as resolved.
Resolved
Expand All @@ -3359,11 +3367,9 @@ trait SqlMappingLike[F[_]] extends CirceMappingLike[F] with SqlModule[F] { self
oss0
.filterA(os => columnForSqlTerm(context, os.term).map(keyCols.contains))
.flatMap { nonKeyOrders =>
val distOrders = keyCols.map(col =>
OrderSelection(
col.derive(baseRef).toTerm,
true,
nullsHigh)) ++ nonKeyOrders
val keyOrders = keyCols.map(col =>
OrderSelection(col.derive(baseRef).toTerm, true, nullsHigh))
val distOrders = keyOrders ++ nonKeyOrders
val distOrderCols =
oss0
.map(_.term)
Expand All @@ -3379,7 +3385,7 @@ trait SqlMappingLike[F[_]] extends CirceMappingLike[F] with SqlModule[F] { self
cols = predCols ++ distOrderCols.map(_._2),
joins = predJoins,
wheres = (pred1 ++ nonNullKeys).distinct,
orders = distOrders,
orders = keyOrders,
offset = None,
limit = None,
distinct = predCols,
Expand Down
30 changes: 29 additions & 1 deletion modules/sql-core/src/test/scala/SqlCompositeKeyMapping.scala
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@

package grackle.sql.test

import grackle.Query._
import grackle.QueryCompiler._
import grackle.Value._
import grackle.syntax._

trait SqlCompositeKeyMapping[F[_]] extends SqlTestMapping[F] {
Expand All @@ -33,7 +36,11 @@ trait SqlCompositeKeyMapping[F[_]] extends SqlTestMapping[F] {
val schema =
schema"""
type Query {
parents: [Parent!]!
parents(limit: Int, order: [ParentOrder!]): [Parent!]!
}
enum ParentOrder {
KEY1
KEY2
}
type Parent {
key1: Int!
Expand Down Expand Up @@ -81,4 +88,25 @@ trait SqlCompositeKeyMapping[F[_]] extends SqlTestMapping[F] {
)
)
)

override val selectElaborator = SelectElaborator {
case (QueryType, "parents", List(Binding("limit", limit), Binding("order", order))) =>
val oss: List[OrderSelection[_]] =
order match {
case ListValue(elems) =>
elems.collect {
case EnumValue("KEY1") => OrderSelection[Int](ParentType / "key1")
case EnumValue("KEY2") => OrderSelection[String](ParentType / "key2")
}
case _ => Nil
}

Elab.transformChild { child =>
val ordered = if (oss.isEmpty) child else OrderBy(OrderSelections(oss), child)
limit match {
case IntValue(num) if num > 0 => Limit(num, ordered)
case _ => ordered
}
}
}
}
45 changes: 45 additions & 0 deletions modules/sql-core/src/test/scala/SqlCompositeKeySuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -97,4 +97,49 @@ trait SqlCompositeKeySuite extends CatsEffectSuite {

assertWeaklyEqualIO(res, expected)
}

test("limited query with subobjects ordered by a repeated key column") {
val query = """
query {
parents(limit: 2, order: [KEY1, KEY1, KEY2]) {
key1
key2
children {
id
}
}
}
"""

val expected = json"""
{
"data" : {
"parents" : [
{
"key1" : 1,
"key2" : "bar",
"children" : [
{
"id" : 2
}
]
},
{
"key1" : 1,
"key2" : "foo",
"children" : [
{
"id" : 1
}
]
}
]
}
}
"""

val res = mapping.compileAndRun(query)

assertWeaklyEqualIO(res, expected, strictPaths = List(List("data", "parents")))
}
}
27 changes: 24 additions & 3 deletions modules/sql-core/src/test/scala/SqlWorldMapping.scala
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ trait SqlWorldMapping[F[_]] extends SqlTestMapping[F] {
cities(namePattern: String = "%"): [City!]
city(id: Int): City
country(code: String): Country
countries(limit: Int = -1, offset: Int = 0, minPopulation: Int = 0, byPopulation: Boolean = false): [Country!]
countries(limit: Int = -1, offset: Int = 0, minPopulation: Int = 0, byPopulation: Boolean = false, order: [CountryOrder!]): [Country!]
language(language: String): Language
languages(languages: [String!]!): [Language!]!
search(minPopulation: Int!, indepSince: Int!): [Country!]!
Expand Down Expand Up @@ -108,6 +108,11 @@ trait SqlWorldMapping[F[_]] extends SqlTestMapping[F] {
city(id: Int): City
languages: [Language!]!
}
enum CountryOrder {
CODE
CODE_DESC
NAME
}
"""

val QueryType = schema.ref("Query")
Expand Down Expand Up @@ -205,7 +210,9 @@ trait SqlWorldMapping[F[_]] extends SqlTestMapping[F] {
Binding("limit", IntValue(num)),
Binding("offset", IntValue(off)),
Binding("minPopulation", IntValue(min)),
Binding("byPopulation", BooleanValue(byPop)))) =>
Binding("byPopulation", BooleanValue(byPop)),
Binding("order", orderValue)
)) =>
def limit(query: Query): Query =
if (num < 1) query
else Limit(num, query)
Expand All @@ -214,8 +221,22 @@ trait SqlWorldMapping[F[_]] extends SqlTestMapping[F] {
if (off < 1) query
else Offset(off, query)

val explicitOrder: List[OrderSelection[_]] =
orderValue match {
case ListValue(elems) =>
elems.collect {
case EnumValue("CODE") => OrderSelection[String](CountryType / "code")
case EnumValue("CODE_DESC") =>
OrderSelection[String](CountryType / "code", ascending = false)
case EnumValue("NAME") => OrderSelection[String](CountryType / "name")
}
case _ => Nil
}

def order(query: Query): Query = {
if (byPop)
if (explicitOrder.nonEmpty)
OrderBy(OrderSelections(explicitOrder), query)
else if (byPop)
OrderBy(OrderSelections(List(OrderSelection[Int](CountryType / "population"))), query)
else if (num > 0 || off > 0)
OrderBy(OrderSelections(List(OrderSelection[String](CountryType / "code"))), query)
Expand Down
Loading
Loading