Skip to content

Commit

Permalink
postgresql for update sample
Browse files Browse the repository at this point in the history
  • Loading branch information
mechairoi committed Aug 20, 2014
1 parent c60ea70 commit 3d6b890
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 2 deletions.
52 changes: 52 additions & 0 deletions src/main/scala/Driver.scala
@@ -0,0 +1,52 @@
package myapp

import slick.driver.PostgresDriver

trait MyPostgresDriver extends PostgresDriver
with PgForUpdateSupport
{
override val simple = new SimpleQLPlus {}

trait SimpleQLPlus extends SimpleQL
with ForUpdateTableImplicits
}

object MyPostgresDriver extends MyPostgresDriver

trait PgForUpdateSupport extends PostgresDriver { driver =>
import scala.slick.ast.{Comprehension, Node, Symbol, TableNode}
import scala.slick.compiler.CompilerState

trait ForUpdateTable

trait ForUpdateTableImplicits {
type ForUpdateTable = driver.ForUpdateTable
}

class QueryBuilder(tree: Node, state: CompilerState) extends super.QueryBuilder(tree, state) {
import scala.slick.util.MacroSupport.macroSupportInterpolation

override protected def buildComprehension(c: Comprehension): Unit = {
super.buildComprehension(c)
buildForUpdateClause(c.from)
}

protected def buildForUpdateClause(from: Seq[(Symbol, Node)]) = building(FromPart) {
val forUpdateFrom = from.filter { case (_, n) =>
n match {
case TableNode(_, _, _, driverTable, _) =>
driverTable.isInstanceOf[ForUpdateTable]
case _ => false
}
}
if(!forUpdateFrom.isEmpty) {
b" for update of "
b.sep(forUpdateFrom , ", ") { case (sym, n) =>
b += symbolName(sym)
}
}
}
}
override def createQueryBuilder(n: Node, state: CompilerState): QueryBuilder = new QueryBuilder(n, state)
}

7 changes: 5 additions & 2 deletions src/main/scala/main.scala
@@ -1,6 +1,6 @@
package myapp

import scala.slick.driver.PostgresDriver.simple._
import MyPostgresDriver.simple._
import scala.util.control.Exception._

object MyApp extends App{
Expand Down Expand Up @@ -31,12 +31,15 @@ object MyApp extends App{
}
val coffees = TableQuery[Coffees]

class CoffeesForUpdate(tag: Tag) extends Coffees(tag) with ForUpdateTable
val coffeesForUpdate = TableQuery[CoffeesForUpdate]

Database.forURL("jdbc:postgresql:test1", driver = "org.postgresql.Driver") withSession {
implicit session =>

allCatch opt (suppliers.ddl ++ coffees.ddl).create
val q = for {
c <- coffees if c.price < 9.0
c <- coffeesForUpdate if c.price < 9.0
s <- suppliers if s.id === c.supID
} yield (c.name, s.name)
q.list
Expand Down

0 comments on commit 3d6b890

Please sign in to comment.