-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathexample.sc
More file actions
100 lines (71 loc) · 2.44 KB
/
Copy pathexample.sc
File metadata and controls
100 lines (71 loc) · 2.44 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import usql.*
import usql.dao.*
import usql.profiles.H2Profile.given
import java.sql.{Connection, DriverManager}
import scala.util.{Try, Using}
Class.forName("org.h2.Driver")
val jdbcUrl = "jdbc:h2:mem:hello;DB_CLOSE_DELAY=-1"
given cp: ConnectionProvider with {
override def withConnection[T](f: Connection ?=> T): T = {
Using.resource(DriverManager.getConnection(jdbcUrl)) { c =>
f(using c)
}
}
}
// Simple Actions
sql"CREATE TABLE person (id INT PRIMARY KEY, name TEXT)"
.execute()
sql"INSERT INTO person (id, name) VALUES (${1}, ${"Alice"})"
.execute()
sql"INSERT INTO person (id, name) VALUES (${2}, ${"Bob"})"
.execute()
// Simple Queries
val all: Vector[(Int, String)] = sql"SELECT id, name FROM person".queryAll[(Int, String)]()
println(s"All=${all}")
// Constant Parts of the query
val one: Option[(Int, String)] = sql"SELECT id, name FROM #${"person"} WHERE id = ${1}".queryOne[(Int, String)]()
println(s"One=${one}")
val ids = Seq(1, 2, 3)
val names = sql"SELECT name FROM person WHERE id IN (${SqlParameters(ids)})".queryAll[String]()
println(s"Names=${names}")
// Inserts
sql"INSERT INTO person (id, name) VALUES(?, ?)".one((3, "Charly")).update.run()
sql"INSERT INTO person (id, name) VALUES(?, ?)"
.batch(
Seq(
4 -> "Dave",
5 -> "Emil"
)
)
.run()
sql"SELECT COUNT(*) FROM person".queryOne[Int]().get
// Reusable Parts
val select = sql"SELECT id, name FROM person"
val selectAlice = (select + sql" WHERE id = ${1}").queryOne[(Int, String)]()
println(s"Alice: ${selectAlice}")
// Transactions
Try {
transaction {
sql"INSERT INTO person(id, name) VALUES(${100}, ${"Duplicate"})".execute()
sql"INSERT INTO person(id, name) VALUES(${100}, ${"Duplicate 2"})".execute()
}
}
// Dao
case class Person(
id: Int,
name: String
) derives SqlTabular
object Person extends KeyedCrudBase[Int, Person] {
override def key: KeyColumnPath = cols.id
override def keyOf(value: Person): Int = value.id
}
println(s"All Persons: ${Person.findAll()}")
Person.insert(Person(6, "Fritz"))
Person.update(Person(6, "Franziska"))
println(Person.findByKey(6)) // Person(6, Franziska)
// Simple Queries (using Scala 3.7.0+ Named Tuples)
val allAgain: Vector[(Int, String)] =
sql"SELECT ${Person.cols.id}, ${Person.cols.name} FROM ${Person}".queryAll[(Int, String)]()
println(s"allAgain=${allAgain}")
// Simple QueryBuilder
println(Person.query.filter(_.id === 6).map(_.name).one()) // Some("Franziska")