Anorm with SQL expressions as parameter values

104 Views Asked by At

I am trying to create this SQL statement with Anorm in Scala. I am using a Postgres DB.

insert into my_table (coords) values (ST_GeomFromText('POINT(26.9484 24.03937)',4326)

I have tried this code:

val lat = 26.9484
val long = 24.03937
val coords = s"ST_GeomFromText('POINT($lat $long)',4326)"
SQL"insert into my_table (coords) values (${coords})".executeInsert()

But I get this error:

[PSQLException: ERROR: subfield "coords" is of type geometry but expression is of type character varying
  Hint: You will need to rewrite or cast the expression.
1

There are 1 best solutions below

1
David MacCallum On

Here was my solution:

val lat = Some(26.9484)
val long = Some(24.03937)
SQL"insert into my_table (coords) values (ST_MakePoint(${lat}, ${long}))".executeInsert()

Nice benefit is that if lat or long are None (null) then the coords field is set to NULL in the table.