如何在 doobie 中配置 transactor?

How to configure transactor in doobie?

最近我开始学习 doobie,但我无法正确创建 hikari 事务处理程序。我正在使用 mysql、Intellij-Idea。

这是我的 build.sbt 文件

name := "doobie"
version := "0.1"
//scalaVersion := "2.13.1"
scalacOptions += "-Ypartial-unification" // 2.11.9+
libraryDependencies ++= {
  lazy val doobieVersion = "0.8.4"
  Seq(
    "org.tpolecat" %% "doobie-core"      % doobieVersion,
    "org.tpolecat"    %% "doobie-h2"            % doobieVersion,
    "org.tpolecat"    %% "doobie-hikari"        % doobieVersion,
    "org.tpolecat"    %% "doobie-quill"         % doobieVersion,
    "org.tpolecat"    %% "doobie-specs2"        % doobieVersion,
    "org.tpolecat"    %% "doobie-scalatest"     % doobieVersion   % "test",
    "mysql"           % "mysql-connector-java"  % "8.0.17",
    "org.slf4j"       % "slf4j-api"             % "1.7.5",
    "ch.qos.logback"  % "logback-classic"       % "1.0.9"
  )
}

resolvers ++= Seq(
  "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/"
)

这是我的 Connection.scala 文件

import cats.effect.IO
import com.zaxxer.hikari.{HikariConfig, HikariDataSource}
import doobie.hikari.HikariTransactor

trait Connection {

  val config = new HikariConfig()
  config.setJdbcUrl("jdbc:mysql://localhost:quill_demo")
  config.setUsername("admin")
  config.setPassword("password")
  config.setMaximumPoolSize(5)

  val transactor: IO[HikariTransactor[IO]] =
    IO.pure(HikariTransactor.apply[IO](new HikariDataSource(config)))

}

问题出在上面的文件中 IO.pure(HikariTransactor.apply[IO](new HikariDataSource(config))) 语句出错。这里最后一个闭合的括号中的 3 个给出了 3 个错误,如下所示。

No implicit arguments of type: ContextShift[IO]
Unspecified value parameters: connectEC: ExecutionContext, transactEC: ExecutionContext
No implicits found for parameter evidence: ContextShift[IO]

我只想知道如何正确执行此操作。

尝试添加以下导入和隐式

import scala.concurrent.ExecutionContext

implicit val cs = IO.contextShift(ExecutionContext.global)

我如下更改依赖的版本后,我可以解决所有错误。

name := "doobie"
version := "0.1"
//scalaVersion := "2.13.1"
scalacOptions += "-Ypartial-unification"
libraryDependencies ++= {
  lazy val doobieVersion = "0.5.4"
  Seq(
    "org.tpolecat" %% "doobie-core"      % doobieVersion,
    "org.tpolecat"    %% "doobie-h2"            % doobieVersion,
    "org.tpolecat"    %% "doobie-hikari"        % doobieVersion,
    "org.tpolecat"    %% "doobie-quill"         % doobieVersion,
    "org.tpolecat"    %% "doobie-specs2"        % doobieVersion,
    "org.tpolecat"    %% "doobie-scalatest"     % doobieVersion   % "test",
    "mysql"           % "mysql-connector-java"  % "5.1.34",
    "org.slf4j"       % "slf4j-api"             % "1.7.5",
    "ch.qos.logback"  % "logback-classic"       % "1.0.9"
  )
}

resolvers ++= Seq(
  "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/"
)