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 Project: SimpleFlatMapper   Author: arnaudroger   File: ArrayFloatResultSetGetter.java    License: 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 Project: calcite-avatica   Author: apache   File: ArrayTypeTest.java    License: 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 #3
Source Project: micro-integrator   Author: wso2   File: SQLQuery.java    License: 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 #4
Source Project: mybaties   Author: shurun19851206   File: SPTest.java    License: 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 #5
Source Project: dalesbred   Author: EvidentSolutions   File: InstantiatorProvider.java    License: 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 #6
Source Project: phoenix   Author: cloudera-labs   File: StringToArrayConverterTest.java    License: 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 #7
Source Project: calcite-avatica   Author: apache   File: TypedValue.java    License: 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 #8
Source Project: phoenix   Author: apache   File: ArrayAppendFunctionIT.java    License: 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 #9
Source Project: mmpt   Author: manniwood   File: IntegerArrayTypeHandler.java    License: 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 #10
Source Project: lutece-core   Author: lutece-platform   File: DAOUtil.java    License: 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 #11
Source Project: dragonwell8_jdk   Author: alibaba   File: SQLOutputImplTests.java    License: 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 #12
Source Project: ClickHouse-Native-JDBC   Author: housepower   File: QueryComplexTypeITest.java    License: 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 #13
Source Project: mmpt   Author: manniwood   File: BooleanArrayTypeHandler.java    License: 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 #14
Source Project: phoenix   Author: forcedotcom   File: PhoenixArray.java    License: 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 #15
Source Project: jdk8u-jdk   Author: lambdalab-mirror   File: BaseRowSetTests.java    License: 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 #16
Source Project: phoenix   Author: cloudera-labs   File: RegexpSplitFunctionIT.java    License: 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 #17
Source Project: phoenix   Author: cloudera-labs   File: StringToArrayConverterTest.java    License: 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 #18
Source Project: tddl   Author: cpsing   File: MockResultSet.java    License: Apache License 2.0 4 votes vote down vote up
public void updateArray(String columnName, Array x) throws SQLException {
    throw new NotSupportException("updateArray(String columnName, Array x)");
}
 
Example #19
Source Project: java-jdbc   Author: opentracing-contrib   File: TracingPreparedStatement.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void setArray(int parameterIndex, Array x) throws SQLException {
  preparedStatement.setArray(parameterIndex, x);
}
 
Example #20
Source Project: mybaties   Author: shurun19851206   File: ArrayTypeHandler.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
  ps.setArray(i, (Array) parameter);
}
 
Example #21
Source Project: dremio-oss   Author: dremio   File: DremioResultSetImpl.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Array getArray( int columnIndex ) throws SQLException {
  throwIfClosed();
  return super.getArray( columnIndex );
}
 
Example #22
Source Project: doma   Author: domaframework   File: MockResultSet.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void updateArray(int columnIndex, Array x) throws SQLException {
  AssertionUtil.notYetImplemented();
}
 
Example #23
Source Project: ultm   Author: witoldsz   File: WrappedConnection.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
    return delegate.createArrayOf(typeName, elements);
}
 
Example #24
Source Project: hottub   Author: dsrg-uoft   File: StubFilteredRowSetImpl.java    License: 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 #25
Source Project: tddl5   Author: loye168   File: ResultSetAutoCloseConnection.java    License: Apache License 2.0 4 votes vote down vote up
public void updateArray(String columnLabel, Array x) throws SQLException {
    rs.updateArray(columnLabel, x);
}
 
Example #26
Source Project: tddl   Author: cpsing   File: MockResultSet.java    License: Apache License 2.0 4 votes vote down vote up
public void updateArray(int columnIndex, Array x) throws SQLException {
    throw new NotSupportException("updateArray(int columnIndex, Array x)");
}
 
Example #27
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: StubJoinRowSetImpl.java    License: 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 #28
Source Project: Agent-Benchmarks   Author: SkyAPMTest   File: SimulateResultSet.java    License: Apache License 2.0 4 votes vote down vote up
@Override public Array getArray(int columnIndex) throws SQLException {
    return null;
}
 
Example #29
Source Project: calcite-avatica   Author: apache   File: ArrayTypeTest.java    License: Apache License 2.0 4 votes vote down vote up
@Override public void validate(Array expected, Array actual) throws SQLException {
  assertEquals(AvaticaUtils.primitiveList(expected.getArray()),
      AvaticaUtils.primitiveList(actual.getArray()));
}
 
Example #30
Source Project: tangyuan2   Author: xsonorg   File: ArrayTypeHandler.java    License: GNU General Public License v3.0 4 votes vote down vote up
@Override
public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
	Array array = rs.getArray(columnName);
	return array == null ? null : array.getArray();
}