java.sql.Array Java Examples

The following examples show how to use java.sql.Array. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ArrayFloatResultSetGetter.java    From SimpleFlatMapper with MIT License 7 votes vote down vote up
@Override
public float[] get(ResultSet target) throws Exception {
    Array sqlArray = target.getArray(index);

    if (sqlArray != null) {
        float[] array = INIT;
        int capacity = 0;
        int size = 0;

        ResultSet rs = sqlArray.getResultSet();
        try {
            while (rs.next()) {
                if (size >= capacity) {
                    int newCapacity = Math.max(Math.max(capacity + 1, capacity + (capacity >> 1)), 10);
                    array = Arrays.copyOf(array, newCapacity);
                    capacity = newCapacity;
                }
                array[size++] = rs.getFloat(VALUE_INDEX);
            }
        } finally {
            rs.close();
        }

        return Arrays.copyOf(array, size);
    }

    return null;
}
 
Example #2
Source File: InstantiatorProvider.java    From dalesbred with MIT License 6 votes vote down vote up
private @NotNull Optional<TypeConversion> findArrayConversion(@NotNull Type source, @NotNull Type target) {
    Class<?> rawTarget = rawType(target);

    if (isAssignable(Array.class, source)) {
        if (rawTarget.equals(Set.class))
            return Optional.of(SqlArrayConversion.sqlArray(typeParameter(target), this, LinkedHashSet::new));

        if (rawTarget.isAssignableFrom(List.class))
            return Optional.of(SqlArrayConversion.sqlArray(typeParameter(target), this, Function.identity()));

        if (rawTarget.isArray())
            return Optional.of(SqlArrayConversion.sqlArray(rawTarget.getComponentType(), this, list -> arrayOfType(rawTarget.getComponentType(), list)));
    }

    return Optional.empty();
}
 
Example #3
Source File: SPTest.java    From mybaties with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetNamesWithArray_a2() throws SQLException {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    SPMapper spMapper = sqlSession.getMapper(SPMapper.class);

    Array array = sqlSession.getConnection().createArrayOf("int", new Integer[] { 1, 2, 5 });

    Map<String, Object> parms = new HashMap<String, Object>();
    parms.put("ids", array);
    List<Name> names = spMapper.getNamesWithArrayAnnotatedWithXMLResultMap(parms);
    Object[] returnedIds = (Object[]) parms.get("returnedIds");
    assertEquals(4, returnedIds.length);
    assertEquals(3, parms.get("requestedRows"));
    assertEquals(2, names.size());
  } finally {
    sqlSession.close();
  }
}
 
Example #4
Source File: SQLQuery.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * Processes a SQL Array instance and transform it into a ParamValue
 * instance
 *
 * @param dataArray
 *            SQLArray instance
 * @param paramValue
 *            Container into which the SQLArray elements should be populated
 * @return ParamValue instance containing all the elements of the
 *         corresponding SQLArray instance
 * @throws SQLException
 *             When it fails to processes the result set produced by the
 *             SQLArray instance
 */
private ParamValue processSQLArray(Array dataArray, ParamValue paramValue) throws SQLException {
    ResultSet rs = null;
    try {
        rs = dataArray.getResultSet();
        while (rs.next()) {
            Object arrayEl = rs.getObject(2);
            if (arrayEl instanceof Struct) {
                paramValue.getArrayValue().add(new ParamValue((Struct) arrayEl));
            } else if (arrayEl instanceof Array) {
                paramValue.getArrayValue().add(
                        processSQLArray((Array) arrayEl, new ParamValue(
                                ParamValue.PARAM_VALUE_ARRAY)));
            } else {
                paramValue.getArrayValue().add(new ParamValue(String.valueOf(arrayEl)));
            }
        }
        return paramValue;
    } finally {
        this.releaseResources(rs, null);
    }
}
 
