Last active
November 30, 2016 19:49
-
-
Save natewave/d023a28d461f29dd15a6cfeb10e836d8 to your computer and use it in GitHub Desktop.
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
def upsert[Pk, A](dbContext: DbContext[Pk, A], x: A): Query[Unit, Connection] = | |
queryBuilder.write { implicit connection => implicit ec => | |
val params = dbContext.params(x) | |
val keys = params.map(_.name) | |
val cols = keys.mkString("(", ",", ")") | |
val placeholders = keys.mkString("({", "},{", "})") | |
val values = keys.flatMap { key => | |
params.find(_.name == key).map(DbContext.anormNamedParameter) | |
} | |
Future { | |
SQL(s""" | |
INSERT INTO ${dbContext.table} $cols | |
VALUES $placeholders | |
""") | |
.on(values:_*) | |
.executeInsert() | |
}.recoverWith { case _: SQLException => | |
val conflictParams = | |
if(dbContext.conflictParams.nonEmpty) | |
params.filter(np => dbContext.conflictParams.contains(np.name)) | |
else | |
dbContext.pkParams(dbContext.pk(x)) | |
val whereClause = conflictParams.map(p => s"${p.name} = {${p.name}}").mkString(" AND ") | |
Future { | |
SQL( | |
s""" | |
UPDATE ${dbContext.table} | |
SET $cols = $placeholders | |
WHERE $whereClause | |
""") | |
.on(values: _*) | |
.executeUpdate() | |
} | |
}.map(_ => {}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment