Search in sources :

Example 31 with SqlRow

use of com.hazelcast.sql.SqlRow in project hazelcast by hazelcast.

the class SqlConsole method executeSqlCmd.

private static void executeSqlCmd(HazelcastInstance hz, String command, Terminal terminal, AtomicReference<SqlResult> activeSqlResult) {
    PrintWriter out = terminal.writer();
    try (SqlResult sqlResult = hz.getSql().execute(command)) {
        activeSqlResult.set(sqlResult);
        // if it's a result with an update count, just print it
        if (sqlResult.updateCount() != -1) {
            String message = new AttributedStringBuilder().style(AttributedStyle.BOLD.foreground(PRIMARY_COLOR)).append("OK").toAnsi();
            out.println(message);
            return;
        }
        SqlRowMetadata rowMetadata = sqlResult.getRowMetadata();
        int[] colWidths = determineColumnWidths(rowMetadata);
        Alignment[] alignments = determineAlignments(rowMetadata);
        // this is a result with rows. Print the header and rows, watch for concurrent cancellation
        printMetadataInfo(rowMetadata, colWidths, alignments, out);
        int rowCount = 0;
        for (SqlRow row : sqlResult) {
            rowCount++;
            printRow(row, colWidths, alignments, out);
        }
        // bottom line after all the rows
        printSeparatorLine(sqlResult.getRowMetadata().getColumnCount(), colWidths, out);
        String message = new AttributedStringBuilder().style(AttributedStyle.BOLD.foreground(PRIMARY_COLOR)).append(String.valueOf(rowCount)).append(" row(s) selected").toAnsi();
        out.println(message);
    } catch (HazelcastSqlException e) {
        // the query failed to execute with HazelcastSqlException
        String errorPrompt = new AttributedStringBuilder().style(AttributedStyle.BOLD.foreground(PRIMARY_COLOR)).append(e.getMessage()).toAnsi();
        out.println(errorPrompt);
    } catch (Exception e) {
        // the query failed to execute with an unexpected exception
        String unexpectedErrorPrompt = new AttributedStringBuilder().style(AttributedStyle.BOLD.foreground(PRIMARY_COLOR)).append("Encountered an unexpected exception while executing the query:\n").append(e.getMessage()).toAnsi();
        out.println(unexpectedErrorPrompt);
        e.printStackTrace(out);
    }
}
Also used : SqlRow(com.hazelcast.sql.SqlRow) SqlResult(com.hazelcast.sql.SqlResult) AttributedStringBuilder(org.jline.utils.AttributedStringBuilder) SqlRowMetadata(com.hazelcast.sql.SqlRowMetadata) HazelcastSqlException(com.hazelcast.sql.HazelcastSqlException) EndOfFileException(org.jline.reader.EndOfFileException) UserInterruptException(org.jline.reader.UserInterruptException) PrintWriter(java.io.PrintWriter) HazelcastSqlException(com.hazelcast.sql.HazelcastSqlException)

Example 32 with SqlRow

use of com.hazelcast.sql.SqlRow in project hazelcast by hazelcast.

the class SqlPageCodecTest method check.

