Slick in Scala

 Slick in Scala


Slick is a database access library for Scala that provides a typesafe DSL for querying databases. It allows you to define database schemas and perform CRUD operations using a Scala API that feels natural and intuitive. Here's an example of defining a simple database schema and querying it


import slick.jdbc.SQLiteProfile.api._


case class User(id: Option[Int], name: String, email: String)


class UsersTable(tag: Tag) extends Table[User](tag, "users") {

  def id = column[Int]("id", O.PrimaryKey, O.AutoInc)

  def name = column[String]("name")

  def email = column[String]("email")

  def * = (id.?, name, email) <> (User.tupled, User.unapply)

}


val db = Database.forConfig("sqlite")


val users = TableQuery[UsersTable]


val setupAction = DBIO.seq(users.schema.create)


val setupFuture = db.run(setupAction)


val insertAction = DBIO.seq(

  users += User(None, "Alice", "alice@example.com"),

  users += User(None, "Bob", "bob@example.com")

)


val insertFuture = db.run(insertAction)


val queryAction = users.result


val queryFuture = db.run(queryAction)


queryFuture.onSuccess {

  case userSeq => userSeq.foreach(println)

}

In this example, a User case class is defined to represent the users table, and a UsersTable class is defined to map the table to the case class using Slick's DSL. A database connection is established using Slick's Database object, and a TableQuery object is created to represent the UsersTable. A setup action is defined to create the table schema, and an insert action is defined to insert two rows into the table. Finally, a query action is defined to retrieve all rows from the table, and the query is executed using db.run. When the query completes successfully, the result is printed to the console.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...