Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Browse the repository at this point in the history
Backports #18075 to the LTS branch. PR submitted by the release tooling. [skip ci]
- Loading branch information
Showing
2 changed files
with
37 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
import scala.annotation.StaticAnnotation | ||
|
||
class SqlName(val sqlName: String) extends StaticAnnotation | ||
|
||
import scala.compiletime.* | ||
import scala.quoted.* | ||
|
||
inline def sqlFieldNamesFor[T]: Vector[(String, String)] = ${ | ||
sqlFieldNamesForImpl[T] | ||
} | ||
|
||
private def sqlFieldNamesForImpl[T: Type](using | ||
Quotes // must be named!! like `q: Quotes` | ||
): Expr[Vector[(String, String)]] = | ||
import quotes.reflect.* | ||
val annot = TypeRepr.of[SqlName].typeSymbol | ||
val tuples: Seq[Expr[(String, String)]] = TypeRepr | ||
.of[T] | ||
.typeSymbol | ||
.primaryConstructor | ||
.paramSymss | ||
.head | ||
.collect: | ||
case sym if sym.hasAnnotation(annot) => | ||
val fieldNameExpr = Expr(sym.name.asInstanceOf[String]) | ||
val annotExpr = sym.getAnnotation(annot).get.asExprOf[SqlName] | ||
'{ ($fieldNameExpr, $annotExpr.sqlName) } | ||
val seq: Expr[Seq[(String, String)]] = Expr.ofSeq(tuples) | ||
'{ $seq.toVector } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
case class AppUser( | ||
id: Long, | ||
firstName: Option[String], | ||
@SqlName("last_name") lastName: String | ||
) | ||
|
||
def hello: Unit = | ||
println(sqlFieldNamesFor[AppUser]) // Vector((lastName, last_name)) |