private void check(SqlColumnType type, List<Object> values, boolean last) {
    SqlRowMetadata rowMetadata = new SqlRowMetadata(Collections.singletonList(new SqlColumnMetadata("a", type, true)));
    List<SqlRow> rows = new ArrayList<>();
    for (Object value : values) {
        if (SqlPage.convertToData(type) && value != null) {
            value = serializationService.toData(value);
        }
        rows.add(new SqlRowImpl(rowMetadata, new JetSqlRow(TEST_SS, new Object[] { value })));
    }
    SqlPage originalPage = SqlPage.fromRows(Collections.singletonList(type), rows, last, serializationService);
    ClientMessage message = ClientMessage.createForEncode();
    SqlPageCodec.encode(message, originalPage);
    SqlPage restoredPage = SqlPageCodec.decode(message.frameIterator());
    assertEquals(1, restoredPage.getColumnCount());
    assertEquals(values.size(), restoredPage.getRowCount());
    assertEquals(last, restoredPage.isLast());
    assertEquals(1, restoredPage.getColumnTypes().size());
    assertEquals(type, restoredPage.getColumnTypes().get(0));
    for (int i = 0; i < values.size(); i++) {
        Object value = values.get(i);
        Object restoredValue = restoredPage.getColumnValueForClient(0, i);
        if (restoredValue instanceof Data) {
            assertTrue(SqlPage.convertToData(type));
            restoredValue = serializationService.toObject(restoredValue);
        }
        assertEquals(value, restoredValue);
    }
}
Also used : JetSqlRow(com.hazelcast.sql.impl.row.JetSqlRow) SqlRow(com.hazelcast.sql.SqlRow) SqlRowImpl(com.hazelcast.sql.impl.SqlRowImpl) ArrayList(java.util.ArrayList) Data(com.hazelcast.internal.serialization.Data) SqlRowMetadata(com.hazelcast.sql.SqlRowMetadata) JetSqlRow(com.hazelcast.sql.impl.row.JetSqlRow) ClientMessage(com.hazelcast.client.impl.protocol.ClientMessage) SqlColumnMetadata(com.hazelcast.sql.SqlColumnMetadata) SqlPage(com.hazelcast.sql.impl.client.SqlPage)

Example 33 with SqlRow

use of com.hazelcast.sql.SqlRow in project hazelcast by hazelcast.

the class SqlIndexConverterMismatchTest method testMismatch.

/**
 * @see MapIndexScanExecIterator#getIndexEntries
 */
@SuppressWarnings({ "StatementWithEmptyBody", "JavadocReference" })
@Ignore("https://github.com/hazelcast/hazelcast/issues/19287")
@Test
public void testMismatch() {
    ExpressionBiValue value1 = new ExpressionBiValue.IntegerIntegerVal();
    value1.field1(10);
    value1.field2(10);
    ExpressionBiValue value2 = new ExpressionBiValue.StringIntegerVal();
    value2.field1("10");
    value2.field2(10);
    map.put(getLocalKey(member1, key -> key), value1);
    map.put(getLocalKey(member2, key -> key), value2);
    try {
        try (SqlResult result = member1.getSql().execute("SELECT key FROM " + MAP_NAME + " WHERE field1=1")) {
            for (SqlRow ignore : result) {
            // No-op.
            }
        }
        fail("Must fail!");
    } catch (HazelcastSqlException e) {
        assertEquals(SqlErrorCode.INDEX_INVALID, e.getCode());
        Throwable ex = findRootQueryException(e);
        assertEquals("Cannot use the index \"index\" of the IMap \"map\" because it has component \"field1\" of type VARCHAR, but INTEGER was expected", ex.getMessage());
    }
}
Also used : ParallelJVMTest(com.hazelcast.test.annotation.ParallelJVMTest) QuickTest(com.hazelcast.test.annotation.QuickTest) RunWith(org.junit.runner.RunWith) ExpressionBiValue(com.hazelcast.jet.sql.impl.support.expressions.ExpressionBiValue) ArrayList(java.util.ArrayList) MapConfig(com.hazelcast.config.MapConfig) IndexType(com.hazelcast.config.IndexType) MapIndexScanExecIterator(com.hazelcast.sql.impl.exec.scan.index.MapIndexScanExecIterator) After(org.junit.After) Assert.fail(org.junit.Assert.fail) SqlRow(com.hazelcast.sql.SqlRow) Parameterized(org.junit.runners.Parameterized) QueryException(com.hazelcast.sql.impl.QueryException) Before(org.junit.Before) UseParametersRunnerFactory(org.junit.runners.Parameterized.UseParametersRunnerFactory) Config(com.hazelcast.config.Config) HazelcastInstance(com.hazelcast.core.HazelcastInstance) TestHazelcastInstanceFactory(com.hazelcast.test.TestHazelcastInstanceFactory) HazelcastSqlException(com.hazelcast.sql.HazelcastSqlException) HazelcastParametrizedRunner(com.hazelcast.test.HazelcastParametrizedRunner) Collection(java.util.Collection) HazelcastParallelParametersRunnerFactory(com.hazelcast.test.HazelcastParallelParametersRunnerFactory) Test(org.junit.Test) Category(org.junit.experimental.categories.Category) IndexConfig(com.hazelcast.config.IndexConfig) List(java.util.List) Ignore(org.junit.Ignore) SqlResult(com.hazelcast.sql.SqlResult) SqlErrorCode(com.hazelcast.sql.impl.SqlErrorCode) Assert.assertEquals(org.junit.Assert.assertEquals) IMap(com.hazelcast.map.IMap) SqlRow(com.hazelcast.sql.SqlRow) SqlResult(com.hazelcast.sql.SqlResult) ExpressionBiValue(com.hazelcast.jet.sql.impl.support.expressions.ExpressionBiValue) HazelcastSqlException(com.hazelcast.sql.HazelcastSqlException) Ignore(org.junit.Ignore) ParallelJVMTest(com.hazelcast.test.annotation.ParallelJVMTest) QuickTest(com.hazelcast.test.annotation.QuickTest) Test(org.junit.Test)

Example 34 with SqlRow

use of com.hazelcast.sql.SqlRow in project hazelcast by hazelcast.

the class SqlPortableTest method test_writingToTopLevelWhileNestedFieldMapped.

public void test_writingToTopLevelWhileNestedFieldMapped(boolean explicit) {
    String mapName = randomName();
    sqlService.execute("CREATE MAPPING " + mapName + "(" + "__key INT" + (explicit ? ", this OBJECT" : "") + ", name VARCHAR" + ") TYPE " + IMapSqlConnector.TYPE_NAME + "\n" + "OPTIONS (\n" + '\'' + OPTION_KEY_FORMAT + "'='" + JAVA_FORMAT + "'\n" + ", '" + OPTION_KEY_CLASS + "'='" + Integer.class.getName() + "'\n" + ", '" + OPTION_VALUE_FORMAT + "'='" + PORTABLE_FORMAT + "'\n" + ", '" + OPTION_VALUE_FACTORY_ID + "'='" + PERSON_FACTORY_ID + "'\n" + ", '" + OPTION_VALUE_CLASS_ID + "'='" + PERSON_CLASS_ID + "'\n" + ", '" + OPTION_VALUE_CLASS_VERSION + "'='" + PERSON_CLASS_VERSION + "'\n" + ")");
    if (explicit) {
        assertThatThrownBy(() -> sqlService.execute("SINK INTO " + mapName + " VALUES(1, null, 'foo')")).isInstanceOf(HazelcastSqlException.class).hasMessageContaining("Writing to top-level fields of type OBJECT not supported");
    }
    assertThatThrownBy(() -> sqlService.execute("SINK INTO " + mapName + "(__key, this) VALUES(1, null)")).isInstanceOf(HazelcastSqlException.class).hasMessageContaining("Writing to top-level fields of type OBJECT not supported");
    sqlService.execute("SINK INTO " + mapName + (explicit ? "(__key, name)" : "") + " VALUES (1, 'foo')");
    Iterator<SqlRow> resultIter = sqlService.execute("SELECT __key, this, name FROM " + mapName).iterator();
    SqlRow row = resultIter.next();
    assertEquals(1, (int) row.getObject(0));
    assertInstanceOf(GenericRecord.class, row.getObject(1));
    assertEquals("foo", row.getObject(2));
    assertFalse(resultIter.hasNext());
}
Also used : SqlRow(com.hazelcast.sql.SqlRow) HazelcastSqlException(com.hazelcast.sql.HazelcastSqlException)

Example 35 with SqlRow

use of com.hazelcast.sql.SqlRow in project hazelcast by hazelcast.

the class BetweenOperatorIntegrationTest method checkSuccessOrFailure.

protected void checkSuccessOrFailure(String sql, Tuple2<List<SqlRow>, HazelcastSqlException> expectedOutcome, Object... params) {
    try {
        List<SqlRow> rows = execute(sql, params);
        assertNull(expectedOutcome.f1());
        assertEquals(expectedOutcome.f0().size(), rows.size());
        List<SqlRow> expectedResultsList = expectedOutcome.f0();
        for (int i = 0; i < rows.size(); i++) {
            SqlColumnType expectedType = expectedResultsList.get(i).getMetadata().getColumn(0).getType();
            SqlColumnType actualType = rows.get(i).getMetadata().getColumn(0).getType();
            assertEquals(expectedType, actualType);
            Object actualObject = rows.get(i).getObject(0);
            Object expectedObject = expectedResultsList.get(i).getObject(0);
            assertEquals(expectedObject, actualObject);
        }
    } catch (HazelcastSqlException e) {
        assertNotNull(expectedOutcome.f1());
        // Expected :At line 1, column [5]5: ...
        // Actual   :At line 1, column [6]5: ...
        // To overcome             this ^ we are comparing substrings like
        // "Parameter at position 1 must be of $1 type, but $2 was found (consider adding an explicit CAST)"
        // 
        // Expected :The Jet SQL job failed: Execution on a member failed: com.hazelcast.jet.JetException: Exception in ProcessorTasklet{06bd-fcd0-9e82-0001/Project(IMap[public.map])#1}: com.hazelcast.sql.impl.QueryException: ...
        // Actual   :The Jet SQL job failed: Execution on a member failed: com.hazelcast.jet.JetException: Exception in ProcessorTasklet{06bd-fcd0-9e83-0001/Project(IMap[public.map])#1}: com.hazelcast.sql.impl.QueryException: ...
        // To overcome                                                                                                                           this ^ we are comparing substrings like
        // "Cannot compare two OBJECT values, because left operand has class com.hazelcast.jet.sql.impl.support.expressions.ExpressionType$ObjectHolder type and right operand has class java.lang.String type
        int startIndex = e.getMessage().indexOf("Parameter");
        if (startIndex == -1) {
            startIndex = e.getMessage().indexOf("Cannot compare");
        }
        assertEquals(expectedOutcome.f1().getMessage().substring(startIndex), e.getMessage().substring(startIndex));
    }
}
Also used : SqlRow(com.hazelcast.sql.SqlRow) SqlColumnType(com.hazelcast.sql.SqlColumnType) HazelcastSqlException(com.hazelcast.sql.HazelcastSqlException)

Aggregations

SqlRow (com.hazelcast.sql.SqlRow)65 Test (org.junit.Test)35 SqlResult (com.hazelcast.sql.SqlResult)29 QuickTest (com.hazelcast.test.annotation.QuickTest)25 ParallelJVMTest (com.hazelcast.test.annotation.ParallelJVMTest)17 SqlRowMetadata (com.hazelcast.sql.SqlRowMetadata)13 HazelcastSqlException (com.hazelcast.sql.HazelcastSqlException)11 ArrayList (java.util.ArrayList)10 HazelcastInstance (com.hazelcast.core.HazelcastInstance)8 SqlStatement (com.hazelcast.sql.SqlStatement)7 SqlService (com.hazelcast.sql.SqlService)5 HashSet (java.util.HashSet)5 SqlColumnType (com.hazelcast.sql.SqlColumnType)3 ClientConfig (com.hazelcast.client.config.ClientConfig)2 Config (com.hazelcast.config.Config)2 IndexConfig (com.hazelcast.config.IndexConfig)2 HazelcastException (com.hazelcast.core.HazelcastException)2 ExpressionBiValue (com.hazelcast.jet.sql.impl.support.expressions.ExpressionBiValue)2 IMap (com.hazelcast.map.IMap)2 SqlColumnMetadata (com.hazelcast.sql.SqlColumnMetadata)2