Skip to content

Commit

Permalink
adding scalafmt to protoquill
Browse files Browse the repository at this point in the history
  • Loading branch information
juliano committed Oct 18, 2023
1 parent feca130 commit 9ec9798
Show file tree
Hide file tree
Showing 364 changed files with 8,367 additions and 5,575 deletions.
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ project/.bloop/
.jvmopts
.DS_Store
.vscode
.scalafmt.conf
project/metals.sbt
project/project/
.sbtopts
Expand Down
25 changes: 25 additions & 0 deletions .scalafmt.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
version = "3.7.14"
maxColumn = 120
align.preset = most
align.multiline = false
continuationIndent.defnSite = 2
assumeStandardLibraryStripMargin = true
docstrings.style = Asterisk
docstrings.wrapMaxColumn = 80
lineEndings = preserve
includeCurlyBraceInSelectChains = false
danglingParentheses.preset = true
optIn.annotationNewlines = true
newlines.alwaysBeforeMultilineDef = false
runner.dialect = scala3
runner.dialectOverride.allowSignificantIndentation = false
rewrite.rules = [RedundantBraces]

project.excludePaths = ["glob:**/scalafix/input/**", "glob:**/scalafix/output/**"]

rewrite.redundantBraces.generalExpressions = false
rewriteTokens = {
"⇒": "=>"
"→": "->"
"←": "<-"
}
3 changes: 3 additions & 0 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ inThisBuild(
ScmInfo(url("https://github.com/zio/zio-protoquill"), "git:git@github.com:zio/zio-protoquill.git")
),
versionScheme := Some("always"),
scalafmtCheck := true,
scalafmtSbtCheck := true,
scalafmtOnCompile := !insideCI.value,
)
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ package io.getquill

import caliban.CalibanError.ExecutionError
import caliban.GraphQL.graphQL
import caliban.introspection.adt.{ __InputValue, __Type, __TypeKind }
import caliban.schema.{ ArgBuilder, Schema, Step }
import caliban.{ InputValue, RootResolver }
import caliban.introspection.adt.{__InputValue, __Type, __TypeKind}
import caliban.schema.{ArgBuilder, Schema, Step}
import caliban.{InputValue, RootResolver}
import caliban.execution.Field
import caliban.schema.Types
import caliban.Value
Expand All @@ -16,7 +16,7 @@ object CalibanIntegration {
def quillColumns(field: Field) = {
def recurseFetchFields(field: Field): List[Field] =
if (Types.innerType(field.fieldType).kind == __TypeKind.OBJECT)
field.fields.flatMap(recurseFetchFields(_))
field.fields.flatMap(recurseFetchFields(_))
else
List(field)
field.fields.flatMap(recurseFetchFields(_)).map(_.name)
Expand All @@ -28,21 +28,21 @@ object CalibanIntegration {
// e.g. for `name` in Person(name: Name, age: Int) this would be Name from which we need first:String, last:String
case InputValue.ObjectValue(fields) => fields.toList.flatMap { case (k, v) => flattenToPairs(k, v) }
// Need to look at StringValue directly because calling .toInputString on it will give double quoting i.e. "\"value\""
case Value.StringValue(value) => List((key, value))
case _ => List((key, value.toInputString))
case Value.StringValue(value) => List((key, value))
case _ => List((key, value.toInputString))
}

implicit def productArgBuilder[T]: ArgBuilder[ProductArgs[T]] = {
case InputValue.ObjectValue(fields) =>
Right(ProductArgs[T](fields.flatMap { case (k, v) => flattenToPairs(k, v).toMap }))
case other => Left(ExecutionError(s"Can't build a ProductArgs from input $other"))
case other => Left(ExecutionError(s"Can't build a ProductArgs from input $other"))
}

implicit def productSchema[T](implicit ev: Schema[Any, T]): Schema[Any, ProductArgs[T]] =
new Schema[Any, ProductArgs[T]] {

def makeOptionalRecurse(f: __InputValue): __InputValue = {
val fieldType = f.`type`()
val fieldType = f.`type`()
val optionalFieldType = fieldType.kind match {
case __TypeKind.NON_NULL => fieldType.ofType.getOrElse(fieldType)
case _ => fieldType
Expand All @@ -64,4 +64,4 @@ object CalibanIntegration {
def resolve(value: ProductArgs[T]): Step[Any] = Step.NullStep
}

} // end CalibanIntegration
} // end CalibanIntegration
Original file line number Diff line number Diff line change
Expand Up @@ -17,36 +17,38 @@ class CalibanIntegrationNestedSpec extends CalibanSpec {
object Dao {
def personAddress(columns: List[String], filters: Map[String, String]) =
Ctx.run {
query[PersonT].leftJoin(query[AddressT]).on((p, a) => p.id == a.ownerId)
query[PersonT]
.leftJoin(query[AddressT])
.on((p, a) => p.id == a.ownerId)
.map((p, a) => PersonAddressNested(p.id, p.name, p.age, a.map(_.street)))
.filterByKeys(filters)
.filterColumns(columns)
.take(10)
}.provideLayer(zioDS).tap(list => {
println(s"Results: $list for columns: $columns and filters: ${io.getquill.util.Messages.qprint(filters)}")
ZIO.unit
})
.tapError(e => {
println(s"ERROR $e")
ZIO.unit
})
}.provideLayer(zioDS)
.tap { list =>
println(s"Results: $list for columns: $columns and filters: ${io.getquill.util.Messages.qprint(filters)}")
ZIO.unit
}
.tapError { e =>
println(s"ERROR $e")
ZIO.unit
}
}
}

case class Queries(
personAddressNested: Field => (ProductArgs[NestedSchema.PersonAddressNested] => Task[List[NestedSchema.PersonAddressNested]])
personAddressNested: Field => (
ProductArgs[NestedSchema.PersonAddressNested] => Task[List[NestedSchema.PersonAddressNested]]
)
)

val api = graphQL(
RootResolver(
Queries(
personAddressNested =>
(productArgs =>
Nested.Dao.personAddress(quillColumns(personAddressNested), productArgs.keyValues)
),
)
RootResolver(
Queries(personAddressNested =>
(productArgs => Nested.Dao.personAddress(quillColumns(personAddressNested), productArgs.keyValues))
)
)
)

"Caliban integration should work for nested object" - {
"with no top-level filter" in {
Expand Down Expand Up @@ -115,7 +117,9 @@ class CalibanIntegrationNestedSpec extends CalibanSpec {
}
}
}"""
unsafeRunQuery(query) mustEqual """{"personAddressNested":[{"id":1,"age":44,"name":{"first":"One","last":"A"}}]}"""
unsafeRunQuery(
query
) mustEqual """{"personAddressNested":[{"id":1,"age":44,"name":{"first":"One","last":"A"}}]}"""
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,32 +17,31 @@ class CalibanIntegrationSpec extends CalibanSpec {
object Dao {
def personAddress(columns: List[String], filters: Map[String, String]): ZIO[Any, Throwable, List[PersonAddress]] =
Ctx.run {
query[PersonT].leftJoin(query[AddressT]).on((p, a) => p.id == a.ownerId)
query[PersonT]
.leftJoin(query[AddressT])
.on((p, a) => p.id == a.ownerId)
.map((p, a) => PersonAddress(p.id, p.first, p.last, p.age, a.map(_.street)))
.filterByKeys(filters)
//.filterColumns(columns) // //
.filterByKeys(filters)
// .filterColumns(columns) // //
.take(10)
}.provideLayer(zioDS).tap(list => {
}.provideLayer(zioDS).tap { list =>
println(s"Results: $list for columns: $columns")
ZIO.unit
})
}
}
}

case class Queries(
personAddressFlat: Field => (ProductArgs[FlatSchema.PersonAddress] => Task[List[FlatSchema.PersonAddress]]),
personAddressFlat: Field => (ProductArgs[FlatSchema.PersonAddress] => Task[List[FlatSchema.PersonAddress]])
)

val api = graphQL(
RootResolver(
Queries(
personAddressFlat =>
(productArgs =>
Flat.Dao.personAddress(quillColumns(personAddressFlat), productArgs.keyValues)
)
)
RootResolver(
Queries(personAddressFlat =>
(productArgs => Flat.Dao.personAddress(quillColumns(personAddressFlat), productArgs.keyValues))
)
)
)

"Caliban integration should work for flat object" - {
"with no filters" in {
Expand Down Expand Up @@ -82,4 +81,4 @@ class CalibanIntegrationSpec extends CalibanSpec {
unsafeRunQuery(query) mustEqual """{"personAddressFlat":[{"id":1,"last":"A","street":"123 St"}]}"""
}
}
}
}
14 changes: 6 additions & 8 deletions quill-caliban/src/test/scala/io/getquill/CalibanSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,10 @@ trait CalibanSpec extends AnyFreeSpec with Matchers with BeforeAndAfterAll {
override def beforeAll() = {
import FlatSchema._
(for { //
_ <- Ctx.run(sql"TRUNCATE TABLE AddressT, PersonT RESTART IDENTITY".as[Delete[PersonT]])
_ <- Ctx.run(liftQuery(ExampleData.people).foreach(row => query[PersonT].insertValue(row)))
_ <- Ctx.run(liftQuery(ExampleData.addresses).foreach(row => query[AddressT].insertValue(row)))
} yield ()
).provideLayer(zioDS).unsafeRunSync()
_ <- Ctx.run(sql"TRUNCATE TABLE AddressT, PersonT RESTART IDENTITY".as[Delete[PersonT]])
_ <- Ctx.run(liftQuery(ExampleData.people).foreach(row => query[PersonT].insertValue(row)))
_ <- Ctx.run(liftQuery(ExampleData.addresses).foreach(row => query[AddressT].insertValue(row)))
} yield ()).provideLayer(zioDS).unsafeRunSync()
}

// override def afterAll() = {
Expand All @@ -45,8 +44,7 @@ trait CalibanSpec extends AnyFreeSpec with Matchers with BeforeAndAfterAll {
(for {
interpreter <- api.interpreter
result <- interpreter.execute(queryString)
} yield (result)
).tapError{ e =>
} yield (result)).tapError { e =>
fail("GraphQL Validation Error", e)
ZIO.unit
}.unsafeRunSync()
Expand All @@ -56,4 +54,4 @@ trait CalibanSpec extends AnyFreeSpec with Matchers with BeforeAndAfterAll {
else
output.data.toString
} // end unsafeRunQuery
}
}
7 changes: 4 additions & 3 deletions quill-caliban/src/test/scala/io/getquill/Schema.scala
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ object FlatSchema {
List(
PersonAddress(1, "One", "A", 44, Some("123 St")),
PersonAddress(2, "Two", "B", 55, Some("123 St")),
PersonAddress(3, "Three", "C", 66, None),
PersonAddress(3, "Three", "C", 66, None)
)
}
}
Expand All @@ -47,6 +47,7 @@ object NestedSchema {
List(
PersonAddressNested(1, Name("One", "A"), 44, Some("123 St")),
PersonAddressNested(2, Name("Two", "B"), 55, Some("123 St")),
PersonAddressNested(3, Name("Three", "C"), 66, None),
) }
PersonAddressNested(3, Name("Three", "C"), 66, None)
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import io.getquill.context.qzio.ImplicitSyntax._
import io.getquill.context.ZioJdbc._
import io.getquill.util.LoadConfig
import zio.Console.printLine
import zio.{ ZIOApp, ExitCode, URIO, Task }
import zio.{ZIOApp, ExitCode, URIO, Task}
import java.io.Closeable
import javax.sql.DataSource

Expand All @@ -23,40 +23,41 @@ import io.getquill.util.ContextLogger
import io.getquill
import io.getquill.FlatSchema._


object Dao {
case class PersonAddressPlanQuery(plan: String, pa: List[PersonAddress])
private val logger = ContextLogger(classOf[Dao.type])

object Ctx extends PostgresZioJdbcContext(Literal)
import Ctx._
lazy val ds = JdbcContextConfig(LoadConfig("testPostgresDB")).dataSource
lazy val ds = JdbcContextConfig(LoadConfig("testPostgresDB")).dataSource
given Implicit[DataSource] = Implicit(ds)

inline def q(inline columns: List[String], inline filters: Map[String, String]) =
quote {
query[PersonT].leftJoin(query[AddressT]).on((p, a) => p.id == a.ownerId)
query[PersonT]
.leftJoin(query[AddressT])
.on((p, a) => p.id == a.ownerId)
.map((p, a) => PersonAddress(p.id, p.first, p.last, p.age, a.map(_.street)))
.filterColumns(columns)
.filterByKeys(filters)
.take(10)
}
inline def plan(inline columns: List[String], inline filters: Map[String, String]) =
quote { sql"EXPLAIN ${q(columns, filters)}".pure.as[Query[String]] }
quote(sql"EXPLAIN ${q(columns, filters)}".pure.as[Query[String]])

def personAddress(columns: List[String], filters: Map[String, String]) = {
println(s"Getting columns: $columns")
run(q(columns, filters)).implicitDS.mapError(e => {
run(q(columns, filters)).implicitDS.mapError { e =>
logger.underlying.error("personAddress query failed", e)
e
})
}
}

def personAddressPlan(columns: List[String], filters: Map[String, String]) =
run(plan(columns, filters), OuterSelectWrap.Never).map(_.mkString("\n")).implicitDS.mapError(e => {
run(plan(columns, filters), OuterSelectWrap.Never).map(_.mkString("\n")).implicitDS.mapError { e =>
logger.underlying.error("personAddressPlan query failed", e)
e
})
}

def resetDatabase() =
(for {
Expand All @@ -69,42 +70,39 @@ object Dao {
object CalibanExample extends zio.ZIOAppDefault {

case class Queries(
personAddress: Field => (ProductArgs[PersonAddress] => Task[List[PersonAddress]]),
personAddressPlan: Field => (ProductArgs[PersonAddress] => Task[Dao.PersonAddressPlanQuery])
personAddress: Field => (ProductArgs[PersonAddress] => Task[List[PersonAddress]]),
personAddressPlan: Field => (ProductArgs[PersonAddress] => Task[Dao.PersonAddressPlanQuery])
)

val endpoints =
graphQL(
graphQL(
RootResolver(
Queries(
personAddress =>
(productArgs =>
Dao.personAddress(quillColumns(personAddress), productArgs.keyValues)
),
personAddress => (productArgs => Dao.personAddress(quillColumns(personAddress), productArgs.keyValues)),
personAddressPlan =>
(productArgs => {
val cols = quillColumns(personAddressPlan)
(Dao.personAddressPlan(cols, productArgs.keyValues) zip Dao.personAddress(cols, productArgs.keyValues)).map(
(pa, plan) => Dao.PersonAddressPlanQuery(pa, plan)
)
(Dao.personAddressPlan(cols, productArgs.keyValues) zip Dao.personAddress(cols, productArgs.keyValues))
.map((pa, plan) => Dao.PersonAddressPlanQuery(pa, plan))
})
)
)
).interpreter

val myApp = for {
_ <- Dao.resetDatabase()
_ <- Dao.resetDatabase()
interpreter <- endpoints
_ <- Server.start(
port = 8088,
http = Http.collectHttp[Request] { case _ -> !! / "api" / "graphql" =>
ZHttpAdapter.makeHttpService(interpreter)
}
)
.forever
_ <- Server
.start(
port = 8088,
http = Http.collectHttp[Request] { case _ -> !! / "api" / "graphql" =>
ZHttpAdapter.makeHttpService(interpreter)
}
)
.forever
} yield ()

override def run =
myApp.exitCode

} // end CalibanExample
} // end CalibanExample
Loading

0 comments on commit 9ec9798

Please sign in to comment.