forked from com-lihaoyi/scalasql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MySqlExample.scala
76 lines (61 loc) · 2.2 KB
/
MySqlExample.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
75
76
package scalasql.example
import org.testcontainers.containers.MySQLContainer
import scalasql.Table
import scalasql.MySqlDialect._
object MySqlExample {
case class ExampleProduct[T[_]](
id: T[Int],
kebabCaseName: T[String],
name: T[String],
price: T[Double]
)
object ExampleProduct extends Table[ExampleProduct]
// The example MySQLContainer comes from the library `org.testcontainers:mysql:1.19.1`
lazy val mysql = {
println("Initializing MySql")
val mysql = new MySQLContainer("mysql:8.0.31")
mysql.setCommand("mysqld", "--character-set-server=utf8mb4", "--collation-server=utf8mb4_bin")
mysql.start()
mysql
}
val dataSource = new com.mysql.cj.jdbc.MysqlDataSource
dataSource.setURL(mysql.getJdbcUrl + "?allowMultiQueries=true")
dataSource.setDatabaseName(mysql.getDatabaseName);
dataSource.setUser(mysql.getUsername);
dataSource.setPassword(mysql.getPassword);
lazy val mysqlClient = new scalasql.DbClient.DataSource(
dataSource,
config = new scalasql.Config {}
)
def main(args: Array[String]): Unit = {
mysqlClient.transaction { db =>
db.updateRaw("""
CREATE TABLE example_product (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
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"))
}
}
}