Skip to content

Wrong array produced when using ARRAY_AGG() on UNNEST(ARRAY[CAST(? AS INT)]) expression in a PreparedStatement #4033

Closed

Description

@lukaseder

Using H2 2.2.224, this statement:

try (PreparedStatement s = connection.prepareStatement("""
    select array_agg(e)
    from unnest(array[cast(? as int), cast(? as int)]) t (e)
    """)
) {
    s.setInt(1, 1);
    s.setInt(2, 2);

    try (ResultSet rs = s.executeQuery()) {
        while (rs.next()) {
            System.out.println(rs.getString(1));
            System.out.println(Arrays.asList((Object[]) rs.getArray(1).getArray()));
        }
    }
}

Produces a wrong result:

[null, null]
[null, null]

It seems to be the combination of:

  • Using a PreparedStatement with cast bind variables (without a cast, there would be an exception about missing data type information)
  • Using UNNEST and then again ARRAY_AGG

E.g. this doesn't use ARRAY_AGG, and it works correctly:

try (PreparedStatement s = connection.prepareStatement("""
    select e
    from unnest(array[cast(? as int), cast(? as int)]) t (e)
    """)
) {
    s.setInt(1, 1);
    s.setInt(2, 2);

    try (ResultSet rs = s.executeQuery()) {
        while (rs.next()) {
            System.out.println(rs.getString(1));
        }
    }
}

Producing

1
2

This doesn't use bind variables, and it also works correctly:

try (PreparedStatement s = connection.prepareStatement("""
    select array_agg(e)
    from unnest(array[1, 2]) t (e)
    """)
) {
    try (ResultSet rs = s.executeQuery()) {
        while (rs.next()) {
            System.out.println(rs.getString(1));
            System.out.println(Arrays.asList((Object[]) rs.getArray(1).getArray()));
        }
    }
}

Producing:

[1, 2]
[1, 2]

Activity

  1. lukaseder commented on Mar 26, 2024

    @lukaseder
    ContributorAuthor
  2. katzyn commented on Mar 26, 2024

    @katzyn
    Contributor

    Something is wrong with determination of a data type.

    An additional cast specification can be used as a temporary workaround:

    unnest(cast(array[cast(? as int), cast(? as int)] as integer array))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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