Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document how to work with Array of custom types #2107

Open
jatcwang opened this issue Sep 25, 2024 · 3 comments
Open

Document how to work with Array of custom types #2107

jatcwang opened this issue Sep 25, 2024 · 3 comments

Comments

@jatcwang
Copy link
Collaborator

jatcwang commented Sep 25, 2024

Expand SQL Arrays page to document how to work with List[MyEnum] instead of just List[String] when fetching and writing to Postgres array columns.

@satorg
Copy link
Contributor

satorg commented Sep 25, 2024

@jatcwang , is this feature supported already?

Last time I checked it (quite long ago though), I could only do value types directly, whereas for structures I had to pass them through JSON – back and forth.

@jatcwang
Copy link
Collaborator Author

You are right - I have updated the title to be more precise.

@jatcwang
Copy link
Collaborator Author

Potential solution https://discord.com/channels/632277896739946517/632727524434247691/1288688733029142588

  @SuppressWarnings(Array("org.wartremover.warts.Equals", "org.wartremover.warts.AsInstanceOf"))
  def putArray[A](
    schemaTypes: NonEmptyList[String],
    elementType: String,
    aToSql: A=> String
  ): Put.Advanced[Array[A]] =
    Put.Advanced.one(
      doobie.enumerated.JdbcType.Array,
      schemaTypes,
      (ps, n, a) => {
        val conn = ps.getConnection
        val arr = conn.createArrayOf(elementType, a.map(aToSql))
        ps.setArray(n, arr)
      },
      (rs, n, a) => {
        val stmt = rs.getStatement
        val conn = stmt.getConnection
        val arr = conn.createArrayOf(elementType, a.map(aToSql))
        rs.updateArray(n, arr)
      }
    )

  implicit val putArr: Put[Array[TestItem]] = 
    putArray[TestItem](
      NonEmptyList("_test_item", List()),
      "test_item",
      (i: TestItem) => itemToSql(i)
    )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants