我将以下10行Python代码移植到Scala:
import psycopg2
def execute(user, password, database, host, port, *queries):
connection = psycopg2.connect(user=user, password=password, host=host, port=port, database=database)
cursor = connection.cursor()
for sql in queries:
print(sql)
cursor.execute(sql)
connection.commit()
cursor.close()
connection.close()
我有以下等效的Scala代码:
def execute(user: String, password: String, database: String, host: String, port: Int, queries: String*): Unit = {
???
}
我想针对数据库(假设它是Postgres)在单个事务中执行(并打印)一堆SQL语句。
如何使用doobie来做到这一点?
注意:
我无法将接口更改为execute()
(包括无法添加类型或隐式参数)。它必须输入字符串用户名,密码等以及一个queries: String*
的变量,从而使接口与Python相同。
也请提及所有需要的进口商品
答案 0 :(得分:1)
您可以使用理解力在doobie的一个事务中运行多个查询,例如:
val query = for {
_ <- sql"insert into person (name, age) values ($name, $age)".update.run
id <- sql"select lastval()".query[Long].unique
} yield p
但是这种解决方案不适用于您的情况,因为您拥有动态查询列表。幸运的是,我们可以在猫中使用traverse:
import cats.effect.ContextShift
import doobie._
import doobie.implicits._
import cats.effect._
import scala.concurrent.ExecutionContext
import cats.implicits._
import cats._
import cats.data._
def execute(user: String, password: String, database: String, host: String, port: Int, queries: String*): Unit = {
//you can use other executor if you want
//it would be better to pass context shift as implicit argument to method
implicit val cs: ContextShift[IO] = IO.contextShift(ExecutionContext.global)
//let's create transactor
val xa = Transactor.fromDriverManager[IO](
"org.postgresql.Driver",
s"jdbc:postgresql://$host:$port/$database", //remember to change url or make it dynamic, if you run it agains another database
user,
password
)
val batch = queries
.toList //we need to change String* to list, since String* doesn't have necessary typeclass for Aplicative
.traverse(query => Update0(query, None).run) //we lift strings to Query0 and then run them, then we change List[ConnectionIO[Int]] to ConnectionIO[List[Int]]
//above can be done in two steps using map and sequence
batch //now we've got single ConnectionIO which will run in one transaction
.transact(xa) //let's make it IO[Int]
.unsafeRunSync() //we need to block since your method returns Unit
}
您的IDE可能会向您显示此代码无效,但这是正确的。 IDE只是无法处理Scala魔术。
您还可以考虑使用unsafeRunTimed
代替unsafeRunSync
来添加时间限制。
此外,请记住将postgresql driver for jdbc和cats添加到您的build.sbt
中。杜比在幕后使用猫,但我认为可能需要明确的依赖。
答案 1 :(得分:-1)
尝试仅对事务中的一个查询解决该问题,并查看该函数签名的外观。
然后看看如何从那里到达最终目的地。