Jer*_*y K 5 scala codegen slick
我目前正在使用Slick代码生成器(版本3.2.0-M1)来为数据库生成Slick代码。我的许多表都包含相同的列(具有相同的名称和类型),因此我想拥有一些可以以通用方式对这些表执行操作的方法,例如,可以从以下任意一种中选择行的通用方法这些表基于特定的共享字段。
为此,我可以创建一个包含这些共享字段的特征,然后让Slick表类对其进行扩展或混合。理想情况下,我想让代码生成器为我添加extends <trait>或添加with <trait>到这些类中。
我看到code生成器中有一个可重写的方法,但是我想避免不得不直接例如通过正则表达式来弄乱代码。
我没有在网上找到任何东西,也没有在Slick文档中找到任何指向使用代码生成器自定义的简单解决方案的东西,所以我想知道是否有人知道这是否有可能。
我已经设法使用修改后的代码覆盖源代码生成器的几个可自定义方法slick.codegen.AbstractSourceCodeGenerator:
/* `TableUtils` contains the definitions of the `GenericRow`
and `GenericTable` traits. */
override def code = "import data.TableUtils._\n" + super.code
override def Table = new Table(_) {
override def EntityType = new EntityTypeDef {
/* This code is adapted from the `EntityTypeDef` trait's `code` method
within `AbstractSourceCodeGenerator`.
All code is identical except for those lines which have a corresponding
comment above them. */
override def code = {
val args = columns.map(c=>
c.default.map( v =>
s"${c.name}: ${c.exposedType} = $v"
).getOrElse(
s"${c.name}: ${c.exposedType}"
)
).mkString(", ")
if(classEnabled){
/* `rowList` contains the names of the generated "Row" case classes we
wish to have extend our `GenericRow` trait. */
val newParents = if (rowList.contains(name)) parents :+ "GenericRow" else parents
/* Use our modified parent class sequence in place of the old one. */
val prns = (newParents.take(1).map(" extends "+_) ++ newParents.drop(1).map(" with "+_)).mkString("")
s"""case class $name($args)$prns"""
} else {
s"""type $name = $types
/** Constructor for $name providing default values if available in the database schema. */
def $name($args): $name = {
${compoundValue(columns.map(_.name))}
}
""".trim
}
}
}
override def TableClass = new TableClassDef {
/* This code is adapted from the `TableClassDef` trait's `code` method
within `AbstractSourceCodeGenerator`.
All code is identical except for those lines which have a corresponding
comment above them. */
override def code = {
/* `tableList` contains the names of the generated table classes we
wish to have extend our `GenericTable` trait. */
val newParents = if (tableList.contains(name)) parents :+ "GenericTable" else parents
/* Use our modified parent class sequence in place of the old one. */
val prns = newParents.map(" with " + _).mkString("")
val args = model.name.schema.map(n => s"""Some("$n")""") ++ Seq("\""+model.name.table+"\"")
s"""class $name(_tableTag: Tag) extends profile.api.Table[$elementType](_tableTag, ${args.mkString(", ")})$prns {
${indent(body.map(_.mkString("\n")).mkString("\n\n"))}
}
""".trim()
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这个解决方案适合我的目的,但复制和修改源代码感觉有点不优雅。如果有人知道更好的方法来做到这一点,我很想看看你想出了什么。
| 归档时间: |
|
| 查看次数: |
706 次 |
| 最近记录: |