-
Notifications
You must be signed in to change notification settings - Fork 23
/
HikariCpExample.scala
74 lines (59 loc) · 2.06 KB
/
HikariCpExample.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package scalasql.example
import org.testcontainers.containers.PostgreSQLContainer
import scalasql.Table
import scalasql.PostgresDialect._
object HikariCpExample {
case class ExampleProduct[T[_]](
id: T[Int],
kebabCaseName: T[String],
name: T[String],
price: T[Double]
)
object ExampleProduct extends Table[ExampleProduct]
lazy val postgres = {
println("Initializing Postgres")
val pg = new PostgreSQLContainer("postgres:15-alpine")
pg.start()
pg
}
// HikariDataSource comes from the library `com.zaxxer:HikariCP:5.1.0`
val hikariDataSource = new com.zaxxer.hikari.HikariDataSource()
hikariDataSource.setJdbcUrl(postgres.getJdbcUrl)
hikariDataSource.setUsername(postgres.getUsername)
hikariDataSource.setPassword(postgres.getPassword)
lazy val hikariClient = new scalasql.DbClient.DataSource(
hikariDataSource,
config = new scalasql.Config {}
)
def main(args: Array[String]): Unit = {
hikariClient.transaction { db =>
db.updateRaw("""
CREATE TABLE example_product (
id SERIAL PRIMARY KEY,
kebab_case_name VARCHAR(256),
name VARCHAR(256),
price DECIMAL(20, 2)
);
""")
val inserted = db.run(
ExampleProduct.insert.batched(_.kebabCaseName, _.name, _.price)(
("face-mask", "Face Mask", 8.88),
("guitar", "Guitar", 300),
("socks", "Socks", 3.14),
("skate-board", "Skate Board", 123.45),
("camera", "Camera", 1000.00),
("cookie", "Cookie", 0.10)
)
)
assert(inserted == 6)
val result =
db.run(ExampleProduct.select.filter(_.price > 10).sortBy(_.price).desc.map(_.name))
assert(result == Seq("Camera", "Guitar", "Skate Board"))
db.run(ExampleProduct.update(_.name === "Cookie").set(_.price := 11.0))
db.run(ExampleProduct.delete(_.name === "Guitar"))
val result2 =
db.run(ExampleProduct.select.filter(_.price > 10).sortBy(_.price).desc.map(_.name))
assert(result2 == Seq("Camera", "Skate Board", "Cookie"))
}
}
}