Last active
March 28, 2023 14:13
-
-
Save etaque/9f675007a45a636deb6664bfd3619757 to your computer and use it in GitHub Desktop.
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
trait Persisted { | |
def id: UUID | |
} | |
trait BasicDoobieTable[M <: Persisted] { | |
def table: String | |
def columns: Seq[String] | |
implicit def composite: Composite[M] | |
def insertColumns = columns.filterNot(_ == "id") | |
def tableF = Fragment.const(table) | |
def columnsF = Fragment.const(columns.map(table ++ "." + _).mkString(", ")) | |
def selectF = fr"SELECT" ++ columnsF ++ fr"FROM" ++ tableF | |
def find(id: Long): ConnectionIO[Option[M]] = { | |
(selectF ++ fr"WHERE id=$id").query[M].option | |
} | |
def findBy[A](column: String, value: A)(implicit meta: Meta[A]): ConnectionIO[Option[M]] = { | |
(selectF ++ Fragment.const(s"WHERE $column=") ++ fr"$value").query[M].option | |
} | |
def list(): ConnectionIO[List[M]] = { | |
selectF.query[M].list | |
} | |
def create(entity: M): ConnectionIO[Int] = { | |
val placeholders = insertColumns.map(_ => "?").mkString(", ") | |
val q = s"INSERT INTO $table (${insertColumns.mkString(", ")}) VALUES ($placeholders)" | |
Update[M](q).run(entity) | |
} | |
def update(id: UUID, entity: M): ConnectionIO[Int] = { | |
val placeholders = insertColumns.map(f => s"$f = ?").mkString(", ") | |
val q = s"update $table set $placeholders where id = ?" | |
Update[(M, UUID)](q).run((entity, id)) | |
} | |
} |
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
object FooTable extends BasicDoobieTable[Foo] { | |
val table = "foos" | |
val columns = | |
Seq("id", "bar", "baz") | |
val composite = Composite[Foo] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment