Skip to content

Commit

Permalink
Fix query syntax when isActive = true (#118)
Browse files Browse the repository at this point in the history
`ServerInternalError` was thrown for this
```
curl -X 'GET' \
  'http://localhost:9669/api/players?sort_by=standard&order_by=desc&is_active=true&name=magnus%20carlsen&page=1&page_size=30' \
  -H 'accept: application/json'
```
with stacktrace:
```
[info] πŸ”₯
[info] πŸ”₯  Postgres ERROR 42601 raised in scanner_yyerror (scan.l:1241)
[info] πŸ”₯
[info] πŸ”₯    Problem: Syntax error at or near "AND".
[info] πŸ”₯
[info] πŸ”₯  The statement under consideration was defined
[info] πŸ”₯    at /Users/tle/git/lichess/fide/modules/db/src/main/scala/Db.scala:262
[info] πŸ”₯
[info] πŸ”₯      SELECT p.id, p.name, p.title, p.women_title, p.other_titles, p.standard, p.rapid, p.blitz, p.sex, p.birth_year, p.active, p.updated_at, p.created_at, f.id, f.name
[info] πŸ”₯      FROM players AS p LEFT JOIN federations AS f ON p.federation_id = f.id
[info] πŸ”₯    WHERE
[info] πŸ”₯      AND p.active = $1
[info] πŸ”₯      └─── Syntax error at or near "AND".
[info] πŸ”₯      ORDER BY p.birth_year ASC NULLS LAST
[info] πŸ”₯      LIMIT $2 OFFSET $3
[info] πŸ”₯
[info] πŸ”₯  If this is an error you wish to trap and handle in your application, you can do
[info] πŸ”₯  so with a SqlState extractor. For example:
[info] πŸ”₯
[info] πŸ”₯    doSomething.recoverWith { case SqlState.SyntaxError(ex) =>  ...}
[info] πŸ”₯
[info] skunk.exception.PostgresErrorException: Syntax error at or near "AND".
```
  • Loading branch information
lenguyenthanh authored May 28, 2024
2 parents e581077 + e3f8b97 commit d1ed6eb
Showing 1 changed file with 4 additions and 6 deletions.
10 changes: 4 additions & 6 deletions modules/db/src/main/scala/Db.scala
Original file line number Diff line number Diff line change
Expand Up @@ -218,15 +218,14 @@ private object Sql:

val f = filter.isActive.fold(bw): x =>
val a = filterActive(x)
bw.fold(a)(_ |+| a).some
bw.fold(a)(_ |+| and |+| a).some

filter.federationId.fold(f): x =>
val a = federationIdFragment(x)
f.fold(a)(_ |+| a).some
f.fold(a)(_ |+| and |+| a).some

private lazy val filterActive: Fragment[Boolean] =
sql"""
AND p.active = $bool"""
sql"p.active = $bool"

private lazy val insertIntoPlayer =
sql"INSERT INTO players (id, name, title, women_title, other_titles, standard, rapid, blitz, sex, birth_year, active, federation_id)"
Expand All @@ -249,8 +248,7 @@ private object Sql:
LIMIT ${int4} OFFSET ${int4}""".apply(page.limit, page.offset)

private def federationIdFragment(id: FederationId): AppliedFragment =
sql"""
AND p.federation_id = $text""".apply(id)
sql"""p.federation_id = $text""".apply(id)

private def sortingFragment(sorting: Sorting): AppliedFragment =
val column = s"p.${sorting.sortBy.value}"
Expand Down

0 comments on commit d1ed6eb

Please sign in to comment.