-
Notifications
You must be signed in to change notification settings - Fork 157
/
NumericCodecs.scala
43 lines (33 loc) · 1.41 KB
/
NumericCodecs.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// Copyright (c) 2018-2021 by Rob Norris
// This software is licensed under the MIT License (MIT).
// For more information see LICENSE or https://opensource.org/licenses/MIT
package skunk.refined.codec
import eu.timepit.refined.boolean.And
import eu.timepit.refined.api.Validate
import skunk.Codec
import skunk.data.Type
import eu.timepit.refined._
import eu.timepit.refined.api.Refined
trait Scale[N]
trait Precision[N]
trait NumericCodecs {
def validateScale[N <: Int](n: Int): Validate.Plain[BigDecimal, Scale[N]] =
Validate.fromPredicate[BigDecimal, Scale[N]](
_.scale <= n, d => s"($d has scale ≤ $n)", new Scale[N] {})
def validatePrecision[N <: Int](n: Int): Validate.Plain[BigDecimal, Precision[N]] =
Validate.fromPredicate[BigDecimal, Precision[N]](
_.precision <= n, d => s"($d has precision ≤ $n)", new Precision[N] {})
implicit class NumericOps(num: Codec[BigDecimal]) {
def apply[S <: Int, P <: Int](precision: P, scale: S): Codec[BigDecimal Refined (Precision[P] And Scale[S])] = {
implicit val __s: Validate.Plain[BigDecimal, Scale[S]] = validateScale(scale)
implicit val __p: Validate.Plain[BigDecimal, Precision[P]] = validatePrecision(precision)
Codec.simple(
bd => bd.toString,
st => refineV[Precision[P] And Scale[S]](BigDecimal(st)),
Type.numeric
)
}
}
skunk.codec.numeric.numeric(3, 4)
}
object numeric extends NumericCodecs