-
-
Save leo-pfeiffer/c02bd07bbe880f7c9cf973e7d7937381 to your computer and use it in GitHub Desktop.
Doobie with SQLite
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
lazy val doobieVersion = "1.0.0-RC1" | |
libraryDependencies ++= Seq( | |
"org.xerial" % "sqlite-jdbc" % "3.36.0.2", | |
"org.tpolecat" %% "doobie-core" % doobieVersion, | |
"org.tpolecat" %% "doobie-hikari" % doobieVersion, | |
"org.tpolecat" %% "doobie-scalatest" % doobieVersion % Test, | |
) | |
*/ | |
import cats.effect.* | |
import cats.implicits.* | |
import doobie.* | |
import doobie.implicits.* | |
import doobie.util.ExecutionContexts | |
// This is just for testing. Consider using cats.effect.IOApp instead of calling | |
// unsafe methods directly. | |
import cats.effect.unsafe.implicits.global | |
// Transactor that gets the database connection | |
val xa = Transactor.fromDriverManager[IO]( | |
"org.sqlite.JDBC", // driver | |
"jdbc:sqlite:src/main/resources/file.db", // connect URL | |
"", // user | |
"" // password | |
) | |
object Hello extends App { | |
val drop = sql"""DROP TABLE IF EXISTS person""".update.run | |
val create = | |
sql""" | |
CREATE TABLE person ( | |
name TEXT NOT NULL UNIQUE, | |
age INTEGER | |
) | |
""".update.run | |
val res = (drop, create).mapN(_ + _).transact(xa).unsafeRunSync() | |
println(res) | |
def insert1(name: String, age: Option[Short]): Update0 = | |
sql"INSERT INTO person (name, age) VALUES ($name, $age)".update | |
insert1("Alice", Some(12)) | |
.run | |
.transact(xa) | |
.unsafeRunSync() | |
insert1("Bob", None) | |
.run | |
.transact(xa) | |
.unsafeRunSync() | |
case class Person(id: Long, name: String, age: Option[Short]) | |
val l = sql"""SELECT rowid, name, age FROM person""" | |
.query[Person] | |
.to[List] | |
.transact(xa) | |
.unsafeRunSync() | |
l.foreach(println) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment