我正在用ScalikeJDBC实现一个流源,并需要它在多个DB类型上运行,包括。甲骨文、赛贝斯等
文档有点混乱,不确定这是否是一种选择:
目前,scalikejdbc-streams本机支持MySQL和PostgreSQL。通常使用SQL#iterator工厂方法时,ScalikeJDBC会自动启用所需的设置来使用游标功能。如果您不喜欢这种行为,则可以自定义调整DBSession属性
流读取可以通过MySQL和PostgreSQL以外的其他DB处理吗?
发布于 2017-08-14 22:29:05
(因为您的问题是关于创建流源的,所以这个答案只针对流支持的发行者端,而忽略了订阅方。)
对流的支持要求数据库一次返回几行查询结果,通常是基于游标,而不是一次全部返回。不同的数据库有不同的方法来启用这个功能。ScalikeJDBC本机支持为MySQL和PostgreSQL驱动程序使用流iterator方法。也就是说,使用MySQL和PostgreSQL驱动程序,可以实现以下工作:
import scalikejdbc._
import scalikejdbc.streams._
// set up a connection pool
import scala.concurrent.ExecutionContext.Implicits.global
val publisher: DatabasePublisher[Int] = DB.readOnlyStream {
sql"select id from users order by id".map(r => r.get[Int]("id")).iterator
}以上工作是针对MySQL和PostgreSQL的,因为这的存在。
/**
* Forcibly changes the database session to be cursor query ready.
*/
val defaultDBSessionForceAdjuster: DBSessionForceAdjuster = (session) => {
// setup required settings to enable cursor operations
session.connectionAttributes.driverName match {
case Some(driver) if driver == "com.mysql.jdbc.Driver" && session.fetchSize.exists(_ > 0) =>
/*
* MySQL - https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-implementation-notes.html
*
* StreamAction.StreamingInvoker prepares the following required settings in advance:
*
* - java.sql.ResultSet.TYPE_FORWARD_ONLY
* - java.sql.ResultSet.CONCUR_READ_ONLY
*
* If the fetchSize is set as 0 or less, we need to forcibly change the value with the Int min value.
*/
session.fetchSize(Int.MinValue)
case Some(driver) if driver == "org.postgresql.Driver" =>
/*
* PostgreSQL - https://jdbc.postgresql.org/documentation/94/query.html
*
* - java.sql.Connection#autocommit false
* - java.sql.ResultSet.TYPE_FORWARD_ONLY
*/
session.conn.setAutoCommit(false)
case _ =>
}
}注意,最后一个case子句意味着ScalikeJDBC在默认情况下不支持除了MySQL和PostgreSQL驱动程序以外的其他驱动程序的流iterator。
这并不意味着不能使用其他驱动程序进行流处理。您引用的文档部分有以下代码示例:
val publisher: DatabasePublisher[Int] = DB readOnlyStream {
sql"select id from users".map(r => r.int("id"))
.iterator
.withDBSessionForceAdjuster(session => {
session.conn.setAutoCommit(true)
})
}文档的意思是,要为MySQL和PostgreSQL以外的数据库启用流,您需要自定义DBSession属性,如上面的示例所示,这样就可以启用游标支持。这种定制到底需要什么(例如,调整fetchSize或禁用连接上的autoCommit ),取决于驱动程序(假设驱动程序支持每次检索查询结果-少量行)。
https://stackoverflow.com/questions/45462001
复制相似问题