forked from com-lihaoyi/scalasql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
H2Example.scala
64 lines (50 loc) · 1.75 KB
/
H2Example.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
package scalasql.example
import scalasql.Table
import scalasql.H2Dialect._
object H2Example {
case class ExampleProduct[T[_]](
id: T[Int],
kebabCaseName: T[String],
name: T[String],
price: T[Double]
)
object ExampleProduct extends Table[ExampleProduct]
// The example H2 database comes from the library `com.h2database:h2:2.2.224`
val dataSource = new org.h2.jdbcx.JdbcDataSource
dataSource.setUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1")
lazy val h2Client = new scalasql.DbClient.DataSource(
dataSource,
config = new scalasql.Config {}
)
def main(args: Array[String]): Unit = {
h2Client.transaction { db =>
db.updateRaw("""
CREATE TABLE example_product (
id INTEGER AUTO_INCREMENT 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"))
}
}
}