Advanced Features

Local Variables

Defining and using local variables inside SQL blocks

Captured functions can also be used to define local variables inside of a capture block. In the introduction we saw a query that looked like this:

sql {
  Table<Stock>().map { stock -> peRatioWeighted(stock, stock.marketCap / totalWeight) }
}

Note how I intentionally left the totalWeight variable undefined. Let’s try to define it as a local varaible:

val q =
  sql {
    val totalWeight = Table<Stock>().map { it.marketCap().use }.sum()
    Table<Stock>().map { stock -> peRatioWeighted(stock, stock.marketCap / totalWeight) }
  }
q.buildFor.Postgres().runOn(myDatabase)
//> SELECT (stock.price / stock.earnings) * ((this.price * this.sharesOutstanding) / (SELECT sum(this.price * this.sharesOutstanding) FROM Stock it)) AS value FROM Stock stock