Skip to content

Instantly share code, notes, and snippets.

@mostafa-asg
Created June 4, 2018 06:41
Show Gist options
  • Save mostafa-asg/adbcf56f766273c84b6066d4b71f019e to your computer and use it in GitHub Desktop.
Save mostafa-asg/adbcf56f766273c84b6066d4b71f019e to your computer and use it in GitHub Desktop.
import slick.jdbc.H2Profile.api._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Await
import scala.concurrent.duration.Duration
object Main {
case class User(username:String, password: String,id:Long=0)
class Users(tag: Tag) extends Table[User](tag , "users") {
def id = column[Long]("id",O.PrimaryKey,O.AutoInc)
def username = column[String]("username")
def password = column[String]("password")
def * = (username,password,id) <> (User.tupled,User.unapply)
}
val users = TableQuery[Users]
case class UserRole(userId:Long, roleId:Long)
class UserRoles(tag: Tag) extends Table[UserRole](tag , "userRoles") {
def userId = column[Long]("userId")
def roleId = column[Long]("roleId")
def * = (userId,roleId) <> (UserRole.tupled,UserRole.unapply)
def user = foreignKey("USER_FK", userId, users)(_.id)
def pk = primaryKey("pk",(userId,roleId))
}
val userRoles = TableQuery[UserRoles]
def insert(urs: Seq[UserRole]) = userRoles ++= urs
def insert(user: User) = (users returning users.map(_.id)) += user
def register(user:User , roleIds: List[Long]) = {
insert(user).flatMap { userId =>
val insertUserRoleAction = insert( roleIds.map(roleId => UserRole(userId,roleId)) )
insertUserRoleAction.map( _ => userId )
}
}
def registerUsingFor(user:User , roleIds: List[Long]) = {
for {
userId <- insert(user)
_ <- insert( roleIds.map(roleId => UserRole(userId,roleId)) )
} yield userId
}
def main(args: Array[String]): Unit = {
val db = Database.forConfig("db")
// Because it is an in-memory database
Await.ready( db.run( (users.schema ++ userRoles.schema).create ) , Duration.Inf )
val userId = Await.result(
db.run(registerUsingFor(User("mostafa.asg","pass"),List(1,2)).transactionally),
Duration.Inf
)
println("userID = " + userId)
// Get all userRoles
val rows = Await.result( db.run(userRoles.result) , Duration.Inf )
rows.foreach( println( _ ) )
db.close()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment