Is it possible to configure the generation of Slick code so that the generated classes extend user-specific features?

I am currently using Slick codegen (version 3.2.0-M1) to generate Slick code for a database. Many of my tables contain the same columns (with the same name and type), and therefore I would like to have some methods that can perform operations on these tables in a general way, for example, a general method that can select rows from any of these tables are based on a specific common field.

To do this, I could create a trait that would contain these common fields, and then extend the Slick table classes or mix them. Ideally, I would like to add a code generator extends <trait>or with <trait>for these classes to me.

I see that there is an override method in the generator code, but I would like to avoid having to contact the code directly, for example. through regular expressions.

I didn't find anything on the Internet or in the Slick documentation that points to a simple solution using the code generator setup, so I was wondering if anyone knew about this, even if it was possible.

+4
source share
3 answers

I was able to override some of the custom methods of the source code generator using code modified from 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 `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 `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()
      }
    }
  }
}

, . - , , .

+1

, , ( , , ). Slick, (, , )

, . :

/** Table description of table user. Objects of this class serve as prototypes for rows in queries. */
class User(_tableTag: Tag) extends Table[UserRow](_tableTag, "user") { ... }

User Slick be.objectify.deadbolt.java.models.Subject Java, Deadbolt2 Scala -.

:

import be.objectify.deadbolt.java.models.Subject     

/**
 * Mixin framework or infrastructural code
 */
trait DynamicMixinCompanion[TT] {
  implicit def baseObject[OT](o: Mixin[OT]): OT = o.obj

  def ::[OT](o: OT): Mixin[OT] with TT
  class Mixin[OT] protected[DynamicMixinCompanion](val obj: OT)
}

/**
 * Subject Mixin implementation
 */
object SubjectMixinHelper extends DynamicMixinCompanion[Subject] {
  def ::[T](o: T) = new Mixin(o) with Subject {
     def getPermissions = ...  
     def getRoles = ...
  }
}

, :

import SubjectMixinHelper._
withSession{ implicit session =>
  val user = Query(User).where(_.id === id).firstOption :: Subject

  // then use user as a Subject too
  user.getPermissions
  user.getRoles
}

, ( )

0

If you want to add a property to each generated table, you need to override the parent method in TableClass and EntityType : code generator:

class ExtSourceCodeGenerator(model: m.Model) extends SourceCodeGenerator(model: m.Model) {

  //Import packages with your traits
  override def code: String = "import models._\n" + super.code

  override def Table = new Table(_) {

    override def TableClass = new TableClass {
      //Add custom traits to Table classes
      override def parents: Seq[String] = {
        Seq("IdentityTable")
      }
    }

    override def EntityType = new EntityType {
      //Add custom traits to rows
      override def parents: Seq[String] = {
        Seq("Entity")
      }
    }
  }
}

If you need to filter out some tables, you can use the model field to get the current table name:

model.name.table

Hope this helps you.

0
source

Source: https://habr.com/ru/post/1654639/


All Articles