Created
September 14, 2016 17:57
-
-
Save pathikrit/89c82a5fe1ae8bbd96803c50a03659ea to your computer and use it in GitHub Desktop.
Batched prepared statements
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.coatue.datascience.util | |
import java.sql.{Connection, PreparedStatement} | |
import com.typesafe.scalalogging.Logger | |
import org.slf4j.LoggerFactory | |
import slick.driver.PostgresDriver.api._ | |
class DbBatchedJob(db: Database, sql: String, batchSize: Int) extends AutoCloseable { | |
private[this] val logger = Logger(LoggerFactory.getLogger(this.getClass)) | |
private[this] var currentConnection: Connection = _ | |
private[this] var currentStatement: PreparedStatement = _ | |
private[this] var count = 0 | |
def +=[U](f: PreparedStatement => U) = synchronized { | |
if (count%batchSize == 0) { | |
currentConnection = db.createSession().conn | |
currentStatement = currentConnection.prepareStatement(sql) | |
} | |
count += 1 | |
f(currentStatement) | |
currentStatement.addBatch() | |
if (count%batchSize == 0) close() | |
} | |
override def close() = if (count > 0) { | |
val updates = currentStatement.executeBatch() | |
logger.info(s"Batch executed ${updates.sum} updates at count=$count") | |
currentStatement.close() | |
currentConnection.close() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment