Scala Slick:有关groupBy和缺少形状的问题

时间:2013-06-07 01:02:49

标签: scala slick

我正在尝试使用Slick来查询多对多关系,但我遇到了各种各样的错误,最突出的是“不知道如何解压缩(用户,技能)到T并包装到G“。

表的结构类似于以下内容:

case class User(val name: String, val picture: Option[URL], val id: Option[UUID])
object Users extends Table[User]("users") {
  def name = column[String]("name")
  def picture = column[Option[URL]]("picture")
  def id = column[UUID]("id")
  def * = name ~ picture ~ id.? <> (User, User.unapply _)
}

case class Skill(val name: String, val id: Option[UUID])
object Skills extends Table[Skill]("skill") {
  def name = column[String]("name")
  def id = column[UUID]("id")
  def * = name ~ id.? <> (Skill, Skill.unapply _)
}

case class UserSkill(val userId: UUID, val skillId: UUID, val id: Option[UUID])
object UserSkills extends Table[UserSkill]("user_skill") {
  def userId = column[UUID]("userId")
  def skillId = column[UUID]("skillId")
  def id = column[UUID]("id")
  def * = userId ~ skillId ~ id.? <> (UserSkill, UserSkill.unapply _)
  def user = foreignKey("userFK", userId, Users)(_.id)
  def skill = foreignKey("skillFK", skillId, Skills)(_.id)
}

最终,我想要实现的是

形式
SELECT u.*, group_concat(s.name) FROM user_skill us, users u, skills s WHERE us.skillId = s.id && us.userId = u.id GROUP BY u.id

但在我花时间尝试让group_concat工作之前,我一直在尝试生成更简单的查询(我相信它仍然有效......)

SELECT u.* FROM user_skill us, users u, skills s WHERE us.skillId = s.id && us.userId = u.id GROUP BY u.id

我尝试了各种scala代码来生成此查询,但是导致上述形状错误的示例是

(for {
  us <- UserSkills
  user <- us.user
  skill <- us.skill
} yield (user, skill)).groupBy(_._1.id).map { case(_, xs) => xs.first }

类似地,以下产生关于“用户”而不是“(用户,技能)”

的打包错误
(for {
  us <- UserSkills
  user <- us.user
  skill <- us.skill
} yield (user, skill)).groupBy(_._1.id).map { case(_, xs) => xs.map(_._1).first }

如果有人有任何建议,我将非常感激:我已经花了大部分时间和昨天搜索google / google群组以及光滑的来源,但我还没有解决方案。

(另外,我正在使用postgre,所以group_concat实际上是string_agg)

修改

因此,当使用groupBy时,似乎应用了映射投影,因为类似

(for {
  us <- UserSkills
  u   <- us.user
  s   <- us.skill
} yield (u,s)).map(_._1)

工作正常,因为_._ 1给出了类型Users,它有一个Shape,因为Users是一个表。但是,当我们调用xs.first时(就像我们调用groupBy时那样),我们实际上会返回一个映射投影类型(User,Skill),或者如果我们先应用map(_._ 1),我们会得到User类型,这不是用户!据我所知,没有使用User作为混合类型的形状,因为定义的唯一形状是Shape [Column [T],T,Column [T]]和表T&lt;:TableNode,Shape [ T,NothingContainer#TableNothing,T]在slick.lifted.Shape中定义。此外,如果我做了像

这样的事情
(for {
  us <- UserSkills
  u   <- us.user
  s   <- us.skill
} yield (u,s))
  .groupBy(_._1.id)
  .map { case (_, xs) => xs.map(_._1.id).first }

我收到“NoSuchElementException:key not found:@ 1515100893”形式的奇怪错误,其中数字键值每次都会更改。这不是我想要的查询,但这是一个奇怪的问题。

2 个答案:

答案 0 :(得分:1)

我也遇到了类似的情况。虽然我喜欢使用Scala和Slick,但我确实相信有时候在数据库本身中反对异常化对象并将Slick Table链接到视图更容易。

例如,我有一个具有Tree对象的应用程序,该对象被规范化为多个数据库表。由于我对SQL很满意,我认为它比编写简单的Scala Slick查询更简洁。 Scala代码:

case class DbGFolder(id: String,
                     eTag: String,
                     url: String,
                     iconUrl: String,
                     title: String,
                     owner: String,
                     parents: Option[String],
                     children: Option[String],
                     scions: Option[String],
                     created: LocalDateTime,
                     modified: LocalDateTime)
object DbGFolders extends Table[DbGFolder]("gfolder_view") {
  def id = column[String]("id")
  def eTag = column[String]("e_tag")
  def url = column[String]("url")
  def iconUrl = column[String]("icon_url")
  def title = column[String]("title")
  def owner = column[String]("file_owner")
  def parents = column[String]("parent_str")
  def children = column[String]("child_str")
  def scions = column[String]("scion_str")
  def created = column[LocalDateTime]("created")
  def modified = column[LocalDateTime]("modified")
  def * = id ~ eTag ~ url ~ iconUrl ~ title ~ owner ~ parents.? ~
          children.? ~ scions.? ~ created ~ modified <> (DbGFolder, DbGFolder.unapply _)

  def findAll(implicit s: Session): List[GFolder] = {
    Query(DbGFolders).list().map {v =>
      GFolder(id = v.id,
              eTag = v.eTag,
              url = v.url,
              iconUrl = v.iconUrl,
              title = v.title,
              owner = v.owner,
              parents = v.parents.map { parentStr =>
                parentStr.split(",").toSet }.getOrElse(Set()),
              children = v.children.map{ childStr =>
                childStr.split(",").toSet }.getOrElse(Set()),
              scions = v.scions.map { scionStr =>
                scionStr.split(",").toSet }.getOrElse(Set()),
              created = v.created,
              modified = v.modified)
    }
  }
}

基础(postgres)观点:

CREATE VIEW scion_view AS
    WITH RECURSIVE scions(id, scion) AS (
      SELECT c.id, c.child
      FROM children AS c
      UNION ALL
      SELECT s.id, c.child
      FROM children AS c, scions AS s
      WHERE c.id = s.scion)
    SELECT * FROM scions ORDER BY id, scion;    

CREATE VIEW gfolder_view AS
  SELECT
    f.id, f.e_tag, f.url, f.icon_url, f.title, m.name, f.file_owner,
    p.parent_str, c.child_str, s.scion_str, f.created, f.modified
  FROM
    gfiles AS f
      JOIN mimes AS m ON (f.mime_type = m.name)
      LEFT JOIN (SELECT DISTINCT id, string_agg(parent, ',' ORDER BY parent) AS parent_str
                 FROM parents GROUP BY id) AS p ON (f.id = p.id)
      LEFT JOIN (SELECT DISTINCT id, string_agg(child, ',' ORDER BY child) AS child_str
                 FROM children GROUP BY id) AS c ON (f.id = c.id)
      LEFT JOIN (SELECT DISTINCT id, string_agg(scion, ',' ORDER BY scion) AS scion_str
                 FROM scion_view GROUP BY id) AS s ON (f.id = s.id)
  WHERE
    m.category = 'folder';

答案 1 :(得分:1)

试试这个。希望它可以产生你所期望的。在案例类下面找到光滑代码。

click here有关提升嵌入的参考。

case class User(val name: String, val picture: Option[URL], val id: Option[UUID])
            class Users(_tableTag: Tag) extends Table[User](_tableTag,"users") {
              def name = column[String]("name")
              def picture = column[Option[URL]]("picture")
              def id = column[UUID]("id")
              def * = name ~ picture ~ id.? <> (User, User.unapply _)
            }
             lazy val userTable = new TableQuery(tag => new Users(tag))

            case class Skill(val name: String, val id: Option[UUID])
            class Skills(_tableTag: Tag) extends Table[Skill](_tableTag,"skill") {
              def name = column[String]("name")
              def id = column[UUID]("id")
              def * = name ~ id.? <> (Skill, Skill.unapply _)
            }
             lazy val skillTable = new TableQuery(tag => new Skills(tag))

            case class UserSkill(val userId: UUID, val skillId: UUID, val id: Option[UUID])
            class UserSkills(_tableTag: Tag) extends Table[UserSkill](_tableTag,"user_skill") {
              def userId = column[UUID]("userId")
              def skillId = column[UUID]("skillId")
              def id = column[UUID]("id")
              def * = userId ~ skillId ~ id.? <> (UserSkill, UserSkill.unapply _)
              def user = foreignKey("userFK", userId, Users)(_.id)
              def skill = foreignKey("skillFK", skillId, Skills)(_.id)
            }
             lazy val userSkillTable = new TableQuery(tag => new UserSkills(tag))






(for {((userSkill, user), skill) <- userSkillTable join userTable.filter on
                    (_.userId === _.id) join skillTable.filter on (_._1.skillId === _.id)
                } yield (userSkill, user, skill)).groupBy(_.2.id)