Permalink
Browse files

Fixing tminglei/slick-pg#288 and slick/slick#966

  • Loading branch information...
1 parent 62f01f3 commit 5dd4f31f2ea7fbb5de02589202c0933911aa9995 @tminglei tminglei committed Jul 6, 2016
@@ -136,6 +136,28 @@ class InsertTest extends AsyncTest[JdbcTestDB] {
} yield ()
}
+ def testInsertOrUpdatePlainWithFuncDefinedPK = {
+ class T(tag: Tag) extends Table[(Int, String)](tag, "t_merge3") {
+ def id = column[Int]("id")
+ def name = column[String]("name")
+ def * = (id, name)
+ def ins = (id, name)
+ def pk = primaryKey("t_merge_pk_a", id)
+ }
+ val ts = TableQuery[T]
+
+ val upsertSql = tdb.profile.compileInsert(ts.toNode).upsert.sql
+ println(s">>> upsert sql: $upsertSql")
+
+ for {
+ _ <- ts.schema.create
+ _ <- ts ++= Seq((1, "a"), (2, "b"))
+ _ <- ts.insertOrUpdate((3, "c")).map(_ shouldBe 1)
+ _ <- ts.insertOrUpdate((1, "d")).map(_ shouldBe 1)
+ _ <- ts.sortBy(_.id).result.map(_ shouldBe Seq((1, "d"), (2, "b"), (3, "c")))
+ } yield ()
+ }
+
def testInsertOrUpdateAutoInc = {
class T(tag: Tag) extends Table[(Int, String)](tag, "T_MERGE2") {
def id = column[Int]("ID", O.AutoInc, O.PrimaryKey)
@@ -529,7 +529,13 @@ trait JdbcStatementBuilderComponent { self: JdbcProfile =>
/** Builder for upsert statements, builds standard SQL MERGE statements by default. */
class UpsertBuilder(ins: Insert) extends InsertBuilder(ins) {
- protected lazy val (pkSyms, softSyms) = syms.toSeq.partition(_.options.contains(ColumnOption.PrimaryKey))
+ /* NOTE: pk defined by using method `primaryKey` and pk defined with `PrimaryKey` can only have one,
+ here we let table ddl to help us ensure this. */
+ private lazy val funcDefinedPKs = table.profileTable.asInstanceOf[Table[_]].primaryKeys
+ protected lazy val (pkSyms, softSyms) = syms.toSeq.partition { sym =>
+ sym.options.contains(ColumnOption.PrimaryKey) || funcDefinedPKs.exists(pk => pk.columns.collect {
+ case Select(_, f: FieldSymbol) => f
+ }.exists(_.name == sym.name)) }
protected lazy val pkNames = pkSyms.map { fs => quoteIdentifier(fs.name) }
protected lazy val softNames = softSyms.map { fs => quoteIdentifier(fs.name) }
protected lazy val nonAutoIncSyms = syms.filter(s => !(s.options contains ColumnOption.AutoInc))

0 comments on commit 5dd4f31

Please sign in to comment.