本文介绍了Scalatra / Slick并插入IF NOT EXISTS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我是一个新手,所以希望有一些耐心。 :)



如果值不存在,我试图填充两个表。基本上我有:

 表b 

id VARCHAR(254)PRIMARY KEY NOT NULL
);


表d

id VARCHAR(254)PRIMARY KEY NOT NULL,
relay INT NOT NULL,
FOREIGN KEY )参考文献b(id)
);

所以我试图写一个函数来填充两个表一个新的值,如果它不存在或忽略它当然包裹在一个事务中:

  IF(NOT EXISTS b其中id ='something'))
插入b值('something')
插入d值(1,'something')
END

最有效的方式是什么?如果它是重要的我使用POstgreSQL 9.1但我想保持它相当通用。



(EDIT)
这些是我当前的表defs用于说明):

  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
}
pre>

解决方案

在Slick 1.0.1中

 code> db.withTransaction {implicit session:Session => 
if(!Query(b).filter(_。id ===something)。exists.run){
b.insert(something)
d.insert (1,something))
}
}
  val b = TableQuery [b] 
db.withTransaction {implicit session =>
if(!b.filter(_。id ===something)。exists.run){
b + =something
d + =(1,something)
}
}


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
}
解决方案

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

这篇关于Scalatra / Slick并插入IF NOT EXISTS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 22:47