Created
April 29, 2017 02:33
-
-
Save ukitaka/69e5080830bc4e8b0473ef5b6d74680f to your computer and use it in GitHub Desktop.
InsertIfNotExists.scala
This file contains 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
trait InsertIfNotExists[T <: AbstractTable[_]] { | |
val driver: JdbcProfile | |
import driver.api._ | |
val tableQuery: TableQuery[T] | |
def exists(e: T#TableElementType): Rep[Boolean] | |
def insertIfNotExists(e: T#TableElementType)(implicit executionContext: ExecutionContext): DBIO[Unit] = for { | |
ex <- exists(e).result | |
_ <- if(ex) DBIO.successful(()) else (tableQuery += e).map(_ => ()) | |
} yield () | |
} | |
import driver.api._ | |
trait InsertIfNotEmptyOps[T <: AbstractTable[_]] { | |
def insertIfNotExists(e: T#TableElementType): DBIO[Unit] | |
def insertIfNotExists(es: Seq[T#TableElementType]): DBIO[Unit] | |
def +=?(e: T#TableElementType): DBIO[Unit] | |
def ++=?(e: Seq[T#TableElementType]): DBIO[Unit] | |
} | |
implicit def upsertQuery[T <: AbstractTable[_]]( | |
tableQuery: TableQuery[T])(implicit u: InsertIfNotExists[T], ec: ExecutionContext) = | |
new InsertIfNotEmptyOps[T] { | |
def insertIfNotExists(e: T#TableElementType): DBIO[Unit] = u.insertIfNotExists(e) | |
def insertIfNotExists(es: Seq[T#TableElementType]): DBIO[Unit] = DBIO.sequence(es.map(insertIfNotExists)).map(_ => ()) | |
def +=?(e: T#TableElementType): DBIO[Unit] = insertIfNotExists(e) | |
def ++=?(es: Seq[T#TableElementType]): DBIO[Unit] = insertIfNotExists(es) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment