加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何在ScalaQuery中撰写查询以创建可重用的特征?

发布时间:2020-12-16 09:15:01 所属栏目:安全 来源:网络整理
导读:我将单个查询中的不同查询组件组合起来有些麻烦.我的目标是创建一组特征(例如SoftDeletable,HasName,SortedByName,WithTimestamps),我可以简单地混合到Table对象来添加该行为. 理想的样子是: abstract class BaseModel[Tuple : Product,CaseClass](tableNam
我将单个查询中的不同查询组件组合起来有些麻烦.我的目标是创建一组特征(例如SoftDeletable,HasName,SortedByName,WithTimestamps),我可以简单地混合到Table对象来添加该行为.

理想的样子是:

abstract class BaseModel[Tuple <: Product,CaseClass](tableName: String)
     extends Table[Tuple](tableName) {
  def id = column[Int]("id",O.AutoInc,O.PrimaryKey)

  def mapped: MappedProjection[CaseClass,TupleClass]

  def allQuery = this.map(_.mapped)
  final def all = database.withSession { implicit session: Session => 
    allQuery.list() 
  }

  ...
}

trait SoftDeletable[Tuple  <: Product,CaseClass]
    extends BaseModel[Tuple,CaseClass] {
  def isActive = column[String]("is_active")

  def * = super.* ~ isActive
  def allQuery = /* here,I'd like to compose super.allQuery 
                    with a filter that returns rows where isActive is true */
}

trait HasName[Tuple <: Product] extends Table[Tuple] {
  def name = column[String]("name")

  def * = super.* ~ name
}

trait SortedByName[Tuple <: Product] extends HasName[Tuple {
  override def allQuery = super.allQuery /* compose somehow 
                                             with (_ <- Query orderBy name */
}

我可以用ScalaQuery做这些事情吗?主要的问题是:

>如何在SoftDeletable.allQuery中清理组合过滤器,并使用BaseModel.allQuery在SortedByName.allQuery中排序?
>通过在*方法的子类实现中添加列,对于表的后缀匹配,元组类型参数 – 是否有一种方法可以让这些特征向最终具体类中的列元组增加新类型? (我不期望会有,但如果有缺少的东西会很好).
>我需要重复每个特征中的长元组声明,如果一个表有五六列,这将变得非常笨重.有什么我可以做的类型成员,以避免做这样的事情:

case class Foo

class Foos[(Int,Int,Boolean,String),Foo] extends 
  Table[(Int,String)] with 
  SoftDeletable[(Int,Foo] with 
  SortedByName[(Int,Foo] with 
  HasName[(Int,String)] {
}

我可以避免所有这些重复吗?根据jesnor在IRC上的建议,我能够避免这样的一些:

abstract class SoftDeletableBaseModel[TupleClass <: Product,CaseClass](tableName: String)
        extends BaseModel[TupleClass,CaseClass](tableName)
        with SoftDeletable[TupleClass,CaseClass]

换句话说,通过将特定的特征组合在一起,我不需要重复整个元组声明;当然,不足之处在于,不可能简单地混合各种特征 – 我需要创建大量特定的子类以避免这种重复.还有另一种方式吗?

更新:所以我意识到我不需要使用单独的CaseClass和TupleClass类型参数.由于案例类实现了Product *,您只需将case类名称传递给Table即可解决3中的问题:

trait SoftDeletable[CaseClass] extends BaseModel[CaseClass] { ... }

class Models extends BaseModel[Model]("models") with SoftDeletable[Model] { ... }

解决方法

如果你的问题只是添加排序,这不是仅仅是一个flatMap的问题吗?

def sortBy[T,U,C](q: Query[T,U],col: NamedColumn[C]) = q.flatMap(_ => Query orderBy col)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读