Scalatra / Slick and insert IF NOT EXISTS

2019-02-21 22:10发布

I am a newbie so hoping for some patience. :)

I am trying to populate two tables if a value does not exist. Basically I have:

TABLE b
(
    id VARCHAR(254) PRIMARY KEY NOT NULL
);


TABLE d
(
    id VARCHAR(254) PRIMARY KEY NOT NULL,
    relay INT NOT NULL,
    FOREIGN KEY ( relay ) REFERENCES b ( id )
);

so I am trying to write a function that populates the two tables with a new value, if it doesn't exist, or ignores it otherwise... of course wrapped in a transaction:

IF (NOT EXISTS(SELECT * FROM b where id='something'))
    insert into b values('something')
    insert into d values(1, 'something')
END

What is the most efficient way of achieving something like this? If it matters I'm using POstgreSQL 9.1 but I'd like to keep it fairly generic.

(EDIT) These are my current table defs (simplified for illustration purposes):

object d extends Table[(String, String, Int)]("d")
{
  def id=column[String]("id", O.PrimaryKey)

  def relay=column[Int]("relay")
  def relay_ref=foreignKey("d2b.fk", relay, b)(_.id)
  def * = id ~ relay
}
object b extends Table[(String)]("b")
{
  def id=column[String]("id", O.PrimaryKey)
  def * = id
}

1条回答
干净又极端
2楼-- · 2019-02-21 22:42

In Slick 1.0.1

db.withTransaction{ implicit session : Session =>
  if( ! Query(b).filter(_.id==="something").exists.run ){
    b.insert( "something" )
    d.insert( (1,"something") )
  }
}

In Slick 2.0

val b = TableQuery[b]
db.withTransaction{ implicit session =>
  if( ! b.filter(_.id==="something").exists.run ){
    b += "something"
    d += (1,"something")
  }
}
查看更多
登录 后发表回答