Skip to content

Instantly share code, notes, and snippets.

@mather
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mather/72ab86a39b7866fe37d2 to your computer and use it in GitHub Desktop.
Save mather/72ab86a39b7866fe37d2 to your computer and use it in GitHub Desktop.
SlickでJDBCドライバを実行時に切り替えるメモ(ver. 2.x) ref: http://qiita.com/mather314/items/f3c1c465aa0b74f10236
trait DatabaseComponent { this: Profile =>
def database: profile.simple.Database
}
// テスト時
trait H2DatabaseComponent extends DatabaseComponent {
import profile.simple._
def database = Database.forURL("jdbc:h2:mem:test")
}
// 稼働時など
trait DbcpBasicDatabaseComponent extends DatabaseComponent {
import profile.simple._
 import org.apache.commons.dbcp2.BasicDataSource
def database = {
val ds = new BasicDataSource
ds.setDriverClassName(driverClassName)
// ...
Database.forDataSource(ds)
}
}
import scala.slick.driver.PostgresDriver.simple._
// データモデル
case class User(id: Int, name: String)
// テーブル定義
class UserTable(tag: Tag) extends Table[User](tag, "users") {
def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
def name = column[String]("name")
def * = (id, name) <> (User.tupled, User.unapply)
}
// クエリ実行オブジェクト
val Users = TableQuery[UserTable]
import scala.slick.driver.H2Driver.simple._
Database.forURL("jdbc:h2:mem:test", driver = "org.h2.Driver") withSession { implicit session =>
// 定義時とドライバが合わないのでコンパイルエラー
Users.insert(User(-1, "sample"))
}
JdbcProfile -> JdbcDriver(class) -> PostgresDriver(class), H2Driver(class), ...
JdbcDriver(object) PostgresDriver(object) H2Driver(object) ...
trait H2Profile extends Profile {
val profile = H2Driver
}
trait PostgresProfile extends Profile {
val profile = PostgresDriver
}
class SomeService { this: UserTableComponent =>
// UserTableの処理
}
// サービスクラスのインスタンス化
object SomeService extends SomeService with UserTableComponent with PostgresProfile
trait Profile {
def profile: JdbcProfile
def driverClassName: String
}
trait UserTableComponent { this: Profile =>
import profile.simple._
// UserTableの定義を内包
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment