This answer attempts to implement Eugene's suggestion (so if it works please give credit to Eugene).
Given the following definition of @ifNotMysql
macro
import scala.reflect.macros.blackbox
import scala.language.experimental.macros
import scala.annotation.{StaticAnnotation, compileTimeOnly}
object ifNotMysqlMacro {
val targetIsMySql = sys.props.get("target-mysql").contains("true")
def impl(c: blackbox.Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
import c.universe._
def mysqlAnnots(annotations: Seq[c.universe.Tree]): Seq[c.universe.Tree] =
annotations
.filterNot(_.toString.contains("SequenceGenerator"))
.filterNot(_.toString.contains("GeneratedValue"))
.:+(q"""new GeneratedValue(strategy = GenerationType.IDENTITY)""")
val result = annottees.map(_.tree).toList match {
case q"@..$annots var $pat: $tpt = $expr" :: Nil =>
q"""
@..${if (targetIsMySql) mysqlAnnots(annots) else annots}
var $pat: $tpt = $expr
"""
}
c.Expr[Any](result)
}
}
@compileTimeOnly("enable macro paradise to expand macro annotations")
class ifNotMysql extends StaticAnnotation {
def macroTransform(annottees: Any*): Any = macro ifNotMysqlMacro.impl
}
if we write @ifNotMysql @GeneratedValue(...) @SequenceGenerator
like so
@ifNotMysql
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "generator")
@SequenceGenerator(name="generator", sequenceName = "cliSeq", allocationSize = 1)
var surrogateKey: Int = _
and provide system property target-mysql
like so
sbt -Dtarget-mysql=true compile
then @SequenceGenerator
annotation will be excluded and @GeneratedValue(strategy = GenerationType.IDENTITY)
added like so
@GeneratedValue(strategy = GenerationType.IDENTITY)
var surrogateKey: Int = _
This implementation is based on scalamacros/sbt-example-paradise