Cast PgArray or java.sql.Array to a Scala collection

Metropolis :

I have a postgres query that uses the array_agg() function to return a PgArray of values. Running this query with a simple java.sql.PreparedStatement I get back a java.sql.ResultSet.

After val arrayCol = resultSet.getArray("array_agg_column_name") I have a java.sql.Array

printing arrayCol looks like

{1, 2, 3}

Calling arrayCol.getArray gives me an Object

I'm unsure of how to work with either of the Object or java.sql.Array types in my Scala code. Doing a simple asInstanceOf[List[Int]] fails with

java.lang.ClassCastException: [Ljava.lang.Integer; cannot be cast to scala.collection.immutable.List

While casing with asInstanceOf[Array[Int]] leads to

java.lang.ClassCastException: [Ljava.lang.Integer; cannot be cast to [I

If I import scala.collection.JavaConverters._

And then try using asScala I get

value asScala is not a member of Object

or " ... of java.sql.Array", depending if I call getArray.

What is the correct way to get parse a field resulting from a psql array_agg function?

Metropolis :

I was able to use json_agg in lieu of array_agg in the postgres query, and then do:

resultSet.getString("array_agg_column_name")

From here, you can do as you like. We use Circe to decode Json to Scala objects.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324446&siteId=1