Skip to content

Instantly share code, notes, and snippets.

@Daenyth
Created June 2, 2022 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Daenyth/80031aca2ac084243d8423148396e791 to your computer and use it in GitHub Desktop.
Save Daenyth/80031aca2ac084243d8423148396e791 to your computer and use it in GitHub Desktop.
Slick utils
import cats.{Contravariant, Functor, Semigroupal}
import slick.jdbc.{
GetResult,
PositionedParameters,
PositionedResult,
SetParameter
}
trait RawSqlInstances {
implicit val getResultInstance
: Functor[GetResult] with Semigroupal[GetResult] =
new Functor[GetResult] with Semigroupal[GetResult] {
override def map[A, B](getA: GetResult[A])(f: A => B): GetResult[B] =
getA.andThen(f)
override def product[A, B](
fa: GetResult[A],
fb: GetResult[B]
): GetResult[(A, B)] = GetResult.createGetTuple2(fa, fb)
}
implicit val setParameterInstance
: Contravariant[SetParameter] with Semigroupal[SetParameter] =
new Contravariant[SetParameter] with Semigroupal[SetParameter] {
override def contramap[A, B](
setA: SetParameter[A]
)(f: B => A): SetParameter[B] =
(b: B, pp: PositionedParameters) => setA(f(b), pp)
override def product[A, B](
fa: SetParameter[A],
fb: SetParameter[B]
): SetParameter[(A, B)] =
SetParameter.createSetTuple2[A, B](fa, fb)
}
}
object RawSqlInstances extends RawSqlInstances
import cats.Monoid
import slick.jdbc.{PositionedParameters, SQLActionBuilder, SetParameter}
trait SQLActionBuilderInstances {
implicit final val catsMonoidForSQLActionBuilder: Monoid[SQLActionBuilder] =
new Monoid[SQLActionBuilder] {
override val empty = SQLActionBuilder(Vector.empty, SetParameter.SetUnit)
override def combine(
x: SQLActionBuilder,
y: SQLActionBuilder
): SQLActionBuilder =
// toVector to avoid List.++ on x.queryParts
SQLActionBuilder(x.queryParts.toVector ++ y.queryParts.toVector,
(p: Unit, pp: PositionedParameters) => {
x.unitPConv.apply(p, pp)
y.unitPConv.apply(p, pp)
})
}
implicit final class SQLActionBuilderOps(a: SQLActionBuilder) {
def ++(b: SQLActionBuilder): SQLActionBuilder =
Monoid[SQLActionBuilder].combine(a, b)
}
}
object SQLActionBuilderInstances extends SQLActionBuilderInstances
@Daenyth
Copy link
Author

Daenyth commented Jun 30, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment