blob: bb8d322732472649e0598dc002b2e3305f837c9b (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
package xyz.driver.pdsuicommon.db
import java.io.Closeable
import java.util.concurrent.Executors
import javax.sql.DataSource
import io.getquill._
import xyz.driver.pdsuicommon.concurrent.MdcExecutionContext
import xyz.driver.pdsuicommon.db.PostgresContext.Settings
import xyz.driver.pdsuicommon.logging._
import scala.concurrent.ExecutionContext
import scala.util.control.NonFatal
import scala.util.{Failure, Success, Try}
object PostgresContext extends PhiLogging {
final case class Settings(connection: com.typesafe.config.Config,
connectionAttemptsOnStartup: Int,
threadPoolSize: Int)
def apply(settings: Settings): PostgresContext = {
// Prevent leaking credentials to a log
Try(JdbcContextConfig(settings.connection).dataSource) match {
case Success(dataSource) => new PostgresContext(dataSource, settings)
case Failure(NonFatal(e)) =>
logger.error(phi"Can not load dataSource, error: ${Unsafe(e.getClass.getName)}")
throw new IllegalArgumentException("Can not load dataSource from config. Check your database and config", e)
}
}
}
class PostgresContext(val dataSource: DataSource with Closeable, settings: Settings)
extends PostgresJdbcContext[SnakeCase](dataSource) with TransactionalContext {
private val tpe = Executors.newFixedThreadPool(settings.threadPoolSize)
implicit val executionContext: ExecutionContext = {
val orig = ExecutionContext.fromExecutor(tpe)
MdcExecutionContext.from(orig)
}
override def close(): Unit = {
super.close()
tpe.shutdownNow()
}
}
|