Skip to content

In PostgreSQL, the subquery toExpr will result in a syntax error. #102

@ETCHKILI

Description

@ETCHKILI

TLDR;

The Select.toExpr function does not add parentheses to the subquery.

Minimal Reproduction

https://scastie.scala-lang.org/s1eHSaYhSV2yrJfhgqpksA

import scalasql.simple.*
import scalasql.PostgresDialect.*

case class Country(id: Long, name: String)
object Country extends SimpleTable[Country]

case class User(id: Long, countryId: Long)
object User extends SimpleTable[User]

val stmt = User
  .select
  .filter(_.id > 0)
  .filter(u =>
    Country
      .select
      .filter(_.id === u.countryId)
      .map(_.name === "xxx")
      .toExpr
  )

// ignoring the construction of dbClient

dbClient.transaction { db =>
  println(db `renderSql` stmt)
}
  

Result SQL

SELECT user0.id AS id, user0.country_id AS country_id FROM user user0 WHERE (user0.id > ?) AND SELECT (country1.name = ?) AS res FROM country country1 WHERE (country1.id = user0.country_id)

Which leads to an syntax error

[2025-11-04 15:39:14] [42601] ERROR: syntax error at or near "SELECT"
[2025-11-04 15:39:14] Position: 96

Possible fix

def toExpr(implicit mt: TypeMapper[R]): Expr[R] = Expr { implicit ctx => this.renderSql(ctx) }

-def toExpr(implicit mt: TypeMapper[R]): Expr[R] = Expr { implicit ctx => this.renderSql(ctx) }
+def toExpr(implicit mt: TypeMapper[R]): Expr[R] = Expr { implicit ctx => sql"(${this.renderSql(ctx)})" }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions