Scalatra / Slick and insert IF NOT EXISTS

非 Y 不嫁゛ 提交于 2019-12-01 15:28: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:


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")
  }
}


来源:https://stackoverflow.com/questions/18864351/scalatra-slick-and-insert-if-not-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!