Adds support for Refinement types to the Anorm database access layer for Scala.
Add the following to your build.sbt
:
libraryDependencies += "com.github.derekmorr" %% "refined-anorm" % "0.1"
refined-anorm
is available for Scala 2.11 and 2.12 for Anorm 2.5.
Add the following to Anorm models:
import refined.anorm._
Then you'll be able to serialize and deserialize refined types with JDBC.
For example:
/** 802.1Q Vlan ID */
type VlanId = Int Refined Interval.Closed[W.`0`.T, W.`4095`.T]
type NonBlankString = String Refined And[NonEmpty, Exists[Not[Whitespace]]]
case class Vlan(id: VlanId, name: NonBlankString)
object Vlan {
import refined.anorm._
val parser: RowParser[Vlan] = Macro.namedParser[Vlan]
def getById(id: VlanId)(implicit connection: Connection): Option[Vlan] = {
SQL"""SELECT id, name FROM vlans WHERE id = $id""".as(Vlan.parser.singleOpt)
}
def create(vlan: Vlan)(implicit connection: Connection): Boolean = {
SQL"""INSERT INTO vlans (id, name) VALUES (${vlan.id}, ${vlan.name})""".executeUpdate() == 1
}
}
There is a complete, working example in the integration tests (in src/it
).
To run unit tests, run
sbt test
To run the integration tests:
- Install a database (PostgreSQL is the default).
- Create a database named
refinement
. Grant a user read/write andcreate table
access to it. - Edit
src/it/resources/application.conf
: - Edit the
username
andpassword
fields - Adjust the database URL if necessary.
- Run
sbt it:test
To generate a code coverage report run,
sbt clean coverage test coverageReport
The HTML report will be written to target/scala-2.12/scoverage-report/index.html
.
The project uses the scapegoat tool for code quality analysis. Run run a scapegoat report, run
sbt scapegoat
The HTML report will be written to target/scala-2.12/scapegoat-report/scapegoat.html