Example #5
Source File: ArrayTypeTest.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
@Test public void shortArraysWithNull() throws Exception {
  final Random r = new Random();
  try (Connection conn = DriverManager.getConnection(url)) {
    ScalarType component = ColumnMetaData.scalar(Types.SMALLINT, "SMALLINT", Rep.SHORT);
    List<Array> arrays = new ArrayList<>();
    // Construct the data
    for (int i = 0; i < 5; i++) {
      List<Short> elements = new ArrayList<>();
      for (int j = 0; j < 4; j++) {
        short value = (short) r.nextInt(Short.MAX_VALUE);
        // 50% of the time, negate the value
        if (0 == r.nextInt(2)) {
          value *= -1;
        }
        elements.add(Short.valueOf(value));
      }
      elements.add(null);
      arrays.add(createArray("SMALLINT", component, elements));
    }
    // Verify read/write
    writeAndReadArrays(conn, "short_arrays", "SMALLINT", component, arrays,
        PRIMITIVE_LIST_VALIDATOR);
  }
}
 
Example #6
Source File: BooleanArrayTypeHandler.java    From mmpt with MIT License 5 votes vote down vote up
@Override
public Boolean[] getNullableResult(ResultSet rs, int columnIndex)
        throws SQLException {
    Array outputArray = rs.getArray(columnIndex);
    if (outputArray == null) {
        return null;
    }
    return (Boolean[])outputArray.getArray();
}
 
Example #7
Source File: PhoenixArray.java    From phoenix with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Object convertObjectArrayToPrimitiveArray(Object[] elements) {
	Object object = java.lang.reflect.Array.newInstance(int.class,
			elements.length);
	intArr = (int[]) object;
	int i = 0;
	for(Object o : elements) {
	    if (o != null) {
	        intArr[i] = (Integer)o;
	    }
	    i++;
	}
	return intArr;
}
 
Example #8
Source File: RegexpSplitFunctionIT.java    From phoenix with Apache License 2.0 5 votes vote down vote up
@Test
public void testSplit_NoSplitString() throws SQLException {
    Connection conn = DriverManager.getConnection(getUrl());
    initTable(conn, "CANNOT BE SPLIT");

    ResultSet rs = conn.createStatement().executeQuery(
            "SELECT REGEXP_SPLIT(VAL, ',') FROM SPLIT_TEST");
    assertTrue(rs.next());
    Array array = rs.getArray(1);
    String[] values = (String[]) array.getArray();
    assertArrayEquals(new String[] { "CANNOT BE SPLIT" }, values);
}
 
Example #9
Source File: DAOUtil.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Register an SQL Array to be able to free it later
 * 
 * @param array
 *            the array to register
 */
private void registerArray( Array array )
{
    if ( _arrays == null )
    {
        _arrays = new ArrayList<>( );
    }
    _arrays.add( array );
}
 
Example #10
Source File: SQLOutputImplTests.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test(enabled = true)
public void test04() throws Exception {
    Object[] coffees = new Object[]{"Espresso", "Colombian", "French Roast",
        "Cappuccino"};
    Array a = new StubArray("VARCHAR", coffees);
    outImpl.writeArray(a);
    SerialArray sa = (SerialArray) results.get(0);
    assertTrue(Arrays.equals(coffees, (Object[]) sa.getArray()));
    assertTrue(a.getBaseTypeName().equals(sa.getBaseTypeName()));
}
 
Example #11
Source File: IntegerArrayTypeHandler.java    From mmpt with MIT License 5 votes vote down vote up
@Override
public Integer[] getNullableResult(ResultSet rs, String columnName)
        throws SQLException {
    Array outputArray = rs.getArray(columnName);
    if (outputArray == null) {
        return null;
    }
    return (Integer[])outputArray.getArray();
}
 
Example #12
Source File: StringToArrayConverterTest.java    From phoenix with Apache License 2.0 5 votes vote down vote up
@Test
public void testToArray_MultipleElements() throws SQLException {
    Array multiElementArray = converter.toArray("one:two");
    assertArrayEquals(
            new Object[]{"one", "two"},
            (Object[]) multiElementArray.getArray());
}
 
Example #13
Source File: ArrayAppendFunctionIT.java    From phoenix with Apache License 2.0 5 votes vote down vote up
@Test
public void testArrayAppendFunctionCharsWithNull() throws Exception {
    Connection conn = DriverManager.getConnection(getUrl());
    String tableName = initTables(conn);

    ResultSet rs;
    rs = conn.createStatement().executeQuery("SELECT ARRAY_APPEND(chars,NULL) FROM " + tableName + " WHERE region_name = 'SF Bay Area'");
    assertTrue(rs.next());

    String[] strings = new String[]{"a", "bbbb", "c", "ddd", "e"};

    Array array = conn.createArrayOf("CHAR", strings);

    assertEquals(array, rs.getArray(1));
    assertFalse(rs.next());
}
 
Example #14
Source File: QueryComplexTypeITest.java    From ClickHouse-Native-JDBC with Apache License 2.0 5 votes vote down vote up
@Test
public void successfullyArray() throws Exception {
    withNewConnection(connection -> {
        Statement statement = connection.createStatement();

        // Array(UInt8)
        ResultSet rs = statement.executeQuery("SELECT [[1], [2], [3], [4,5,6]] from numbers(10)");

        for (int i = 0; i < 10; i ++) {
            Assert.assertTrue(rs.next());
            Array array1 = rs.getArray(1);
            Object[] objects = (Object[]) array1.getArray();
            Assert.assertEquals(objects.length, 4);

            ClickHouseArray a1 = (ClickHouseArray)(objects[0]);
            ClickHouseArray a2 = (ClickHouseArray)(objects[1]);
            ClickHouseArray a3 = (ClickHouseArray)(objects[2]);
            ClickHouseArray a4 = (ClickHouseArray)(objects[3]);

            Assert.assertArrayEquals((Object[]) a1.getArray(), new Short[]{(short) 1});
            Assert.assertArrayEquals((Object[]) a2.getArray(), new Short[]{(short) 2});
            Assert.assertArrayEquals((Object[]) a3.getArray(), new Short[]{(short) 3});
            Assert.assertArrayEquals((Object[]) a4.getArray(), new Short[]{(short) 4, (short)5, (short)6});
        }
        Assert.assertFalse(rs.next());
    });
}
 
Example #15
Source File: TypedValue.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
/** Creates a TypedValue from a value in JDBC representation. */
public static TypedValue ofJdbc(ColumnMetaData.Rep rep, Object value,
    Calendar calendar) {
  if (value == null) {
    return EXPLICIT_NULL;
  }
  final Object serialValue;
  if (ColumnMetaData.Rep.ARRAY == rep) {
    // Sanity check that we were given an Array
    if (null != value && !(value instanceof Array)) {
      throw new IllegalArgumentException("Provided Rep was ARRAY, but the value was "
          + value.getClass());
    }
    final Array array = (Array) value;
    try {
      SqlType type = SqlType.valueOf(array.getBaseType());
      serialValue = jdbcToSerial(rep, array, calendar, type);
      // Because an Array may have null entries, we must always return the non-primitive type
      // variants of the array values.
      return new TypedValue(rep, Rep.nonPrimitiveRepOf(type), serialValue);
    } catch (SQLException e) {
      throw new RuntimeException("Could not extract Array component type", e);
    }
  } else {
    serialValue = jdbcToSerial(rep, value, calendar);
  }
  return new TypedValue(rep, serialValue);
}
 
Example #16
Source File: StringToArrayConverterTest.java    From phoenix with Apache License 2.0 5 votes vote down vote up
@Test
public void testToArray_IntegerValues() throws SQLException {
    StringToArrayConverter intArrayConverter = new StringToArrayConverter(
        conn, ":", PInteger.INSTANCE);
    Array intArray = intArrayConverter.toArray("1:2:3");
    assertArrayEquals(
            new int[]{1, 2, 3},
            (int[]) intArray.getArray());
}
 
Example #17
Source File: BaseRowSetTests.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@DataProvider(name = "testAdvancedParameters")
private Object[][] testAdvancedParameters() throws SQLException {

    byte[] bytes = new byte[10];
    Ref aRef = new SerialRef(new StubRef("INTEGER", query));
    Array aArray = new SerialArray(new StubArray("INTEGER", new Object[1]));
    Blob aBlob = new SerialBlob(new StubBlob());
    Clob aClob = new SerialClob(new StubClob());
    Reader rdr = new StringReader(query);
    InputStream is = new StringBufferInputStream(query);;
    brs = new StubBaseRowSet();
    brs.setBytes(1, bytes);
    brs.setAsciiStream(2, is, query.length());
    brs.setRef(3, aRef);
    brs.setArray(4, aArray);
    brs.setBlob(5, aBlob);
    brs.setClob(6, aClob);
    brs.setBinaryStream(7, is, query.length());
    brs.setUnicodeStream(8, is, query.length());
    brs.setCharacterStream(9, rdr, query.length());

    return new Object[][]{
        {1, bytes},
        {2, is},
        {3, aRef},
        {4, aArray},
        {5, aBlob},
        {6, aClob},
        {7, is},
        {8, is},
        {9, rdr}
    };
}
 
Example #18
Source File: StubJoinRowSetImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void updateArray(String columnLabel, Array x) throws SQLException {
    throw new UnsupportedOperationException("Not supported yet.");
}
 
Example #19
Source File: CountingConnection.java    From rxjava-jdbc with Apache License 2.0 4 votes vote down vote up
@Override
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
    return con.createArrayOf(typeName, elements);
}
 
Example #20
Source File: TestResultSet.java    From commons-beanutils with Apache License 2.0 4 votes vote down vote up
public void updateArray(final String columnName, final Array x)
    throws SQLException {
    throw new UnsupportedOperationException();
}
 
Example #21
Source File: StubSyncResolver.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Array getArray(String columnLabel) throws SQLException {
    throw new UnsupportedOperationException("Not supported yet.");
}
 
Example #22
Source File: TResultSetWrapper.java    From tddl5 with Apache License 2.0 4 votes vote down vote up
public Array getArray(int i) throws SQLException {
    return this.targetResultSet.getArray(i);
}
 
Example #23
Source File: ForceConnection.java    From salesforce-jdbc with MIT License 4 votes vote down vote up
@Override
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
    // TODO Auto-generated method stub
    return null;
}
 
Example #24
Source File: ClientCallableStatement.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Array getArray(String parameterName) throws SQLException {
  return getArray(getParameterIndex(parameterName));
}
 
Example #25
Source File: StubFilteredRowSetImpl.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Array getArray(int columnIndex) throws SQLException {
    throw new UnsupportedOperationException("Not supported yet.");
}
 
Example #26
Source File: AbstractCloudSpannerResultSet.java    From spanner-jdbc with MIT License 4 votes vote down vote up
@Override
public void updateArray(int columnIndex, Array x) throws SQLException {
  throw new SQLFeatureNotSupportedException();
}
 
Example #27
Source File: Connection.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
@Override
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
    return null;
}
 
Example #28
Source File: ResultSetEnvelope.java    From cactoos-jdbc with MIT License 4 votes vote down vote up
@Override
public Array getArray(final int index) throws SQLException {
    return this.origin.getArray(index);
}
 
Example #29
Source File: StubSyncResolver.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void updateArray(int columnIndex, Array x) throws SQLException {
    throw new UnsupportedOperationException("Not supported yet.");
}
 
Example #30
Source File: StubFilteredRowSetImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void updateArray(int columnIndex, Array x) throws SQLException {
    throw new UnsupportedOperationException("Not supported yet.");
}