Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add an extension module for Doobie #149

Merged
merged 4 commits into from
Mar 29, 2019
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
22 changes: 20 additions & 2 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -216,8 +216,8 @@ lazy val cron4sJVM = (project in file(".jvm"))
.settings(commonJvmSettings)
.settings(consoleSettings)
.settings(publishSettings)
.aggregate(coreJVM, joda, circeJVM, declineJVM, testkitJVM, testsJVM)
.dependsOn(coreJVM, joda, circeJVM, declineJVM, testkitJVM, testsJVM % Test)
.aggregate(coreJVM, joda, doobie, circeJVM, declineJVM, testkitJVM, testsJVM)
.dependsOn(coreJVM, joda, doobie, circeJVM, declineJVM, testkitJVM, testsJVM % Test)

lazy val docs = project
.enablePlugins(MicrositesPlugin, ScalaUnidocPlugin, GhpagesPlugin)
Expand Down Expand Up @@ -292,6 +292,7 @@ lazy val bench = (project in file("bench"))
)
.settings(commonSettings)
.settings(noPublishSettings)
.settings(commonJvmSettings)
.enablePlugins(JmhPlugin)
.dependsOn(coreJVM)

Expand Down Expand Up @@ -335,6 +336,8 @@ lazy val circe = (crossProject(JSPlatform, JVMPlatform).crossType(CrossType.Pure
.settings(publishSettings)
.settings(Dependencies.circe)
.settings(mimaSettings("circe", Set("0.5.0")))
.jvmSettings(commonJvmSettings)
.jsSettings(commonJsSettings)
.dependsOn(core, testkit % Test)

lazy val circeJVM = circe.jvm
Expand All @@ -350,11 +353,26 @@ lazy val decline = (crossProject(JSPlatform, JVMPlatform).crossType(CrossType.Pu
.settings(publishSettings)
.settings(Dependencies.decline)
.settings(mimaSettings("decline", Set("0.5.0")))
.jvmSettings(commonJvmSettings)
.jsSettings(commonJsSettings)
.dependsOn(core, testkit % Test)

lazy val declineJVM = decline.jvm
lazy val declineJS = decline.js

lazy val doobie = (project in file("modules/doobie"))
.enablePlugins(AutomateHeaderPlugin, ScalafmtPlugin)
.settings(
name := "doobie",
moduleName := "cron4s-doobie"
)
.settings(commonSettings)
.settings(publishSettings)
.settings(commonJvmSettings)
.settings(mimaSettings("doobie", Set()))
.settings(Dependencies.doobie)
.dependsOn(coreJVM, testkitJVM % Test)

// Utility command aliases

addCommandAlias("testJVM", "cron4sJVM/test")
Expand Down
42 changes: 41 additions & 1 deletion docs/src/main/tut/userguide/extensions.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,44 @@ Now you can define options based on cron expressions:

```tut:book
val cronOpt = Opts.option[CronExpr]("frequency", "A cron expression")
```
```

### Doobie

The [`doobie`](https://tpolecat.github.io/doobie/) module adds support for reading and writing `CronExpr` to a database via JDBC. Since JDBC is a JVM-only concept this module can not be used with non-JVM targets. To use it, add the corresponding dependency to your project in SBT:

```
libraryDependencies += "com.github.alonsodomin.cron4s" %% "cron4s-doobie" % "x.y.z"
```

And now you will need some imports:

```tut:silent
import cron4s.CronExpr
import cron4s.doobie._
import doobie._
import doobie.implicits._
```

Now define a case class that represents your database data (and which should contain a cron expression):

```tut:book
case class MeetingId(value: Long) extends AnyVal
case class RecurringMeeting(subject: String, description: String, frequency: CronExpr)
```

With this, you now are capable of writing read and write queries for that given data structure:

```tut:book
def loadAllMeetings =
sql"select subject, description, frequency from meetings"
.query[RecurringMeeting]
.to[List]

def updateMeetingFrequency(meetingId: MeetingId, freq: CronExpr) =
sql"update meetings set frequency = $freq where meetingId = ${meetingId.value}"
.update
.quick
```

For more information, go to [Doobie's User Guide](https://tpolecat.github.io/doobie/docs/01-Introduction.html).
39 changes: 39 additions & 0 deletions modules/doobie/src/main/scala/cron4s/doobie/package.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* Copyright 2017 Antonio Alonso Dominguez
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package cron4s

import _root_.doobie.{Meta, Read, Write}
import _root_.doobie.util.invariant.SecondaryValidationFailed

package object doobie {

implicit val cronExprMeta: Meta[CronExpr] =
Meta[String].imap(parseOrException)(_.toString)

implicit val cronExprWrite: Write[CronExpr] =
Write[String].contramap(_.toString)

implicit val cronExprRead: Read[CronExpr] =
Read[String].map(parseOrException)

private def parseOrException(str: String): CronExpr =
Cron.parse(str) match {
case Right(expr) => expr
case Left(err) => throw new SecondaryValidationFailed[CronExpr](err.getMessage)
}

}
89 changes: 89 additions & 0 deletions modules/doobie/src/test/scala/cron4s/doobie/DoobieSpec.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
* Copyright 2017 Antonio Alonso Dominguez
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package cron4s
package doobie

import cats.effect.{IO, ContextShift}

import _root_.doobie._
import _root_.doobie.implicits._
import _root_.doobie.util.invariant._

import org.scalatest._

import scala.concurrent.ExecutionContext

class DoobieSpec extends FlatSpec with Matchers {
implicit val contextShift: ContextShift[IO] =
IO.contextShift(ExecutionContext.global)

val xa = Transactor.fromDriverManager[IO](
"org.h2.Driver",
"jdbc:h2:mem:refined;DB_CLOSE_DELAY=-1",
"sa",
""
)

def insertMeeting(meeting: Meeting) = {
val createTable = sql"""
create table meeting(
meeting_id BIGINT AUTO_INCREMENT PRIMARY KEY,
subject VARCHAR(255) NOT NULL,
description VARCHAR(255) NOT NULL,
frequency VARCHAR(255) NOT NULL
)
"""

val insertRecord = sql"""
insert into meeting(subject, description, frequency)
values(${meeting.subject}, ${meeting.description}, ${meeting.frequency})
"""

for {
_ <- createTable.update.run
id <- insertRecord.update.withUniqueGeneratedKeys[Long]("meeting_id")
} yield MeetingId(id)
}

def loadMeeting(meetingId: MeetingId) =
sql"select subject, description, frequency from meeting where meeting_id = $meetingId"
.query[Meeting]
.unique

"Doobie" should "store and retrieve a cron expression as a member of a storable data structure" in {
val standUpMeeting = Meeting(
"Daily stand-up",
"Daily team morning stand-up meeting",
cron"0 0 10 ? * mon-fri"
)

val tx = for {
meetingId <- insertMeeting(standUpMeeting)
loaded <- loadMeeting(meetingId)
} yield loaded

val loadedMeeting = tx.transact(xa).unsafeRunSync()
loadedMeeting shouldBe standUpMeeting
}

it should "throw a SecondaryValidationFailed in case the cron expression is invalid" in {
assertThrows[SecondaryValidationFailed[CronExpr]] {
sql"select '0- 0 30 * * ?'".query[CronExpr].unique.transact(xa).unsafeRunSync()
}
}

}
21 changes: 21 additions & 0 deletions modules/doobie/src/test/scala/cron4s/doobie/model.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
* Copyright 2017 Antonio Alonso Dominguez
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package cron4s
package doobie

final case class MeetingId(value: Long) extends AnyVal
final case class Meeting(subject: String, description: String, frequency: CronExpr)
8 changes: 8 additions & 0 deletions project/Dependencies.scala
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ object Dependencies {
val decline = "0.6.2"
val circe = "0.11.1"
val parser = "1.1.1"
val doobie = "0.6.0"

val jodaTime = "2.10.1"
val jodaConvert = "2.2.0"
Expand Down Expand Up @@ -102,4 +103,11 @@ object Dependencies {
libraryDependencies += "com.monovore" %%% "decline" % version.decline
)

lazy val doobie = Def.settings(
libraryDependencies ++= Seq(
"org.tpolecat" %% "doobie-core" % version.doobie,
"org.tpolecat" %% "doobie-h2" % version.doobie % Test
)
)

}