|
| 1 | +package scalasql.example |
| 2 | + |
| 3 | +import scalasql.Table |
| 4 | +import scalasql.H2Dialect._ |
| 5 | + |
| 6 | +object Scala3H2Example: |
| 7 | + |
| 8 | + case class ExampleProduct[T[_]]( |
| 9 | + id: T[Int], |
| 10 | + kebabCaseName: T[String], |
| 11 | + name: T[String], |
| 12 | + price: T[Double] |
| 13 | + ) |
| 14 | + |
| 15 | + object ExampleProduct extends Table[ExampleProduct] |
| 16 | + |
| 17 | + // The example H2 database comes from the library `com.h2database:h2:2.2.224` |
| 18 | + val dataSource = new org.h2.jdbcx.JdbcDataSource |
| 19 | + dataSource.setUrl("jdbc:h2:mem:testScala3;DB_CLOSE_DELAY=-1") |
| 20 | + lazy val h2Client = new scalasql.DbClient.DataSource( |
| 21 | + dataSource, |
| 22 | + config = new scalasql.Config {} |
| 23 | + ) |
| 24 | + |
| 25 | + def main(args: Array[String]): Unit = |
| 26 | + h2Client.transaction: db => |
| 27 | + db.updateRaw(""" |
| 28 | + CREATE TABLE example_product ( |
| 29 | + id INTEGER AUTO_INCREMENT PRIMARY KEY, |
| 30 | + kebab_case_name VARCHAR(256), |
| 31 | + name VARCHAR(256), |
| 32 | + price DECIMAL(20, 2) |
| 33 | + ); |
| 34 | + """) |
| 35 | + |
| 36 | + val inserted = db.run( |
| 37 | + ExampleProduct.insert.batched(_.kebabCaseName, _.name, _.price)( |
| 38 | + ("face-mask", "Face Mask", 8.88), |
| 39 | + ("guitar", "Guitar", 300), |
| 40 | + ("socks", "Socks", 3.14), |
| 41 | + ("skate-board", "Skate Board", 123.45), |
| 42 | + ("camera", "Camera", 1000.00), |
| 43 | + ("cookie", "Cookie", 0.10) |
| 44 | + ) |
| 45 | + ) |
| 46 | + |
| 47 | + assert(inserted == 6) |
| 48 | + |
| 49 | + val result = |
| 50 | + db.run(ExampleProduct.select.filter(_.price > 10).sortBy(_.price).desc.map(_.name)) |
| 51 | + |
| 52 | + assert(result == Seq("Camera", "Guitar", "Skate Board")) |
| 53 | + |
| 54 | + db.run(ExampleProduct.update(_.name === "Cookie").set(_.price := 11.0)) |
| 55 | + |
| 56 | + db.run(ExampleProduct.delete(_.name === "Guitar")) |
| 57 | + |
| 58 | + val result2 = |
| 59 | + db.run(ExampleProduct.select.filter(_.price > 10).sortBy(_.price).desc.map(_.name)) |
| 60 | + |
| 61 | + assert(result2 == Seq("Camera", "Skate Board", "Cookie")) |
0 commit comments