index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin/resultset/GremlinResultSetTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.gremlin.resultset; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import software.aws.neptune.gremlin.GremlinConnection; import software.aws.neptune.gremlin.GremlinConnectionProperties; import software.aws.neptune.gremlin.mock.MockGremlinDatabase; import java.io.IOException; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import static software.aws.neptune.gremlin.GremlinHelper.createVertex; import static software.aws.neptune.gremlin.GremlinHelper.dropVertex; import static software.aws.neptune.gremlin.GremlinHelper.getProperties; import static software.aws.neptune.gremlin.GremlinHelper.getVertex; class GremlinResultSetTest { private static final String HOSTNAME = "localhost"; private static final int PORT = 8181; // Mock server uses 8181. private static final String VERTEX = "planet"; @SuppressWarnings({"unchecked", "rawtypes"}) private static final Map<String, Object> VERTEX_PROPERTIES_MAP = new HashMap(); private static java.sql.Connection connection; private static java.sql.ResultSet resultSet; static { VERTEX_PROPERTIES_MAP.put("name", "Earth"); VERTEX_PROPERTIES_MAP.put("continents", 7); VERTEX_PROPERTIES_MAP.put("diameter", 12742); VERTEX_PROPERTIES_MAP.put("age", 4500000000L); VERTEX_PROPERTIES_MAP.put("tilt", 23.4392811); VERTEX_PROPERTIES_MAP.put("density", 5.514F); VERTEX_PROPERTIES_MAP.put("supportsLife", true); } @BeforeAll static void beforeAll() throws SQLException, IOException, InterruptedException { MockGremlinDatabase.startGraph(); connection = new GremlinConnection(new GremlinConnectionProperties(getProperties(HOSTNAME, PORT))); createVertex(connection, VERTEX, VERTEX_PROPERTIES_MAP); resultSet = getVertex(connection, VERTEX); Assertions.assertNotNull(resultSet); Assertions.assertDoesNotThrow(() -> resultSet.next()); } @AfterAll static void shutdown() throws SQLException, IOException, InterruptedException { dropVertex(connection, VERTEX); connection.close(); MockGremlinDatabase.stopGraph(); } @Test void testBooleanType() throws SQLException { final int col = resultSet.findColumn("supportsLife"); Assertions.assertTrue(resultSet.getBoolean(col)); Assertions.assertEquals(((Boolean) true).toString(), resultSet.getString(col)); Assertions.assertThrows(SQLException.class, () -> resultSet.getByte(col)); Assertions.assertThrows(SQLException.class, () -> resultSet.getShort(col)); Assertions.assertThrows(SQLException.class, () -> resultSet.getInt(col)); Assertions.assertThrows(SQLException.class, () -> resultSet.getLong(col)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDouble(col)); Assertions.assertThrows(SQLException.class, () -> resultSet.getFloat(col)); } @Test void testShortType() throws SQLException { final int col = resultSet.findColumn("continents"); final int expected = (int) VERTEX_PROPERTIES_MAP.get("continents"); Assertions.assertEquals(expected, 7); Assertions.assertEquals((byte) expected, resultSet.getByte(col)); Assertions.assertEquals((short) expected, resultSet.getShort(col)); Assertions.assertEquals(expected, resultSet.getInt(col)); Assertions.assertEquals(expected, resultSet.getLong(col)); Assertions.assertEquals(expected, resultSet.getDouble(col)); Assertions.assertEquals(expected, resultSet.getFloat(col)); Assertions.assertEquals(((Integer) expected).toString(), resultSet.getString(col)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(col)); } @Test void testIntegerType() throws SQLException { final int col = resultSet.findColumn("diameter"); final int expected = (int) VERTEX_PROPERTIES_MAP.get("diameter"); Assertions.assertEquals(expected, 12742); Assertions.assertEquals(expected, resultSet.getInt(col)); Assertions.assertEquals(expected, resultSet.getLong(col)); Assertions.assertEquals(expected, resultSet.getDouble(col)); Assertions.assertEquals(expected, resultSet.getFloat(col)); Assertions.assertEquals(((Integer) expected).toString(), resultSet.getString(col)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(col)); } @Test void testLongType() throws SQLException { final int col = resultSet.findColumn("age"); final long expected = (long) VERTEX_PROPERTIES_MAP.get("age"); Assertions.assertEquals(expected, 4500000000L); Assertions.assertEquals(expected, resultSet.getLong(col)); Assertions.assertEquals(expected, resultSet.getDouble(col)); Assertions.assertEquals(expected, resultSet.getFloat(col)); Assertions.assertEquals(((Long) expected).toString(), resultSet.getString(col)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(col)); } @Test void testDoubleType() throws SQLException { // TODO AN-813: Fix insert type of data. final int col = resultSet.findColumn("tilt"); final String expected = VERTEX_PROPERTIES_MAP.get("tilt").toString(); Assertions.assertEquals(expected, resultSet.getString(col)); } @Test void testFloatingPointType() throws SQLException { // TODO AN-813: Fix insert type of data. final int col = resultSet.findColumn("density"); final String expected = VERTEX_PROPERTIES_MAP.get("density").toString(); Assertions.assertEquals(expected, resultSet.getString(col)); } @Test void testStringType() throws SQLException { final int col = resultSet.findColumn("name"); final String expected = (String) VERTEX_PROPERTIES_MAP.get("name"); Assertions.assertEquals(expected, "Earth"); Assertions.assertEquals(expected, resultSet.getString(col)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(col)); Assertions.assertThrows(SQLException.class, () -> resultSet.getByte(col)); Assertions.assertThrows(SQLException.class, () -> resultSet.getShort(col)); Assertions.assertThrows(SQLException.class, () -> resultSet.getInt(col)); Assertions.assertThrows(SQLException.class, () -> resultSet.getLong(col)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDouble(col)); Assertions.assertThrows(SQLException.class, () -> resultSet.getFloat(col)); } @Test void testScalarResult() throws SQLException { final GremlinResultSet scalarResultSet = (GremlinResultSet) connection.createStatement() .executeQuery("g.V().count()"); Assertions.assertNotNull(scalarResultSet); Assertions.assertDoesNotThrow(scalarResultSet::next); final int col = scalarResultSet.findColumn("_col0"); Assertions.assertEquals(1, scalarResultSet.getLong(col)); } @Test void testMultipleScalarResults() throws SQLException { final GremlinResultSet scalarResultSet = (GremlinResultSet) connection.createStatement() .executeQuery(String.format("g.V().hasLabel('%s').properties().key()", VERTEX)); Assertions.assertNotNull(scalarResultSet); int unnamedColumnsFound = 0; while (scalarResultSet.next()) { final int col = scalarResultSet.findColumn("_col" + unnamedColumnsFound); Assertions.assertTrue(VERTEX_PROPERTIES_MAP.containsKey(scalarResultSet.getString(col))); unnamedColumnsFound++; } Assertions.assertEquals(VERTEX_PROPERTIES_MAP.keySet().size(), unnamedColumnsFound); } }
7,300
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin/mock/MockGremlinDatabase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.gremlin.mock; import org.apache.commons.lang3.SystemUtils; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; public class MockGremlinDatabase { private static final String WINDOWS_SERVER = "gremlin-server.bat"; private static final String NIX_SERVER = "gremlin-server.sh"; private static final String SERVER_PATH = "./gremlin-server/target/apache-tinkerpop-gremlin-server-3.5.0-SNAPSHOT-standalone/bin/"; private static final String SERVER_COMMAND = SERVER_PATH + NIX_SERVER; private static final String START_COMMAND = String.format("%s start", SERVER_COMMAND); private static final String STOP_COMMAND = String.format("%s stop", SERVER_COMMAND); private static Process serverProcess = null; /** * Simple function to start the database. * * @throws IOException thrown if command fails. * @throws InterruptedException thrown if command fails. */ public static void startGraph() throws IOException, InterruptedException { final String output = runCommand(START_COMMAND); if (output.startsWith("Server already running with PID")) { return; } Thread.sleep(10000); } /** * Simple function to shut the database down. * * @throws IOException thrown if command fails. */ public static void stopGraph() throws IOException, InterruptedException { runCommand(STOP_COMMAND); Thread.sleep(10000); } private static String runCommand(final String command) throws IOException { if (SystemUtils.IS_OS_WINDOWS) { runWindowsCommand(command); } else { serverProcess = Runtime.getRuntime().exec(command); } final BufferedReader input = new BufferedReader(new InputStreamReader(serverProcess.getInputStream())); return input.readLine(); } private static void runWindowsCommand(final String command) throws IOException { if (command.equals(START_COMMAND)) { final ProcessBuilder pb = new ProcessBuilder("cmd", "/c", WINDOWS_SERVER); final File directoryFile = new File(SERVER_PATH); pb.directory(directoryFile); serverProcess = pb.start(); } if (command.equals(STOP_COMMAND) && serverProcess != null) { serverProcess.destroy(); } } }
7,301
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin/adapter/GremlinSqlBasicSelectTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.gremlin.adapter; import com.google.common.collect.ImmutableList; import org.junit.jupiter.api.Test; import software.aws.neptune.gremlin.adapter.graphs.GraphConstants; import java.sql.SQLException; import java.util.List; public class GremlinSqlBasicSelectTest extends GremlinSqlBaseTest { GremlinSqlBasicSelectTest() throws SQLException { } @Override protected DataSet getDataSet() { return DataSet.DATA_TYPES; } @Test void testStringQuery() throws SQLException { runQueryTestResults("SELECT \"key\" FROM stringtype", columns("key"), rows(r(GraphConstants.STRING_VALUE))); } @Test void testByteQuery() throws SQLException { runQueryTestResults("SELECT \"key\" FROM bytetype", columns("key"), rows(r(GraphConstants.BYTE_VALUE))); } @Test void testShortQuery() throws SQLException { runQueryTestResults("SELECT \"key\" FROM shorttype", columns("key"), rows(r(GraphConstants.SHORT_VALUE))); } @Test void testIntegerQuery() throws SQLException { runQueryTestResults("SELECT \"key\" FROM inttype", columns("key"), rows(r(GraphConstants.INTEGER_VALUE))); } @Test void testLongQuery() throws SQLException { runQueryTestResults("SELECT \"key\" FROM longtype", columns("key"), rows(r(GraphConstants.LONG_VALUE))); } @Test void testFloatQuery() throws SQLException { runQueryTestResults("SELECT \"key\" FROM floattype", columns("key"), rows(r(GraphConstants.FLOAT_VALUE))); } @Test void testDoubleQuery() throws SQLException { runQueryTestResults("SELECT \"key\" FROM doubletype", columns("key"), rows(r(GraphConstants.DOUBLE_VALUE))); } @Test void testDateQuery() throws SQLException { runQueryTestResults("SELECT \"key\" FROM datetype", columns("key"), rows(r(GraphConstants.DATE_VALUE))); } @Test void testEdgeQueries() throws SQLException { runQueryTestResults("SELECT key FROM stringtypeedge", columns("key"), rows(r(GraphConstants.STRING_VALUE))); runQueryTestResults("SELECT * FROM stringtypeedge", columns("stringtype_IN_ID", "stringtypeedge_ID", "stringtype_OUT_ID", "key"), rows(r(0L, 16L, 0L, GraphConstants.STRING_VALUE))); } String getAsOperatorQuery(final String column, final String asColumn, final String table) { return String.format("SELECT %s AS %s FROM %s", column, asColumn, table); } String getAsOperatorQuery(final String column, final String asColumn, final String table, final String asTable) { return String.format("SELECT %s.%s AS %s FROM %s %s", asTable, column, asColumn, table, asTable); } @Test void testAsOperator() throws SQLException { final List<String> columns = ImmutableList.of("key", "\"key\""); final List<String> asColumns = ImmutableList.of("key", "\"key\"", "k", "\"k\""); final List<String> tables = ImmutableList.of("stringtype", "\"stringtype\""); final List<String> asTables = ImmutableList.of("st", "\"st\""); for (final String column : columns) { for (final String asColumn : asColumns) { for (final String table : tables) { runQueryTestResults(getAsOperatorQuery(column, asColumn, table), columns(asColumn.replace("\"", "")), rows(r(GraphConstants.STRING_VALUE))); for (final String asTable : asTables) { runQueryTestResults(getAsOperatorQuery(column, asColumn, table, asTable), columns(asColumn.replace("\"", "")), rows(r(GraphConstants.STRING_VALUE))); } } } } } }
7,302
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin/adapter/GremlinSqlAggregateTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.gremlin.adapter; import org.junit.jupiter.api.Test; import java.sql.SQLException; public class GremlinSqlAggregateTest extends GremlinSqlBaseTest { GremlinSqlAggregateTest() throws SQLException { } @Override protected DataSet getDataSet() { return DataSet.SPACE; } @Test public void testAggregateFunctions() throws SQLException { runQueryTestResults("select count(age), min(age), max(age), avg(age) from person", columns("COUNT(age)", "MIN(age)", "MAX(age)", "AVG(age)"), rows(r(6L, 29, 50, 36.666666666666664))); } @Test public void testAggregateColumnTypeNoRename() throws SQLException { // validate the metadata type matches return type runQueryTestColumnType("select count(age), min(age), max(age), avg(age) from person"); } @Test public void testAggregateColumnTypeOneRename() throws SQLException { // validate the metadata type matches return type runQueryTestColumnType("select count(age) as c from person"); } @Test public void testAggregateColumnTypeAllRename() throws SQLException { // validate the metadata type matches return type runQueryTestColumnType("select count(age) as c, min(age) as m1, max(age) as m2, avg(age) as a from person"); } @Test public void testAggregateColumnTypeMixedRename() throws SQLException { // validate the metadata type matches return type runQueryTestColumnType("select count(age) as c, min(age) as m1, max(age), avg(age) from person"); } @Test public void testAggregateColumnTypeMixedAgg() throws SQLException { // validate the metadata type matches return type runQueryTestColumnType("select age, count(age) from person group by age"); } @Test public void testCountStar() throws SQLException { // Validate that the output column is COUNT(*) and the value is correct. runQueryTestResults("SELECT COUNT(*) FROM person", columns("COUNT(*)"), rows(r(6L))); } @Test public void testCountWhereGroupBy() throws SQLException { runQueryTestResults("SELECT wentToSpace, COUNT(age) FROM person WHERE age > 30 GROUP BY wentToSpace", columns("wentToSpace", "COUNT(age)"), rows(r(false, 2L), r(true, 2L))); runQueryTestResults("SELECT wentToSpace, COUNT(age) FROM person WHERE age > 50 GROUP BY wentToSpace", columns("wentToSpace", "COUNT(age)"), rows()); runQueryTestResults("SELECT wentToSpace, COUNT(age) FROM person WHERE age > 0 GROUP BY wentToSpace", columns("wentToSpace", "COUNT(age)"), rows(r(false, 3L), r(true, 3L))); runQueryTestResults("SELECT wentToSpace, COUNT(age) FROM person WHERE age < 100 AND wentToSpace = FALSE GROUP BY wentToSpace", columns("wentToSpace", "COUNT(age)"), rows(r(false, 3L))); runQueryTestResults("SELECT wentToSpace, COUNT(age) FROM person WHERE age > 31 AND wentToSpace = FALSE GROUP BY wentToSpace", columns("wentToSpace", "COUNT(age)"), rows(r(false, 1L))); } }
7,303
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin/adapter/GremlinSqlJoinTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.gremlin.adapter; import org.junit.jupiter.api.Test; import software.aws.neptune.gremlin.adapter.util.SqlGremlinError; import java.sql.SQLException; public class GremlinSqlJoinTest extends GremlinSqlBaseTest { GremlinSqlJoinTest() throws SQLException { } @Override protected DataSet getDataSet() { return DataSet.SPACE; } @Test void testJoinSameVertex() throws SQLException { runJoinQueryTestResults("SELECT person.name AS name1, person1.name AS name2 FROM gremlin.person person " + "INNER JOIN gremlin.person person1 ON (person.friendsWith_OUT_ID = person1.friendsWith_IN_ID)", columns("name1", "name2"), rows(r("Tom", "Patty"), r("Patty", "Juanita"), r("Phil", "Susan"), r("Susan", "Pavel"))); runJoinQueryTestResults("SELECT person.name AS name1, person1.name AS name2 FROM gremlin.person person " + "INNER JOIN gremlin.person person1 ON (person.friendsWith_OUT_ID = person1.friendsWith_IN_ID) " + "GROUP BY person.name, person1.name", columns("name1", "name2"), rows(r("Tom", "Patty"), r("Patty", "Juanita"), r("Phil", "Susan"), r("Susan", "Pavel"))); runJoinQueryTestResults("SELECT person.name FROM gremlin.person person " + "INNER JOIN gremlin.person person1 ON (person.friendsWith_OUT_ID = person1.friendsWith_IN_ID) " + "GROUP BY person.name", columns("name"), rows(r("Tom"), r("Patty"), r("Phil"), r("Susan"))); runJoinQueryTestResults("SELECT person1.name FROM gremlin.person person " + "INNER JOIN gremlin.person person1 ON (person.friendsWith_OUT_ID = person1.friendsWith_IN_ID) " + "GROUP BY person1.name", columns("name"), rows(r("Patty"), r("Juanita"), r("Susan"), r("Pavel"))); runJoinQueryTestResults("SELECT p.name FROM gremlin.person p " + "INNER JOIN gremlin.person p1 ON (p.friendsWith_OUT_ID = p1.friendsWith_IN_ID) " + "GROUP BY p.name", columns("name"), rows(r("Tom"), r("Patty"), r("Phil"), r("Susan"))); runJoinQueryTestResults("SELECT p.name, COUNT(p1.name) FROM gremlin.person p " + "INNER JOIN gremlin.person p1 ON (p.friendsWith_OUT_ID = p1.friendsWith_IN_ID) " + "GROUP BY p.name", columns("name", "COUNT(name)"), rows(r("Tom", 1L), r("Patty", 1L), r("Phil", 1L), r("Susan", 1L))); } @Test void testJoinDiffVertex() throws SQLException { runJoinQueryTestResults("SELECT person.name, spaceship.model FROM gremlin.person person " + "INNER JOIN gremlin.spaceship spaceship ON (person.pilots_OUT_ID = spaceship.pilots_IN_ID)", columns("name", "model"), rows(r("Tom", "delta 1"), r("Patty", "delta 1"), r("Phil", "delta 1"), r("Susan", "delta 2"), r("Juanita", "delta 3"), r("Pavel", "delta 3"))); runJoinQueryTestResults("SELECT person.name, spaceship.model FROM gremlin.person person " + "INNER JOIN gremlin.spaceship spaceship ON (person.pilots_OUT_ID = spaceship.pilots_IN_ID) " + "GROUP BY person.name, spaceship.model", columns("name", "model"), rows(r("Tom", "delta 1"), r("Patty", "delta 1"), r("Phil", "delta 1"), r("Susan", "delta 2"), r("Juanita", "delta 3"), r("Pavel", "delta 3"))); runJoinQueryTestResults("SELECT person.name FROM gremlin.person person " + "INNER JOIN gremlin.spaceship spaceship ON (person.pilots_OUT_ID = spaceship.pilots_IN_ID) " + "GROUP BY person.name", columns("name"), rows(r("Tom"), r("Patty"), r("Phil"), r("Susan"), r("Juanita"), r("Pavel"))); runJoinQueryTestResults("SELECT spaceship.model FROM gremlin.person person " + "INNER JOIN gremlin.spaceship spaceship ON (person.pilots_OUT_ID = spaceship.pilots_IN_ID) " + "GROUP BY spaceship.model", columns("model"), rows(r("delta 1"), r("delta 2"), r("delta 3"))); } @Test void testJoinDiffEdge() { // Same vertex label, different edge. runQueryTestThrows("SELECT person.name AS name1, person1.name AS name2 FROM gremlin.person person " + "INNER JOIN gremlin.person person1 ON (person.worksFor_OUT_ID = person1.friendsWith_IN_ID)", SqlGremlinError.CANNOT_JOIN_DIFFERENT_EDGES, "worksFor", "friendsWith"); runQueryTestThrows("SELECT person.name AS name1, person1.name AS name2 FROM gremlin.person person " + "INNER JOIN gremlin.person person1 ON (person.friendsWith_IN_ID = person1.worksFor_OUT_ID)", SqlGremlinError.CANNOT_JOIN_DIFFERENT_EDGES, "friendsWith", "worksFor"); // Different vertex label, different edge. runQueryTestThrows("SELECT person.name, spaceship.model FROM gremlin.person person " + "INNER JOIN gremlin.spaceship spaceship ON (person.worksFor_OUT_ID = spaceship.pilots_IN_ID)", SqlGremlinError.CANNOT_JOIN_DIFFERENT_EDGES, "worksFor", "pilots"); // Different vertex label, different edge. runQueryTestThrows("SELECT person.name, spaceship.model FROM gremlin.person person " + "INNER JOIN gremlin.spaceship spaceship ON (spaceship.pilots_IN_ID = person.worksFor_OUT_ID)", SqlGremlinError.CANNOT_JOIN_DIFFERENT_EDGES, "worksFor", "pilots"); } @Test void testJoinWhere() throws SQLException { runJoinQueryTestResults("SELECT person.name FROM gremlin.person person " + "INNER JOIN gremlin.person person1 ON (person.friendsWith_OUT_ID = person1.friendsWith_IN_ID) " + "WHERE person.name = 'Tom'" + "GROUP BY person.name", columns("name"), rows(r("Tom"))); runJoinQueryTestResults("SELECT person.name FROM gremlin.person person " + "INNER JOIN gremlin.person person1 ON (person.friendsWith_OUT_ID = person1.friendsWith_IN_ID) " + "WHERE person.name = 'Tom'", columns("name"), rows(r("Tom"))); runJoinQueryTestResults("SELECT person.name FROM gremlin.person person " + "INNER JOIN gremlin.person person1 ON (person.friendsWith_OUT_ID = person1.friendsWith_IN_ID) " + "WHERE person.name <> 'Tom'", columns("name"), rows(r("Patty"), r("Phil"), r("Susan"))); runJoinQueryTestResults("SELECT person.name, person.wentToSpace FROM gremlin.person person " + "INNER JOIN gremlin.person person1 ON (person.friendsWith_OUT_ID = person1.friendsWith_IN_ID) " + "WHERE person.wentToSpace", columns("name", "wentToSpace"), rows(r("Susan", true))); runJoinQueryTestResults("SELECT person.name FROM gremlin.person person " + "INNER JOIN gremlin.person person1 ON (person.friendsWith_OUT_ID = person1.friendsWith_IN_ID) " + "WHERE NOT person.wentToSpace", columns("name"), rows(r("Tom"), r("Patty"), r("Phil"))); runJoinQueryTestResults("SELECT person.name FROM gremlin.person person " + "INNER JOIN gremlin.person person1 ON (person.friendsWith_OUT_ID = person1.friendsWith_IN_ID) " + "WHERE person.age = 35", columns("name"), rows(r("Tom"))); runJoinQueryTestResults("SELECT person.name FROM gremlin.person person " + "INNER JOIN gremlin.person person1 ON (person.friendsWith_OUT_ID = person1.friendsWith_IN_ID) " + "WHERE person.age >= 35", columns("name"), rows(r("Tom"), r("Susan"))); runJoinQueryTestResults("SELECT person.name FROM gremlin.person person " + "INNER JOIN gremlin.person person1 ON (person.friendsWith_OUT_ID = person1.friendsWith_IN_ID) " + "WHERE person.age <= 35", columns("name"), rows(r("Tom"), r("Patty"), r("Phil"))); runJoinQueryTestResults("SELECT person.name FROM gremlin.person person " + "INNER JOIN gremlin.person person1 ON (person.friendsWith_OUT_ID = person1.friendsWith_IN_ID) " + "WHERE person.age < 35", columns("name"), rows(r("Patty"), r("Phil"))); runJoinQueryTestResults("SELECT person.name FROM gremlin.person person " + "INNER JOIN gremlin.person person1 ON (person.friendsWith_OUT_ID = person1.friendsWith_IN_ID) " + "WHERE person.age > 35", columns("name"), rows(r("Susan"))); runJoinQueryTestResults("SELECT person.name FROM gremlin.person person " + "INNER JOIN gremlin.person person1 ON (person.friendsWith_OUT_ID = person1.friendsWith_IN_ID) " + "WHERE person.age <> 35", columns("name"), rows(r("Patty"), r("Phil"), r("Susan"))); runJoinQueryTestResults("SELECT person.name FROM gremlin.person person " + "INNER JOIN gremlin.person person1 ON (person.friendsWith_OUT_ID = person1.friendsWith_IN_ID) " + "WHERE person.age >= 35 AND person.name = 'Tom'", columns("name"), rows(r("Tom"))); runJoinQueryTestResults("SELECT person.name FROM gremlin.person person " + "INNER JOIN gremlin.person person1 ON (person.friendsWith_OUT_ID = person1.friendsWith_IN_ID) " + "WHERE person.age <> 35 OR person.name = 'Tom'", columns("name"), rows(r("Tom"), r("Patty"), r("Phil"), r("Susan"))); runJoinQueryTestResults("SELECT person.name FROM gremlin.person person " + "INNER JOIN gremlin.person person1 ON (person.friendsWith_OUT_ID = person1.friendsWith_IN_ID) " + "WHERE person.age <= 35 AND person.name <> 'Tom' AND NOT person.wentToSpace", columns("name"), rows(r("Patty"), r("Phil"))); runJoinQueryTestResults("SELECT person.name FROM gremlin.person person " + "INNER JOIN gremlin.person person1 ON (person.friendsWith_OUT_ID = person1.friendsWith_IN_ID) " + "WHERE NOT person.name = 'Tom'", columns("name"), rows(r("Patty"), r("Phil"), r("Susan"))); } @Test void testJoinHaving() throws SQLException { runJoinQueryTestResults( "SELECT person.name, COUNT(person1.age) FROM gremlin.person person " + "INNER JOIN gremlin.person person1 ON person.friendsWith_OUT_ID = person1.friendsWith_IN_ID " + "GROUP BY person.name HAVING COUNT(person1.age) > 0", columns("name", "COUNT(age)"), rows(r("Tom", 1L), r("Patty", 1L), r("Phil", 1L), r("Susan", 1L))); runJoinQueryTestResults("SELECT spaceship.model, COUNT(person.name) FROM gremlin.person person " + "INNER JOIN gremlin.spaceship spaceship ON (person.pilots_OUT_ID = spaceship.pilots_IN_ID) " + "GROUP BY spaceship.model HAVING COUNT(person.name) >= 1", columns("model", "COUNT(name)"), rows(r("delta 1", 3L), r("delta 2", 1L), r("delta 3", 2L))); runJoinQueryTestResults("SELECT spaceship.model, COUNT(person.name) FROM gremlin.person person " + "INNER JOIN gremlin.spaceship spaceship ON (person.pilots_OUT_ID = spaceship.pilots_IN_ID) " + "GROUP BY spaceship.model HAVING COUNT(person.name) <> 2", columns("model", "COUNT(name)"), rows(r("delta 1", 3L), r("delta 2", 1L))); runJoinQueryTestResults("SELECT spaceship.model, COUNT(person.name) FROM gremlin.person person " + "INNER JOIN gremlin.spaceship spaceship ON (person.pilots_OUT_ID = spaceship.pilots_IN_ID) " + "GROUP BY spaceship.model HAVING COUNT(person.name) > 1", columns("model", "COUNT(name)"), rows(r("delta 1", 3L), r("delta 3", 2L))); runJoinQueryTestResults("SELECT spaceship.model, COUNT(person.name) FROM gremlin.person person " + "INNER JOIN gremlin.spaceship spaceship ON (person.pilots_OUT_ID = spaceship.pilots_IN_ID) " + "GROUP BY spaceship.model HAVING COUNT(person.name) <= 1 OR COUNT(person.name) >= 3", columns("model", "COUNT(name)"), rows(r("delta 1", 3L), r("delta 2", 1L))); runJoinQueryTestResults("SELECT spaceship.model, COUNT(person.name) FROM gremlin.person person " + "INNER JOIN gremlin.spaceship spaceship ON (person.pilots_OUT_ID = spaceship.pilots_IN_ID) " + "GROUP BY spaceship.model HAVING COUNT(person.name) <= 1", columns("model", "COUNT(name)"), rows(r("delta 2", 1L))); runJoinQueryTestResults("SELECT spaceship.model, SUM(person.age) FROM gremlin.person person " + "INNER JOIN gremlin.spaceship spaceship ON (person.pilots_OUT_ID = spaceship.pilots_IN_ID) " + "GROUP BY spaceship.model HAVING SUM(person.age) > 50", columns("model", "SUM(age)"), rows(r("delta 1", 95L), r("delta 3", 80L))); runJoinQueryTestResults("SELECT spaceship.model, SUM(person.age) FROM gremlin.person person " + "INNER JOIN gremlin.spaceship spaceship ON (person.pilots_OUT_ID = spaceship.pilots_IN_ID) " + "GROUP BY spaceship.model HAVING SUM(person.age) <> 80", columns("model", "SUM(age)"), rows(r("delta 1", 95L), r("delta 2", 45L))); runJoinQueryTestResults("SELECT spaceship.model, SUM(person.age) FROM gremlin.person person " + "INNER JOIN gremlin.spaceship spaceship ON (person.pilots_OUT_ID = spaceship.pilots_IN_ID) " + "GROUP BY spaceship.model HAVING SUM(person.age) <> 95", columns("model", "SUM(age)"), rows(r("delta 2", 45L), r("delta 3", 80L))); runJoinQueryTestResults("SELECT spaceship.model, MAX(person.age) FROM gremlin.person person " + "INNER JOIN gremlin.spaceship spaceship ON (person.pilots_OUT_ID = spaceship.pilots_IN_ID) " + "GROUP BY spaceship.model HAVING MAX(person.age) > 40", columns("model", "MAX(age)"), rows(r("delta 2", 45), r("delta 3", 50))); runJoinQueryTestResults("SELECT spaceship.model, MIN(person.age) FROM gremlin.person person " + "INNER JOIN gremlin.spaceship spaceship ON (person.pilots_OUT_ID = spaceship.pilots_IN_ID) " + "GROUP BY spaceship.model HAVING MIN(person.age) < 40", columns("model", "MIN(age)"), rows(r("delta 1", 29), r("delta 3", 30))); runJoinQueryTestResults("SELECT spaceship.model, AVG(person.age) FROM gremlin.person person " + "INNER JOIN gremlin.spaceship spaceship ON (person.pilots_OUT_ID = spaceship.pilots_IN_ID) " + "GROUP BY spaceship.model HAVING AVG(person.age) > 35", columns("model", "AVG(age)"), rows(r("delta 2", 45.0), r("delta 3", 40.0))); runJoinQueryTestResults("SELECT spaceship.model FROM gremlin.person person " + "INNER JOIN gremlin.spaceship spaceship ON (person.pilots_OUT_ID = spaceship.pilots_IN_ID) " + "GROUP BY spaceship.model HAVING MIN(person.age) < 40 AND AVG(person.age) > 35", columns("model"), rows(r("delta 3"))); runJoinQueryTestResults("SELECT spaceship.model FROM gremlin.person person " + "INNER JOIN gremlin.spaceship spaceship ON (person.pilots_OUT_ID = spaceship.pilots_IN_ID) " + "GROUP BY spaceship.model HAVING MIN(person.age) < 40 OR AVG(person.age) > 35", columns("model"), rows(r("delta 1"), r("delta 2"), r("delta 3"))); runJoinQueryTestResults("SELECT spaceship.model FROM gremlin.person person " + "INNER JOIN gremlin.spaceship spaceship ON (person.pilots_OUT_ID = spaceship.pilots_IN_ID) " + "GROUP BY spaceship.model HAVING spaceship.model = 'delta 2'", columns("model"), rows(r("delta 2"))); } }
7,304
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin/adapter/GremlinSqlBaseTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.gremlin.adapter; import lombok.Getter; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.structure.Graph; import org.junit.Assert; import org.junit.jupiter.api.Assertions; import software.aws.neptune.gremlin.adapter.converter.SqlConverter; import software.aws.neptune.gremlin.adapter.converter.schema.SqlSchemaGrabber; import software.aws.neptune.gremlin.adapter.converter.schema.calcite.GremlinSchema; import software.aws.neptune.gremlin.adapter.graphs.TestGraphFactory; import software.aws.neptune.gremlin.adapter.results.SqlGremlinQueryResult; import software.aws.neptune.gremlin.adapter.util.SQLNotSupportedException; import software.aws.neptune.gremlin.adapter.util.SqlGremlinError; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; /** * Created by twilmes on 12/4/15. */ public abstract class GremlinSqlBaseTest { private final Graph graph; private final GraphTraversalSource g; private final SqlConverter converter; GremlinSqlBaseTest() throws SQLException { graph = TestGraphFactory.createGraph(getDataSet()); g = graph.traversal(); final GremlinSchema gremlinSchema = SqlSchemaGrabber.getSchema(g, SqlSchemaGrabber.ScanType.All); converter = new SqlConverter(gremlinSchema); } protected abstract DataSet getDataSet(); protected void runQueryTestColumnType(final String query) throws SQLException { final SqlGremlinQueryResult sqlGremlinQueryResult = converter.executeQuery(g, query); final int columnCount = sqlGremlinQueryResult.getColumns().size(); final SqlGremlinTestResult result = new SqlGremlinTestResult(sqlGremlinQueryResult); final List<Class<?>> returnedColumnType = new ArrayList<>(); final List<Class<?>> metadataColumnType = new ArrayList<>(); for (int i = 0; i < columnCount; i++) { returnedColumnType.add(result.getRows().get(0).get(i).getClass()); metadataColumnType.add(getType(sqlGremlinQueryResult.getColumnTypes().get(i))); } assertResultTypes(returnedColumnType, metadataColumnType); } public void assertResultTypes(final List<Class<?>> actual, final List<Class<?>> expected) { Assertions.assertEquals(expected.size(), actual.size()); for (int i = 0; i < actual.size(); i++) { Assertions.assertEquals(expected.get(i), actual.get(i)); } } private Class<?> getType(final String className) { if ("string".equalsIgnoreCase(className)) { return String.class; } else if ("integer".equalsIgnoreCase(className)) { return Integer.class; } else if ("float".equalsIgnoreCase(className)) { return Float.class; } else if ("byte".equalsIgnoreCase(className)) { return Byte.class; } else if ("short".equalsIgnoreCase(className)) { return Short.class; } else if ("double".equalsIgnoreCase(className)) { return Double.class; } else if ("long".equalsIgnoreCase(className)) { return Long.class; } else if ("boolean".equalsIgnoreCase(className)) { return Boolean.class; } else if ("date".equalsIgnoreCase(className) || "long_date".equalsIgnoreCase(className)) { return java.sql.Date.class; } else if ("timestamp".equalsIgnoreCase(className) || "long_timestamp".equalsIgnoreCase(className)) { return java.sql.Timestamp.class; } else { return null; } } protected void runQueryTestResults(final String query, final List<String> columnNames, final List<List<?>> rows) throws SQLException { final SqlGremlinTestResult result = new SqlGremlinTestResult(converter.executeQuery(g, query)); assertColumns(result.getColumns(), columnNames); assertRows(result.getRows(), rows); } protected void runJoinQueryTestResults(final String query, final List<String> columnNames, final List<List<?>> rows) throws SQLException { final SqlGremlinTestResult result = new SqlGremlinTestResult(converter.executeQuery(g, query)); assertColumns(new HashSet<>(result.getColumns()), new HashSet<>(columnNames)); assertJoinRows(result.getRows().stream().map(HashSet::new).collect(Collectors.toList()), rows.stream().map(HashSet::new).collect(Collectors.toList())); } protected void runQueryTestThrows(final String query, final SqlGremlinError messageKey, final Object... formatArgs) { final Throwable t = Assertions.assertThrows(SQLException.class, () -> converter.executeQuery(g, query)); Assert.assertEquals(SqlGremlinError.getMessage(messageKey, formatArgs), t.getMessage()); } protected void runNotSupportedQueryTestThrows(final String query, final SqlGremlinError messageKey, final Object... formatArgs) { final Throwable t = Assertions.assertThrows(SQLNotSupportedException.class, () -> converter.executeQuery(g, query)); Assert.assertEquals(SqlGremlinError.getMessage(messageKey, formatArgs), t.getMessage()); } @SafeVarargs public final List<List<?>> rows(final List<Object>... rows) { return new ArrayList<>(Arrays.asList(rows)); } public List<String> columns(final String... columns) { return new ArrayList<>(Arrays.asList(columns)); } public List<Object> r(final Object... row) { return new ArrayList<>(Arrays.asList(row)); } public void assertRows(final List<List<?>> actual, final List<List<?>> expected) { Assertions.assertEquals(expected.size(), actual.size()); for (int i = 0; i < actual.size(); i++) { Assertions.assertEquals(expected.get(i).size(), actual.get(i).size()); for (int j = 0; j < actual.get(i).size(); j++) { Assertions.assertEquals(expected.get(i).get(j), actual.get(i).get(j)); } } } public void assertJoinRows(final List<Set<?>> actual, final List<Set<?>> expected) { Assertions.assertEquals(expected.size(), actual.size()); for (int i = 0; i < actual.size(); i++) { Assertions.assertEquals(expected.get(i).size(), actual.get(i).size()); for (int j = 0; j < actual.get(i).size(); j++) { Assertions.assertEquals(expected.get(i), actual.get(i)); } } } public void assertColumns(final List<String> actual, final List<String> expected) { Assertions.assertEquals(expected.size(), actual.size()); for (int i = 0; i < actual.size(); i++) { Assertions.assertEquals(expected.get(i), actual.get(i)); } } public void assertColumns(final Set<String> actual, final Set<String> expected) { Assertions.assertEquals(expected, actual); } public enum DataSet { SPACE, SPACE_INCOMPLETE, DATA_TYPES } @Getter static class SqlGremlinTestResult { private final List<List<?>> rows = new ArrayList<>(); private final List<String> columns; SqlGremlinTestResult(final SqlGremlinQueryResult sqlGremlinQueryResult) throws SQLException { columns = sqlGremlinQueryResult.getColumns(); List<?> res; do { res = sqlGremlinQueryResult.getResult(); if (!(res instanceof SqlGremlinQueryResult.EmptyResult)) { this.rows.add(res); } } while (!(res instanceof SqlGremlinQueryResult.EmptyResult)); } } }
7,305
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin/adapter/GremlinSqlNotSupportedTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.gremlin.adapter; import org.junit.jupiter.api.Test; import software.aws.neptune.gremlin.adapter.util.SqlGremlinError; import java.sql.SQLException; public class GremlinSqlNotSupportedTest extends GremlinSqlBaseTest { GremlinSqlNotSupportedTest() throws SQLException { } @Override protected DataSet getDataSet() { return DataSet.SPACE; } @Test public void testOffset() throws SQLException { // OFFSET testing - currently not implemented. runNotSupportedQueryTestThrows("SELECT name FROM person OFFSET 1", SqlGremlinError.OFFSET_NOT_SUPPORTED); } @Test public void testSubQuery() throws SQLException { // Sub Query testing = currently caught by generic catch-all runQueryTestThrows("Select name FROM Person WHERE age = (SELECT age FROM person WHERE name = 'Tom')", SqlGremlinError.UNKNOWN_OPERATOR, "SCALAR_QUERY"); } @Test public void testCast() throws SQLException { runNotSupportedQueryTestThrows("SELECT CAST(17 AS varchar)", SqlGremlinError.UNSUPPORTED_LITERAL_EXPRESSION); runQueryTestThrows("SELECT CAST(person.age as CHAR) FROM person", SqlGremlinError.UNKNOWN_OPERATOR, "CAST"); } }
7,306
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin/adapter/GremlinSqlAdvancedSelectTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.gremlin.adapter; import org.junit.jupiter.api.Test; import software.aws.neptune.gremlin.adapter.util.SqlGremlinError; import java.math.BigDecimal; import java.sql.SQLException; /** * Created by twilmes on 12/7/15. */ public class GremlinSqlAdvancedSelectTest extends GremlinSqlBaseTest { GremlinSqlAdvancedSelectTest() throws SQLException { } @Override protected DataSet getDataSet() { return DataSet.SPACE; } @Test public void testProject() throws SQLException { runQueryTestResults("select name from person", columns("name"), rows(r("Tom"), r("Patty"), r("Phil"), r("Susan"), r("Juanita"), r("Pavel"))); } @Test public void testEdges() throws SQLException { runQueryTestResults("select * from worksFor where yearsWorked = 9", columns("person_OUT_ID", "company_IN_ID", "yearsWorked", "worksFor_ID"), rows(r(26L, 2L, 9, 64L))); } @Test public void testOrder() throws SQLException { // ORDER with integer column. runQueryTestResults("SELECT name, age FROM person ORDER BY age", columns("name", "age"), rows(r("Patty", 29), r("Pavel", 30), r("Phil", 31), r("Tom", 35), r("Susan", 45), r("Juanita", 50))); runQueryTestResults("SELECT name, age FROM person ORDER BY age DESC", columns("name", "age"), rows(r("Juanita", 50), r("Susan", 45), r("Tom", 35), r("Phil", 31), r("Pavel", 30), r("Patty", 29))); runQueryTestResults("SELECT name, age AS a FROM person ORDER BY a", columns("name", "a"), rows(r("Patty", 29), r("Pavel", 30), r("Phil", 31), r("Tom", 35), r("Susan", 45), r("Juanita", 50))); runQueryTestResults("SELECT name, age AS a FROM person ORDER BY a DESC", columns("name", "a"), rows(r("Juanita", 50), r("Susan", 45), r("Tom", 35), r("Phil", 31), r("Pavel", 30), r("Patty", 29))); // ORDER with string column. runQueryTestResults("SELECT name, age FROM person ORDER BY name", columns("name", "age"), rows(r("Juanita", 50), r("Patty", 29), r("Pavel", 30), r("Phil", 31), r("Susan", 45), r("Tom", 35))); runQueryTestResults("SELECT name, age FROM person ORDER BY name DESC", columns("name", "age"), rows(r("Tom", 35), r("Susan", 45), r("Phil", 31), r("Pavel", 30), r("Patty", 29), r("Juanita", 50))); runQueryTestResults("SELECT name AS n, age AS a FROM person ORDER BY n", columns("n", "a"), rows(r("Juanita", 50), r("Patty", 29), r("Pavel", 30), r("Phil", 31), r("Susan", 45), r("Tom", 35))); runQueryTestResults("SELECT name AS n, age AS a FROM person ORDER BY n DESC", columns("n", "a"), rows(r("Tom", 35), r("Susan", 45), r("Phil", 31), r("Pavel", 30), r("Patty", 29), r("Juanita", 50))); } @Test public void testWhere() throws SQLException { // WHERE with string literal. runQueryTestResults("SELECT name, age FROM person WHERE name = 'Tom' ORDER BY age", columns("name", "age"), rows(r("Tom", 35))); runQueryTestResults("SELECT name, age FROM person WHERE name <> 'Tom' ORDER BY age", columns("name", "age"), rows(r("Patty", 29), r("Pavel", 30), r("Phil", 31), r("Susan", 45), r("Juanita", 50))); // WHERE with boolean literal. runQueryTestResults("SELECT name, age FROM person WHERE wentToSpace ORDER BY age", columns("name", "age"), rows(r("Pavel", 30), r("Susan", 45), r("Juanita", 50))); runQueryTestResults("SELECT name, age FROM person WHERE NOT wentToSpace ORDER BY age", columns("name", "age"), rows(r("Patty", 29), r("Phil", 31), r("Tom", 35))); runQueryTestResults("SELECT name, age FROM person WHERE wentToSpace = 1 ORDER BY age", columns("name", "age"), rows(r("Pavel", 30), r("Susan", 45), r("Juanita", 50))); runQueryTestResults("SELECT name, age FROM person WHERE wentToSpace = 0 ORDER BY age", columns("name", "age"), rows(r("Patty", 29), r("Phil", 31), r("Tom", 35))); // WHERE with numeric literal. runQueryTestResults("SELECT name, age FROM person WHERE age = 35 ORDER BY age", columns("name", "age"), rows(r("Tom", 35))); runQueryTestResults("SELECT name, age FROM person WHERE age >= 35 ORDER BY age", columns("name", "age"), rows(r("Tom", 35), r("Susan", 45), r("Juanita", 50))); runQueryTestResults("SELECT name, age FROM person WHERE age <= 35 ORDER BY age", columns("name", "age"), rows(r("Patty", 29), r("Pavel", 30), r("Phil", 31), r("Tom", 35))); runQueryTestResults("SELECT name, age FROM person WHERE age < 35 ORDER BY age", columns("name", "age"), rows(r("Patty", 29), r("Pavel", 30), r("Phil", 31))); runQueryTestResults("SELECT name, age FROM person WHERE age > 35 ORDER BY age", columns("name", "age"), rows(r("Susan", 45), r("Juanita", 50))); runQueryTestResults("SELECT name, age FROM person WHERE age <> 50 ORDER BY age", columns("name", "age"), rows(r("Patty", 29), r("Pavel", 30), r("Phil", 31), r("Tom", 35), r("Susan", 45))); // WHERE with numeric literal and descending order (just for fun). runQueryTestResults("SELECT name, age FROM person WHERE age >= 35 ORDER BY age DESC", columns("name", "age"), rows(r("Juanita", 50), r("Susan", 45), r("Tom", 35))); runQueryTestResults("SELECT name, age FROM person WHERE age <= 35 ORDER BY age DESC", columns("name", "age"), rows(r("Tom", 35), r("Phil", 31), r("Pavel", 30), r("Patty", 29))); runQueryTestResults("SELECT name, age FROM person WHERE age < 35 ORDER BY age DESC", columns("name", "age"), rows(r("Phil", 31), r("Pavel", 30), r("Patty", 29))); runQueryTestResults("SELECT name, age FROM person WHERE age > 35 ORDER BY age DESC", columns("name", "age"), rows(r("Juanita", 50), r("Susan", 45))); // WHERE with AND. runQueryTestResults("SELECT name, age FROM person WHERE name = 'Tom' AND age = 35 ORDER BY age", columns("name", "age"), rows(r("Tom", 35))); runQueryTestResults( "SELECT name, age FROM person WHERE name = 'Tom' AND age = 35 AND NOT wentToSpace ORDER BY age", columns("name", "age"), rows(r("Tom", 35))); runQueryTestResults("SELECT name, age FROM person WHERE name = 'Tom' AND age = 35 AND wentToSpace ORDER BY age", columns("name", "age"), rows()); runQueryTestResults( "SELECT name, age FROM person WHERE name = 'Pavel' AND age = 30 AND wentToSpace ORDER BY age", columns("name", "age"), rows(r("Pavel", 30))); // WHERE with OR. runQueryTestResults("SELECT name, age FROM person WHERE name = 'Tom' OR name = 'Juanita' ORDER BY age", columns("name", "age"), rows(r("Tom", 35), r("Juanita", 50))); runQueryTestResults( "SELECT name, age FROM person WHERE name = 'Tom' OR name = 'Juanita' OR age = 31 ORDER BY age", columns("name", "age"), rows(r("Phil", 31), r("Tom", 35), r("Juanita", 50))); runQueryTestResults("SELECT name, age FROM person WHERE name = 'Tom' OR name = 'Juanita' ORDER BY age", columns("name", "age"), rows(r("Tom", 35), r("Juanita", 50))); } @Test public void testWhereNot() throws SQLException { runQueryTestResults("select name from person WHERE NOT name = 'Tom'", columns("name"), rows(r("Patty"), r("Phil"), r("Susan"), r("Juanita"), r("Pavel"))); } @Test public void testHaving() throws SQLException { // HAVING with aggregate literal. runQueryTestResults("SELECT wentToSpace, SUM(age) FROM person GROUP BY wentToSpace HAVING SUM(age) > 1000", columns("wentToSpace", "SUM(age)"), rows()); runQueryTestResults("SELECT wentToSpace, COUNT(age) FROM person GROUP BY wentToSpace HAVING COUNT(age) < 1000", columns("wentToSpace", "COUNT(age)"), rows(r(false, 3L), r(true, 3L))); runQueryTestResults("SELECT wentToSpace, COUNT(age) FROM person GROUP BY wentToSpace HAVING COUNT(age) <> 3", columns("wentToSpace", "COUNT(age)"), rows()); runQueryTestResults("SELECT COUNT(age), SUM(age) FROM person GROUP BY wentToSpace HAVING SUM(age) > 100", columns("COUNT(age)", "SUM(age)"), rows(r(3L, 125L))); runQueryTestResults("SELECT COUNT(age), SUM(age) FROM person GROUP BY wentToSpace HAVING SUM(age) < 100", columns("COUNT(age)", "SUM(age)"), rows(r(3L, 95L))); runQueryTestResults("SELECT COUNT(age), SUM(age) FROM person GROUP BY age HAVING SUM(age) <> 1000", columns("COUNT(age)", "SUM(age)"), rows(r(1L, 35L), r(1L, 29L), r(1L, 31L), r(1L, 45L), r(1L, 50L), r(1L, 30L))); runQueryTestResults("SELECT COUNT(age), SUM(age) FROM person GROUP BY age HAVING SUM(age) = 35", columns("COUNT(age)", "SUM(age)"), rows(r(1L, 35L))); // Having with AND. runQueryTestResults( "SELECT COUNT(age), SUM(age) FROM person GROUP BY wentToSpace HAVING SUM(age) <> 1000 AND COUNT(age) = 3", columns("COUNT(age)", "SUM(age)"), rows(r(3L, 95L), r(3L, 125L))); runQueryTestResults( "SELECT COUNT(age), SUM(age) FROM person GROUP BY wentToSpace HAVING SUM(age) = 125 AND COUNT(age) = 3", columns("COUNT(age)", "SUM(age)"), rows(r(3L, 125L))); runQueryTestResults( "SELECT COUNT(age), SUM(age) FROM person GROUP BY wentToSpace HAVING SUM(age) <> 125 AND COUNT(age) = 3", columns("COUNT(age)", "SUM(age)"), rows(r(3L, 95L))); runQueryTestResults( "SELECT COUNT(age), SUM(age) FROM person GROUP BY wentToSpace HAVING SUM(age) <> 125 AND COUNT(age) <> 3", columns("COUNT(age)", "SUM(age)"), rows()); // Having with OR. runQueryTestResults( "SELECT COUNT(age), SUM(age) FROM person GROUP BY wentToSpace HAVING SUM(age) = 1000 OR COUNT(age) = 3", columns("COUNT(age)", "SUM(age)"), rows(r(3L, 95L), r(3L, 125L))); runQueryTestResults( "SELECT COUNT(age), SUM(age) FROM person GROUP BY wentToSpace HAVING SUM(age) = 1000 OR COUNT(age) <> 3", columns("COUNT(age)", "SUM(age)"), rows()); runQueryTestResults( "SELECT COUNT(age), SUM(age) FROM person GROUP BY wentToSpace HAVING SUM(age) = 125 OR COUNT(age) <> 3", columns("COUNT(age)", "SUM(age)"), rows(r(3L, 125L))); runQueryTestResults( "SELECT COUNT(age), SUM(age) FROM person GROUP BY wentToSpace HAVING SUM(age) <> 125 OR COUNT(age) <> 3", columns("COUNT(age)", "SUM(age)"), rows(r(3L, 95L))); } @Test void testMisc() throws SQLException { runQueryTestResults( "SELECT wentToSpace, COUNT(wentToSpace) FROM person GROUP BY wentToSpace HAVING COUNT(wentToSpace) > 1", columns("wentToSpace", "COUNT(wentToSpace)"), rows(r(false, 3L), r(true, 3L))); runQueryTestResults("SELECT COUNT(name), COUNT(name) FROM person error", columns("COUNT(name)", "COUNT(name)"), rows(r(6L, 6L))); runQueryTestResults("SELECT SUM(age) FROM \"gremlin\".\"person\" WHERE name = 'test'", columns("SUM(age)"), rows()); runQueryTestResults("SELECT COUNT(name), COUNT(*) FROM person error", columns("COUNT(name)", "COUNT(*)"), rows(r(6L, 6L))); runQueryTestResults("SELECT name, COUNT(name), count(1) from \"gremlin\".\"person\" group by name", columns("name", "COUNT(name)", "COUNT(1)"), rows(r("Tom", 1L, 1L), r("Patty", 1L, 1L), r("Phil", 1L, 1L), r("Susan", 1L, 1L), r("Juanita", 1L, 1L), r("Pavel", 1L, 1L))); runQueryTestResults("SELECT name, COUNT(name), count(1) AS cnt from \"gremlin\".\"person\" group by name", columns("name", "COUNT(name)", "cnt"), rows(r("Tom", 1L, 1L), r("Patty", 1L, 1L), r("Phil", 1L, 1L), r("Susan", 1L, 1L), r("Juanita", 1L, 1L), r("Pavel", 1L, 1L))); runQueryTestResults( "SELECT wentToSpace, COUNT(name), SUM(age), AVG(age), MIN(age), MAX(age) FROM \"gremlin\".\"person\" GROUP BY wentToSpace", columns("wentToSpace", "COUNT(name)", "SUM(age)", "AVG(age)", "MIN(age)", "MAX(age)"), rows( r(false, 3L, 95L, 31.666666666666668, 29, 35), r(true, 3L, 125L, 41.666666666666664, 30, 50)) ); runQueryTestResults("SELECT name FROM \"gremlin\".\"person\" ORDER BY 1", columns("name"), rows(r("Juanita"), r("Patty"), r("Pavel"), r("Phil"), r("Susan"), r("Tom"))); runQueryTestResults("SELECT DISTINCT name FROM \"gremlin\".\"person\" ORDER BY name", columns("name"), rows(r("Juanita"), r("Patty"), r("Pavel"), r("Phil"), r("Susan"), r("Tom"))); runQueryTestResults("SELECT DISTINCT name FROM \"gremlin\".\"person\" ORDER BY name DESC", columns("name"), rows(r("Tom"), r("Susan"), r("Phil"), r("Pavel"), r("Patty"), r("Juanita"))); // NULLS FIRST predicate is not currently supported. runQueryTestThrows("SELECT name FROM \"gremlin\".\"person\" ORDER BY name NULLS FIRST", SqlGremlinError.NO_ORDER, "NULLS_FIRST"); } @Test void testAggregateLiteralHavingNoGroupBy() throws SQLException { // Tableau was sending queries like this for the preview in 2021.3 runQueryTestResults( "SELECT SUM(1) AS \"cnt:airport_03C2E834E28942D3AA2423AC01F4B33D:ok\" FROM gremlin.person AS person HAVING COUNT(1) > 0", columns("cnt:airport_03C2E834E28942D3AA2423AC01F4B33D:ok"), rows(r(new BigDecimal(6)))); runQueryTestResults( "SELECT MIN(1) AS \"cnt:airport_03C2E834E28942D3AA2423AC01F4B33D:ok\" FROM gremlin.person AS person HAVING COUNT(1) > 0", columns("cnt:airport_03C2E834E28942D3AA2423AC01F4B33D:ok"), rows(r(new BigDecimal(1)))); runQueryTestResults( "SELECT MAX(1) AS \"cnt:airport_03C2E834E28942D3AA2423AC01F4B33D:ok\" FROM gremlin.person AS person HAVING COUNT(1) > 0", columns("cnt:airport_03C2E834E28942D3AA2423AC01F4B33D:ok"), rows(r(new BigDecimal(1)))); runQueryTestResults( "SELECT AVG(1) AS \"cnt:airport_03C2E834E28942D3AA2423AC01F4B33D:ok\" FROM gremlin.person AS person HAVING COUNT(1) > 0", columns("cnt:airport_03C2E834E28942D3AA2423AC01F4B33D:ok"), rows(r(new BigDecimal(1)))); runQueryTestResults( "SELECT SUM(2) AS \"cnt:airport_03C2E834E28942D3AA2423AC01F4B33D:ok\" FROM gremlin.person AS person HAVING COUNT(1) > 0", columns("cnt:airport_03C2E834E28942D3AA2423AC01F4B33D:ok"), rows(r(new BigDecimal(12)))); runQueryTestResults( "SELECT MIN(2) AS \"cnt:airport_03C2E834E28942D3AA2423AC01F4B33D:ok\" FROM gremlin.person AS person HAVING COUNT(1) > 0", columns("cnt:airport_03C2E834E28942D3AA2423AC01F4B33D:ok"), rows(r(new BigDecimal(2)))); runQueryTestResults( "SELECT MAX(2) AS \"cnt:airport_03C2E834E28942D3AA2423AC01F4B33D:ok\" FROM gremlin.person AS person HAVING COUNT(1) > 0", columns("cnt:airport_03C2E834E28942D3AA2423AC01F4B33D:ok"), rows(r(new BigDecimal(2)))); runQueryTestResults( "SELECT AVG(2) AS \"cnt:airport_03C2E834E28942D3AA2423AC01F4B33D:ok\" FROM gremlin.person AS person HAVING COUNT(1) > 0", columns("cnt:airport_03C2E834E28942D3AA2423AC01F4B33D:ok"), rows(r(new BigDecimal(2)))); } @Test void testLimit() throws SQLException { // LIMIT 1 tests. // Single result query. runQueryTestResults("SELECT name, age FROM person WHERE name = 'Tom' ORDER BY age LIMIT 1", columns("name", "age"), rows(r("Tom", 35))); // Multi result query. runQueryTestResults("SELECT name, age FROM person ORDER BY age LIMIT 1", columns("name", "age"), rows(r("Patty", 29))); // LIMIT > 1 tests. runQueryTestResults("SELECT name, age FROM person WHERE name <> 'Tom' ORDER BY age LIMIT 2", columns("name", "age"), rows(r("Patty", 29), r("Pavel", 30))); runQueryTestResults("SELECT name, age FROM person WHERE name <> 'Tom' ORDER BY age LIMIT 3", columns("name", "age"), rows(r("Patty", 29), r("Pavel", 30), r("Phil", 31))); runQueryTestResults("SELECT name, age FROM person WHERE name <> 'Tom' ORDER BY age LIMIT 4", columns("name", "age"), rows(r("Patty", 29), r("Pavel", 30), r("Phil", 31), r("Susan", 45))); runQueryTestResults("SELECT name, age FROM person WHERE name <> 'Tom' ORDER BY age LIMIT 5", columns("name", "age"), rows(r("Patty", 29), r("Pavel", 30), r("Phil", 31), r("Susan", 45), r("Juanita", 50))); runQueryTestResults("SELECT name, age FROM person WHERE name <> 'Tom' ORDER BY age LIMIT 6", columns("name", "age"), rows(r("Patty", 29), r("Pavel", 30), r("Phil", 31), r("Susan", 45), r("Juanita", 50))); runQueryTestResults("SELECT name, age FROM person WHERE name <> 'Tom' ORDER BY age LIMIT 1000", columns("name", "age"), rows(r("Patty", 29), r("Pavel", 30), r("Phil", 31), r("Susan", 45), r("Juanita", 50))); runQueryTestResults( String.format("SELECT name, age FROM person WHERE name <> 'Tom' ORDER BY age LIMIT %d", Long.MAX_VALUE), columns("name", "age"), rows(r("Patty", 29), r("Pavel", 30), r("Phil", 31), r("Susan", 45), r("Juanita", 50))); } @Test void testSingleComparisonOperator() throws SQLException { runQueryTestResults( "SELECT COUNT(wentToSpace) > 0 FROM person GROUP BY wentToSpace HAVING COUNT(wentToSpace) > 1", columns("COUNT(wentToSpace) > 0"), rows(r(true), r(true))); runQueryTestResults( "SELECT COUNT(wentToSpace) <> 0 FROM person GROUP BY wentToSpace", columns("COUNT(wentToSpace) <> 0"), rows(r(true), r(true))); runQueryTestResults( "SELECT COUNT(wentToSpace) = 0 FROM person GROUP BY wentToSpace", columns("COUNT(wentToSpace) = 0"), rows(r(false), r(false))); runQueryTestResults( "SELECT AVG(age) > 100 FROM person GROUP BY wentToSpace", columns("AVG(age) > 100"), rows(r(false), r(false))); runQueryTestResults( "SELECT AVG(age) < 100 FROM person GROUP BY wentToSpace", columns("AVG(age) < 100"), rows(r(true), r(true))); runQueryTestResults( "SELECT AVG(age) = 100 FROM person GROUP BY wentToSpace", columns("AVG(age) = 100"), rows(r(false), r(false))); runQueryTestResults( "SELECT wentToSpace = 0 FROM person", columns("wentToSpace = false"), rows(r(true), r(true), r(true), r(false), r(false), r(false))); runQueryTestResults( "SELECT name, wentToSpace = 0 FROM person", columns("name", "wentToSpace = false"), rows(r("Tom", true), r("Patty", true), r("Phil", true), r("Susan", false), r("Juanita", false), r("Pavel", false))); runQueryTestResults( "SELECT age <= 35 FROM person", columns("age <= 35"), rows(r(true), r(true), r(true), r(false), r(false), r(true))); } @Test void testMultiComparisonOperator() throws SQLException { runQueryTestResults( "SELECT age <= 35 AND age > 30 FROM person", columns("age <= 35 AND age > 30"), rows(r(true), r(false), r(true), r(false), r(false), r(false))); runQueryTestResults( "SELECT age <= 35 OR age > 30 FROM person", columns("age <= 35 OR age > 30"), rows(r(true), r(true), r(true), r(true), r(true), r(true))); runQueryTestResults( "SELECT (age <= 35 AND age > 30) OR age = 29 FROM person", columns("age <= 35 AND age > 30 OR age = 29"), rows(r(true), r(true), r(true), r(false), r(false), r(false))); runQueryTestResults( "SELECT age <= 35 AND age > 30 or age > 0 FROM person", columns("age <= 35 AND age > 30 OR age > 0"), rows(r(true), r(true), r(true), r(true), r(true), r(true))); runQueryTestResults( "SELECT age <= 35 and NOT age > 30 FROM person", columns("age <= 35 AND NOT age > 30"), rows(r(false), r(true), r(false), r(false), r(false), r(true))); runQueryTestResults( "SELECT NOT age > 0 FROM person", columns("NOT age > 0"), rows(r(false), r(false), r(false), r(false), r(false), r(false))); runQueryTestResults( "SELECT NOT name = 'Tom' FROM person", columns("NOT name = Tom"), rows(r(false), r(true), r(true), r(true), r(true), r(true))); } @Test void testComparisonWithAsOperator() throws SQLException { runQueryTestResults( "SELECT COUNT(wentToSpace) > 0 AS a FROM person GROUP BY wentToSpace HAVING COUNT(wentToSpace) > 1", columns("a"), rows(r(true), r(true))); runQueryTestResults( "SELECT COUNT(wentToSpace) <> 0 AS a FROM person GROUP BY wentToSpace", columns("a"), rows(r(true), r(true))); runQueryTestResults( "SELECT wentToSpace = 0 AS a FROM person", columns("a"), rows(r(true), r(true), r(true), r(false), r(false), r(false))); runQueryTestResults( "SELECT age <= 35 AS a FROM person", columns("a"), rows(r(true), r(true), r(true), r(false), r(false), r(true))); runQueryTestResults( "SELECT age <= 35 AND age > 30 AS a FROM person", columns("a"), rows(r(true), r(false), r(true), r(false), r(false), r(false))); runQueryTestResults( "SELECT age <= 35 AND age > 30 or age > 0 AS a FROM person", columns("a"), rows(r(true), r(true), r(true), r(true), r(true), r(true))); runQueryTestResults( "SELECT NOT age > 0 AS a FROM person", columns("a"), rows(r(false), r(false), r(false), r(false), r(false), r(false))); runQueryTestResults( "SELECT NOT name = 'Tom' AS a FROM person", columns("a"), rows(r(false), r(true), r(true), r(true), r(true), r(true))); } }
7,307
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin/adapter/GremlinSqlIncompleteSelectTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.gremlin.adapter; import org.junit.jupiter.api.Test; import java.sql.SQLException; public class GremlinSqlIncompleteSelectTest extends GremlinSqlBaseTest { GremlinSqlIncompleteSelectTest() throws SQLException { } @Override protected DataSet getDataSet() { return DataSet.SPACE_INCOMPLETE; } @Test public void testProject() throws SQLException { runQueryTestResults("select name from person", columns("name"), rows(r("Tom"), r("Patty"), r("Phil"), r("Susan"), r("Juanita"), r((Object) null))); } @Test public void testEdges() throws SQLException { runQueryTestResults("select * from worksFor where yearsWorked = 9", columns("person_OUT_ID", "company_IN_ID", "yearsWorked", "worksFor_ID"), rows(r(25L, 2L, 9, 61L))); } @Test public void testSelectNull() throws SQLException { runQueryTestResults("SELECT name, age FROM person", columns("name", "age"), rows(r("Tom", null), r("Patty", 29), r("Phil", 31), r("Susan", 45), r("Juanita", 50), r(null, 30))); } @Test public void testOrderWithNull() throws SQLException { // ORDER with integer column. runQueryTestResults("SELECT name, age FROM person ORDER BY age", columns("name", "age"), rows(r("Patty", 29), r(null, 30), r("Phil", 31), r("Susan", 45), r("Juanita", 50), r("Tom", null))); runQueryTestResults("SELECT name, age FROM person ORDER BY age DESC", columns("name", "age"), rows(r("Tom", null), r("Juanita", 50), r("Susan", 45), r("Phil", 31), r(null, 30), r("Patty", 29))); runQueryTestResults("SELECT name, age AS a FROM person ORDER BY a", columns("name", "a"), rows(r("Patty", 29), r(null, 30), r("Phil", 31), r("Susan", 45), r("Juanita", 50), r("Tom", null))); runQueryTestResults("SELECT name, age AS a FROM person ORDER BY a DESC", columns("name", "a"), rows(r("Tom", null), r("Juanita", 50), r("Susan", 45), r("Phil", 31), r(null, 30), r("Patty", 29))); // ORDER with string column. runQueryTestResults("SELECT name, age FROM person ORDER BY name", columns("name", "age"), rows(r(null, 30), r("Juanita", 50), r("Patty", 29), r("Phil", 31), r("Susan", 45), r("Tom", null))); runQueryTestResults("SELECT name, age FROM person ORDER BY name DESC", columns("name", "age"), rows(r("Tom", null), r("Susan", 45), r("Phil", 31), r("Patty", 29), r("Juanita", 50), r(null, 30))); runQueryTestResults("SELECT name AS n, age AS a FROM person ORDER BY n", columns("n", "a"), rows(r(null, 30), r("Juanita", 50), r("Patty", 29), r("Phil", 31), r("Susan", 45), r("Tom", null))); runQueryTestResults("SELECT name AS n, age AS a FROM person ORDER BY n DESC", columns("n", "a"), rows(r("Tom", null), r("Susan", 45), r("Phil", 31), r("Patty", 29), r("Juanita", 50), r(null, 30))); } @Test public void testWhereNull() throws SQLException { // WHERE with string literal. runQueryTestResults("SELECT name, age FROM person WHERE age <> 30", columns("name", "age"), rows(r("Tom", null), r("Patty", 29), r("Phil", 31), r("Susan", 45), r("Juanita", 50))); } // TODO: Support aggregates for null values @Test public void testHavingNull() throws SQLException { runQueryTestResults("SELECT MIN(age) AS age FROM person GROUP BY name HAVING MIN(age) > 1", columns("age"), rows(r((Object) null), r(29), r(31), r(45), r(50), r(30))); runQueryTestResults("SELECT wentToSpace, SUM(age) FROM person GROUP BY wentToSpace HAVING SUM(age) > 1000", columns("wentToSpace", "SUM(age)"), rows()); runQueryTestResults("SELECT wentToSpace, COUNT(age) FROM person GROUP BY wentToSpace HAVING COUNT(age) < 1000", columns("wentToSpace", "COUNT(age)"), rows(r(false, 2L), r(true, 2L), r(null, 1L))); runQueryTestResults("SELECT wentToSpace, COUNT(age) FROM person GROUP BY wentToSpace HAVING COUNT(age) <> 2", columns("wentToSpace", "COUNT(age)"), rows(r(null, 1L))); runQueryTestResults("SELECT COUNT(age), SUM(age) FROM person GROUP BY wentToSpace HAVING SUM(age) > 100", columns("COUNT(age)", "SUM(age)"), rows()); runQueryTestResults("SELECT COUNT(age), SUM(age) FROM person GROUP BY wentToSpace HAVING SUM(age) > 80", columns("COUNT(age)", "SUM(age)"), rows(r(2L, 95L))); runQueryTestResults("SELECT COUNT(age), SUM(age) FROM person GROUP BY wentToSpace HAVING SUM(age) < 100", columns("COUNT(age)", "SUM(age)"), rows(r(2L, 60L), r(2L, 95L), r(1L, 30L))); runQueryTestResults("SELECT COUNT(age), SUM(age) FROM person GROUP BY age HAVING SUM(age) <> 1000", columns("COUNT(age)", "SUM(age)"), rows(r(0L, null), r(1L, 29L), r(1L, 31L), r(1L, 45L), r(1L, 50L), r(1L, 30L))); runQueryTestResults("SELECT COUNT(age), SUM(age) FROM person GROUP BY age HAVING SUM(age) = 29", columns("COUNT(age)", "SUM(age)"), rows(r(1L, 29L))); // Having with AND. runQueryTestResults( "SELECT COUNT(age), SUM(age) FROM person GROUP BY wentToSpace HAVING SUM(age) <> 1000 AND COUNT(age) = 3", columns("COUNT(age)", "SUM(age)"), rows()); runQueryTestResults( "SELECT COUNT(age), SUM(age) FROM person GROUP BY wentToSpace HAVING SUM(age) = 125 AND COUNT(age) = 3", columns("COUNT(age)", "SUM(age)"), rows()); runQueryTestResults( "SELECT COUNT(age), SUM(age) FROM person GROUP BY wentToSpace HAVING SUM(age) <> 125 AND COUNT(age) = 3", columns("COUNT(age)", "SUM(age)"), rows()); runQueryTestResults( "SELECT COUNT(age), SUM(age) FROM person GROUP BY wentToSpace HAVING SUM(age) <> 125 AND COUNT(age) <> 3", columns("COUNT(age)", "SUM(age)"), rows(r(2L, 60L), r(2L, 95L), r(1L, 30L))); // Having with OR. runQueryTestResults( "SELECT COUNT(age), SUM(age) FROM person GROUP BY wentToSpace HAVING SUM(age) = 1000 OR COUNT(age) = 3", columns("COUNT(age)", "SUM(age)"), rows()); runQueryTestResults( "SELECT COUNT(age), SUM(age) FROM person GROUP BY wentToSpace HAVING SUM(age) = 1000 OR COUNT(age) <> 3", columns("COUNT(age)", "SUM(age)"), rows(r(2L, 60L), r(2L, 95L), r(1L, 30L))); runQueryTestResults( "SELECT COUNT(age), SUM(age) FROM person GROUP BY wentToSpace HAVING SUM(age) = 125 OR COUNT(age) <> 3", columns("COUNT(age)", "SUM(age)"), rows(r(2L, 60L), r(2L, 95L), r(1L, 30L))); runQueryTestResults( "SELECT COUNT(age), SUM(age) FROM person GROUP BY wentToSpace HAVING SUM(age) <> 125 OR COUNT(age) <> 3", columns("COUNT(age)", "SUM(age)"), rows(r(2L, 60L), r(2L, 95L), r(1L, 30L))); } @Test void testLimitNull() throws SQLException { // LIMIT 1 tests. // Single result query. runQueryTestResults("SELECT name, age FROM person WHERE name = 'Patty' LIMIT 1", columns("name", "age"), rows(r("Patty", 29))); // Multi result query. runQueryTestResults("SELECT name, age FROM person LIMIT 1", columns("name", "age"), rows(r("Tom", null))); } }
7,308
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin/adapter
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin/adapter/graphs/DataTypeGraph.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.gremlin.adapter.graphs; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.structure.Vertex; import static org.apache.tinkerpop.gremlin.structure.T.label; public class DataTypeGraph implements TestGraph { @Override public void populate(final Graph graph) { // Create vertices for each data type. final Vertex stringtype = graph.addVertex(label, "stringtype", "key", GraphConstants.STRING_VALUE); final Vertex bytetype = graph.addVertex(label, "bytetype", "key", GraphConstants.BYTE_VALUE); final Vertex shorttype = graph.addVertex(label, "shorttype", "key", GraphConstants.SHORT_VALUE); final Vertex inttype = graph.addVertex(label, "inttype", "key", GraphConstants.INTEGER_VALUE); final Vertex longtype = graph.addVertex(label, "longtype", "key", GraphConstants.LONG_VALUE); final Vertex floattype = graph.addVertex(label, "floattype", "key", GraphConstants.FLOAT_VALUE); final Vertex doubletype = graph.addVertex(label, "doubletype", "key", GraphConstants.DOUBLE_VALUE); final Vertex datetype = graph.addVertex(label, "datetype", "key", GraphConstants.DATE_VALUE); // Create edge from vertices to themselves with data types so they can be tested. stringtype.addEdge("stringtypeedge", stringtype, "key", GraphConstants.STRING_VALUE); bytetype.addEdge("bytetypeedge", bytetype, "key", GraphConstants.BYTE_VALUE); shorttype.addEdge("shorttypeedge", shorttype, "key", GraphConstants.SHORT_VALUE); inttype.addEdge("inttypeedge", inttype, "key", GraphConstants.INTEGER_VALUE); longtype.addEdge("longtypeedge", longtype, "key", GraphConstants.LONG_VALUE); floattype.addEdge("floattypeedge", floattype, "key", GraphConstants.FLOAT_VALUE); doubletype.addEdge("doubletypeedge", doubletype, "key", GraphConstants.DOUBLE_VALUE); datetype.addEdge("datetypeedge", datetype, "key", GraphConstants.DATE_VALUE); } }
7,309
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin/adapter
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin/adapter/graphs/TestGraphFactory.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.gremlin.adapter.graphs; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph; import software.aws.neptune.gremlin.adapter.GremlinSqlBaseTest; public class TestGraphFactory { private static final TestGraph SPACE_GRAPH = new SpaceTestGraph(); private static final TestGraph SPACE_INCOMPLETE_GRAPH = new SpaceTestIncompleteGraph(); private static final TestGraph DATA_TYPE_GRAPH = new DataTypeGraph(); public static Graph createGraph(final GremlinSqlBaseTest.DataSet dataSet) { final Graph graph = TinkerGraph.open(); switch (dataSet) { case SPACE: SPACE_GRAPH.populate(graph); break; case SPACE_INCOMPLETE: SPACE_INCOMPLETE_GRAPH.populate(graph); break; case DATA_TYPES: DATA_TYPE_GRAPH.populate(graph); break; default: throw new UnsupportedOperationException("Unsupported graph " + dataSet.name()); } return graph; } }
7,310
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin/adapter
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin/adapter/graphs/SpaceTestIncompleteGraph.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.gremlin.adapter.graphs; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.structure.Vertex; import java.util.concurrent.TimeUnit; import static org.apache.tinkerpop.gremlin.structure.T.label; public class SpaceTestIncompleteGraph implements TestGraph { @Override public void populate(final Graph graph) { // companies final Vertex acmeSpaceCo = graph.addVertex(label, "company", "name", "Acme Space"); final Vertex newFrontiers = graph.addVertex(label, "company", "name", "New Frontiers"); final Vertex tomorrowUnlimited = graph.addVertex(label, "company", "name", "Tomorrow Unlimited"); final Vertex spaceTruckers = graph.addVertex(label, "company", "name", "Space Truckers"); final Vertex bankruptCo = graph.addVertex(label, "company", "name", "Bankrupt Co."); // planets final Vertex earth = graph.addVertex(label, "planet", "name", "earth"); final Vertex mars = graph.addVertex(label, "planet", "name", "mars"); final Vertex saturn = graph.addVertex(label, "planet", "name", "saturn"); final Vertex jupiter = graph.addVertex(label, "planet", "name", "jupiter"); // astronauts final Vertex tom = graph.addVertex(label, "person", "name", "Tom", "wentToSpace", false); final Vertex patty = graph.addVertex(label, "person", "name", "Patty", "age", 29, "wentToSpace", false); final Vertex phil = graph.addVertex(label, "person", "name", "Phil", "age", 31, "wentToSpace", false); final Vertex susan = graph.addVertex(label, "person", "name", "Susan", "age", 45, "wentToSpace", true); final Vertex juanita = graph.addVertex(label, "person", "name", "Juanita", "age", 50, "wentToSpace", true); final Vertex pavel = graph.addVertex(label, "person", "age", 30); // spaceships final Vertex spaceship1 = graph.addVertex(label, "spaceship", "name", "Ship 1", "model", "delta 1"); final Vertex spaceship2 = graph.addVertex(label, "spaceship", "name", "Ship 2", "model", "delta 1"); final Vertex spaceship3 = graph.addVertex(label, "spaceship", "name", "Ship 3", "model", "delta 2"); final Vertex spaceship4 = graph.addVertex(label, "spaceship", "name", "Ship 4", "model", "delta 3"); // satellite final Vertex satellite1 = graph.addVertex(label, "satellite", "name", "sat1"); final Vertex satellite2 = graph.addVertex(label, "satellite", "name", "sat2"); final Vertex satellite3 = graph.addVertex(label, "satellite", "name", "sat3"); // rocket fuel final Vertex s1Fuel = graph.addVertex(label, "sensor", "type", "rocket fuel"); // astronaut company relationships tom.addEdge("worksFor", acmeSpaceCo, "yearsWorked", 5); patty.addEdge("worksFor", acmeSpaceCo, "yearsWorked", 1); phil.addEdge("worksFor", newFrontiers, "yearsWorked", 9); susan.addEdge("worksFor", tomorrowUnlimited, "yearsWorked", 4); juanita.addEdge("worksFor", spaceTruckers, "yearsWorked", 4); pavel.addEdge("worksFor", spaceTruckers, "yearsWorked", 10); // astronaut spaceship tom.addEdge("pilots", spaceship1); patty.addEdge("pilots", spaceship1); phil.addEdge("pilots", spaceship2); susan.addEdge("pilots", spaceship3); juanita.addEdge("pilots", spaceship4); pavel.addEdge("pilots", spaceship4); // astronauts to planets tom.addEdge("fliesTo", earth).property("trips", 10); tom.addEdge("fliesTo", mars).property("trips", 3); patty.addEdge("fliesTo", mars).property("trips", 1); phil.addEdge("fliesTo", saturn).property("trips", 9); phil.addEdge("fliesTo", earth).property("trips", 4); susan.addEdge("fliesTo", jupiter).property("trips", 20); juanita.addEdge("fliesTo", earth).property("trips", 4); juanita.addEdge("fliesTo", saturn).property("trips", 7); juanita.addEdge("fliesTo", jupiter).property("trips", 9); pavel.addEdge("fliesTo", mars).property("trips", 0); // astronaut friends tom.addEdge("friendsWith", patty); patty.addEdge("friendsWith", juanita); phil.addEdge("friendsWith", susan); susan.addEdge("friendsWith", pavel); // satellites to planets satellite1.addEdge("orbits", earth).property("launched", 1995); satellite2.addEdge("orbits", mars).property("launched", 2020); satellite3.addEdge("orbits", jupiter).property("launched", 2005); // fuel sensor readings long timestamp = 1765258774000L; for (int i = 0; i < 10; i++) { final Vertex s1Reading = graph.addVertex(label, "sensorReading", "timestamp", timestamp, "date", timestamp, "value", 10.0); s1Fuel.addEdge("hasReading", s1Reading); timestamp += TimeUnit.MINUTES.toMillis(5); } } }
7,311
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin/adapter
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin/adapter/graphs/TestGraph.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.gremlin.adapter.graphs; import org.apache.tinkerpop.gremlin.structure.Graph; public interface TestGraph { void populate(Graph graph); }
7,312
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin/adapter
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin/adapter/graphs/SpaceTestGraph.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.gremlin.adapter.graphs; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.structure.Vertex; import java.util.concurrent.TimeUnit; import static org.apache.tinkerpop.gremlin.structure.T.label; public class SpaceTestGraph implements TestGraph { @Override public void populate(final Graph graph) { // companies final Vertex acmeSpaceCo = graph.addVertex(label, "company", "name", "Acme Space"); final Vertex newFrontiers = graph.addVertex(label, "company", "name", "New Frontiers"); final Vertex tomorrowUnlimited = graph.addVertex(label, "company", "name", "Tomorrow Unlimited"); final Vertex spaceTruckers = graph.addVertex(label, "company", "name", "Space Truckers"); final Vertex bankruptCo = graph.addVertex(label, "company", "name", "Bankrupt Co."); // planets final Vertex earth = graph.addVertex(label, "planet", "name", "earth"); final Vertex mars = graph.addVertex(label, "planet", "name", "mars"); final Vertex saturn = graph.addVertex(label, "planet", "name", "saturn"); final Vertex jupiter = graph.addVertex(label, "planet", "name", "jupiter"); // astronauts final Vertex tom = graph.addVertex(label, "person", "name", "Tom", "age", 35, "wentToSpace", false); final Vertex patty = graph.addVertex(label, "person", "name", "Patty", "age", 29, "wentToSpace", false); final Vertex phil = graph.addVertex(label, "person", "name", "Phil", "age", 31, "wentToSpace", false); final Vertex susan = graph.addVertex(label, "person", "name", "Susan", "age", 45, "wentToSpace", true); final Vertex juanita = graph.addVertex(label, "person", "name", "Juanita", "age", 50, "wentToSpace", true); final Vertex pavel = graph.addVertex(label, "person", "name", "Pavel", "age", 30, "wentToSpace", true); // spaceships final Vertex spaceship1 = graph.addVertex(label, "spaceship", "name", "Ship 1", "model", "delta 1"); final Vertex spaceship2 = graph.addVertex(label, "spaceship", "name", "Ship 2", "model", "delta 1"); final Vertex spaceship3 = graph.addVertex(label, "spaceship", "name", "Ship 3", "model", "delta 2"); final Vertex spaceship4 = graph.addVertex(label, "spaceship", "name", "Ship 4", "model", "delta 3"); // satellite final Vertex satellite1 = graph.addVertex(label, "satellite", "name", "sat1"); final Vertex satellite2 = graph.addVertex(label, "satellite", "name", "sat2"); final Vertex satellite3 = graph.addVertex(label, "satellite", "name", "sat3"); // rocket fuel final Vertex s1Fuel = graph.addVertex(label, "sensor", "type", "rocket fuel"); // astronaut company relationships tom.addEdge("worksFor", acmeSpaceCo, "yearsWorked", 5); patty.addEdge("worksFor", acmeSpaceCo, "yearsWorked", 1); phil.addEdge("worksFor", newFrontiers, "yearsWorked", 9); susan.addEdge("worksFor", tomorrowUnlimited, "yearsWorked", 4); juanita.addEdge("worksFor", spaceTruckers, "yearsWorked", 4); pavel.addEdge("worksFor", spaceTruckers, "yearsWorked", 10); // astronaut spaceship tom.addEdge("pilots", spaceship1); patty.addEdge("pilots", spaceship1); phil.addEdge("pilots", spaceship2); susan.addEdge("pilots", spaceship3); juanita.addEdge("pilots", spaceship4); pavel.addEdge("pilots", spaceship4); // astronauts to planets tom.addEdge("fliesTo", earth).property("trips", 10); tom.addEdge("fliesTo", mars).property("trips", 3); patty.addEdge("fliesTo", mars).property("trips", 1); phil.addEdge("fliesTo", saturn).property("trips", 9); phil.addEdge("fliesTo", earth).property("trips", 4); susan.addEdge("fliesTo", jupiter).property("trips", 20); juanita.addEdge("fliesTo", earth).property("trips", 4); juanita.addEdge("fliesTo", saturn).property("trips", 7); juanita.addEdge("fliesTo", jupiter).property("trips", 9); pavel.addEdge("fliesTo", mars).property("trips", 0); // astronaut friends tom.addEdge("friendsWith", patty); patty.addEdge("friendsWith", juanita); phil.addEdge("friendsWith", susan); susan.addEdge("friendsWith", pavel); // satellites to planets satellite1.addEdge("orbits", earth).property("launched", 1995); satellite2.addEdge("orbits", mars).property("launched", 2020); satellite3.addEdge("orbits", jupiter).property("launched", 2005); // fuel sensor readings long timestamp = 1765258774000L; for (int i = 0; i < 10; i++) { final Vertex s1Reading = graph.addVertex(label, "sensorReading", "timestamp", timestamp, "date", timestamp, "value", 10.0); s1Fuel.addEdge("hasReading", s1Reading); timestamp += TimeUnit.MINUTES.toMillis(5); } } }
7,313
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin/adapter
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin/adapter/graphs/GraphConstants.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.gremlin.adapter.graphs; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class GraphConstants { public static final String STRING_VALUE = "value"; public static final Long LONG_VALUE = 100L; public static final Integer INTEGER_VALUE = LONG_VALUE.intValue(); public static final Short SHORT_VALUE = LONG_VALUE.shortValue(); public static final Byte BYTE_VALUE = LONG_VALUE.byteValue(); public static final Double DOUBLE_VALUE = LONG_VALUE.doubleValue(); public static final Float FLOAT_VALUE = LONG_VALUE.floatValue(); public static final Date DATE_VALUE; private static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat("yyyy-mm-dd"); static { Date date = null; try { date = DATE_FORMATTER.parse("1993-03-30"); } catch (final ParseException e) { e.printStackTrace(); } DATE_VALUE = date; } }
7,314
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/gremlin/sql/SqlGremlinTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.gremlin.sql; import com.github.javafaker.Address; import com.github.javafaker.Cat; import com.github.javafaker.Commerce; import com.github.javafaker.Faker; import com.github.javafaker.Name; import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.ThreadFactoryBuilder; import dnl.utils.text.table.TextTable; import lombok.AllArgsConstructor; import org.apache.calcite.util.Pair; import org.apache.tinkerpop.gremlin.driver.Client; import org.apache.tinkerpop.gremlin.driver.Cluster; import org.apache.tinkerpop.gremlin.driver.Result; import org.apache.tinkerpop.gremlin.driver.ResultSet; import org.apache.tinkerpop.gremlin.driver.remote.DriverRemoteConnection; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import software.aws.neptune.common.IAMHelper; import software.aws.neptune.gremlin.adapter.converter.SqlConverter; import software.aws.neptune.gremlin.adapter.converter.schema.calcite.GremlinSchema; import software.aws.neptune.gremlin.adapter.converter.schema.gremlin.GremlinEdgeTable; import software.aws.neptune.gremlin.adapter.converter.schema.gremlin.GremlinProperty; import software.aws.neptune.gremlin.adapter.converter.schema.gremlin.GremlinVertexTable; import software.aws.neptune.gremlin.adapter.results.SqlGremlinQueryResult; import software.aws.neptune.gremlin.GremlinConnection; import software.aws.neptune.gremlin.GremlinConnectionProperties; import software.aws.neptune.jdbc.utilities.AuthScheme; import software.aws.neptune.jdbc.utilities.ConnectionProperties; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import static org.apache.tinkerpop.gremlin.process.traversal.AnonymousTraversalSource.traversal; import static software.aws.neptune.gremlin.GremlinConnectionProperties.CONTACT_POINT_KEY; import static software.aws.neptune.gremlin.GremlinConnectionProperties.ENABLE_SSL_KEY; import static software.aws.neptune.gremlin.GremlinConnectionProperties.PORT_KEY; import static software.aws.neptune.jdbc.utilities.ConnectionProperties.SCAN_TYPE_KEY; import static software.aws.neptune.jdbc.utilities.ConnectionProperties.SERVICE_REGION_KEY; import static software.aws.neptune.jdbc.utilities.ConnectionProperties.SSH_HOSTNAME; import static software.aws.neptune.jdbc.utilities.ConnectionProperties.SSH_PRIVATE_KEY_FILE; import static software.aws.neptune.jdbc.utilities.ConnectionProperties.SSH_STRICT_HOST_KEY_CHECKING; import static software.aws.neptune.jdbc.utilities.ConnectionProperties.SSH_USER; // Temporary test file to do ad hoc testing. @Disabled public class SqlGremlinTest { private static final String ENDPOINT = "database-1.cluster-cdubgfjknn5r.us-east-1.neptune.amazonaws.com"; private static final int PORT = 8182; private static final String AUTH = "IamSigV4"; private static final String ENABLE_SSL = "true"; private static final String SERVICE_REGION = "us-east-1"; private static final String USER = "ec2-user"; //54.210.60.246 private static final String HOSTNAME = "54.210.60.246"; private static final String SSH_PRIVATE_KEY = "~/Repos/jdbc-ec2-connect.pem"; private static final String SSH_STRICT_HOST = "true"; private static final String SCAN_TYPE = "first"; private static final String CONNECTION_STRING = String.format("jdbc:neptune:sqlgremlin://%s;enableSsl=%s;authScheme=%s;sshUser=%s;sshHost=%s;" + "sshPrivateKeyFile=%s;sshStrictHostKeyChecking=%s;serviceRegion=%s;scanType=%s", ENDPOINT, ENABLE_SSL, AUTH, USER, HOSTNAME, SSH_PRIVATE_KEY, SSH_STRICT_HOST, SERVICE_REGION, SCAN_TYPE); private static final Map<Class<?>, String> TYPE_MAP = new HashMap<>(); static { TYPE_MAP.put(String.class, "String"); TYPE_MAP.put(Boolean.class, "Boolean"); TYPE_MAP.put(Byte.class, "Byte"); TYPE_MAP.put(Short.class, "Short"); TYPE_MAP.put(Integer.class, "Integer"); TYPE_MAP.put(Long.class, "Long"); TYPE_MAP.put(Float.class, "Float"); TYPE_MAP.put(Double.class, "Double"); TYPE_MAP.put(Date.class, "Date"); } private static String getType(final Set<Object> data) { final Set<String> types = new HashSet<>(); for (final Object d : data) { types.add(TYPE_MAP.getOrDefault(d.getClass(), "String")); } if (types.size() == 1) { return types.iterator().next(); } return "String"; } GraphTraversalSource getGraphTraversalSource() { final Cluster.Builder builder = Cluster.build(); builder.addContactPoint(ENDPOINT); builder.port(PORT); builder.enableSsl(true); IAMHelper.addHandshakeInterceptor(builder); final Cluster cluster = builder.create(); final Client client = cluster.connect().init(); return traversal().withRemote(DriverRemoteConnection.using(client)); } @Test @Disabled void load() throws SQLException { final Properties properties = new Properties(); properties.put(ConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.IAMSigV4); // set default to IAMSigV4 properties.put(CONTACT_POINT_KEY, ENDPOINT); properties.put(PORT_KEY, PORT); properties.put(ENABLE_SSL_KEY, true); final java.sql.Connection connection = new GremlinConnection(new GremlinConnectionProperties(properties)); final Faker faker = new Faker(); for (int i = 0; i < 10000; i++) { System.out.println("Executing query " + (i + 1) + " / 10000."); connection.createStatement() .executeQuery(addV(faker.address(), faker.cat(), faker.name(), faker.commerce())); } } String addV(final Address address, final Cat cat, final Name name, final Commerce commerce) { final String stringBuilder = "g" + // Generate vertexes String.format(".addV('%s')", "Address") + String.format(".property('streetAddress', '%s')", address.streetAddress().replace("'", "")) + String.format(".property('buildingNumber', '%s')", address.buildingNumber().replace("'", "")) + String.format(".property('cityName', '%s')", address.cityName().replace("'", "")) + String.format(".property('state', '%s')", address.state().replace("'", "")) + ".as('addr')" + String.format(".addV('%s')", "Cat") + String.format(".property('name', '%s')", cat.name().replace("'", "")) + String.format(".property('breed', '%s')", cat.breed().replace("'", "")) + ".as('c')" + String.format(".addV('%s')", "Person") + String.format(".property('firstName', '%s')", name.firstName().replace("'", "")) + String.format(".property('lastName', '%s')", name.lastName().replace("'", "")) + String.format(".property('title', '%s')", name.title().replace("'", "")) + ".as('p')" + String.format(".addV('%s'n)", "Commerce") + String.format(".property('color', '%s')", commerce.color().replace("'", "")) + String.format(".property('department', '%s')", commerce.department().replace("'", "")) + String.format(".property('material', '%s')", commerce.material().replace("'", "")) + String.format(".property('price', '%s')", commerce.price().replace("'", "")) + String.format(".property('productName', '%s')", commerce.productName().replace("'", "")) + String.format(".property('promotionCode', '%s')", commerce.promotionCode().replace("'", "")) + ".as('comm')"; return stringBuilder; } @Test void testQueryThroughDriverAndConnString() throws Exception { final Connection connection = DriverManager.getConnection(CONNECTION_STRING); Assertions.assertTrue(connection.isValid(1)); final java.sql.Statement statement = connection.createStatement(); statement.execute( "SELECT count(region) from airport limit 10"); } @Test void testSql() throws SQLException { final Properties properties = new Properties(); properties.put(ConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.IAMSigV4); // set default to IAMSigV4 properties.put(CONTACT_POINT_KEY, ENDPOINT); properties.put(PORT_KEY, PORT); properties.put(ENABLE_SSL_KEY, ENABLE_SSL); properties.put(SERVICE_REGION_KEY, SERVICE_REGION); properties.put(SSH_USER, USER); properties.put(SSH_HOSTNAME, HOSTNAME); properties.put(SSH_PRIVATE_KEY_FILE, SSH_PRIVATE_KEY); properties.put(SSH_STRICT_HOST_KEY_CHECKING, SSH_STRICT_HOST); properties.put(SCAN_TYPE_KEY, SCAN_TYPE); final List<String> queries = ImmutableList.of( "SELECT count(region) from airport limit 10", "SELECT COUNT(\"Calcs\".\"bool0\") AS \"TEMP(Test)(1133866179)(0)\"\n" + "FROM \"gremlin\".\"Calcs\" \"Calcs\"\n" + "HAVING (COUNT(1) > 0)", "SELECT COUNT(`Calcs`.`int0`) AS `TEMP(Test)(3910975586)(0)` " + "FROM `gremlin`.`Calcs` `Calcs` " + "HAVING (COUNT(1) > 0)", "SELECT \"Staples\".\"Discount\" AS \"TEMP(Test)(1913174168)(0)\" " + "FROM \"gremlin\".\"Staples\" \"Staples\" " + "GROUP BY \"Staples\".\"Discount\"", "SELECT `airport`.`country`, `airport`.`region` FROM `airport` ORDER BY `airport`.`country`, `airport`.`region` DESC LIMIT 10", "SELECT `airport`.`country`, `airport`.`region` FROM `airport` ORDER BY `airport`.`country`, `airport`.`region` ASC LIMIT 10", "SELECT \"Calcs\".\"Calcs_ID\" AS \"Calcs_ID\", \"Calcs\".\"bool0\" AS \"bool_\", \"Calcs\".\"bool1\" AS \"bool_1\", \"Calcs\".\"bool2\" AS \"bool_2\", \"Calcs\".\"bool3\" AS \"bool_3\", \"Calcs\".\"date0\" AS \"date_\", \"Calcs\".\"date1\" AS \"date_1\", \"Calcs\".\"date2\" AS \"date_2\", \"Calcs\".\"date3\" AS \"date_3\", \"Calcs\".\"datetime0\" AS \"datetime_\", \"Calcs\".\"datetime1\" AS \"datetime_1\", \"Calcs\".\"int0\" AS \"int_\", \"Calcs\".\"int1\" AS \"int_1\", \"Calcs\".\"int2\" AS \"int_2\", \"Calcs\".\"int3\" AS \"int_3\", \"Calcs\".\"key\" AS \"key\", \"Calcs\".\"num0\" AS \"num_\", \"Calcs\".\"num1\" AS \"num_1\", \"Calcs\".\"num2\" AS \"num_2\", \"Calcs\".\"num3\" AS \"num_3\", \"Calcs\".\"num4\" AS \"num_4\", \"Calcs\".\"str0\" AS \"str_\", \"Calcs\".\"str1\" AS \"str_1\", \"Calcs\".\"str2\" AS \"str_2\", \"Calcs\".\"str3\" AS \"str_3\", \"Calcs\".\"time0\" AS \"time_\", \"Calcs\".\"time1\" AS \"time_1\", \"Calcs\".\"zzz\" AS \"zzz\" FROM \"gremlin\".\"Calcs\" \"Calcs\" LIMIT 10000 ", "SELECT \n" + " `airport`.`city` AS `city`,\n" + " `airport`.`city` AS `city`,\n" + " `airport`.`code` AS `code`,\n" + " `airport`.`country` AS `country`,\n" + " `airport`.`desc` AS `desc`,\n" + " `airport`.`elev` AS `elev`,\n" + " `airport`.`icao` AS `icao`,\n" + " `airport`.`lat` AS `lat`,\n" + " `airport`.`lon` AS `lon`,\n" + " `airport`.`longest` AS `longest`,\n" + " `airport`.`region` AS `region`,\n" + " `airport`.`runways` AS `runways`,\n" + " `airport`.`type` AS `type`\n" + " FROM `gremlin`.`airport` `airport`\n" + " LIMIT 100", "SELECT " + " AVG(`airport`.`lat`) AS `avg`," + " `airport`.`lat` AS `lat`" + " FROM `gremlin`.`airport` `airport`" + " GROUP BY `airport`.`lat` LIMIT 100", "SELECT `airport`.`country`, `airport`.`region` FROM `airport` ORDER BY `airport`.`country`, `airport`.`region` LIMIT 100", "SELECT `airport`.`code` AS `code` FROM `gremlin`.`airport` `airport` " + "INNER JOIN `gremlin`.`airport` `airport1` " + "ON (`airport`.`route_IN_ID` = `airport1`.`route_OUT_ID`) " + "GROUP BY `airport`.`code`", "SELECT " + " `airport1`.`ROUTE_OUT_ID` as `arid1`, " + " `airport`.`ROUTE_IN_ID` as `arid0`, " + " `airport1`.`city` AS `city__airport__`, " + " `airport`.`city` AS `city`, " + " AVG(`airport`.`lat`) AS `avg`" + " FROM `gremlin`.`airport` `airport` " + " INNER JOIN `gremlin`.`airport` `airport1` " + " ON (`airport`.`ROUTE_IN_ID` = `airport1`.`ROUTE_OUT_ID`) " + " GROUP BY `airport`.`lat`, `airport1`.`city`, `airport`.`city`," + " `airport1`.`ROUTE_OUT_ID`, `airport`.`ROUTE_IN_ID`" + " LIMIT 100", "SELECT \"route\".\"dist\" AS \"dist\" FROM \"gremlin\".\"route\" \"route\" LIMIT 100", "SELECT `airport`.`country`, `airport`.`region`, " + " SUM(`airport`.`elev`) AS `elev_sum`, " + "AVG(`airport`.`elev`) AS `elev_avg`, " + "MIN(`airport`.`elev`) AS `elev_min`, " + "MAX(`airport`.`elev`) AS `elev_max`," + " SUM(`airport`.`lat`) AS `lat_sum`, " + "AVG(`airport`.`lat`) AS `lat_avg`, " + "MIN(`airport`.`lat`) AS `lat_min`, " + "MAX(`airport`.`lat`) AS `lat_max` " + " FROM `airport` GROUP BY `airport`.`country`, `airport`.`region`", "SELECT " + " `airport1`.`ROUTE_OUT_ID` as `arid1`, " + " `airport`.`ROUTE_IN_ID` as `arid0`, " + " `airport1`.`city` AS `city__airport__`, " + " `airport`.`city` AS `city`, " + " AVG(`airport`.`lat`) AS `avg`" + " FROM `gremlin`.`airport` `airport` " + " INNER JOIN `gremlin`.`airport` `airport1` " + " ON (`airport`.`ROUTE_IN_ID` = `airport1`.`ROUTE_OUT_ID`) " + " GROUP BY `airport`.`lat`, `airport1`.`city`, `airport`.`city`," + " `airport1`.`ROUTE_OUT_ID`, `airport`.`ROUTE_IN_ID`" + " ORDER BY `arid1`, `arid0`, `city__airport__`, `city`" + " LIMIT 100" ); // Issue is in ROUTE / ROUTE_OUT_ID final java.sql.Connection connection = new SqlGremlinConnection(new GremlinConnectionProperties(properties)); for (final String query : queries) { runQueryPrintResults(query, connection.createStatement()); } } @Test void testHaving() throws SQLException { final Properties properties = new Properties(); properties.put(ConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.IAMSigV4); // set default to IAMSigV4 properties.put(CONTACT_POINT_KEY, ENDPOINT); properties.put(PORT_KEY, PORT); properties.put(ENABLE_SSL_KEY, true); properties.put(SSH_USER, "ec2-user"); properties.put(SSH_HOSTNAME, "52.14.185.245"); properties.put(SSH_PRIVATE_KEY_FILE, "~/Downloads/EC2/neptune-test.pem"); properties.put(SSH_STRICT_HOST_KEY_CHECKING, "false"); properties.put(SCAN_TYPE_KEY, "first"); final List<String> queries = ImmutableList.of( /*"SELECT `airport`.`country`, `airport`.`region`, " + " SUM(`airport`.`elev`) AS `elev_sum`, " + "AVG(`airport`.`elev`) AS `elev_avg`, " + "MIN(`airport`.`elev`) AS `elev_min`, " + "MAX(`airport`.`elev`) AS `elev_max`," + " SUM(`airport`.`lat`) AS `lat_sum`, " + "AVG(`airport`.`lat`) AS `lat_avg`, " + "MIN(`airport`.`lat`) AS `lat_min`, " + "MAX(`airport`.`lat`) AS `lat_max` " + " FROM `airport` GROUP BY `airport`.`country`, `airport`.`region` ORDER BY SUM(`airport`.`elev`)",*/ "SELECT `airport`.`country` FROM `airport` GROUP BY `airport`.`country` " + " HAVING (COUNT(1) > 0) LIMIT 10", "SELECT `airport`.`country`, `airport`.`region`, " + " SUM(`airport`.`elev`) AS `elev_sum`, " + "AVG(`airport`.`elev`) AS `elev_avg`, " + "MIN(`airport`.`elev`) AS `elev_min`, " + "MAX(`airport`.`elev`) AS `elev_max`," + " SUM(`airport`.`lat`) AS `lat_sum`, " + "AVG(`airport`.`lat`) AS `lat_avg`, " + "MIN(`airport`.`lat`) AS `lat_min`, " + "MAX(`airport`.`lat`) AS `lat_max` " + " FROM `airport` GROUP BY `airport`.`country`, `airport`.`region`, `airport`.`elev`, `airport`.`lat`" + " HAVING (COUNT(1) > 0) LIMIT 10", "SELECT `airport`.`country`, `airport`.`region`, " + " SUM(`airport`.`elev`) AS `elev_sum`, " + "AVG(`airport`.`elev`) AS `elev_avg`, " + "MIN(`airport`.`elev`) AS `elev_min`, " + "MAX(`airport`.`elev`) AS `elev_max`," + " SUM(`airport`.`lat`) AS `lat_sum`, " + "AVG(`airport`.`lat`) AS `lat_avg`, " + "MIN(`airport`.`lat`) AS `lat_min`, " + "MAX(`airport`.`lat`) AS `lat_max` " + " FROM `airport` GROUP BY `airport`.`country`, `airport`.`region`, `airport`.`elev`, `airport`.`lat`" + " HAVING `airport`.`lat` >= 8 LIMIT 10", "SELECT `airport`.`country`, `airport`.`region`, " + " SUM(`airport`.`elev`) AS `elev_sum`, " + "AVG(`airport`.`elev`) AS `elev_avg`, " + "MIN(`airport`.`elev`) AS `elev_min`, " + "MAX(`airport`.`elev`) AS `elev_max`," + " SUM(`airport`.`lat`) AS `lat_sum`, " + "AVG(`airport`.`lat`) AS `lat_avg`, " + "MIN(`airport`.`lat`) AS `lat_min`, " + "MAX(`airport`.`lat`) AS `lat_max` " + " FROM `airport` GROUP BY `airport`.`country`, `airport`.`region`, `airport`.`elev`, `airport`.`lat`" + " HAVING `airport`.`lat` <= 8 LIMIT 10", "SELECT `airport`.`lat`, `airport`.`lon`, " + " SUM(`airport`.`elev`) AS `elev_sum`, " + "AVG(`airport`.`elev`) AS `elev_avg`, " + "MIN(`airport`.`elev`) AS `elev_min`, " + "MAX(`airport`.`elev`) AS `elev_max`," + " SUM(`airport`.`lat`) AS `lat_sum`, " + "AVG(`airport`.`lat`) AS `lat_avg`, " + "MIN(`airport`.`lat`) AS `lat_min`, " + "MAX(`airport`.`lat`) AS `lat_max` " + " FROM `airport` GROUP BY `airport`.`country`, `airport`.`region`, `airport`.`elev`, `airport`.`lat`, `airport`.`lon`" + " HAVING COUNT(`airport`.`city`) > 8 LIMIT 10", "SELECT `airport`.`lat`, `airport`.`lon`, " + " SUM(`airport`.`elev`) AS `elev_sum`, " + "AVG(`airport`.`elev`) AS `elev_avg`, " + "MIN(`airport`.`elev`) AS `elev_min`, " + "MAX(`airport`.`elev`) AS `elev_max`," + " SUM(`airport`.`lat`) AS `lat_sum`, " + "AVG(`airport`.`lat`) AS `lat_avg`, " + "MIN(`airport`.`lat`) AS `lat_min`, " + "MAX(`airport`.`lat`) AS `lat_max` " + " FROM `airport` GROUP BY `airport`.`lat`, `airport`.`lon`, `airport`.`country`, `airport`.`region`" + " HAVING `airport`.`lat` > `airport`.`lon` LIMIT 10", "SELECT `airport`.`lat`, `airport`.`lon`, " + " SUM(`airport`.`elev`) AS `elev_sum`, " + "AVG(`airport`.`elev`) AS `elev_avg`, " + "MIN(`airport`.`elev`) AS `elev_min`, " + "MAX(`airport`.`elev`) AS `elev_max`," + " SUM(`airport`.`lat`) AS `lat_sum`, " + "AVG(`airport`.`lat`) AS `lat_avg`, " + "MIN(`airport`.`lat`) AS `lat_min`, " + "MAX(`airport`.`lat`) AS `lat_max` " + " FROM `airport` GROUP BY `airport`.`country`, `airport`.`region`, `airport`.`elev`, `airport`.`lat`, `airport`.`lon`" + " HAVING `airport`.`lat` > 8 LIMIT 10", "SELECT `airport`.`country`, `airport`.`region`, " + " SUM(`airport`.`elev`) AS `elev_sum`, " + "AVG(`airport`.`elev`) AS `elev_avg`, " + "MIN(`airport`.`elev`) AS `elev_min`, " + "MAX(`airport`.`elev`) AS `elev_max`," + " SUM(`airport`.`lat`) AS `lat_sum`, " + "AVG(`airport`.`lat`) AS `lat_avg`, " + "MIN(`airport`.`lat`) AS `lat_min`, " + "MAX(`airport`.`lat`) AS `lat_max` " + " FROM `airport` GROUP BY `airport`.`country`, `airport`.`region`, `airport`.`elev`, `airport`.`lat`" + " HAVING `airport`.`lat` > 8 LIMIT 10" ); // Issue is in ROUTE / ROUTE_OUT_ID final java.sql.Connection connection = new SqlGremlinConnection(new GremlinConnectionProperties(properties)); for (final String query : queries) { runQueryPrintResults(query, connection.createStatement()); } } @Test void testAggregateFunctions() throws SQLException { final Properties properties = new Properties(); properties.put(ConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.IAMSigV4); // set default to IAMSigV4 properties.put(CONTACT_POINT_KEY, ENDPOINT); properties.put(PORT_KEY, PORT); properties.put(ENABLE_SSL_KEY, true); properties.put(SSH_USER, "ec2-user"); properties.put(SSH_HOSTNAME, "52.14.185.245"); properties.put(SSH_PRIVATE_KEY_FILE, "~/Downloads/EC2/neptune-test.pem"); properties.put(SSH_STRICT_HOST_KEY_CHECKING, "false"); properties.put(SCAN_TYPE_KEY, "first"); final Properties gremlinProperties = new Properties(); gremlinProperties.put(ConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.IAMSigV4); // set default to IAMSigV4 gremlinProperties.put(CONTACT_POINT_KEY, ENDPOINT); gremlinProperties.put(PORT_KEY, PORT); final List<Pair<String, String>> queries = ImmutableList.of( new Pair<>(generateAggregateSQLQueries("AVG", "airport", "lat"), generateAggregateGremlinQueries("mean", "airport", "lat")), new Pair<>(generateAggregateSQLQueries("SUM", "airport", "lat"), generateAggregateGremlinQueries("sum", "airport", "lat")), new Pair<>(generateAggregateSQLQueries("COUNT", "airport", "lat"), generateAggregateGremlinQueries("count", "airport", "lat")), new Pair<>(generateAggregateSQLQueries("MAX", "airport", "lat"), generateAggregateGremlinQueries("max", "airport", "lat")), new Pair<>(generateAggregateSQLQueries("MIN", "airport", "lat"), generateAggregateGremlinQueries("min", "airport", "lat")), new Pair<>(generateAggregateSQLQueries("AVG", "airport", "elev"), generateAggregateGremlinQueries("mean", "airport", "elev")), new Pair<>(generateAggregateSQLQueries("SUM", "airport", "elev"), generateAggregateGremlinQueries("sum", "airport", "elev")), new Pair<>(generateAggregateSQLQueries("COUNT", "airport", "elev"), generateAggregateGremlinQueries("count", "airport", "elev")), new Pair<>(generateAggregateSQLQueries("MAX", "airport", "elev"), generateAggregateGremlinQueries("max", "airport", "elev")), new Pair<>(generateAggregateSQLQueries("MIN", "airport", "elev"), generateAggregateGremlinQueries("min", "airport", "elev")) ); final List<Pair<String, String>> groupQuery = ImmutableList.of( new Pair<>(generateAggregateSQLQueriesWithGroup("AVG", "airport", "lat", "country"), generateAggregateGremlinQueriesWithGroup("mean", "airport", "lat", "country")), new Pair<>(generateAggregateSQLQueriesWithGroup("SUM", "airport", "lat", "country"), generateAggregateGremlinQueriesWithGroup("sum", "airport", "lat", "country")), new Pair<>(generateAggregateSQLQueriesWithGroup("COUNT", "airport", "lat", "country"), generateAggregateGremlinQueriesWithGroup("count", "airport", "lat", "country")), new Pair<>(generateAggregateSQLQueriesWithGroup("MAX", "airport", "lat", "country"), generateAggregateGremlinQueriesWithGroup("max", "airport", "lat", "country")), new Pair<>(generateAggregateSQLQueriesWithGroup("MIN", "airport", "lat", "country"), generateAggregateGremlinQueriesWithGroup("min", "airport", "lat", "country")), new Pair<>(generateAggregateSQLQueriesWithGroup("AVG", "airport", "elev", "country"), generateAggregateGremlinQueriesWithGroup("mean", "airport", "elev", "country")), new Pair<>(generateAggregateSQLQueriesWithGroup("SUM", "airport", "elev", "country"), generateAggregateGremlinQueriesWithGroup("sum", "airport", "elev", "country")), new Pair<>(generateAggregateSQLQueriesWithGroup("COUNT", "airport", "elev", "country"), generateAggregateGremlinQueriesWithGroup("count", "airport", "elev", "country")), new Pair<>(generateAggregateSQLQueriesWithGroup("MAX", "airport", "elev", "country"), generateAggregateGremlinQueriesWithGroup("max", "airport", "elev", "country")), new Pair<>(generateAggregateSQLQueriesWithGroup("MIN", "airport", "elev", "country"), generateAggregateGremlinQueriesWithGroup("min", "airport", "elev", "country")) ); final GremlinConnectionProperties sqlGremlinConnectionProperties = new GremlinConnectionProperties(properties); final java.sql.Connection sqlGremlinConnection = new SqlGremlinConnection(sqlGremlinConnectionProperties); final GremlinConnectionProperties gremlinConnectionProperties = new GremlinConnectionProperties(gremlinProperties); gremlinConnectionProperties.sshTunnelOverride(sqlGremlinConnectionProperties.getPort()); final java.sql.Connection gremlinConnection = new GremlinConnection(gremlinConnectionProperties); for (final Pair<String, String> query : queries) { runQueriesCompareResults(query.getKey(), query.getValue(), sqlGremlinConnection.createStatement(), gremlinConnection.createStatement()); } } private String generateAggregateSQLQueries(final String operator, final String table, final String column) { // Returns a simple SQL query in the form: // "SELECT OPERATOR(`table`.`column`) AS `OPERATOR` FROM `gremlin`.`table` `table` GROUP BY `table`.`column`" return String.format("SELECT %s(`%s`.`%s`) AS `%s` FROM `gremlin`.`%s` `%s` GROUP BY `%s`.`%s`", operator, table, column, operator, table, table, table, column); } private String generateAggregateGremlinQueriesWithGroup(final String operator, final String table, final String column, final String groupColumn) { // Returns a simple Gremlin query in the form: return String.format( "g.V().hasLabel('%s')." + "group()." + "by(union(values('%s')).fold()).unfold()." + "select(values)." + "order()." + "by(unfold().values())." + "project('%s_%s')." + "by(unfold().values('%s').%s())", table, groupColumn, column, operator.toLowerCase(), column, operator.toLowerCase()); } private String generateAggregateSQLQueriesWithGroup(final String operator, final String table, final String column, final String groupColumn) { // Returns a simple SQL query in the form: // "SELECT OPERATOR(`table`.`column`) AS `OPERATOR` FROM `gremlin`.`table` `table` GROUP BY `table`.`column`" return String.format("SELECT `%s`.`%s` %s(`%s`.`%s`) AS `%s` FROM `gremlin`.`%s` `%s` GROUP BY `%s`.`%s`", table, groupColumn, operator, table, column, operator, table, table, table, groupColumn); } private String generateAggregateGremlinQueries(final String operator, final String table, final String column) { // Returns a simple Gremlin query in the form: return String .format("g.V().hasLabel('%s').group().by(union(values('%s')).fold()).unfold().select(values).order().by(unfold().values())" + ".fold().project('%s_%s').by(unfold().unfold().values('%s').%s())", table, column, column, operator.toLowerCase(), column, operator.toLowerCase()); } void runQueriesCompareResults(final String sqlQuery, final String gremlinQuery, final java.sql.Statement sqlGremlinStatement, final java.sql.Statement gremlinStatement) throws SQLException { System.out.println("SQL: " + sqlQuery); System.out.println("Gremlin: " + gremlinQuery); final java.sql.ResultSet sqlGremlinResultSet = sqlGremlinStatement.executeQuery(sqlQuery); final java.sql.ResultSet gremlinResultSet = gremlinStatement.executeQuery(gremlinQuery); final int sqlGremlinColumnCount = sqlGremlinResultSet.getMetaData().getColumnCount(); final int gremlinColumnCount = gremlinResultSet.getMetaData().getColumnCount(); // we expect aggregate results to be of 1 column Assertions.assertEquals(sqlGremlinColumnCount, 1); Assertions.assertEquals(gremlinColumnCount, 1); while (sqlGremlinResultSet.next() && gremlinResultSet.next()) { Assertions.assertEquals(sqlGremlinResultSet.getObject(1), gremlinResultSet.getObject(1)); } } @Test void testSqlConnectionExecution() throws SQLException { final Properties properties = new Properties(); properties.put(ConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.IAMSigV4); // set default to IAMSigV4 properties.put(CONTACT_POINT_KEY, ENDPOINT); properties.put(PORT_KEY, PORT); properties.put(ENABLE_SSL_KEY, true); properties.put(SSH_USER, "ec2-user"); properties.put(SSH_HOSTNAME, "52.14.185.245"); properties.put(SSH_PRIVATE_KEY_FILE, "~/Downloads/EC2/neptune-test.pem"); properties.put(SSH_STRICT_HOST_KEY_CHECKING, "false"); properties.put(SCAN_TYPE_KEY, "first"); final List<String> queries = ImmutableList.of("SELECT * FROM Person", "SELECT `Person`.`firstName` AS `firstName`, `Cat`.`name` AS `name` FROM `Cat` INNER JOIN `Person` ON (`Cat`.`name` = `Person`.`name`) GROUP BY `Person`.`firstName`, `Cat`.`name`", "SELECT `Person`.`age` AS `age`, `Cat`.`name` AS `name__Cat_` FROM `Person` INNER JOIN `Cat` ON (`Person`.`firstName` = `Cat`.`name`) GROUP BY `Person`.`age`, `Cat`.`name`", "SELECT `Person`.`firstName` AS `firstName`, `Cat`.`name` AS `name` FROM `Cat` INNER JOIN `Person` ON `Cat`.`name` = `Person`.`name`", "SELECT `Person`.`age` AS `age`, SUM(1) AS `cnt_Person_4A9569D21233471BB4DC6258F15087AD_ok`, `Person`.`pets` AS `pets` FROM `Person` GROUP BY `Person`.`age`, `Person`.`pets`", "SELECT `Person`.`age` AS `age`, `Person`.`cat` AS `cat`, `Person`.`dog` AS `dog`, `Person`.`firstName` AS `firstName`, `Person`.`lastName` AS `lastName`, `Person`.`name` AS `name`, `Person`.`pets` AS `pets`, `Person`.`title` AS `title` FROM `Person` LIMIT 10000"); final java.sql.Connection connection = new SqlGremlinConnection(new GremlinConnectionProperties(properties)); final java.sql.DatabaseMetaData databaseMetaData = connection.getMetaData(); databaseMetaData.getTables(null, null, null, null); final java.sql.ResultSet columns = databaseMetaData.getColumns(null, null, null, null); while (columns.next()) { System.out.println("Column " + columns.getString("COLUMN_NAME") + " - " + columns.getString("TYPE_NAME") + " - " + columns.getString("DATA_TYPE")); } for (final String query : queries) { runQueryPrintResults(query, connection.createStatement()); } } @Test void testSchema() throws SQLException { final Properties properties = new Properties(); properties.put(ConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.IAMSigV4); // set default to IAMSigV4 properties.put(CONTACT_POINT_KEY, ENDPOINT); properties.put(PORT_KEY, PORT); properties.put(ENABLE_SSL_KEY, true); final java.sql.Connection connection = new SqlGremlinConnection(new GremlinConnectionProperties(properties)); final java.sql.Statement statement = connection.createStatement(); runQueryPrintResults("SELECT category FROM websiteGroup LIMIT 5", statement); runQueryPrintResults("SELECT title FROM website LIMIT 10", statement); runQueryPrintResults("SELECT visited_id FROM website LIMIT 5", statement); runQueryPrintResults("SELECT visited_id, title FROM website LIMIT 15", statement); runQueryPrintResults("SELECT title, visited_id FROM website LIMIT 15", statement); runQueryPrintResults("SELECT * FROM website LIMIT 10", statement); runQueryPrintResults( "SELECT `website`.`url` AS `url` FROM `website` INNER JOIN `transientId` ON " + "(`website`.`visited_id` = `transientId`.`visited_id`) LIMIT 5", statement); runQueryPrintResults( "SELECT `transientId`.`os` AS `os` FROM `transientId` INNER JOIN `website` ON " + "(`website`.`visited_id` = `transientId`.`visited_id`) LIMIT 10", statement); } void runQueryPrintResults(final String query, final java.sql.Statement statement) throws SQLException { System.out.println("Executing query: " + query); final java.sql.ResultSet resultSet = statement.executeQuery(query); final int columnCount = resultSet.getMetaData().getColumnCount(); final List<String> columns = new ArrayList<>(); for (int i = 1; i <= columnCount; i++) { columns.add(resultSet.getMetaData().getColumnName(i)); } final List<List<Object>> rows = new ArrayList<>(); while (resultSet.next()) { final List<Object> row = new ArrayList<>(); for (int i = 1; i <= columnCount; i++) { row.add(resultSet.getObject(i)); } rows.add(row); } final Object[][] rowObjects = new Object[rows.size()][]; final String[] colString = new String[columns.size()]; for (int i = 0; i < columns.size(); i++) { colString[i] = columns.get(i); } for (int i = 0; i < rows.size(); i++) { rowObjects[i] = rows.get(i) == null ? null : rows.get(i).toArray(); } final TextTable tt = new TextTable(colString, rowObjects); tt.printTable(); } @Test void getGremlinSchema() throws Exception { final Properties properties = new Properties(); properties.put(ConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.IAMSigV4); // set default to IAMSigV4 properties.put(CONTACT_POINT_KEY, ENDPOINT); properties.put(PORT_KEY, PORT); properties.put(ENABLE_SSL_KEY, true); properties.put(SSH_USER, "ec2-user"); properties.put(SSH_HOSTNAME, "52.14.185.245"); properties.put(SSH_PRIVATE_KEY_FILE, "~/Downloads/EC2/neptune-test.pem"); properties.put(SSH_STRICT_HOST_KEY_CHECKING, "false"); final GremlinConnectionProperties gremlinConnectionProperties = new GremlinConnectionProperties(properties); final java.sql.Connection connection = new SqlGremlinConnection(gremlinConnectionProperties); final Cluster cluster = SqlGremlinQueryExecutor.createClusterBuilder(gremlinConnectionProperties).create(); final Client client = cluster.connect().init(); final ExecutorService executor = Executors.newFixedThreadPool(96, new ThreadFactoryBuilder().setNameFormat("RxSessionRunner-%d").setDaemon(true).build()); final Future<List<GremlinVertexTable>> gremlinVertexTablesFuture = executor.submit(new RunGremlinQueryVertices(client, executor, TraversalStrategy.First)); final Future<List<GremlinEdgeTable>> gremlinEdgeTablesFuture = executor.submit(new RunGremlinQueryEdges(client, executor, TraversalStrategy.First)); final List<GremlinVertexTable> vertices = gremlinVertexTablesFuture.get(); final List<GremlinEdgeTable> edges = gremlinEdgeTablesFuture.get(); final GremlinSchema gremlinSchema = new GremlinSchema(vertices, edges); final SqlConverter sqlConverter = new SqlConverter(gremlinSchema); SqlGremlinQueryResult result = sqlConverter.executeQuery(traversal().withRemote(DriverRemoteConnection.using(client)), "SELECT airport.city AS c FROM airport"); System.out.println("Columns: " + result.getColumns()); result = sqlConverter.executeQuery(traversal().withRemote(DriverRemoteConnection.using(client)), "SELECT city AS c FROM airport"); System.out.println("Columns: " + result.getColumns()); result = sqlConverter.executeQuery(traversal().withRemote(DriverRemoteConnection.using(client)), "SELECT city FROM airport HAVING (COUNT(1) > 0)"); System.out.println("Columns: " + result.getColumns()); } enum TraversalStrategy { First, RandomN, All } @AllArgsConstructor class RunGremlinQueryVertices implements Callable<List<GremlinVertexTable>> { private final Client client; private final ExecutorService service; private final TraversalStrategy traversalStrategy; @Override public List<GremlinVertexTable> call() throws Exception { final List<Future<List<GremlinProperty>>> gremlinProperties = new ArrayList<>(); final List<Future<List<String>>> gremlinVertexInEdgeLabels = new ArrayList<>(); final List<Future<List<String>>> gremlinVertexOutEdgeLabels = new ArrayList<>(); final List<String> labels = service.submit(new RunGremlinQueryLabels(true, client)).get(); for (final String label : labels) { gremlinProperties.add(service.submit( new RunGremlinQueryPropertiesList(true, label, client, traversalStrategy, service))); gremlinVertexInEdgeLabels.add(service.submit(new RunGremlinQueryVertexEdges(client, label, "in"))); gremlinVertexOutEdgeLabels.add(service.submit(new RunGremlinQueryVertexEdges(client, label, "out"))); } final List<GremlinVertexTable> gremlinVertexTables = new ArrayList<>(); for (int i = 0; i < labels.size(); i++) { gremlinVertexTables.add(new GremlinVertexTable(labels.get(i), gremlinProperties.get(i).get(), gremlinVertexInEdgeLabels.get(i).get(), gremlinVertexOutEdgeLabels.get(i).get())); } return gremlinVertexTables; } } @AllArgsConstructor class RunGremlinQueryVertexEdges implements Callable<List<String>> { private final Client client; private final String label; private final String direction; @Override public List<String> call() throws Exception { final String query = String.format("g.V().hasLabel('%s').%sE().label().dedup()", label, direction); System.out.printf("Start %s%n", query); final ResultSet resultSet = client.submit(query); final List<String> labels = new ArrayList<>(); resultSet.stream().iterator().forEachRemaining(it -> labels.add(it.getString())); System.out.printf("End %s%n", query); return labels; } } @AllArgsConstructor class RunGremlinQueryEdges implements Callable<List<GremlinEdgeTable>> { private final Client client; private final ExecutorService service; private final TraversalStrategy traversalStrategy; @Override public List<GremlinEdgeTable> call() throws Exception { final List<Future<List<GremlinProperty>>> futureTableColumns = new ArrayList<>(); final List<Future<List<Pair<String, String>>>> inOutLabels = new ArrayList<>(); final List<String> labels = service.submit(new RunGremlinQueryLabels(false, client)).get(); for (final String label : labels) { futureTableColumns.add(service.submit( new RunGremlinQueryPropertiesList(false, label, client, traversalStrategy, service))); inOutLabels.add(service.submit(new RunGremlinQueryInOutV(client, label))); } final List<GremlinEdgeTable> gremlinEdgeTables = new ArrayList<>(); for (int i = 0; i < labels.size(); i++) { gremlinEdgeTables.add(new GremlinEdgeTable(labels.get(i), futureTableColumns.get(i).get(), inOutLabels.get(i).get())); } return gremlinEdgeTables; } } @AllArgsConstructor class RunGremlinQueryPropertyType implements Callable<String> { private final boolean isVertex; private final String label; private final String property; private final Client client; private final TraversalStrategy strategy; @Override public String call() { final String query; if (strategy.equals(TraversalStrategy.First)) { query = String.format("g.%s().hasLabel('%s').values('%s').next(1)", isVertex ? "V" : "E", label, property); } else { query = String.format("g.%s().hasLabel('%s').values('%s').toSet()", isVertex ? "V" : "E", label, property); } System.out.printf("Start %s%n", query); final ResultSet resultSet = client.submit(query); final Set<Object> data = new HashSet<>(); resultSet.stream().iterator().forEachRemaining(data::add); System.out.printf("End %s%n", query); return getType(data); } } @AllArgsConstructor class RunGremlinQueryPropertiesList implements Callable<List<GremlinProperty>> { private final boolean isVertex; private final String label; private final Client client; private final TraversalStrategy traversalStrategy; private final ExecutorService service; @Override public List<GremlinProperty> call() throws ExecutionException, InterruptedException { final String query = String.format("g.%s().hasLabel('%s').properties().key().dedup()", isVertex ? "V" : "E", label); System.out.printf("Start %s%n", query); final ResultSet resultSet = client.submit(query); final Iterator<Result> iterator = resultSet.stream().iterator(); final List<String> properties = new ArrayList<>(); final List<Future<String>> propertyTypes = new ArrayList<>(); while (iterator.hasNext()) { final String property = iterator.next().getString(); propertyTypes.add(service .submit(new RunGremlinQueryPropertyType(isVertex, label, property, client, traversalStrategy))); properties.add(property); } final List<GremlinProperty> columns = new ArrayList<>(); for (int i = 0; i < properties.size(); i++) { columns.add(new GremlinProperty(properties.get(i), propertyTypes.get(i).get().toLowerCase())); } System.out.printf("End %s%n", query); return columns; } } @AllArgsConstructor class RunGremlinQueryLabels implements Callable<List<String>> { private final boolean isVertex; private final Client client; @Override public List<String> call() throws Exception { // Get labels. final String query = String.format("g.%s().label().dedup()", isVertex ? "V" : "E"); System.out.printf("Start %s%n", query); final List<String> labels = new ArrayList<>(); final ResultSet resultSet = client.submit(query); resultSet.stream().iterator().forEachRemaining(it -> labels.add(it.getString())); System.out.printf("End %s%n", query); return labels; } } @AllArgsConstructor class RunGremlinQueryInOutV implements Callable<List<Pair<String, String>>> { private final Client client; private final String label; @Override public List<Pair<String, String>> call() throws Exception { // Get labels. final String query = String.format( "g.E().hasLabel('%s').project('in','out').by(inV().label()).by(outV().label()).dedup()", label); System.out.printf("Start %s%n", query); final List<Pair<String, String>> labels = new ArrayList<>(); final ResultSet resultSet = client.submit(query); resultSet.stream().iterator().forEachRemaining(map -> { final Map<String, String> m = (Map<String, String>) map.getObject(); m.forEach((key, value) -> labels.add(new Pair<>(key, value))); }); System.out.printf("End %s%n", query); return labels; } } @AllArgsConstructor class RunGremlinQueryOutV implements Callable<List<String>> { private final Client client; private final String label; @Override public List<String> call() throws Exception { // Get labels. final String query = String.format("g.E().hasLabel('%s').out().label().dedup()", label); System.out.printf("Start %s%n", query); final List<String> labels = new ArrayList<>(); final ResultSet resultSet = client.submit(query); resultSet.stream().iterator().forEachRemaining(it -> labels.add(it.getString())); System.out.printf("End %s%n", query); return labels; } } }
7,315
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/sparql/SparqlConnectionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.sparql; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.aws.neptune.jdbc.utilities.AuthScheme; import software.aws.neptune.jdbc.utilities.ConnectionProperties; import software.aws.neptune.sparql.mock.SparqlMockServer; import java.sql.SQLException; import java.util.Properties; public class SparqlConnectionTest { private static final String HOSTNAME = "http://localhost"; private static final String DATASET = "mock"; private static final String QUERY_ENDPOINT = "query"; private static final int PORT = SparqlMockServer.port(); // Mock server dynamically generates port private java.sql.Connection connection; private static Properties sparqlProperties() { final Properties properties = new Properties(); properties.put(ConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.None); // set default to None properties.put(SparqlConnectionProperties.ENDPOINT_KEY, HOSTNAME); properties.put(SparqlConnectionProperties.PORT_KEY, PORT); properties.put(SparqlConnectionProperties.DATASET_KEY, DATASET); properties.put(SparqlConnectionProperties.QUERY_ENDPOINT_KEY, QUERY_ENDPOINT); return properties; } /** * Function to start the mock server before testing. */ @BeforeAll public static void initializeMockServer() { SparqlMockServer.ctlBeforeClass(); } /** * Function to tear down server after testing. */ @AfterAll public static void shutdownMockServer() { SparqlMockServer.ctlAfterClass(); } @BeforeEach void initialize() throws SQLException { connection = new SparqlConnection(new SparqlConnectionProperties(sparqlProperties())); } @AfterEach void shutdown() throws SQLException { connection.close(); } @Test void testIsValid() throws SQLException { Assertions.assertTrue(connection.isValid(1)); final Throwable negativeTimeout = Assertions.assertThrows(SQLException.class, () -> connection.isValid(-1)); Assertions.assertEquals("Timeout value must be greater than or equal to 0", negativeTimeout.getMessage()); final Properties timeoutProperties = new Properties(); timeoutProperties.put(ConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.None); // set default to None // setting to non-routable IP for timeout timeoutProperties.put(SparqlConnectionProperties.ENDPOINT_KEY, "http://10.255.255.1"); timeoutProperties.put(SparqlConnectionProperties.PORT_KEY, 1234); timeoutProperties.put(SparqlConnectionProperties.DATASET_KEY, "timeout"); timeoutProperties.put(SparqlConnectionProperties.QUERY_ENDPOINT_KEY, "query"); final java.sql.Connection timeoutConnection = new SparqlConnection( new SparqlConnectionProperties(timeoutProperties)); Assertions.assertFalse(timeoutConnection.isValid(2)); final Properties invalidProperties = new Properties(); invalidProperties.put(ConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.None); // set default to None invalidProperties.put(SparqlConnectionProperties.ENDPOINT_KEY, HOSTNAME); invalidProperties.put(SparqlConnectionProperties.PORT_KEY, 1234); invalidProperties.put(SparqlConnectionProperties.DATASET_KEY, "invalid"); invalidProperties.put(SparqlConnectionProperties.QUERY_ENDPOINT_KEY, "query"); final java.sql.Connection invalidConnection = new SparqlConnection( new SparqlConnectionProperties(invalidProperties)); Assertions.assertFalse(invalidConnection.isValid(1)); } }
7,316
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/sparql/SparqlStatementTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.sparql; import org.apache.jena.rdfconnection.RDFConnection; import org.apache.jena.rdfconnection.RDFConnectionRemote; import org.apache.jena.rdfconnection.RDFConnectionRemoteBuilder; import org.apache.jena.update.UpdateFactory; import org.apache.jena.update.UpdateRequest; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import software.aws.neptune.NeptuneStatementTestHelper; import software.aws.neptune.jdbc.utilities.AuthScheme; import software.aws.neptune.jdbc.utilities.ConnectionProperties; import software.aws.neptune.sparql.mock.SparqlMockServer; import java.sql.SQLException; import java.util.Properties; // TODO AN-887: Fix query cancellation issue and enable tests. @Disabled public class SparqlStatementTest extends SparqlStatementTestBase { private static final String HOSTNAME = "http://localhost"; private static final String ENDPOINT = "mock"; private static final String QUERY_ENDPOINT = "query"; private static final int PORT = SparqlMockServer.port(); // Mock server dynamically generates port private static NeptuneStatementTestHelper neptuneStatementTestHelper; private static Properties sparqlProperties() { final Properties properties = new Properties(); properties.put(ConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.None); // set default to None properties.put(SparqlConnectionProperties.ENDPOINT_KEY, HOSTNAME); properties.put(SparqlConnectionProperties.PORT_KEY, PORT); properties.put(SparqlConnectionProperties.DATASET_KEY, ENDPOINT); properties.put(SparqlConnectionProperties.QUERY_ENDPOINT_KEY, QUERY_ENDPOINT); return properties; } /** * Function to start the mock server before testing. */ @BeforeEach public void initializeMockServer() throws SQLException { SparqlMockServer.ctlBeforeEach(); final RDFConnectionRemoteBuilder builder = RDFConnectionRemote.create() .destination(SparqlMockServer.urlDataset()) .queryEndpoint("/query") .updateEndpoint("/update"); final UpdateRequest update = UpdateFactory.create(LONG_UPDATE); // load dataset in try (final RDFConnection conn = builder.build()) { conn.load("src/test/java/software/aws/neptune/sparql/mock/sparql_mock_data.rdf"); conn.update(update); } final java.sql.Connection connection = new SparqlConnection( new SparqlConnectionProperties(sparqlProperties())); neptuneStatementTestHelper = new NeptuneStatementTestHelper(connection.createStatement(), LONG_QUERY, QUICK_QUERY); } /** * Function to tear down server after testing. */ @AfterEach public void shutdownMockServer() { SparqlMockServer.ctlAfterEach(); } @Test void testCancelQueryWithoutExecute() { neptuneStatementTestHelper.testCancelQueryWithoutExecute(); } // TODO: Disabling this test due to query timing inconsistency across different machines leading to failed test. // Will address this issue in ticket AN-597 @Test @Disabled void testCancelQueryTwice() { neptuneStatementTestHelper.testCancelQueryTwice(); } @Test void testCancelQueryAfterExecuteComplete() { neptuneStatementTestHelper.testCancelQueryAfterExecuteComplete(); } }
7,317
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/sparql/SparqlManualNeptuneVerificationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.sparql; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; import com.amazonaws.neptune.auth.NeptuneApacheHttpSigV4Signer; import com.amazonaws.neptune.auth.NeptuneSigV4SignerException; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.protocol.HttpContext; import org.apache.jena.query.Query; import org.apache.jena.query.QueryFactory; import org.apache.jena.query.ResultSetFormatter; import org.apache.jena.rdfconnection.RDFConnection; import org.apache.jena.rdfconnection.RDFConnectionRemote; import org.apache.jena.rdfconnection.RDFConnectionRemoteBuilder; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import software.aws.neptune.jdbc.utilities.AuthScheme; import software.aws.neptune.jdbc.utilities.ConnectionProperties; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; @Disabled public class SparqlManualNeptuneVerificationTest { private static final String NEPTUNE_HOSTNAME = "https://jdbc-bug-bash-iam-instance-1.cdubgfjknn5r.us-east-1.neptune.amazonaws.com"; private static final int NEPTUNE_DEFAULT_PORT = 8182; private static final String AUTH = "IamSigV4"; private static final String REGION = "us-east-1"; private static final String NEPTUNE_QUERY_ENDPOINT = "sparql"; private static final String NEPTUNE_DESTINATION_STRING = String.format("%s:%d", NEPTUNE_HOSTNAME, NEPTUNE_DEFAULT_PORT); private static final String CONNECTION_STRING = String.format("jdbc:neptune:sparql://%s;queryEndpoint=%s;authScheme=%s;serviceRegion=%s;", NEPTUNE_HOSTNAME, NEPTUNE_QUERY_ENDPOINT, AUTH, REGION); private static java.sql.Statement statement; private static java.sql.Connection authConnection; private static java.sql.DatabaseMetaData databaseMetaData; private static Properties authProperties() { final Properties properties = new Properties(); properties.put(ConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.IAMSigV4); properties.put(SparqlConnectionProperties.ENDPOINT_KEY, NEPTUNE_HOSTNAME); properties.put(SparqlConnectionProperties.PORT_KEY, NEPTUNE_DEFAULT_PORT); properties.put(SparqlConnectionProperties.QUERY_ENDPOINT_KEY, NEPTUNE_QUERY_ENDPOINT); properties.put(SparqlConnectionProperties.SERVICE_REGION_KEY, REGION); // properties.put(SSH_USER, "ec2-user"); // properties.put(SSH_HOSTNAME, "52.14.185.245"); // properties.put(SSH_PRIVATE_KEY_FILE, "~/Downloads/EC2/neptune-test.pem"); // properties.put(SSH_STRICT_HOST_KEY_CHECKING, "false"); return properties; } @BeforeAll static void initialize() throws SQLException { authConnection = new SparqlConnection(new SparqlConnectionProperties(authProperties())); statement = authConnection.createStatement(); databaseMetaData = authConnection.getMetaData(); } @Disabled @Test void testBasicIamAuth() throws Exception { Assertions.assertTrue(authConnection.isValid(1)); } @Disabled @Test void testBasicIamAuthThoughConnString() throws Exception { final Connection connection = DriverManager.getConnection(CONNECTION_STRING); Assertions.assertTrue(connection.isValid(1)); } @Disabled @Test void testSigV4Auth() throws SQLException { Assertions.assertTrue(authConnection.isValid(1)); final String query = "SELECT ?s ?p ?o WHERE {?s ?p ?o}"; final java.sql.ResultSet resultSet = statement.executeQuery(query); while (resultSet.next()) { Assertions.assertNotNull(resultSet.getString(1)); Assertions.assertNotNull(resultSet.getString(2)); Assertions.assertNotNull(resultSet.getString(3)); } final java.sql.ResultSet metadataResultSet = databaseMetaData.getColumns(null, null, null, null); Assertions.assertFalse(metadataResultSet.next()); } @Test @Disabled void testRunBasicAuthConnection() throws NeptuneSigV4SignerException { //TODO: remove this test after completing the driver and rest of this test class final AWSCredentialsProvider awsCredentialsProvider = new DefaultAWSCredentialsProviderChain(); final NeptuneApacheHttpSigV4Signer v4Signer = new NeptuneApacheHttpSigV4Signer("us-east-1", awsCredentialsProvider); final HttpClient v4SigningClient = HttpClientBuilder.create().addInterceptorLast(new HttpRequestInterceptor() { @Override public void process(final HttpRequest req, final HttpContext ctx) throws HttpException { if (req instanceof HttpUriRequest) { final HttpUriRequest httpUriReq = (HttpUriRequest) req; try { v4Signer.signRequest(httpUriReq); } catch (final NeptuneSigV4SignerException e) { throw new HttpException("Problem signing the request: ", e); } } else { throw new HttpException("Not an HttpUriRequest"); // this should never happen } } }).build(); final RDFConnectionRemoteBuilder builder = RDFConnectionRemote.create() .httpClient(v4SigningClient) .destination(NEPTUNE_DESTINATION_STRING) // Query only. .queryEndpoint("sparql"); final Query query = QueryFactory.create("SELECT * { ?s ?p ?o } LIMIT 100"); // Whether the connection can be reused depends on the details of the implementation. // See example 5. try (final RDFConnection conn = builder.build()) { System.out.println("connecting"); conn.queryResultSet(query, ResultSetFormatter::out); } } }
7,318
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/sparql/SparqlDataSourceTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.sparql; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import software.aws.neptune.jdbc.helpers.HelperFunctions; import software.aws.neptune.jdbc.utilities.AuthScheme; import software.aws.neptune.jdbc.utilities.SqlError; import software.aws.neptune.sparql.mock.SparqlMockServer; import java.sql.SQLException; public class SparqlDataSourceTest { private static final String HOSTNAME = "http://localhost"; private static final String VALID_ENDPOINT = String.format("%s:%d/mock/query", HOSTNAME, SparqlMockServer.port()); private SparqlDataSource dataSource; /** * Function to get a random available port and initialize database before testing. */ @BeforeAll public static void initializeMockServer() { SparqlMockServer.ctlBeforeClass(); } /** * Function to get a shutdown database after testing. */ @AfterAll public static void shutdownMockServer() { SparqlMockServer.ctlAfterClass(); } @BeforeEach void initialize() throws SQLException { dataSource = new SparqlDataSource(); } @Test @Disabled void testGetConnectionSuccess() throws SQLException { dataSource.setEndpoint(HOSTNAME); dataSource.setPort(SparqlMockServer.port()); dataSource.setDataset(SparqlMockServer.datasetPath()); dataSource.setQueryEndpoint("query"); Assertions.assertTrue(dataSource.getConnection() instanceof SparqlConnection); Assertions.assertTrue(dataSource.getPooledConnection() instanceof SparqlPooledConnection); } @Test void testGetConnectionFailure() throws SQLException { HelperFunctions .expectFunctionThrows(SqlError.FEATURE_NOT_SUPPORTED, () -> dataSource.getConnection("name", "psw")); HelperFunctions.expectFunctionThrows(SqlError.FEATURE_NOT_SUPPORTED, () -> dataSource.getPooledConnection("name", "psw")); } @Test void testSupportedProperties() throws SQLException { Assertions.assertDoesNotThrow(() -> dataSource.setEndpoint(VALID_ENDPOINT)); Assertions.assertEquals(VALID_ENDPOINT, dataSource.getEndpoint()); Assertions.assertDoesNotThrow(() -> dataSource.setApplicationName("appName")); Assertions.assertEquals("appName", dataSource.getApplicationName()); Assertions.assertDoesNotThrow(() -> dataSource.setAuthScheme(AuthScheme.None)); Assertions.assertEquals(AuthScheme.None, dataSource.getAuthScheme()); Assertions.assertDoesNotThrow(() -> dataSource.setConnectionRetryCount(5)); Assertions.assertEquals(5, dataSource.getConnectionRetryCount()); Assertions.assertDoesNotThrow(() -> dataSource.setConnectionTimeoutMillis(1000)); Assertions.assertEquals(1000, dataSource.getConnectionTimeoutMillis()); Assertions.assertDoesNotThrow(() -> dataSource.setLoginTimeout(50)); Assertions.assertEquals(50, dataSource.getLoginTimeout()); } }
7,319
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/sparql/SparqlDatabaseMetadataTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.sparql; import org.apache.jena.rdfconnection.RDFConnection; import org.apache.jena.rdfconnection.RDFConnectionRemote; import org.apache.jena.rdfconnection.RDFConnectionRemoteBuilder; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.aws.neptune.jdbc.utilities.AuthScheme; import software.aws.neptune.jdbc.utilities.ConnectionProperties; import software.aws.neptune.sparql.mock.SparqlMockServer; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.Properties; public class SparqlDatabaseMetadataTest { private static final String HOSTNAME = "http://localhost"; private static final String DATASET = "mock"; private static final String QUERY_ENDPOINT = "query"; private static final int PORT = SparqlMockServer.port(); // Mock server dynamically generates port private static java.sql.Connection connection; private static java.sql.DatabaseMetaData databaseMetaData; private static Properties sparqlProperties() { final Properties properties = new Properties(); properties.put(ConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.None); // set default to None properties.put(SparqlConnectionProperties.ENDPOINT_KEY, HOSTNAME); properties.put(SparqlConnectionProperties.PORT_KEY, PORT); properties.put(SparqlConnectionProperties.DATASET_KEY, DATASET); properties.put(SparqlConnectionProperties.QUERY_ENDPOINT_KEY, QUERY_ENDPOINT); return properties; } /** * Function to start the mock server and populate database before testing. */ @BeforeAll public static void initializeMockServer() throws SQLException { SparqlMockServer.ctlBeforeClass(); // insert into the database here // Query only. final RDFConnectionRemoteBuilder rdfConnBuilder = RDFConnectionRemote.create() .destination(SparqlMockServer.urlDataset()) // Query only. .queryEndpoint("/query"); // load dataset in try (final RDFConnection conn = rdfConnBuilder.build()) { conn.load("src/test/java/software/aws/neptune/sparql/mock/sparql_mock_data.rdf"); } } /** * Function to tear down server after testing. */ @AfterAll public static void shutdownMockServer() { SparqlMockServer.ctlAfterClass(); } @BeforeEach void initialize() throws SQLException { connection = new SparqlConnection(new SparqlConnectionProperties(sparqlProperties())); databaseMetaData = connection.getMetaData(); } @AfterEach void shutdown() throws SQLException { connection.close(); } @Test void testGetCatalogs() throws SQLException { final java.sql.ResultSet resultSet = databaseMetaData.getCatalogs(); // Catalog is not currently supported Assertions.assertFalse(resultSet.next()); } @Test void testGetSchemas() throws SQLException { final java.sql.ResultSet resultSet = databaseMetaData.getSchemas(); Assertions.assertTrue(resultSet.next()); } @Test void testGetTableTypes() throws SQLException { final java.sql.ResultSet resultSet = databaseMetaData.getTableTypes(); Assertions.assertTrue(resultSet.next()); final ResultSetMetaData metaData = resultSet.getMetaData(); final int columnCount = metaData.getColumnCount(); Assertions.assertEquals(1, columnCount); Assertions.assertEquals("TABLE", resultSet.getString(1)); Assertions.assertFalse(resultSet.next()); } @Test void testGetTypeInfo() throws SQLException { final java.sql.ResultSet resultSet = databaseMetaData.getTypeInfo(); Assertions.assertTrue(resultSet.next()); final ResultSetMetaData metaData = resultSet.getMetaData(); final int columnCount = metaData.getColumnCount(); Assertions.assertEquals(18, columnCount); Assertions.assertEquals("XSDboolean", resultSet.getString(1)); Assertions.assertTrue(resultSet.next()); } }
7,320
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/sparql/SparqlConnectionPropertiesTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.sparql; import org.apache.http.client.HttpClient; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.protocol.HttpContext; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.aws.neptune.jdbc.helpers.HelperFunctions; import software.aws.neptune.jdbc.utilities.AuthScheme; import software.aws.neptune.jdbc.utilities.ConnectionProperties; import java.sql.SQLException; import java.util.Properties; public class SparqlConnectionPropertiesTest { private static final String HOSTNAME = "http://localhost"; private static final int PORT = 8182; private static final String ENDPOINT = "mock"; private SparqlConnectionProperties connectionProperties; private int randomIntValue; protected void assertDoesNotThrowOnNewConnectionProperties(final Properties properties) { Assertions.assertDoesNotThrow(() -> { // Since we have added the check for service region and IAMSigV4 is set by default, we need to add a mock // region property here in case the system running these tests does not have SERVICE_REGION variable set. properties.put("serviceRegion", "mock-region"); connectionProperties = new SparqlConnectionProperties(properties); }); } protected void assertThrowsOnNewConnectionProperties(final Properties properties) { Assertions.assertThrows(SQLException.class, () -> connectionProperties = new SparqlConnectionProperties(properties)); } // set the DESTINATION properties properly to avoid throws on tests not related to the exception private void setInitialDestinationProperty(final SparqlConnectionProperties connectionProperties) throws SQLException { connectionProperties.setEndpoint(HOSTNAME); connectionProperties.setPort(PORT); connectionProperties.setDataset(ENDPOINT); } @BeforeEach void beforeEach() { randomIntValue = HelperFunctions.randomPositiveIntValue(1000); } @Test void testDefaultValues() throws SQLException { connectionProperties = new SparqlConnectionProperties(); Assertions.assertEquals("", connectionProperties.getDataset()); Assertions.assertEquals(SparqlConnectionProperties.DEFAULT_CONNECTION_TIMEOUT_MILLIS, connectionProperties.getConnectionTimeoutMillis()); Assertions.assertEquals(SparqlConnectionProperties.DEFAULT_CONNECTION_RETRY_COUNT, connectionProperties.getConnectionRetryCount()); Assertions .assertEquals(SparqlConnectionProperties.DEFAULT_AUTH_SCHEME, connectionProperties.getAuthScheme()); Assertions.assertEquals(SparqlConnectionProperties.DEFAULT_SERVICE_REGION, connectionProperties.getServiceRegion()); } @Test void testApplicationName() throws SQLException { final String testValue = "test application name"; connectionProperties = new SparqlConnectionProperties(); connectionProperties.setApplicationName(testValue); Assertions.assertEquals(testValue, connectionProperties.getApplicationName()); // the constructor test with DESTINATION properties properly set to avoid throws setInitialDestinationProperty(connectionProperties); final Properties properties = new Properties(); properties.putAll(connectionProperties); assertDoesNotThrowOnNewConnectionProperties(properties); } @Test void testConnectionTimeout() throws SQLException { connectionProperties = new SparqlConnectionProperties(); connectionProperties.setConnectionTimeoutMillis(randomIntValue); Assertions.assertEquals(randomIntValue, connectionProperties.getConnectionTimeoutMillis()); // the constructor test with DESTINATION properties properly set to avoid throws setInitialDestinationProperty(connectionProperties); final Properties properties = new Properties(); properties.putAll(connectionProperties); assertDoesNotThrowOnNewConnectionProperties(properties); } @Test void testConnectionRetryCount() throws SQLException { connectionProperties = new SparqlConnectionProperties(); connectionProperties.setConnectionRetryCount(randomIntValue); Assertions.assertEquals(randomIntValue, connectionProperties.getConnectionRetryCount()); // the constructor test with DESTINATION properties properly set to avoid throws setInitialDestinationProperty(connectionProperties); final Properties properties = new Properties(); properties.putAll(connectionProperties); assertDoesNotThrowOnNewConnectionProperties(properties); } @Test void testContactPoint() throws SQLException { final String testValue = "test contact point"; connectionProperties = new SparqlConnectionProperties(); connectionProperties.setEndpoint(testValue); Assertions.assertEquals(testValue, connectionProperties.getEndpoint()); // the constructor test with DESTINATION properties properly set to avoid throws setInitialDestinationProperty(connectionProperties); final Properties properties = new Properties(); properties.putAll(connectionProperties); assertDoesNotThrowOnNewConnectionProperties(properties); } @Test void testEndpoint() throws SQLException { final String testValue = "test endpoint"; connectionProperties = new SparqlConnectionProperties(); connectionProperties.setDataset(testValue); Assertions.assertEquals(testValue, connectionProperties.getDataset()); // will throw because only Endpoint is set assertThrowsOnNewConnectionProperties(connectionProperties); // the constructor test with DESTINATION properties properly set to avoid throws setInitialDestinationProperty(connectionProperties); final Properties properties = new Properties(); properties.putAll(connectionProperties); assertDoesNotThrowOnNewConnectionProperties(properties); } @Test void testQueryEndpoint() throws SQLException { final String testValue = "test query endpoint"; connectionProperties = new SparqlConnectionProperties(); connectionProperties.setQueryEndpoint(testValue); Assertions.assertEquals(testValue, connectionProperties.getQueryEndpoint()); // will throw because only QueryEndpoint is set assertThrowsOnNewConnectionProperties(connectionProperties); // the constructor test with DESTINATION properties properly set to avoid throws setInitialDestinationProperty(connectionProperties); final Properties properties = new Properties(); properties.putAll(connectionProperties); assertDoesNotThrowOnNewConnectionProperties(properties); } @Test void testPort() throws SQLException { final int testValue = 12345; connectionProperties = new SparqlConnectionProperties(); connectionProperties.setPort(testValue); Assertions.assertEquals(testValue, connectionProperties.getPort()); // will throw because only Port is set assertThrowsOnNewConnectionProperties(connectionProperties); // the constructor test with DESTINATION properties properly set to avoid throws setInitialDestinationProperty(connectionProperties); final Properties properties = new Properties(); properties.putAll(connectionProperties); assertDoesNotThrowOnNewConnectionProperties(properties); } @Test void testAuthScheme() throws SQLException { connectionProperties = new SparqlConnectionProperties(); connectionProperties.setAuthScheme(AuthScheme.None); Assertions.assertEquals(AuthScheme.None, connectionProperties.getAuthScheme()); System.out.println("region is: " + connectionProperties.getServiceRegion()); // the constructor test with DESTINATION properties properly set to avoid throws setInitialDestinationProperty(connectionProperties); final Properties properties = new Properties(); properties.putAll(connectionProperties); assertDoesNotThrowOnNewConnectionProperties(properties); } @Test void testRegion() throws SQLException { connectionProperties = new SparqlConnectionProperties(); connectionProperties.put(ConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.None); // set to None connectionProperties.setServiceRegion("ca-central-1"); Assertions.assertEquals("ca-central-1", connectionProperties.getServiceRegion()); connectionProperties.put(ConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.IAMSigV4); // set to IAMSigV4 connectionProperties.setServiceRegion("us-east-1"); Assertions.assertEquals("us-east-1", connectionProperties.getServiceRegion()); // the constructor test with DESTINATION properties properly set to avoid throws setInitialDestinationProperty(connectionProperties); final Properties properties = new Properties(); properties.putAll(connectionProperties); assertDoesNotThrowOnNewConnectionProperties(properties); } @Test void testConcurrentModificationExceptionHttpClient() throws SQLException { final HttpClient testClient = HttpClientBuilder.create().build(); connectionProperties = new SparqlConnectionProperties(); Assertions.assertNull(connectionProperties.getHttpClient()); connectionProperties.setHttpClient(testClient); Assertions.assertEquals(testClient, connectionProperties.getHttpClient()); connectionProperties.put(ConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.None); Assertions.assertEquals(AuthScheme.None, connectionProperties.getAuthScheme()); // the constructor test with DESTINATION properties properly set to avoid throws setInitialDestinationProperty(connectionProperties); final Properties properties = new Properties(); properties.putAll(connectionProperties); assertDoesNotThrowOnNewConnectionProperties(properties); } @Test void testHttpClient() throws SQLException { final HttpClient testClient = HttpClientBuilder.create().build(); connectionProperties = new SparqlConnectionProperties(); Assertions.assertNull(connectionProperties.getHttpClient()); connectionProperties.setHttpClient(testClient); Assertions.assertEquals(testClient, connectionProperties.getHttpClient()); connectionProperties.put(ConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.None); Assertions.assertEquals(AuthScheme.None, connectionProperties.getAuthScheme()); final Properties testProperties = new Properties(); testProperties.put(ConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.None); testProperties.put(SparqlConnectionProperties.ENDPOINT_KEY, "http://localhost"); testProperties.put(SparqlConnectionProperties.PORT_KEY, 8182); testProperties.put(SparqlConnectionProperties.DATASET_KEY, "mock"); testProperties.put(SparqlConnectionProperties.QUERY_ENDPOINT_KEY, "query"); testProperties.put(SparqlConnectionProperties.HTTP_CLIENT_KEY, testClient); Assertions.assertEquals(testClient, testProperties.get(SparqlConnectionProperties.HTTP_CLIENT_KEY)); assertDoesNotThrowOnNewConnectionProperties(testProperties); } @Test void testHttpClientWithSigV4Auth() { final HttpClient testClient = HttpClientBuilder.create().build(); Assertions.assertNotNull(testClient); final Properties testProperties = new Properties(); testProperties.put(ConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.IAMSigV4); testProperties.put(SparqlConnectionProperties.ENDPOINT_KEY, "http://localhost"); testProperties.put(SparqlConnectionProperties.PORT_KEY, 8182); testProperties.put(SparqlConnectionProperties.DATASET_KEY, "mock"); testProperties.put(SparqlConnectionProperties.QUERY_ENDPOINT_KEY, "query"); testProperties.put(SparqlConnectionProperties.HTTP_CLIENT_KEY, testClient); Assertions.assertEquals(testClient, testProperties.get(SparqlConnectionProperties.HTTP_CLIENT_KEY)); assertThrowsOnNewConnectionProperties(testProperties); } @Test void testHttpContext() throws SQLException { final HttpContext testContext = new HttpClientContext(); connectionProperties = new SparqlConnectionProperties(); Assertions.assertNull(connectionProperties.getHttpContext()); connectionProperties.setHttpContext(testContext); Assertions.assertEquals(testContext, connectionProperties.getHttpContext()); final Properties testProperties = new Properties(); testProperties.put(ConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.None); testProperties.put(SparqlConnectionProperties.ENDPOINT_KEY, "http://localhost"); testProperties.put(SparqlConnectionProperties.PORT_KEY, 8182); testProperties.put(SparqlConnectionProperties.DATASET_KEY, "mock"); testProperties.put(SparqlConnectionProperties.QUERY_ENDPOINT_KEY, "query"); testProperties.put(SparqlConnectionProperties.HTTP_CONTEXT_KEY, testContext); Assertions.assertEquals(testContext, testProperties.get(SparqlConnectionProperties.HTTP_CONTEXT_KEY)); assertDoesNotThrowOnNewConnectionProperties(testProperties); } @Test void testAcceptHeaderAskQuery() throws SQLException { final String testValue = "test accept header ask query"; connectionProperties = new SparqlConnectionProperties(); connectionProperties.setAcceptHeaderAskQuery(testValue); Assertions.assertEquals(testValue, connectionProperties.getAcceptHeaderAskQuery()); // the constructor test with DESTINATION properties properly set to avoid throws setInitialDestinationProperty(connectionProperties); final Properties properties = new Properties(); properties.putAll(connectionProperties); assertDoesNotThrowOnNewConnectionProperties(properties); } @Test void testAcceptHeaderDataset() throws SQLException { final String testValue = "test accept header graph"; connectionProperties = new SparqlConnectionProperties(); connectionProperties.setAcceptHeaderDataset(testValue); Assertions.assertEquals(testValue, connectionProperties.getAcceptHeaderDataset()); // the constructor test with DESTINATION properties properly set to avoid throws setInitialDestinationProperty(connectionProperties); final Properties properties = new Properties(); properties.putAll(connectionProperties); assertDoesNotThrowOnNewConnectionProperties(properties); } @Test void testAcceptHeaderQuery() throws SQLException { final String testValue = "test accept header query"; connectionProperties = new SparqlConnectionProperties(); connectionProperties.setAcceptHeaderQuery(testValue); Assertions.assertEquals(testValue, connectionProperties.getAcceptHeaderQuery()); // the constructor test with DESTINATION properties properly set to avoid throws setInitialDestinationProperty(connectionProperties); final Properties properties = new Properties(); properties.putAll(connectionProperties); assertDoesNotThrowOnNewConnectionProperties(properties); } @Test void testAcceptHeaderSelectQuery() throws SQLException { final String testValue = "test accept header select query"; connectionProperties = new SparqlConnectionProperties(); connectionProperties.setAcceptHeaderSelectQuery(testValue); Assertions.assertEquals(testValue, connectionProperties.getAcceptHeaderSelectQuery()); // the constructor test with DESTINATION properties properly set to avoid throws setInitialDestinationProperty(connectionProperties); final Properties properties = new Properties(); properties.putAll(connectionProperties); assertDoesNotThrowOnNewConnectionProperties(properties); } @Test void testParseCheckSparql() throws SQLException { final boolean testValue = true; connectionProperties = new SparqlConnectionProperties(); connectionProperties.setParseCheckSparql(testValue); Assertions.assertTrue(connectionProperties.getParseCheckSparql()); // the constructor test with DESTINATION properties properly set to avoid throws setInitialDestinationProperty(connectionProperties); final Properties properties = new Properties(); properties.putAll(connectionProperties); assertDoesNotThrowOnNewConnectionProperties(properties); } @Test void testChangeAuthSchemeToNone() throws SQLException { // Use encryption is always set because Neptune only supports encrypted connections on SPARQL. final Properties properties = new Properties(); properties.put("authScheme", "IAMSigV4"); properties.put("endpointURL", "mock"); properties.put("port", "1234"); properties.put("serviceRegion", "mock-region"); connectionProperties = new SparqlConnectionProperties(properties); Assertions.assertEquals(connectionProperties.getAuthScheme(), AuthScheme.IAMSigV4); Assertions.assertDoesNotThrow(() -> connectionProperties.setAuthScheme(AuthScheme.None)); Assertions.assertEquals(connectionProperties.getAuthScheme(), AuthScheme.None); } @Test void testChangeAuthSchemeToIAMSigV4() throws SQLException { final Properties properties = new Properties(); properties.put("authScheme", "None"); properties.put("endpointURL", "mock"); properties.put("port", "1234"); connectionProperties = new SparqlConnectionProperties(properties); Assertions.assertEquals(connectionProperties.getAuthScheme(), AuthScheme.None); Assertions.assertDoesNotThrow(() -> connectionProperties.setAuthScheme(AuthScheme.IAMSigV4)); Assertions.assertEquals(connectionProperties.getAuthScheme(), AuthScheme.IAMSigV4); } }
7,321
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/sparql/SparqlStatementTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.sparql; public class SparqlStatementTestBase { protected static final String QUICK_QUERY; protected static final String LONG_QUERY; public static final String LONG_UPDATE; protected static final int LONG_UPDATE_COUNT = 500; private static int currentIndex = 0; static { QUICK_QUERY = "SELECT * { ?s ?p ?o } LIMIT 10"; LONG_QUERY = "SELECT ?s ?p ?o WHERE { " + "{ SELECT * WHERE { ?s ?p ?o FILTER(CONTAINS(LCASE(?o), \"string\")) } " + "} " + "UNION " + "{ SELECT * WHERE { ?s ?p ?o FILTER(!ISNUMERIC(?o)) } " + "} " + "UNION " + "{ SELECT * WHERE { ?s ?p ?o FILTER(CONTAINS(LCASE(?s), \"example\")) } " + "} " + "}"; final StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("PREFIX : <http://example/> "); for (int i = currentIndex; i < (currentIndex + LONG_UPDATE_COUNT); i++) { stringBuilder.append(String.format("INSERT DATA { :s :p \"string%d\" };", i)); } currentIndex += LONG_UPDATE_COUNT; LONG_UPDATE = stringBuilder.toString(); } }
7,322
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/sparql
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/sparql/resultset/SparqlResultSetTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.sparql.resultset; import org.apache.jena.rdfconnection.RDFConnection; import org.apache.jena.rdfconnection.RDFConnectionRemote; import org.apache.jena.rdfconnection.RDFConnectionRemoteBuilder; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.aws.neptune.jdbc.utilities.AuthScheme; import software.aws.neptune.jdbc.utilities.ConnectionProperties; import software.aws.neptune.sparql.SparqlConnection; import software.aws.neptune.sparql.SparqlConnectionProperties; import software.aws.neptune.sparql.mock.SparqlMockDataQuery; import software.aws.neptune.sparql.mock.SparqlMockServer; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; public class SparqlResultSetTest { private static final String HOSTNAME = "http://localhost"; private static final String DATASET = "mock"; private static final String QUERY_ENDPOINT = "query"; private static final int PORT = SparqlMockServer.port(); // Mock server dynamically generates port private static final int SUBJECT_COLUMN_INDEX = 1; private static final int PREDICATE_COLUMN_INDEX = 2; private static final int OBJECT_COLUMN_INDEX = 3; private static final int SELECT_RESULT_INDEX = 2; private static final BigInteger EXPECTED_BIG_INTEGER_VALUE = new BigInteger("18446744073709551615"); private static final BigDecimal EXPECTED_BIG_DECIMAL_VALUE = new BigDecimal("180.5555"); private static final int EXPECTED_BYTE_VALUE = 127; private static final int EXPECTED_SHORT_VALUE = 32767; private static final Long EXPECTED_LONG_VALUE = 3000000000L; private static final double EXPECTED_DOUBLE_VALUE = 100000.00; private static final float EXPECTED_FLOAT_VALUE = 80.5f; private static final Long EXPECTED_UNSIGNED_LONG_VALUE = 4294970000L; private static final String EXPECTED_YEAR_VALUE = "2020"; private static java.sql.Connection connection; private static java.sql.Statement statement; private static Properties sparqlProperties() { final Properties properties = new Properties(); properties.put(ConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.None); // set default to None properties.put(SparqlConnectionProperties.ENDPOINT_KEY, HOSTNAME); properties.put(SparqlConnectionProperties.PORT_KEY, PORT); properties.put(SparqlConnectionProperties.DATASET_KEY, DATASET); properties.put(SparqlConnectionProperties.QUERY_ENDPOINT_KEY, QUERY_ENDPOINT); return properties; } /** * Function to start the mock server and populate database before testing. */ @BeforeAll public static void initializeMockServer() throws SQLException { SparqlMockServer.ctlBeforeClass(); // Query only. final RDFConnectionRemoteBuilder rdfConnBuilder = RDFConnectionRemote.create() .destination(SparqlMockServer.urlDataset()) .queryEndpoint("/query"); // Load dataset in. try (final RDFConnection conn = rdfConnBuilder.build()) { conn.load("src/test/java/software/aws/neptune/sparql/mock/sparql_mock_data.rdf"); } } /** * Function to tear down server after testing. */ @AfterAll public static void shutdownMockServer() { SparqlMockServer.ctlAfterClass(); } // helper function for testing queries with Java String outputs private static void testStringResultTypes(final String query, final String expectedValue, final int columnIdx) throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(query); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(expectedValue, resultSet.getString(columnIdx)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(columnIdx)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTimestamp(columnIdx)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTime(columnIdx)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDate(columnIdx)); Assertions.assertThrows(SQLException.class, () -> resultSet.getString(0)); expectNumericTypesToThrow(resultSet, columnIdx); } // helper function for testing queries with Java Integer outputs private static void testIntegerResultTypes(final String query, final int expectedValue, final int columnIdx) throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(query); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(getExpectedByteValue(expectedValue), resultSet.getByte(columnIdx)); Assertions.assertEquals(getExpectedShortValue(expectedValue), resultSet.getShort(columnIdx)); Assertions.assertEquals(expectedValue, resultSet.getInt(columnIdx)); Assertions.assertEquals(expectedValue, resultSet.getLong(columnIdx)); Assertions.assertEquals(String.valueOf(expectedValue), resultSet.getString(columnIdx)); Assertions.assertThrows(SQLException.class, () -> resultSet.getString(0)); } private static void expectNumericTypesToThrow(final ResultSet resultSet, final int columnIdx) { Assertions.assertThrows(SQLException.class, () -> resultSet.getByte(columnIdx)); Assertions.assertThrows(SQLException.class, () -> resultSet.getShort(columnIdx)); Assertions.assertThrows(SQLException.class, () -> resultSet.getInt(columnIdx)); Assertions.assertThrows(SQLException.class, () -> resultSet.getLong(columnIdx)); Assertions.assertThrows(SQLException.class, () -> resultSet.getFloat(columnIdx)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDouble(columnIdx)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBigDecimal(columnIdx)); } @BeforeEach void initialize() throws SQLException { connection = new SparqlConnection(new SparqlConnectionProperties(sparqlProperties())); statement = connection.createStatement(); } @AfterEach void shutdown() throws SQLException { connection.close(); } @Test void testNullType() throws SQLException { final java.sql.ResultSet resultSet = statement .executeQuery("SELECT ?s ?x ?fname WHERE {?x <http://www.w3.org/2001/vcard-rdf/3.0#FN> ?fname}"); Assertions.assertTrue(resultSet.next()); Assertions.assertFalse(resultSet.getBoolean(1)); Assertions.assertTrue(resultSet.wasNull()); Assertions.assertEquals((byte) 0, resultSet.getByte(1)); Assertions.assertTrue(resultSet.wasNull()); Assertions.assertEquals((short) 0, resultSet.getShort(1)); Assertions.assertTrue(resultSet.wasNull()); Assertions.assertEquals(0, resultSet.getInt(1)); Assertions.assertTrue(resultSet.wasNull()); Assertions.assertEquals(0, resultSet.getLong(1)); Assertions.assertTrue(resultSet.wasNull()); Assertions.assertEquals(0.0f, resultSet.getFloat(1)); Assertions.assertTrue(resultSet.wasNull()); Assertions.assertEquals(0.0, resultSet.getDouble(1)); Assertions.assertTrue(resultSet.wasNull()); Assertions.assertNull(resultSet.getString(1)); Assertions.assertTrue(resultSet.wasNull()); Assertions.assertNull(resultSet.getDate(1)); Assertions.assertTrue(resultSet.wasNull()); Assertions.assertNull(resultSet.getTime(1)); Assertions.assertTrue(resultSet.wasNull()); Assertions.assertNull(resultSet.getTimestamp(1)); Assertions.assertTrue(resultSet.wasNull()); } @Test void testStringType() throws SQLException { testStringResultTypes(SparqlMockDataQuery.STRING_QUERY, "http://somewhere/JohnSmith", 1); testStringResultTypes(SparqlMockDataQuery.STRING_QUERY, "John Smith", SELECT_RESULT_INDEX); testStringResultTypes(SparqlMockDataQuery.CONSTRUCT_STRING_QUERY, "http://somewhere/JohnSmith", SUBJECT_COLUMN_INDEX); testStringResultTypes(SparqlMockDataQuery.CONSTRUCT_STRING_QUERY, "http://www.w3.org/2001/vcard-rdf/3.0#FN", PREDICATE_COLUMN_INDEX); testStringResultTypes(SparqlMockDataQuery.CONSTRUCT_STRING_QUERY, "John Smith", OBJECT_COLUMN_INDEX); } private static byte getExpectedByteValue(final long value) { return (value > Byte.MAX_VALUE) ? 0 : (byte) value; } private static short getExpectedShortValue(final long value) { return (value > Short.MAX_VALUE) ? 0 : (short) value; } private static int getExpectedIntValue(final long value) { return (value > Integer.MAX_VALUE) ? 0 : (int) value; } @Test void testBooleanType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.BOOL_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertTrue(resultSet.getBoolean(SELECT_RESULT_INDEX)); Assertions.assertEquals(String.valueOf(true), resultSet.getString(SELECT_RESULT_INDEX)); expectNumericTypesToThrow(resultSet, SELECT_RESULT_INDEX); Assertions.assertThrows(SQLException.class, () -> resultSet.getTimestamp(SELECT_RESULT_INDEX)); } @Test void testConstructBooleanType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.CONSTRUCT_BOOL_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertTrue(resultSet.getBoolean(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(String.valueOf(true), resultSet.getString(OBJECT_COLUMN_INDEX)); expectNumericTypesToThrow(resultSet, OBJECT_COLUMN_INDEX); Assertions.assertThrows(SQLException.class, () -> resultSet.getTimestamp(OBJECT_COLUMN_INDEX)); } @Test void testByteType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.BYTE_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(getExpectedByteValue(EXPECTED_BYTE_VALUE), resultSet.getByte(SELECT_RESULT_INDEX)); Assertions.assertEquals((short) EXPECTED_BYTE_VALUE, resultSet.getShort(SELECT_RESULT_INDEX)); Assertions.assertEquals(EXPECTED_BYTE_VALUE, resultSet.getInt(SELECT_RESULT_INDEX)); Assertions.assertEquals(EXPECTED_BYTE_VALUE, resultSet.getLong(SELECT_RESULT_INDEX)); Assertions.assertEquals(String.valueOf(EXPECTED_BYTE_VALUE), resultSet.getString(SELECT_RESULT_INDEX)); } @Test void testConstructByteType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.CONSTRUCT_BYTE_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(getExpectedByteValue(EXPECTED_BYTE_VALUE), resultSet.getByte(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(getExpectedShortValue(EXPECTED_BYTE_VALUE), resultSet.getShort(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(EXPECTED_BYTE_VALUE, resultSet.getInt(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(EXPECTED_BYTE_VALUE, resultSet.getLong(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(String.valueOf(EXPECTED_BYTE_VALUE), resultSet.getString(OBJECT_COLUMN_INDEX)); } @Test void testShortType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.SHORT_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(getExpectedByteValue(EXPECTED_SHORT_VALUE), resultSet.getByte(SELECT_RESULT_INDEX)); Assertions.assertEquals((short) EXPECTED_SHORT_VALUE, resultSet.getShort(SELECT_RESULT_INDEX)); Assertions.assertEquals(EXPECTED_SHORT_VALUE, resultSet.getInt(SELECT_RESULT_INDEX)); Assertions.assertEquals(EXPECTED_SHORT_VALUE, resultSet.getLong(SELECT_RESULT_INDEX)); Assertions.assertEquals(String.valueOf(EXPECTED_SHORT_VALUE), resultSet.getString(SELECT_RESULT_INDEX)); } @Test void testConstructShortType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.CONSTRUCT_SHORT_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(getExpectedByteValue(EXPECTED_SHORT_VALUE), resultSet.getByte(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(getExpectedShortValue(EXPECTED_SHORT_VALUE), resultSet.getShort(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(EXPECTED_SHORT_VALUE, resultSet.getInt(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(EXPECTED_SHORT_VALUE, resultSet.getLong(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(String.valueOf(EXPECTED_SHORT_VALUE), resultSet.getString(OBJECT_COLUMN_INDEX)); } @Test void testIntegerSmallType() throws SQLException { testIntegerResultTypes(SparqlMockDataQuery.INTEGER_SMALL_QUERY, 25, SELECT_RESULT_INDEX); testIntegerResultTypes(SparqlMockDataQuery.CONSTRUCT_INTEGER_SMALL_QUERY, 25, OBJECT_COLUMN_INDEX); } @Test void testIntegerLargeType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.INTEGER_LARGE_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(EXPECTED_BIG_INTEGER_VALUE, resultSet.getObject(SELECT_RESULT_INDEX)); Assertions.assertEquals(String.valueOf(EXPECTED_BIG_INTEGER_VALUE), resultSet.getString(SELECT_RESULT_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(SELECT_RESULT_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getByte(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getShort(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getInt(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDouble(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getFloat(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getLong(OBJECT_COLUMN_INDEX)); } @Test void testConstructIntegerLargeType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.CONSTRUCT_INTEGER_LARGE_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(EXPECTED_BIG_INTEGER_VALUE, resultSet.getObject(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(String.valueOf(EXPECTED_BIG_INTEGER_VALUE), resultSet.getString(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getByte(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getShort(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getInt(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDouble(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getFloat(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getLong(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(OBJECT_COLUMN_INDEX)); } @Test void testLongType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.LONG_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(getExpectedByteValue(EXPECTED_LONG_VALUE), resultSet.getByte(SELECT_RESULT_INDEX)); Assertions.assertEquals(getExpectedShortValue(EXPECTED_LONG_VALUE), resultSet.getShort(SELECT_RESULT_INDEX)); Assertions.assertEquals(getExpectedIntValue(EXPECTED_LONG_VALUE), resultSet.getInt(SELECT_RESULT_INDEX)); Assertions.assertEquals(EXPECTED_LONG_VALUE, resultSet.getLong(SELECT_RESULT_INDEX)); Assertions.assertEquals(String.valueOf(EXPECTED_LONG_VALUE), resultSet.getString(SELECT_RESULT_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDate(SELECT_RESULT_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTime(SELECT_RESULT_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTimestamp(SELECT_RESULT_INDEX)); } @Test void testConstructLongType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.CONSTRUCT_LONG_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(getExpectedByteValue(EXPECTED_LONG_VALUE), resultSet.getByte(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(getExpectedShortValue(EXPECTED_LONG_VALUE), resultSet.getShort(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(getExpectedIntValue(EXPECTED_LONG_VALUE), resultSet.getInt(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(EXPECTED_LONG_VALUE, resultSet.getLong(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(String.valueOf(EXPECTED_LONG_VALUE), resultSet.getString(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDate(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTime(OBJECT_COLUMN_INDEX).toLocalTime()); Assertions.assertThrows(SQLException.class, () -> resultSet.getTimestamp(OBJECT_COLUMN_INDEX)); } @Test void testIntType() throws SQLException { testIntegerResultTypes(SparqlMockDataQuery.INT_QUERY, -100, SELECT_RESULT_INDEX); testIntegerResultTypes(SparqlMockDataQuery.CONSTRUCT_INT_QUERY, -100, OBJECT_COLUMN_INDEX); } @Test void testBigDecimalType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.DECIMAL_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(EXPECTED_BIG_DECIMAL_VALUE, resultSet.getBigDecimal(SELECT_RESULT_INDEX)); Assertions.assertEquals(String.valueOf(EXPECTED_BIG_DECIMAL_VALUE), resultSet.getString(SELECT_RESULT_INDEX)); Assertions.assertEquals(getExpectedByteValue(EXPECTED_BIG_DECIMAL_VALUE.longValue()), resultSet.getByte(SELECT_RESULT_INDEX)); Assertions.assertEquals(getExpectedShortValue(EXPECTED_BIG_DECIMAL_VALUE.shortValue()), resultSet.getShort(SELECT_RESULT_INDEX)); Assertions.assertEquals(getExpectedIntValue(EXPECTED_BIG_DECIMAL_VALUE.longValue()), resultSet.getInt(SELECT_RESULT_INDEX)); Assertions.assertEquals(EXPECTED_BIG_DECIMAL_VALUE.floatValue(), resultSet.getFloat(SELECT_RESULT_INDEX)); Assertions.assertEquals(EXPECTED_BIG_DECIMAL_VALUE.doubleValue(), resultSet.getDouble(SELECT_RESULT_INDEX)); Assertions.assertEquals(EXPECTED_BIG_DECIMAL_VALUE.longValue(), resultSet.getLong(SELECT_RESULT_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(SELECT_RESULT_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTimestamp(SELECT_RESULT_INDEX)); } @Test void testConstructBigDecimalType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.CONSTRUCT_DECIMAL_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(EXPECTED_BIG_DECIMAL_VALUE, resultSet.getBigDecimal(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(String.valueOf(EXPECTED_BIG_DECIMAL_VALUE), resultSet.getString(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(getExpectedByteValue(EXPECTED_BIG_DECIMAL_VALUE.longValue()), resultSet.getByte(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(getExpectedShortValue(EXPECTED_BIG_DECIMAL_VALUE.longValue()), resultSet.getShort(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(getExpectedIntValue(EXPECTED_BIG_DECIMAL_VALUE.longValue()), resultSet.getInt(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(EXPECTED_BIG_DECIMAL_VALUE.floatValue(), resultSet.getFloat(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(EXPECTED_BIG_DECIMAL_VALUE.doubleValue(), resultSet.getDouble(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(EXPECTED_BIG_DECIMAL_VALUE.longValue(), resultSet.getLong(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTimestamp(OBJECT_COLUMN_INDEX)); } @Test void testDoubleType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.DOUBLE_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(EXPECTED_DOUBLE_VALUE, resultSet.getFloat(SELECT_RESULT_INDEX)); Assertions.assertEquals(EXPECTED_DOUBLE_VALUE, resultSet.getDouble(SELECT_RESULT_INDEX)); Assertions.assertEquals(getExpectedByteValue((long) EXPECTED_DOUBLE_VALUE), resultSet.getByte(SELECT_RESULT_INDEX)); Assertions.assertEquals(getExpectedShortValue((long) EXPECTED_DOUBLE_VALUE), resultSet.getShort(SELECT_RESULT_INDEX)); Assertions.assertEquals(getExpectedIntValue((long) EXPECTED_DOUBLE_VALUE), resultSet.getInt(SELECT_RESULT_INDEX)); Assertions.assertEquals((long) EXPECTED_DOUBLE_VALUE, resultSet.getLong(SELECT_RESULT_INDEX)); Assertions.assertEquals(String.valueOf(EXPECTED_DOUBLE_VALUE), resultSet.getString(SELECT_RESULT_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(SELECT_RESULT_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTimestamp(SELECT_RESULT_INDEX)); } @Test void testConstructDoubleType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.CONSTRUCT_DOUBLE_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(EXPECTED_DOUBLE_VALUE, resultSet.getFloat(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(EXPECTED_DOUBLE_VALUE, resultSet.getDouble(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(getExpectedByteValue((long) EXPECTED_DOUBLE_VALUE), resultSet.getByte(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(getExpectedShortValue((long) EXPECTED_DOUBLE_VALUE), resultSet.getShort(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(getExpectedIntValue((long) EXPECTED_DOUBLE_VALUE), resultSet.getInt(OBJECT_COLUMN_INDEX)); Assertions.assertEquals((long) EXPECTED_DOUBLE_VALUE, resultSet.getLong(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(String.valueOf(EXPECTED_DOUBLE_VALUE), resultSet.getString(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTimestamp(OBJECT_COLUMN_INDEX)); } @Test void testFloatType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.FLOAT_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(EXPECTED_FLOAT_VALUE, resultSet.getFloat(SELECT_RESULT_INDEX)); Assertions.assertEquals(EXPECTED_FLOAT_VALUE, resultSet.getDouble(SELECT_RESULT_INDEX)); Assertions.assertEquals(getExpectedByteValue((long) EXPECTED_FLOAT_VALUE), resultSet.getByte(SELECT_RESULT_INDEX)); Assertions.assertEquals(getExpectedShortValue((long) EXPECTED_FLOAT_VALUE), resultSet.getShort(SELECT_RESULT_INDEX)); Assertions.assertEquals(getExpectedIntValue((long) EXPECTED_FLOAT_VALUE), resultSet.getInt(SELECT_RESULT_INDEX)); Assertions.assertEquals((long) EXPECTED_FLOAT_VALUE, resultSet.getLong(SELECT_RESULT_INDEX)); Assertions.assertEquals(String.valueOf(EXPECTED_FLOAT_VALUE), resultSet.getString(SELECT_RESULT_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(SELECT_RESULT_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTimestamp(SELECT_RESULT_INDEX)); } @Test void testConstructFloatType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.CONSTRUCT_FLOAT_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(EXPECTED_FLOAT_VALUE, resultSet.getFloat(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(EXPECTED_FLOAT_VALUE, resultSet.getDouble(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(getExpectedByteValue((long) EXPECTED_FLOAT_VALUE), resultSet.getByte(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(getExpectedShortValue((long) EXPECTED_FLOAT_VALUE), resultSet.getShort(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(getExpectedIntValue((long) EXPECTED_FLOAT_VALUE), resultSet.getInt(OBJECT_COLUMN_INDEX)); Assertions.assertEquals((long) EXPECTED_FLOAT_VALUE, resultSet.getLong(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(String.valueOf(EXPECTED_FLOAT_VALUE), resultSet.getString(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTimestamp(OBJECT_COLUMN_INDEX)); } @Test void testUnsignedByteType() throws SQLException { testIntegerResultTypes(SparqlMockDataQuery.UNSIGNED_BYTE_QUERY, 200, SELECT_RESULT_INDEX); testIntegerResultTypes(SparqlMockDataQuery.CONSTRUCT_UNSIGNED_BYTE_QUERY, 200, OBJECT_COLUMN_INDEX); } @Test void testUnsignedShortType() throws SQLException { testIntegerResultTypes(SparqlMockDataQuery.UNSIGNED_SHORT_QUERY, 300, SELECT_RESULT_INDEX); testIntegerResultTypes(SparqlMockDataQuery.CONSTRUCT_UNSIGNED_SHORT_QUERY, 300, OBJECT_COLUMN_INDEX); } @Test void testUnsignedIntType() throws SQLException { testIntegerResultTypes(SparqlMockDataQuery.UNSIGNED_INT_QUERY, 65600, SELECT_RESULT_INDEX); testIntegerResultTypes(SparqlMockDataQuery.CONSTRUCT_UNSIGNED_INT_QUERY, 65600, OBJECT_COLUMN_INDEX); } @Test void testUnsignedLongSmallType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.UNSIGNED_LONG_SMALL_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(getExpectedByteValue(EXPECTED_UNSIGNED_LONG_VALUE), resultSet.getByte(SELECT_RESULT_INDEX)); Assertions.assertEquals(getExpectedShortValue(EXPECTED_UNSIGNED_LONG_VALUE), resultSet.getInt(SELECT_RESULT_INDEX)); Assertions.assertEquals(getExpectedIntValue(EXPECTED_UNSIGNED_LONG_VALUE), resultSet.getInt(SELECT_RESULT_INDEX)); Assertions.assertEquals(EXPECTED_UNSIGNED_LONG_VALUE, resultSet.getLong(SELECT_RESULT_INDEX)); Assertions.assertEquals(String.valueOf(EXPECTED_UNSIGNED_LONG_VALUE), resultSet.getString(SELECT_RESULT_INDEX)); } @Test void testConstructUnsignedLongSmallType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.CONSTRUCT_UNSIGNED_LONG_SMALL_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(getExpectedByteValue(EXPECTED_UNSIGNED_LONG_VALUE), resultSet.getByte(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(getExpectedShortValue(EXPECTED_UNSIGNED_LONG_VALUE), resultSet.getInt(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(getExpectedIntValue(EXPECTED_UNSIGNED_LONG_VALUE), resultSet.getInt(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(EXPECTED_UNSIGNED_LONG_VALUE, resultSet.getLong(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(String.valueOf(EXPECTED_UNSIGNED_LONG_VALUE), resultSet.getString(OBJECT_COLUMN_INDEX)); } @Test void testUnsignedLongLargeType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.UNSIGNED_LONG_LARGE_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(EXPECTED_BIG_INTEGER_VALUE, resultSet.getObject(SELECT_RESULT_INDEX)); Assertions.assertEquals(String.valueOf(EXPECTED_BIG_INTEGER_VALUE), resultSet.getString(SELECT_RESULT_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getByte(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBigDecimal(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getInt(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getShort(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getLong(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getFloat(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(SELECT_RESULT_INDEX)); } @Test void testConstructUnsignedLongLargeType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.CONSTRUCT_UNSIGNED_LONG_LARGE_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(EXPECTED_BIG_INTEGER_VALUE, resultSet.getObject(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(String.valueOf(EXPECTED_BIG_INTEGER_VALUE), resultSet.getString(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getByte(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getShort(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getInt(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDouble(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getFloat(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getLong(OBJECT_COLUMN_INDEX)); } @Test void testSmallRangedIntegerTypes() throws SQLException { testIntegerResultTypes(SparqlMockDataQuery.POSITIVE_INTEGER_QUERY, 5, SELECT_RESULT_INDEX); testIntegerResultTypes(SparqlMockDataQuery.NON_NEGATIVE_INTEGER_QUERY, 1, SELECT_RESULT_INDEX); testIntegerResultTypes(SparqlMockDataQuery.NEGATIVE_INTEGER_QUERY, -5, SELECT_RESULT_INDEX); testIntegerResultTypes(SparqlMockDataQuery.NON_POSITIVE_INTEGER_QUERY, -1, SELECT_RESULT_INDEX); testIntegerResultTypes(SparqlMockDataQuery.CONSTRUCT_POSITIVE_INTEGER_QUERY, 5, OBJECT_COLUMN_INDEX); testIntegerResultTypes(SparqlMockDataQuery.CONSTRUCT_NON_NEGATIVE_INTEGER_QUERY, 1, OBJECT_COLUMN_INDEX); testIntegerResultTypes(SparqlMockDataQuery.CONSTRUCT_NEGATIVE_INTEGER_QUERY, -5, OBJECT_COLUMN_INDEX); testIntegerResultTypes(SparqlMockDataQuery.CONSTRUCT_NON_POSITIVE_INTEGER_QUERY, -1, OBJECT_COLUMN_INDEX); } @Test void testDateType() throws SQLException { final ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.DATE_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals("1996-01-01", resultSet.getString(SELECT_RESULT_INDEX)); Assertions.assertEquals(java.sql.Date.valueOf("1996-01-01"), resultSet.getDate(SELECT_RESULT_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(SELECT_RESULT_INDEX)); expectNumericTypesToThrow(resultSet, SELECT_RESULT_INDEX); } @Test void testConstructDateType() throws SQLException { final ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.CONSTRUCT_DATE_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals("1996-01-01", resultSet.getString(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(java.sql.Date.valueOf("1996-01-01"), resultSet.getDate(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(OBJECT_COLUMN_INDEX)); expectNumericTypesToThrow(resultSet, OBJECT_COLUMN_INDEX); } @Test void testTimeType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.TIME_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals("22:10:10", resultSet.getString(SELECT_RESULT_INDEX)); Assertions.assertEquals(java.sql.Time.valueOf("22:10:10"), resultSet.getTime(SELECT_RESULT_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(SELECT_RESULT_INDEX)); expectNumericTypesToThrow(resultSet, SELECT_RESULT_INDEX); } @Test void testConstructTimeType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.CONSTRUCT_TIME_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals("22:10:10", resultSet.getString(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(java.sql.Time.valueOf("22:10:10"), resultSet.getTime(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(OBJECT_COLUMN_INDEX)); expectNumericTypesToThrow(resultSet, OBJECT_COLUMN_INDEX); } @Test void testDateTimeType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.DATE_TIME_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals("2020-01-01 00:10:10.0", resultSet.getString(SELECT_RESULT_INDEX)); Assertions.assertEquals(java.sql.Time.valueOf("00:10:10").toString(), resultSet.getTime(SELECT_RESULT_INDEX).toString()); Assertions.assertEquals(java.sql.Date.valueOf("2020-01-01").toString(), resultSet.getDate(SELECT_RESULT_INDEX).toString()); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(SELECT_RESULT_INDEX)); expectNumericTypesToThrow(resultSet, SELECT_RESULT_INDEX); } @Test void testConstructDateTimeType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.CONSTRUCT_DATE_TIME_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals("2020-01-01 00:10:10.0", resultSet.getString(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(java.sql.Time.valueOf("00:10:10").toString(), resultSet.getTime(OBJECT_COLUMN_INDEX).toString()); Assertions.assertEquals(java.sql.Date.valueOf("2020-01-01").toString(), resultSet.getDate(OBJECT_COLUMN_INDEX).toString()); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(OBJECT_COLUMN_INDEX)); expectNumericTypesToThrow(resultSet, OBJECT_COLUMN_INDEX); } @Test void testDateTimeStampType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.DATE_TIME_STAMP_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals("2020-01-01T06:10:10Z[UTC]", resultSet.getString(SELECT_RESULT_INDEX)); Assertions.assertEquals(java.sql.Time.valueOf("06:10:10").toString(), resultSet.getTime(SELECT_RESULT_INDEX).toString()); Assertions.assertEquals(java.sql.Date.valueOf("2020-01-01").toString(), resultSet.getDate(SELECT_RESULT_INDEX).toString()); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(SELECT_RESULT_INDEX)); expectNumericTypesToThrow(resultSet, SELECT_RESULT_INDEX); } @Test void testConstructDateTimeStampType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.CONSTRUCT_DATE_TIME_STAMP_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals("2020-01-01T06:10:10Z[UTC]", resultSet.getString(OBJECT_COLUMN_INDEX)); Assertions.assertEquals(java.sql.Time.valueOf("06:10:10").toString(), resultSet.getTime(OBJECT_COLUMN_INDEX).toString()); Assertions.assertEquals(java.sql.Date.valueOf("2020-01-01").toString(), resultSet.getDate(OBJECT_COLUMN_INDEX).toString()); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(OBJECT_COLUMN_INDEX)); expectNumericTypesToThrow(resultSet, OBJECT_COLUMN_INDEX); } @Test void testGYearType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.G_YEAR_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(EXPECTED_YEAR_VALUE, resultSet.getString(SELECT_RESULT_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getByte(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBigDecimal(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getInt(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getShort(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getLong(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getFloat(OBJECT_COLUMN_INDEX)); } @Test void testConstructGYearType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.CONSTRUCT_G_YEAR_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(EXPECTED_YEAR_VALUE, resultSet.getString(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getByte(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getShort(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getInt(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getLong(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBigDecimal(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getFloat(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDouble(OBJECT_COLUMN_INDEX)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(OBJECT_COLUMN_INDEX)); } @Test void testGMonthType() throws SQLException { testStringResultTypes(SparqlMockDataQuery.G_MONTH_QUERY, "--10", SELECT_RESULT_INDEX); testStringResultTypes(SparqlMockDataQuery.CONSTRUCT_G_MONTH_QUERY, "--10", OBJECT_COLUMN_INDEX); } @Test void testGDayType() throws SQLException { testStringResultTypes(SparqlMockDataQuery.G_DAY_QUERY, "---20", SELECT_RESULT_INDEX); testStringResultTypes(SparqlMockDataQuery.CONSTRUCT_G_DAY_QUERY, "---20", OBJECT_COLUMN_INDEX); } @Test void testGYearMonthType() throws SQLException { testStringResultTypes(SparqlMockDataQuery.G_YEAR_MONTH_QUERY, "2020-06", SELECT_RESULT_INDEX); testStringResultTypes(SparqlMockDataQuery.CONSTRUCT_G_YEAR_MONTH_QUERY, "2020-06", OBJECT_COLUMN_INDEX); } @Test void testGMonthDayType() throws SQLException { testStringResultTypes(SparqlMockDataQuery.G_MONTH_DAY_QUERY, "--06-01", SELECT_RESULT_INDEX); testStringResultTypes(SparqlMockDataQuery.CONSTRUCT_G_MONTH_DAY_QUERY, "--06-01", OBJECT_COLUMN_INDEX); } @Test void testDurationTypes() throws SQLException { testStringResultTypes(SparqlMockDataQuery.DURATION_QUERY, "P30D", SELECT_RESULT_INDEX); testStringResultTypes(SparqlMockDataQuery.YEAR_MONTH_DURATION_QUERY, "P2M", SELECT_RESULT_INDEX); testStringResultTypes(SparqlMockDataQuery.DAY_TIME_DURATION_QUERY, "P5D", SELECT_RESULT_INDEX); testStringResultTypes(SparqlMockDataQuery.CONSTRUCT_DURATION_QUERY, "P30D", OBJECT_COLUMN_INDEX); testStringResultTypes(SparqlMockDataQuery.CONSTRUCT_YEAR_MONTH_DURATION_QUERY, "P2M", OBJECT_COLUMN_INDEX); testStringResultTypes(SparqlMockDataQuery.CONSTRUCT_DAY_TIME_DURATION_QUERY, "P5D", OBJECT_COLUMN_INDEX); } @Test void testEmptySelectResult() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.EMPTY_SELECT_RESULT_QUERY); Assertions.assertThrows(SQLException.class, () -> resultSet.getString(SELECT_RESULT_INDEX)); } @Test void testAskQueryType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(SparqlMockDataQuery.ASK_QUERY); Assertions.assertTrue(resultSet.next()); Assertions.assertTrue(resultSet.getBoolean(1)); Assertions.assertEquals(String.valueOf(true), resultSet.getString(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTimestamp(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getString(SELECT_RESULT_INDEX)); expectNumericTypesToThrow(resultSet, 1); Assertions.assertFalse(resultSet.next()); } // DESCRIBE and CONSTRUCT share ResultSet formats, so we just use this to test that this query type works. @Test void testDescribeQueryType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery("DESCRIBE <http://somewhere/JohnSmith>"); while (resultSet.next()) { Assertions.assertNotNull(resultSet.getString(SUBJECT_COLUMN_INDEX)); Assertions.assertNotNull(resultSet.getString(PREDICATE_COLUMN_INDEX)); Assertions.assertNotNull(resultSet.getString(OBJECT_COLUMN_INDEX)); } } }
7,323
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/sparql
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/sparql/resultset/SparqlSelectResultSetGetColumnsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.sparql.resultset; import org.junit.jupiter.api.BeforeAll; import software.aws.neptune.jdbc.utilities.AuthScheme; import software.aws.neptune.sparql.SparqlConnection; import software.aws.neptune.sparql.SparqlConnectionProperties; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.Properties; public class SparqlSelectResultSetGetColumnsTest { protected static final Properties PROPERTIES = new Properties(); private static final Map<String, Map<String, Map<String, Object>>> COLUMNS = new HashMap<>(); private static java.sql.Statement statement; /** * Function to initialize java.sql.Statement for use in tests. * * @throws SQLException Thrown if initialization fails. */ @BeforeAll public static void initialize() throws SQLException { PROPERTIES.put(SparqlConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.None); // reverse default to None // Make up fake endpoint since we aren't actually connection. PROPERTIES.putIfAbsent(SparqlConnectionProperties.ENDPOINT_KEY, "http://localhost"); PROPERTIES.putIfAbsent(SparqlConnectionProperties.PORT_KEY, 123); final java.sql.Connection connection = new SparqlConnection(new SparqlConnectionProperties(PROPERTIES)); statement = connection.createStatement(); } }
7,324
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/sparql
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/sparql/resultset/SparqlResultSetMetadataTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.sparql.resultset; import com.google.common.collect.ImmutableList; import lombok.AllArgsConstructor; import lombok.Getter; import org.apache.jena.datatypes.xsd.XSDDatatype; import org.apache.jena.query.Query; import org.apache.jena.query.QueryFactory; import org.apache.jena.query.ResultSetFormatter; import org.apache.jena.rdfconnection.RDFConnection; import org.apache.jena.rdfconnection.RDFConnectionRemote; import org.apache.jena.rdfconnection.RDFConnectionRemoteBuilder; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.aws.neptune.jdbc.utilities.AuthScheme; import software.aws.neptune.jdbc.utilities.ConnectionProperties; import software.aws.neptune.sparql.SparqlConnection; import software.aws.neptune.sparql.SparqlConnectionProperties; import software.aws.neptune.sparql.mock.SparqlMockDataQuery; import software.aws.neptune.sparql.mock.SparqlMockServer; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.List; import java.util.Properties; public class SparqlResultSetMetadataTest { // TODO: Test cases may change when we address type promotion in performance ticket. private static final String HOSTNAME = "http://localhost"; private static final String DATASET = "mock"; private static final String QUERY_ENDPOINT = "query"; private static final int PORT = SparqlMockServer.port(); // Mock server dynamically generates port private static final String STRING_QUERY_ONE_COLUMN = "SELECT ?fname WHERE {?x <http://www.w3.org/2001/vcard-rdf/3.0#FN> ?fname}"; private static final String STRING_QUERY_TWO_COLUMN = "SELECT ?x ?fname WHERE {?x <http://www.w3.org/2001/vcard-rdf/3.0#FN> ?fname}"; private static final String STRING_QUERY_THREE_COLUMN = "SELECT ?s ?x ?fname WHERE {?x <http://www.w3.org/2001/vcard-rdf/3.0#FN> ?fname}"; private static final List<SparqlResultSetMetadataTest.MetadataTestHelper> METADATA_TEST_HELPER = ImmutableList.of( new SparqlResultSetMetadataTest.MetadataTestHelper(SparqlMockDataQuery.ALL_DATA_TWO_COLUMNS_QUERY, Integer.MAX_VALUE, Integer.MAX_VALUE, 0, true, false, java.sql.Types.VARCHAR, String.class.getTypeName(), String.class.toString()), new SparqlResultSetMetadataTest.MetadataTestHelper(SparqlMockDataQuery.STRING_QUERY, Integer.MAX_VALUE, Integer.MAX_VALUE, 0, true, false, java.sql.Types.VARCHAR, String.class.getTypeName(), XSDDatatype.XSDstring.toString()), new SparqlResultSetMetadataTest.MetadataTestHelper(SparqlMockDataQuery.LONG_QUERY, 20, 20, 0, false, true, java.sql.Types.BIGINT, Long.class.getTypeName(), XSDDatatype.XSDlong.toString()), new SparqlResultSetMetadataTest.MetadataTestHelper(SparqlMockDataQuery.INTEGER_SMALL_QUERY, 20, 20, 0, false, true, java.sql.Types.BIGINT, java.math.BigInteger.class.getName(), XSDDatatype.XSDinteger.toString()), new SparqlResultSetMetadataTest.MetadataTestHelper(SparqlMockDataQuery.DECIMAL_QUERY, 25, 15, 15, false, true, java.sql.Types.DECIMAL, java.math.BigDecimal.class.getName(), XSDDatatype.XSDdecimal.toString()), new SparqlResultSetMetadataTest.MetadataTestHelper(SparqlMockDataQuery.SHORT_QUERY, 20, 5, 0, false, true, java.sql.Types.SMALLINT, Short.class.getTypeName(), XSDDatatype.XSDshort.toString()), new SparqlResultSetMetadataTest.MetadataTestHelper(SparqlMockDataQuery.BOOL_QUERY, 1, 1, 0, false, false, java.sql.Types.BIT, Boolean.class.getTypeName(), XSDDatatype.XSDboolean.toString()), new SparqlResultSetMetadataTest.MetadataTestHelper(SparqlMockDataQuery.DOUBLE_QUERY, 25, 15, 15, false, true, java.sql.Types.DOUBLE, Double.class.getTypeName(), XSDDatatype.XSDdouble.toString()), new SparqlResultSetMetadataTest.MetadataTestHelper(SparqlMockDataQuery.FLOAT_QUERY, 25, 15, 6, false, true, java.sql.Types.REAL, Float.class.getTypeName(), XSDDatatype.XSDfloat.toString()), new SparqlResultSetMetadataTest.MetadataTestHelper(SparqlMockDataQuery.DATE_QUERY, 24, 24, 0, false, false, java.sql.Types.DATE, java.sql.Date.class.getTypeName(), XSDDatatype.XSDdate.toString()), new SparqlResultSetMetadataTest.MetadataTestHelper(SparqlMockDataQuery.TIME_QUERY, 24, 24, 0, false, false, java.sql.Types.TIME, java.sql.Time.class.getTypeName(), XSDDatatype.XSDtime.toString()), new SparqlResultSetMetadataTest.MetadataTestHelper(SparqlMockDataQuery.DATE_TIME_QUERY, 24, 24, 0, false, false, java.sql.Types.TIMESTAMP, java.sql.Timestamp.class.getTypeName(), XSDDatatype.XSDdateTime.toString()), new SparqlResultSetMetadataTest.MetadataTestHelper(SparqlMockDataQuery.DATE_TIME_STAMP_QUERY, 24, 24, 0, false, false, java.sql.Types.TIMESTAMP, java.sql.Timestamp.class.getTypeName(), XSDDatatype.XSDdateTimeStamp.toString()), new SparqlResultSetMetadataTest.MetadataTestHelper(SparqlMockDataQuery.DURATION_QUERY, Integer.MAX_VALUE, Integer.MAX_VALUE, 0, true, false, java.sql.Types.VARCHAR, String.class.getTypeName(), XSDDatatype.XSDduration.toString()), new SparqlResultSetMetadataTest.MetadataTestHelper(SparqlMockDataQuery.PREDICATE_QUERY, Integer.MAX_VALUE, Integer.MAX_VALUE, 0, true, false, java.sql.Types.VARCHAR, String.class.getTypeName(), org.apache.jena.graph.Node_URI.class.toString()) ); private static final List<SparqlResultSetMetadataTest.MetadataTestHelper> CONSTRUCT_METADATA_TEST_HELPER = ImmutableList.of( new SparqlResultSetMetadataTest.MetadataTestHelper(SparqlMockDataQuery.CONSTRUCT_STRING_QUERY, Integer.MAX_VALUE, Integer.MAX_VALUE, 0, true, false, java.sql.Types.VARCHAR, String.class.getTypeName(), XSDDatatype.XSDstring.toString()), new SparqlResultSetMetadataTest.MetadataTestHelper(SparqlMockDataQuery.CONSTRUCT_LONG_QUERY, 20, 20, 0, false, true, java.sql.Types.BIGINT, Long.class.getTypeName(), XSDDatatype.XSDlong.toString()), new SparqlResultSetMetadataTest.MetadataTestHelper( SparqlMockDataQuery.CONSTRUCT_INTEGER_SMALL_QUERY, 20, 20, 0, false, true, java.sql.Types.BIGINT, java.math.BigInteger.class.getName(), XSDDatatype.XSDinteger.toString()), new SparqlResultSetMetadataTest.MetadataTestHelper(SparqlMockDataQuery.CONSTRUCT_DECIMAL_QUERY, 25, 15, 15, false, true, java.sql.Types.DECIMAL, java.math.BigDecimal.class.getName(), XSDDatatype.XSDdecimal.toString()), new SparqlResultSetMetadataTest.MetadataTestHelper(SparqlMockDataQuery.CONSTRUCT_SHORT_QUERY, 20, 5, 0, false, true, java.sql.Types.SMALLINT, Short.class.getTypeName(), XSDDatatype.XSDshort.toString()), new SparqlResultSetMetadataTest.MetadataTestHelper(SparqlMockDataQuery.CONSTRUCT_BOOL_QUERY, 1, 1, 0, false, false, java.sql.Types.BIT, Boolean.class.getTypeName(), XSDDatatype.XSDboolean.toString()), new SparqlResultSetMetadataTest.MetadataTestHelper(SparqlMockDataQuery.CONSTRUCT_DOUBLE_QUERY, 25, 15, 15, false, true, java.sql.Types.DOUBLE, Double.class.getTypeName(), XSDDatatype.XSDdouble.toString()), new SparqlResultSetMetadataTest.MetadataTestHelper(SparqlMockDataQuery.CONSTRUCT_FLOAT_QUERY, 25, 15, 6, false, true, java.sql.Types.REAL, Float.class.getTypeName(), XSDDatatype.XSDfloat.toString()), new SparqlResultSetMetadataTest.MetadataTestHelper(SparqlMockDataQuery.CONSTRUCT_DATE_QUERY, 24, 24, 0, false, false, java.sql.Types.DATE, java.sql.Date.class.getTypeName(), XSDDatatype.XSDdate.toString()), new SparqlResultSetMetadataTest.MetadataTestHelper(SparqlMockDataQuery.CONSTRUCT_TIME_QUERY, 24, 24, 0, false, false, java.sql.Types.TIME, java.sql.Time.class.getTypeName(), XSDDatatype.XSDtime.toString()), new SparqlResultSetMetadataTest.MetadataTestHelper(SparqlMockDataQuery.CONSTRUCT_DATE_TIME_QUERY, 24, 24, 0, false, false, java.sql.Types.TIMESTAMP, java.sql.Timestamp.class.getTypeName(), XSDDatatype.XSDdateTime.toString()), new SparqlResultSetMetadataTest.MetadataTestHelper( SparqlMockDataQuery.CONSTRUCT_DATE_TIME_STAMP_QUERY, 24, 24, 0, false, false, java.sql.Types.TIMESTAMP, java.sql.Timestamp.class.getTypeName(), XSDDatatype.XSDdateTimeStamp.toString()), new SparqlResultSetMetadataTest.MetadataTestHelper(SparqlMockDataQuery.CONSTRUCT_DURATION_QUERY, Integer.MAX_VALUE, Integer.MAX_VALUE, 0, true, false, java.sql.Types.VARCHAR, String.class.getTypeName(), XSDDatatype.XSDduration.toString()) ); private static java.sql.Connection connection; private static RDFConnectionRemoteBuilder rdfConnBuilder; private static Properties sparqlProperties() { final Properties properties = new Properties(); properties.put(ConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.None); // set default to None properties.put(SparqlConnectionProperties.ENDPOINT_KEY, HOSTNAME); properties.put(SparqlConnectionProperties.PORT_KEY, PORT); properties.put(SparqlConnectionProperties.DATASET_KEY, DATASET); properties.put(SparqlConnectionProperties.QUERY_ENDPOINT_KEY, QUERY_ENDPOINT); return properties; } /** * Function to start the mock server and populate database before testing. */ @BeforeAll public static void initializeMockServer() throws SQLException { SparqlMockServer.ctlBeforeClass(); // insert into the database here rdfConnBuilder = RDFConnectionRemote.create() .destination(SparqlMockServer.urlDataset()) // Query only. .queryEndpoint("/query"); // load dataset in try (final RDFConnection conn = rdfConnBuilder.build()) { conn.load("src/test/java/software/aws/neptune/sparql/mock/sparql_mock_data.rdf"); } } /** * Function to tear down server after testing. */ @AfterAll public static void shutdownMockServer() { SparqlMockServer.ctlAfterClass(); } // to printout result in format of Jena ResultSet private static void printJenaResultSetOut(final String query) { final Query jenaQuery = QueryFactory.create(query); try (final RDFConnection conn = rdfConnBuilder.build()) { conn.queryResultSet(jenaQuery, ResultSetFormatter::out); } } @BeforeEach void initialize() throws SQLException { connection = new SparqlConnection(new SparqlConnectionProperties(sparqlProperties())); } @AfterEach void shutdown() throws SQLException { connection.close(); } ResultSetMetaData getResultSetMetaData(final String query) throws SQLException { final java.sql.ResultSet resultSet = connection.createStatement().executeQuery(query); return resultSet.getMetaData(); } @Test void testGetColumnCount() throws SQLException { Assertions.assertEquals(1, getResultSetMetaData(STRING_QUERY_ONE_COLUMN).getColumnCount()); Assertions.assertEquals(2, getResultSetMetaData(STRING_QUERY_TWO_COLUMN).getColumnCount()); Assertions.assertEquals(3, getResultSetMetaData(STRING_QUERY_THREE_COLUMN).getColumnCount()); Assertions.assertEquals(3, getResultSetMetaData(SparqlMockDataQuery.CONSTRUCT_STRING_QUERY).getColumnCount()); Assertions.assertEquals(1, getResultSetMetaData(SparqlMockDataQuery.ASK_QUERY).getColumnCount()); } @Test void testGetColumnDisplaySize() throws SQLException { for (final SparqlResultSetMetadataTest.MetadataTestHelper helper : METADATA_TEST_HELPER) { Assertions.assertEquals(helper.getDisplaySize(), getResultSetMetaData(helper.getQuery()).getColumnDisplaySize(2), "For query: " + helper.getQuery()); } } @Test void testConstructGetColumnDisplaySize() throws SQLException { for (final SparqlResultSetMetadataTest.MetadataTestHelper helper : CONSTRUCT_METADATA_TEST_HELPER) { Assertions.assertEquals(helper.getDisplaySize(), getResultSetMetaData(helper.getQuery()).getColumnDisplaySize(3), "For query: " + helper.getQuery()); } } @Test void testAskGetColumnDisplaySize() throws SQLException { Assertions.assertEquals(1, getResultSetMetaData(SparqlMockDataQuery.ASK_QUERY).getColumnDisplaySize(1)); } @Test void testGetPrecision() throws SQLException { for (final SparqlResultSetMetadataTest.MetadataTestHelper helper : METADATA_TEST_HELPER) { Assertions.assertEquals(helper.getPrecision(), getResultSetMetaData(helper.getQuery()).getPrecision(2), "For query: " + helper.getQuery()); } } @Test void testConstructGetPrecision() throws SQLException { for (final SparqlResultSetMetadataTest.MetadataTestHelper helper : CONSTRUCT_METADATA_TEST_HELPER) { Assertions.assertEquals(helper.getPrecision(), getResultSetMetaData(helper.getQuery()).getPrecision(3), "For query: " + helper.getQuery()); } } @Test void testAskGetPrecision() throws SQLException { Assertions.assertEquals(1, getResultSetMetaData(SparqlMockDataQuery.ASK_QUERY).getPrecision(1)); } @Test void testGetScale() throws SQLException { for (final SparqlResultSetMetadataTest.MetadataTestHelper helper : METADATA_TEST_HELPER) { Assertions.assertEquals(helper.getScale(), getResultSetMetaData(helper.getQuery()).getScale(2), "For query: " + helper.getQuery()); } } @Test void testConstructGetScale() throws SQLException { for (final SparqlResultSetMetadataTest.MetadataTestHelper helper : CONSTRUCT_METADATA_TEST_HELPER) { Assertions.assertEquals(helper.getScale(), getResultSetMetaData(helper.getQuery()).getScale(3), "For query: " + helper.getQuery()); } } @Test void testAskGetScale() throws SQLException { Assertions.assertEquals(0, getResultSetMetaData(SparqlMockDataQuery.ASK_QUERY).getScale(1)); } @Test void testIsAutoIncrement() throws SQLException { Assertions.assertFalse(getResultSetMetaData(STRING_QUERY_TWO_COLUMN).isAutoIncrement(1)); Assertions.assertFalse(getResultSetMetaData(STRING_QUERY_TWO_COLUMN).isAutoIncrement(2)); Assertions.assertFalse(getResultSetMetaData(SparqlMockDataQuery.CONSTRUCT_STRING_QUERY).isAutoIncrement(1)); Assertions.assertFalse(getResultSetMetaData(SparqlMockDataQuery.CONSTRUCT_STRING_QUERY).isAutoIncrement(2)); Assertions.assertFalse(getResultSetMetaData(SparqlMockDataQuery.CONSTRUCT_STRING_QUERY).isAutoIncrement(3)); Assertions.assertFalse(getResultSetMetaData(SparqlMockDataQuery.ASK_QUERY).isAutoIncrement(1)); } @Test void testIsCaseSensitive() throws SQLException { Assertions.assertTrue(getResultSetMetaData(STRING_QUERY_TWO_COLUMN).isCaseSensitive(2)); Assertions.assertFalse(getResultSetMetaData(SparqlMockDataQuery.INT_QUERY).isCaseSensitive(2)); Assertions.assertTrue(getResultSetMetaData(SparqlMockDataQuery.CONSTRUCT_INT_QUERY).isCaseSensitive(2)); Assertions.assertFalse(getResultSetMetaData(SparqlMockDataQuery.CONSTRUCT_INT_QUERY).isCaseSensitive(3)); Assertions.assertFalse(getResultSetMetaData(SparqlMockDataQuery.ASK_QUERY).isCaseSensitive(1)); } @Test void testIsSearchable() throws SQLException { Assertions.assertFalse(getResultSetMetaData(STRING_QUERY_TWO_COLUMN).isSearchable(2)); Assertions.assertFalse(getResultSetMetaData(SparqlMockDataQuery.CONSTRUCT_STRING_QUERY).isSearchable(3)); Assertions.assertFalse(getResultSetMetaData(SparqlMockDataQuery.ASK_QUERY).isSearchable(1)); } @Test void testIsCurrency() throws SQLException { Assertions.assertFalse(getResultSetMetaData(STRING_QUERY_TWO_COLUMN).isCurrency(2)); Assertions.assertFalse(getResultSetMetaData(SparqlMockDataQuery.INT_QUERY).isCurrency(2)); Assertions.assertFalse(getResultSetMetaData(SparqlMockDataQuery.CONSTRUCT_INT_QUERY).isCurrency(2)); Assertions.assertFalse(getResultSetMetaData(SparqlMockDataQuery.CONSTRUCT_INT_QUERY).isCurrency(3)); Assertions.assertFalse(getResultSetMetaData(SparqlMockDataQuery.ASK_QUERY).isCurrency(1)); } @Test void testIsNullable() throws SQLException { Assertions.assertEquals(ResultSetMetaData.columnNullableUnknown, getResultSetMetaData(STRING_QUERY_TWO_COLUMN).isNullable(2)); Assertions.assertEquals(ResultSetMetaData.columnNullableUnknown, getResultSetMetaData(SparqlMockDataQuery.INT_QUERY).isNullable(2)); Assertions.assertEquals(ResultSetMetaData.columnNullableUnknown, getResultSetMetaData(SparqlMockDataQuery.BOOL_QUERY).isNullable(2)); Assertions.assertEquals(ResultSetMetaData.columnNullableUnknown, getResultSetMetaData(SparqlMockDataQuery.CONSTRUCT_INT_QUERY).isNullable(3)); Assertions.assertEquals(ResultSetMetaData.columnNullableUnknown, getResultSetMetaData(SparqlMockDataQuery.CONSTRUCT_BOOL_QUERY).isNullable(3)); Assertions.assertEquals(ResultSetMetaData.columnNullableUnknown, getResultSetMetaData(SparqlMockDataQuery.ASK_QUERY).isNullable(1)); } @Test void testIsSigned() throws SQLException { for (final SparqlResultSetMetadataTest.MetadataTestHelper helper : METADATA_TEST_HELPER) { Assertions.assertEquals(helper.isSigned(), getResultSetMetaData(helper.getQuery()).isSigned(2), "For query: " + helper.getQuery()); } } @Test void testConstructIsSigned() throws SQLException { for (final SparqlResultSetMetadataTest.MetadataTestHelper helper : CONSTRUCT_METADATA_TEST_HELPER) { Assertions.assertEquals(helper.isSigned(), getResultSetMetaData(helper.getQuery()).isSigned(3), "For query: " + helper.getQuery()); } } @Test void testAskIsSigned() throws SQLException { Assertions.assertFalse(getResultSetMetaData(SparqlMockDataQuery.ASK_QUERY).isSigned(1)); } @Test void testGetColumnLabel() throws SQLException { Assertions.assertEquals("fname", getResultSetMetaData(STRING_QUERY_ONE_COLUMN).getColumnName(1)); Assertions.assertEquals("Subject", getResultSetMetaData(SparqlMockDataQuery.CONSTRUCT_STRING_QUERY).getColumnName(1)); Assertions.assertEquals("Ask", getResultSetMetaData(SparqlMockDataQuery.ASK_QUERY).getColumnName(1)); } @Test void testGetColumnName() throws SQLException { Assertions.assertEquals("fname", getResultSetMetaData(STRING_QUERY_ONE_COLUMN).getColumnName(1)); Assertions.assertEquals("Subject", getResultSetMetaData(SparqlMockDataQuery.CONSTRUCT_STRING_QUERY).getColumnName(1)); Assertions.assertEquals("Ask", getResultSetMetaData(SparqlMockDataQuery.ASK_QUERY).getColumnName(1)); } @Test void testGetColumnType() throws SQLException { for (final SparqlResultSetMetadataTest.MetadataTestHelper helper : METADATA_TEST_HELPER) { Assertions.assertEquals(helper.getJdbcType(), getResultSetMetaData(helper.getQuery()).getColumnType(2), "For query: " + helper.getQuery()); } } @Test void testConstructGetColumnType() throws SQLException { for (final SparqlResultSetMetadataTest.MetadataTestHelper helper : CONSTRUCT_METADATA_TEST_HELPER) { Assertions.assertEquals(helper.getJdbcType(), getResultSetMetaData(helper.getQuery()).getColumnType(3), "For query: " + helper.getQuery()); } } @Test void testAskGetColumnType() throws SQLException { Assertions .assertEquals(java.sql.Types.BIT, getResultSetMetaData(SparqlMockDataQuery.ASK_QUERY).getColumnType(1)); } @Test void testGetColumnTypeName() throws SQLException { for (final SparqlResultSetMetadataTest.MetadataTestHelper helper : METADATA_TEST_HELPER) { Assertions.assertEquals(helper.getColumnJenaClassName(), getResultSetMetaData(helper.getQuery()).getColumnTypeName(2), "For query: " + helper.getQuery()); } } @Test void testConstructGetColumnTypeName() throws SQLException { for (final SparqlResultSetMetadataTest.MetadataTestHelper helper : CONSTRUCT_METADATA_TEST_HELPER) { Assertions.assertEquals(helper.getColumnJenaClassName(), getResultSetMetaData(helper.getQuery()).getColumnTypeName(3), "For query: " + helper.getQuery()); } } @Test void testAskGetColumnTypeName() throws SQLException { Assertions.assertEquals(Boolean.class.getName(), getResultSetMetaData(SparqlMockDataQuery.ASK_QUERY).getColumnTypeName(1)); } @Test void testGetColumnClassName() throws SQLException { for (final SparqlResultSetMetadataTest.MetadataTestHelper helper : METADATA_TEST_HELPER) { Assertions.assertEquals(helper.getColumnJavaClassName(), getResultSetMetaData(helper.getQuery()).getColumnClassName(2), "For query: " + helper.getQuery()); } } @Test void testConstructGetColumnClassName() throws SQLException { for (final SparqlResultSetMetadataTest.MetadataTestHelper helper : CONSTRUCT_METADATA_TEST_HELPER) { Assertions.assertEquals(helper.getColumnJavaClassName(), getResultSetMetaData(helper.getQuery()).getColumnClassName(3), "For query: " + helper.getQuery()); } } @Test void testAskGetColumnClassName() throws SQLException { Assertions.assertEquals(Boolean.class.getName(), getResultSetMetaData(SparqlMockDataQuery.ASK_QUERY).getColumnClassName(1)); } @Test void testIsReadOnly() throws SQLException { Assertions.assertTrue(getResultSetMetaData(STRING_QUERY_ONE_COLUMN).isReadOnly(1)); Assertions.assertTrue(getResultSetMetaData(SparqlMockDataQuery.CONSTRUCT_STRING_QUERY).isReadOnly(3)); Assertions.assertTrue(getResultSetMetaData(SparqlMockDataQuery.ASK_QUERY).isReadOnly(1)); } @Test void testIsWritable() throws SQLException { Assertions.assertFalse(getResultSetMetaData(STRING_QUERY_ONE_COLUMN).isWritable(1)); Assertions.assertFalse(getResultSetMetaData(SparqlMockDataQuery.CONSTRUCT_STRING_QUERY).isWritable(3)); Assertions.assertFalse(getResultSetMetaData(SparqlMockDataQuery.ASK_QUERY).isWritable(1)); } @Test void testIsDefinitelyWritable() throws SQLException { Assertions.assertFalse(getResultSetMetaData(STRING_QUERY_ONE_COLUMN).isDefinitelyWritable(1)); Assertions .assertFalse(getResultSetMetaData(SparqlMockDataQuery.CONSTRUCT_STRING_QUERY).isDefinitelyWritable(3)); Assertions.assertFalse(getResultSetMetaData(SparqlMockDataQuery.ASK_QUERY).isDefinitelyWritable(1)); } @Test void testGetTableName() throws SQLException { Assertions.assertEquals("", getResultSetMetaData(STRING_QUERY_ONE_COLUMN).getTableName(1)); Assertions.assertEquals("", getResultSetMetaData(SparqlMockDataQuery.CONSTRUCT_STRING_QUERY).getTableName(3)); Assertions.assertEquals("", getResultSetMetaData(SparqlMockDataQuery.ASK_QUERY).getTableName(1)); } @Test void testGetSchemaName() throws SQLException { Assertions.assertEquals("", getResultSetMetaData(STRING_QUERY_ONE_COLUMN).getSchemaName(1)); Assertions.assertEquals("", getResultSetMetaData(SparqlMockDataQuery.CONSTRUCT_STRING_QUERY).getSchemaName(3)); Assertions.assertEquals("", getResultSetMetaData(SparqlMockDataQuery.ASK_QUERY).getSchemaName(1)); } @Test void testGetCatalogName() throws SQLException { Assertions.assertEquals("", getResultSetMetaData(STRING_QUERY_ONE_COLUMN).getCatalogName(1)); Assertions.assertEquals("", getResultSetMetaData(SparqlMockDataQuery.CONSTRUCT_STRING_QUERY).getCatalogName(3)); Assertions.assertEquals("", getResultSetMetaData(SparqlMockDataQuery.ASK_QUERY).getCatalogName(1)); } @AllArgsConstructor @Getter static class MetadataTestHelper { private final String query; private final int displaySize; private final int precision; private final int scale; private final boolean caseSensitive; private final boolean signed; private final int jdbcType; private final String columnJavaClassName; private final String columnJenaClassName; } }
7,325
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/sparql
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/sparql/mock/SparqlMockServer.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ /** * Modified from Jena JDBC FusekiTestServer.java source file with original * License header below. */ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package software.aws.neptune.sparql.mock; import org.apache.http.client.HttpClient; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.jena.atlas.io.IO; import org.apache.jena.atlas.web.WebLib; import org.apache.jena.fuseki.main.FusekiServer; import org.apache.jena.riot.web.HttpOp; import org.apache.jena.sparql.core.DatasetGraph; import org.apache.jena.sparql.core.DatasetGraphFactory; import org.apache.jena.sparql.modify.request.Target; import org.apache.jena.sparql.modify.request.UpdateDrop; import org.apache.jena.system.Txn; import org.apache.jena.update.Update; import org.apache.jena.update.UpdateExecutionFactory; import org.apache.jena.update.UpdateProcessor; import java.util.concurrent.atomic.AtomicInteger; import static software.aws.neptune.sparql.mock.SparqlMockServer.ServerScope.CLASS; import static software.aws.neptune.sparql.mock.SparqlMockServer.ServerScope.SUITE; import static software.aws.neptune.sparql.mock.SparqlMockServer.ServerScope.TEST; public class SparqlMockServer { /* Cut&Paste versions: Test suite (TS_*) @BeforeClass static public void beforeSuiteClass() { FusekiTestServer.ctlBeforeTestSuite(); } @AfterClass static public void afterSuiteClass() { FusekiTestServer.ctlAfterTestSuite(); } Test class (Test*) @BeforeClass public static void ctlBeforeClass() { FusekiTestServer.ctlBeforeClass(); } @AfterClass public static void ctlAfterClass() { FusekiTestServer.ctlAfterClass(); } @Before public void ctlBeforeTest() { FusekiTestServer.ctlBeforeTest(); } @After public void ctlAfterTest() { FusekiTestServer.ctlAfterTest(); } */ // Note: it is important to cleanly close a PoolingHttpClient across server restarts // otherwise the pooled connections remain for the old server. private static final ServerScope SERVER_SCOPE = ServerScope.CLASS; private static final int CHOOSE_PORT = WebLib.choosePort(); // Whether to use a transaction on the dataset or to use SPARQL Update. private static DatasetGraph dsgTesting; private static final boolean CLEAR_DSG_DIRECTLY = true; // reference count of start/stop server private static final AtomicInteger COUNT_SERVER = new AtomicInteger(); private static FusekiServer server = null; // Abstraction that runs a SPARQL server for tests. /** * Returns currently used port * * @return the currently used port. */ public static int port() { return CHOOSE_PORT; } /** * Function to get root url. * * @return root url */ public static String urlRoot() { return "http://localhost:" + port() + "/"; } /** * Function to get database path. * * @return database path */ public static String datasetPath() { return "/mock"; } /** * Function to get full database url. * * @return full database url */ public static String urlDataset() { return "http://localhost:" + port() + datasetPath(); } /** * Function to get update api. * * @return update url */ public static String serviceUpdate() { return "http://localhost:" + port() + datasetPath() + "/update"; } /** * Function to get query api. * * @return query url */ public static String serviceQuery() { return "http://localhost:" + port() + datasetPath() + "/query"; } /** * Function to get data api. * * @return dataGSP url */ public static String serviceGSP() { return "http://localhost:" + port() + datasetPath() + "/data"; } /** * Setup for the tests by allocating a Fuseki instance to work with */ public static void ctlBeforeTestSuite() { if (SERVER_SCOPE == SUITE) { setPoolingHttpClient(); allocServer(); } } /** * Setup for the tests by allocating a Fuseki instance to work with */ public static void ctlAfterTestSuite() { if (SERVER_SCOPE == SUITE) { freeServer(); resetDefaultHttpClient(); } } /** * Setup for the tests by allocating a Fuseki instance to work with */ public static void ctlBeforeClass() { if (SERVER_SCOPE == CLASS) { setPoolingHttpClient(); allocServer(); } } /** * Clean up after tests by de-allocating the Fuseki instance */ public static void ctlAfterClass() { if (SERVER_SCOPE == CLASS) { freeServer(); resetDefaultHttpClient(); } } /** * Placeholder. */ public static void ctlBeforeTest() { if (SERVER_SCOPE == TEST) { setPoolingHttpClient(); allocServer(); } } /** * Clean up after each test by resetting the Fuseki dataset */ public static void ctlAfterTest() { if (SERVER_SCOPE == TEST) { freeServer(); resetDefaultHttpClient(); } else { resetServer(); } } /** * Setup for the tests by allocating a Fuseki instance to work with */ public static void ctlBeforeEach() { setPoolingHttpClient(); allocServer(); } /** * Clean up after tests by de-allocating the Fuseki instance */ public static void ctlAfterEach() { freeServer(); resetDefaultHttpClient(); } /** * Set a PoolingHttpClient */ public static void setPoolingHttpClient() { setHttpClient(HttpOp.createPoolingHttpClient()); } /** * Restore the original setup */ private static void resetDefaultHttpClient() { setHttpClient(HttpOp.createDefaultHttpClient()); } /** * Set the HttpClient - close the old one if appropriate */ public static void setHttpClient(final HttpClient newHttpClient) { final HttpClient hc = HttpOp.getDefaultHttpClient(); if (hc instanceof CloseableHttpClient) { IO.close((CloseableHttpClient) hc); } HttpOp.setDefaultHttpClient(newHttpClient); } /*package*/ static void allocServer() { if (COUNT_SERVER.getAndIncrement() == 0) { setupServer(true); } } /*package*/ static void freeServer() { if (COUNT_SERVER.decrementAndGet() == 0) { teardownServer(); } } /*package*/ static void setupServer(final boolean updateable) { dsgTesting = DatasetGraphFactory.createTxnMem(); server = FusekiServer.create() .add(datasetPath(), dsgTesting) .port(port()) .loopback(true) .build() .start(); } /*package*/ static void teardownServer() { if (server != null) { server.stop(); server = null; } } /*package*/ static void resetServer() { if (COUNT_SERVER.get() == 0) { throw new RuntimeException("No server started!"); } if (CLEAR_DSG_DIRECTLY) { Txn.executeWrite(dsgTesting, () -> dsgTesting.clear()); } else { final Update clearRequest = new UpdateDrop(Target.ALL); final UpdateProcessor proc = UpdateExecutionFactory.createRemote(clearRequest, serviceUpdate()); try { proc.execute(); } catch (final Throwable e) { e.printStackTrace(); throw e; } } } /*package : for import static */ enum ServerScope { SUITE, CLASS, TEST } // ---- Helper code. }
7,326
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/sparql
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/sparql/mock/SparqlMockDataQuery.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.sparql.mock; public class SparqlMockDataQuery { public static final String ALL_DATA_TWO_COLUMNS_QUERY = "SELECT ?p ?o WHERE {?s ?p ?o}"; public static final String STRING_QUERY = "SELECT ?x ?fname WHERE {?x <http://www.w3.org/2001/vcard-rdf/3.0#FN> ?fname}"; public static final String BOOL_QUERY = "SELECT ?x ?bool WHERE {?x <http://somewhere/peopleInfo#bool> ?bool}"; public static final String BYTE_QUERY = "SELECT ?x ?byte WHERE {?x <http://somewhere/peopleInfo#byte> ?byte}"; public static final String SHORT_QUERY = "SELECT ?x ?short WHERE {?x <http://somewhere/peopleInfo#short> ?short}"; public static final String INTEGER_SMALL_QUERY = "SELECT ?x ?integerSm WHERE {?x <http://somewhere/peopleInfo#integerSm> ?integerSm}"; public static final String INTEGER_LARGE_QUERY = "SELECT ?x ?integerLg WHERE {?x <http://somewhere/peopleInfo#integerLg> ?integerLg}"; public static final String LONG_QUERY = "SELECT ?x ?long WHERE {?x <http://somewhere/peopleInfo#long> ?long}"; public static final String INT_QUERY = "SELECT ?x ?int WHERE {?x <http://somewhere/peopleInfo#int> ?int}"; public static final String DECIMAL_QUERY = "SELECT ?x ?decimal WHERE {?x <http://somewhere/peopleInfo#decimal> ?decimal}"; public static final String DOUBLE_QUERY = "SELECT ?x ?double WHERE {?x <http://somewhere/peopleInfo#double> ?double}"; public static final String FLOAT_QUERY = "SELECT ?x ?float WHERE {?x <http://somewhere/peopleInfo#float> ?float}"; // NOTE: all unsigned XSD classes are wrapped into Java Integer or Long depending on size by the Jena library public static final String UNSIGNED_BYTE_QUERY = "SELECT ?x ?unsignedByte WHERE {?x <http://somewhere/peopleInfo#unsignedByte> ?unsignedByte}"; public static final String UNSIGNED_SHORT_QUERY = "SELECT ?x ?unsignedShort WHERE {?x <http://somewhere/peopleInfo#unsignedShort> ?unsignedShort}"; public static final String UNSIGNED_INT_QUERY = "SELECT ?x ?unsignedInt WHERE {?x <http://somewhere/peopleInfo#unsignedInt> ?unsignedInt}"; public static final String UNSIGNED_LONG_SMALL_QUERY = "SELECT ?x ?unsignedLongSm WHERE {?x <http://somewhere/peopleInfo#unsignedLongSm> ?unsignedLongSm}"; public static final String UNSIGNED_LONG_LARGE_QUERY = "SELECT ?x ?unsignedLongLg WHERE {?x <http://somewhere/peopleInfo#unsignedLongLg> ?unsignedLongLg}"; public static final String POSITIVE_INTEGER_QUERY = "SELECT ?x ?positiveInteger WHERE {?x <http://somewhere/peopleInfo#positiveInteger> ?positiveInteger}"; public static final String NON_NEGATIVE_INTEGER_QUERY = "SELECT ?x ?nonNegativeInteger WHERE {?x <http://somewhere/peopleInfo#nonNegativeInteger> ?nonNegativeInteger}"; public static final String NEGATIVE_INTEGER_QUERY = "SELECT ?x ?negativeInteger WHERE {?x <http://somewhere/peopleInfo#negativeInteger> ?negativeInteger}"; public static final String NON_POSITIVE_INTEGER_QUERY = "SELECT ?x ?nonPositiveInteger WHERE {?x <http://somewhere/peopleInfo#nonPositiveInteger> ?nonPositiveInteger}"; public static final String DATE_QUERY = "SELECT ?x ?date WHERE {?x <http://somewhere/peopleInfo#date> ?date}"; public static final String TIME_QUERY = "SELECT ?x ?time WHERE {?x <http://somewhere/peopleInfo#time> ?time}"; public static final String DATE_TIME_QUERY = "SELECT ?x ?dateTime WHERE {?x <http://somewhere/peopleInfo#dateTime> ?dateTime}"; public static final String DATE_TIME_STAMP_QUERY = "SELECT ?x ?dateTimeStamp WHERE {?x <http://somewhere/peopleInfo#dateTimeStamp> ?dateTimeStamp}"; public static final String G_YEAR_QUERY = "SELECT ?x ?gYear WHERE {?x <http://somewhere/peopleInfo#gYear> ?gYear}"; public static final String G_MONTH_QUERY = "SELECT ?x ?gMonth WHERE {?x <http://somewhere/peopleInfo#gMonth> ?gMonth}"; public static final String G_DAY_QUERY = "SELECT ?x ?gDay WHERE {?x <http://somewhere/peopleInfo#gDay> ?gDay}"; public static final String G_YEAR_MONTH_QUERY = "SELECT ?x ?gYearMonth WHERE {?x <http://somewhere/peopleInfo#gYearMonth> ?gYearMonth}"; public static final String G_MONTH_DAY_QUERY = "SELECT ?x ?gMonthDay WHERE {?x <http://somewhere/peopleInfo#gMonthDay> ?gMonthDay}"; public static final String DURATION_QUERY = "SELECT ?x ?duration WHERE {?x <http://somewhere/peopleInfo#duration> ?duration}"; public static final String YEAR_MONTH_DURATION_QUERY = "SELECT ?x ?yearMonthDuration WHERE {?x <http://somewhere/peopleInfo#yearMonthDuration> ?yearMonthDuration}"; public static final String DAY_TIME_DURATION_QUERY = "SELECT ?x ?dayTimeDuration WHERE {?x <http://somewhere/peopleInfo#dayTimeDuration> ?dayTimeDuration}"; public static final String PREDICATE_QUERY = "SELECT ?fname ?x WHERE {?x <http://www.w3.org/2001/vcard-rdf/3.0#FN> ?fname}"; public static final String EMPTY_SELECT_RESULT_QUERY = "SELECT ?x ?fname WHERE {?x <http://www.w3.org/2001/vcard-rdf/3.0#FN> ?fname FILTER(ISNUMERIC(?fname))}"; public static final String CONSTRUCT_STRING_QUERY = "CONSTRUCT WHERE {?x <http://www.w3.org/2001/vcard-rdf/3.0#FN> ?fname}"; public static final String CONSTRUCT_BOOL_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#bool> ?bool}"; public static final String CONSTRUCT_BYTE_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#byte> ?byte}"; public static final String CONSTRUCT_SHORT_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#short> ?short}"; public static final String CONSTRUCT_INTEGER_SMALL_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#integerSm> ?integerSm}"; public static final String CONSTRUCT_INTEGER_LARGE_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#integerLg> ?integerLg}"; public static final String CONSTRUCT_LONG_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#long> ?long}"; public static final String CONSTRUCT_INT_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#int> ?int}"; public static final String CONSTRUCT_DECIMAL_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#decimal> ?decimal}"; public static final String CONSTRUCT_DOUBLE_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#double> ?double}"; public static final String CONSTRUCT_FLOAT_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#float> ?float}"; // NOTE: all unsigned XSD classes are wrapped into Java Integer or Long depending on size by the Jena library public static final String CONSTRUCT_UNSIGNED_BYTE_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#unsignedByte> ?unsignedByte}"; public static final String CONSTRUCT_UNSIGNED_SHORT_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#unsignedShort> ?unsignedShort}"; public static final String CONSTRUCT_UNSIGNED_INT_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#unsignedInt> ?unsignedInt}"; public static final String CONSTRUCT_UNSIGNED_LONG_SMALL_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#unsignedLongSm> ?unsignedLongSm}"; public static final String CONSTRUCT_UNSIGNED_LONG_LARGE_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#unsignedLongLg> ?unsignedLongLg}"; public static final String CONSTRUCT_POSITIVE_INTEGER_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#positiveInteger> ?positiveInteger}"; public static final String CONSTRUCT_NON_NEGATIVE_INTEGER_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#nonNegativeInteger> ?nonNegativeInteger}"; public static final String CONSTRUCT_NEGATIVE_INTEGER_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#negativeInteger> ?negativeInteger}"; public static final String CONSTRUCT_NON_POSITIVE_INTEGER_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#nonPositiveInteger> ?nonPositiveInteger}"; public static final String CONSTRUCT_DATE_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#date> ?date}"; public static final String CONSTRUCT_TIME_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#time> ?time}"; public static final String CONSTRUCT_DATE_TIME_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#dateTime> ?dateTime}"; public static final String CONSTRUCT_DATE_TIME_STAMP_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#dateTimeStamp> ?dateTimeStamp}"; public static final String CONSTRUCT_G_YEAR_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#gYear> ?gYear}"; public static final String CONSTRUCT_G_MONTH_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#gMonth> ?gMonth}"; public static final String CONSTRUCT_G_DAY_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#gDay> ?gDay}"; public static final String CONSTRUCT_G_YEAR_MONTH_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#gYearMonth> ?gYearMonth}"; public static final String CONSTRUCT_G_MONTH_DAY_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#gMonthDay> ?gMonthDay}"; public static final String CONSTRUCT_DURATION_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#duration> ?duration}"; public static final String CONSTRUCT_YEAR_MONTH_DURATION_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#yearMonthDuration> ?yearMonthDuration}"; public static final String CONSTRUCT_DAY_TIME_DURATION_QUERY = "CONSTRUCT WHERE {?x <http://somewhere/peopleInfo#dayTimeDuration> ?dayTimeDuration}"; public static final String ASK_QUERY = "ASK {}"; }
7,327
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/jdbc/DatabaseMetaDataTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.jdbc; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.aws.neptune.jdbc.helpers.HelperFunctions; import software.aws.neptune.jdbc.mock.MockConnection; import software.aws.neptune.jdbc.mock.MockDatabaseMetadata; import software.aws.neptune.jdbc.mock.MockStatement; import software.aws.neptune.opencypher.OpenCypherConnectionProperties; import java.sql.RowIdLifetime; import java.sql.SQLException; /** * Test for abstract DatabaseMetaData Object. */ public class DatabaseMetaDataTest { private java.sql.DatabaseMetaData databaseMetaData; private java.sql.Connection connection; @BeforeEach void initialize() throws SQLException { connection = new MockConnection(new OpenCypherConnectionProperties()); databaseMetaData = new MockDatabaseMetadata(connection); } @Test void testSupport() { HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsANSI92FullSQL(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsANSI92IntermediateSQL(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsAlterTableWithAddColumn(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsAlterTableWithDropColumn(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsBatchUpdates(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsCatalogsInDataManipulation(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsCatalogsInIndexDefinitions(), false); HelperFunctions .expectFunctionDoesntThrow(() -> databaseMetaData.supportsCatalogsInPrivilegeDefinitions(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsCatalogsInProcedureCalls(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsCatalogsInTableDefinitions(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsColumnAliasing(), true); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsConvert(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsConvert(0, 0), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsCoreSQLGrammar(), true); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsCorrelatedSubqueries(), true); HelperFunctions.expectFunctionDoesntThrow( () -> databaseMetaData.supportsDataDefinitionAndDataManipulationTransactions(), false); HelperFunctions .expectFunctionDoesntThrow(() -> databaseMetaData.supportsDataManipulationTransactionsOnly(), false); HelperFunctions .expectFunctionDoesntThrow(() -> databaseMetaData.supportsDifferentTableCorrelationNames(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsExpressionsInOrderBy(), true); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsExtendedSQLGrammar(), true); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsFullOuterJoins(), true); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsGetGeneratedKeys(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsGroupBy(), true); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsGroupByBeyondSelect(), true); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsGroupByUnrelated(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsIntegrityEnhancementFacility(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsLikeEscapeClause(), true); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsLimitedOuterJoins(), true); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsMinimumSQLGrammar(), true); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsMixedCaseIdentifiers(), true); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsMixedCaseQuotedIdentifiers(), true); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsMultipleOpenResults(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsMultipleResultSets(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsMultipleTransactions(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsNamedParameters(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsNonNullableColumns(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsOpenCursorsAcrossCommit(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsOpenCursorsAcrossRollback(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsOpenStatementsAcrossCommit(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsOpenStatementsAcrossRollback(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsOrderByUnrelated(), true); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsOuterJoins(), true); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsPositionedDelete(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsPositionedUpdate(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsResultSetHoldability(0), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsSavepoints(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsSchemasInDataManipulation(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsSchemasInIndexDefinitions(), false); HelperFunctions .expectFunctionDoesntThrow(() -> databaseMetaData.supportsSchemasInPrivilegeDefinitions(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsSchemasInProcedureCalls(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsSchemasInTableDefinitions(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsSelectForUpdate(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsStatementPooling(), false); HelperFunctions .expectFunctionDoesntThrow(() -> databaseMetaData.supportsStoredFunctionsUsingCallSyntax(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsStoredProcedures(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsSubqueriesInComparisons(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsSubqueriesInExists(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsSubqueriesInIns(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsSubqueriesInQuantifieds(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsTableCorrelationNames(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsTransactionIsolationLevel(0), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsTransactions(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsUnion(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsUnionAll(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsResultSetConcurrency( java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY), true); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsResultSetConcurrency( java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_UPDATABLE), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsResultSetConcurrency( java.sql.ResultSet.TYPE_SCROLL_SENSITIVE, java.sql.ResultSet.CONCUR_READ_ONLY), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsResultSetType( java.sql.ResultSet.TYPE_FORWARD_ONLY), true); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsResultSetType( java.sql.ResultSet.TYPE_SCROLL_SENSITIVE), false); } @Test void testMaxValues() { HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.getMaxCharLiteralLength(), 0); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.getMaxColumnNameLength(), 0); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.getMaxColumnsInGroupBy(), 0); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.getMaxColumnsInIndex(), 0); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.getMaxColumnsInOrderBy(), 0); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.getMaxColumnsInSelect(), 0); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.getMaxColumnsInTable(), 0); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.getMaxConnections(), 0); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.getMaxCursorNameLength(), 0); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.getMaxIndexLength(), 0); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.getMaxProcedureNameLength(), 0); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.getMaxSchemaNameLength(), 0); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.getMaxStatements(), 0); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.getMaxBinaryLiteralLength(), 0); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.getMaxTablesInSelect(), 1); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.getMaxUserNameLength(), 0); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.getMaxCatalogNameLength(), 60); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.getMaxTableNameLength(), 60); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.getMaxStatementLength(), 65536); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.getDefaultTransactionIsolation(), java.sql.Connection.TRANSACTION_NONE); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.getResultSetHoldability(), java.sql.ResultSet.CLOSE_CURSORS_AT_COMMIT); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.getSQLStateType(), java.sql.DatabaseMetaData.sqlStateSQL); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.getProcedureTerm(), ""); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.getSchemaTerm(), ""); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.getIdentifierQuoteString(), "\""); HelperFunctions .expectFunctionDoesntThrow(() -> databaseMetaData.getRowIdLifetime(), RowIdLifetime.ROWID_UNSUPPORTED); HelperFunctions.expectFunctionThrows(() -> databaseMetaData.getCrossReference("", "", "", "", "", "")); HelperFunctions.expectFunctionThrows(() -> databaseMetaData.getExportedKeys("", "", "")); HelperFunctions.expectFunctionThrows(() -> databaseMetaData.getFunctionColumns("", "", "", "")); HelperFunctions.expectFunctionThrows(() -> databaseMetaData.getFunctions("", "", "")); HelperFunctions.expectFunctionThrows(() -> databaseMetaData.getProcedureColumns("", "", "", "")); HelperFunctions.expectFunctionThrows(() -> databaseMetaData.getPseudoColumns("", "", "", "")); HelperFunctions.expectFunctionThrows(() -> databaseMetaData.getTablePrivileges("", "", "")); HelperFunctions.expectFunctionThrows(() -> databaseMetaData.getUDTs("", "", "", new int[] {})); HelperFunctions.expectFunctionThrows(() -> databaseMetaData.getVersionColumns("", "", "")); HelperFunctions.expectFunctionThrows(() -> databaseMetaData.getSuperTables("", "", "")); HelperFunctions.expectFunctionThrows(() -> databaseMetaData.getSuperTypes("", "", "")); } @Test void testConnection() { HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.getConnection(), connection); } @Test void testWrap() { HelperFunctions .expectFunctionDoesntThrow(() -> databaseMetaData.isWrapperFor(MockDatabaseMetadata.class), true); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.isWrapperFor(MockStatement.class), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.isWrapperFor(null), false); HelperFunctions .expectFunctionDoesntThrow(() -> databaseMetaData.unwrap(MockDatabaseMetadata.class), databaseMetaData); HelperFunctions.expectFunctionThrows(() -> databaseMetaData.unwrap(MockStatement.class)); } @Test void testDriverVersion() { HelperFunctions .expectFunctionDoesntThrow(() -> databaseMetaData.getDriverMajorVersion(), Driver.DRIVER_MAJOR_VERSION); HelperFunctions .expectFunctionDoesntThrow(() -> databaseMetaData.getDriverMinorVersion(), Driver.DRIVER_MINOR_VERSION); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.getDriverVersion(), Driver.DRIVER_FULL_VERSION); } @Test void testUpdates() { HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.updatesAreDetected(1), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.usesLocalFilePerTable(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.usesLocalFiles(), false); } @Test void testAll() { HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.allProceduresAreCallable(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.allTablesAreSelectable(), true); } @Test void testDataDefinition() { HelperFunctions .expectFunctionDoesntThrow(() -> databaseMetaData.dataDefinitionCausesTransactionCommit(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.dataDefinitionIgnoredInTransactions(), false); } @Test void testMisc() { HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.autoCommitFailureClosesAllResultSets(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.deletesAreDetected(1), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.insertsAreDetected(1), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.locatorsUpdateCopy(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.generatedKeyAlwaysReturned(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.doesMaxRowSizeIncludeBlobs(), true); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.isCatalogAtStart(), true); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.isReadOnly(), true); } @Test void testNull() { HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.nullPlusNonNullIsNull(), true); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.nullsAreSortedAtEnd(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.nullsAreSortedAtStart(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.nullsAreSortedHigh(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.nullsAreSortedLow(), false); } @Test void testOthers() { HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.othersDeletesAreVisible(1), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.othersInsertsAreVisible(1), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.othersUpdatesAreVisible(1), false); } @Test void testOwn() { HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.ownDeletesAreVisible(1), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.ownInsertsAreVisible(1), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.ownUpdatesAreVisible(1), false); } @Test void testStores() { HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.storesLowerCaseIdentifiers(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.storesLowerCaseQuotedIdentifiers(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.storesUpperCaseIdentifiers(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.storesUpperCaseQuotedIdentifiers(), false); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.storesMixedCaseIdentifiers(), true); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.storesMixedCaseQuotedIdentifiers(), true); HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.supportsANSI92EntryLevelSQL(), true); } @Test void testGetTypeInfo() { HelperFunctions.expectFunctionDoesntThrow(() -> databaseMetaData.getTypeInfo()); } }
7,328
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/jdbc/DataSourceTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.jdbc; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.aws.neptune.jdbc.helpers.HelperFunctions; import software.aws.neptune.jdbc.mock.MockDataSource; import software.aws.neptune.jdbc.mock.MockStatement; import software.aws.neptune.jdbc.utilities.SqlError; /** * Test for abstract DataSource Object. */ public class DataSourceTest { private javax.sql.DataSource dataSource; @BeforeEach void initialize() { dataSource = new MockDataSource(); } @Test void testUnwrap() { HelperFunctions.expectFunctionDoesntThrow(() -> dataSource.isWrapperFor(MockDataSource.class), true); HelperFunctions.expectFunctionDoesntThrow(() -> dataSource.isWrapperFor(MockStatement.class), false); HelperFunctions.expectFunctionDoesntThrow(() -> dataSource.isWrapperFor(null), false); HelperFunctions.expectFunctionDoesntThrow(() -> dataSource.unwrap(MockDataSource.class), dataSource); HelperFunctions.expectFunctionThrows(() -> dataSource.unwrap(MockStatement.class)); } @Test void testLoggers() { HelperFunctions.expectFunctionDoesntThrow(() -> dataSource.getLogWriter(), null); HelperFunctions.expectFunctionDoesntThrow(() -> dataSource.setLogWriter(null)); HelperFunctions.expectFunctionDoesntThrow(() -> dataSource.getLogWriter(), null); HelperFunctions.expectFunctionThrows(SqlError.FEATURE_NOT_SUPPORTED, () -> dataSource.getParentLogger()); } }
7,329
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/jdbc/PreparedStatementTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.jdbc; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.aws.neptune.jdbc.helpers.HelperFunctions; import software.aws.neptune.jdbc.mock.MockConnection; import software.aws.neptune.jdbc.mock.MockPreparedStatement; import software.aws.neptune.opencypher.OpenCypherConnectionProperties; import java.io.InputStream; import java.io.Reader; import java.sql.Blob; import java.sql.Clob; import java.sql.NClob; import java.sql.SQLException; /** * Test for abstract PreparedStatement Object. */ public class PreparedStatementTest { private java.sql.Connection connection; private java.sql.PreparedStatement preparedStatement; @BeforeEach void initialize() throws SQLException { connection = new MockConnection(new OpenCypherConnectionProperties()); preparedStatement = new MockPreparedStatement(connection, ""); } @Test void testExecute() { HelperFunctions.expectFunctionDoesntThrow(() -> preparedStatement.execute(), true); HelperFunctions.expectFunctionThrows(() -> preparedStatement.execute("")); HelperFunctions.expectFunctionThrows(() -> preparedStatement.executeQuery("")); HelperFunctions.expectFunctionThrows(() -> preparedStatement.executeUpdate()); } @Test void testMisc() { HelperFunctions.expectFunctionThrows(() -> preparedStatement.addBatch()); HelperFunctions.expectFunctionThrows(() -> preparedStatement.clearParameters()); HelperFunctions.expectFunctionThrows(() -> preparedStatement.getParameterMetaData()); } @Test void testSet() { HelperFunctions.expectFunctionThrows(() -> preparedStatement.setArray(0, null)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setAsciiStream(0, null, 0)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setAsciiStream(0, null, 0)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setAsciiStream(0, null, (long) 0)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setAsciiStream(0, null)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setBigDecimal(0, null)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setBinaryStream(0, null, 0)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setBinaryStream(0, null, (long) 0)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setBinaryStream(0, null)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setBlob(0, (Blob) null)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setBlob(0, null, 0)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setBlob(0, (InputStream) null)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setBoolean(0, false)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setByte(0, (byte) 0)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setBytes(0, null)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setCharacterStream(0, null, 0)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setCharacterStream(0, null, (long) 0)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setCharacterStream(0, null)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setClob(0, (Clob) null)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setClob(0, null, 0)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setClob(0, (Reader) null)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setDate(0, null)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setDate(0, null, null)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setDouble(0, 0)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setFloat(0, (float) 0)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setInt(0, 0)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setLong(0, 0)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setNCharacterStream(0, null, 0)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setNCharacterStream(0, null)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setNClob(0, (NClob) null)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setNClob(0, null, 0)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setNClob(0, (Reader) null)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setNString(0, null)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setNull(0, 0)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setNull(0, 0, "")); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setObject(0, null, 0)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setObject(0, null)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setObject(0, null, 0, 0)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setRef(0, null)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setRowId(0, null)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setSQLXML(0, null)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setShort(0, (short) 0)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setString(0, null)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setTime(0, null)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setTime(0, null, null)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setTimestamp(0, null)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setTimestamp(0, null, null)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setURL(0, null)); HelperFunctions.expectFunctionThrows(() -> preparedStatement.setUnicodeStream(0, null, 0)); } }
7,330
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/jdbc/PooledConnectionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.jdbc; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.aws.neptune.jdbc.helpers.HelperFunctions; import software.aws.neptune.jdbc.mock.MockConnection; import software.aws.neptune.jdbc.mock.MockPooledConnection; import software.aws.neptune.opencypher.OpenCypherConnectionProperties; import javax.sql.ConnectionEvent; import javax.sql.ConnectionEventListener; import java.sql.SQLException; /** * Test for abstract PooledConnection Object. */ public class PooledConnectionTest { private javax.sql.PooledConnection pooledConnection; private boolean isClosed; private boolean isError; private final ConnectionEventListener listener = new ConnectionEventListener() { @Override public void connectionClosed(final ConnectionEvent event) { isClosed = true; } @Override public void connectionErrorOccurred(final ConnectionEvent event) { isError = true; } }; @BeforeEach void initialize() throws SQLException { pooledConnection = new MockPooledConnection(new MockConnection(new OpenCypherConnectionProperties())); isClosed = false; isError = false; } @Test void testListeners() { pooledConnection.addConnectionEventListener(listener); Assertions.assertFalse(isClosed); Assertions.assertFalse(isError); HelperFunctions.expectFunctionDoesntThrow(() -> pooledConnection.close()); Assertions.assertTrue(isClosed); Assertions.assertFalse(isError); pooledConnection.removeConnectionEventListener(listener); isClosed = false; HelperFunctions.expectFunctionDoesntThrow(() -> pooledConnection.close()); Assertions.assertFalse(isClosed); Assertions.assertFalse(isError); pooledConnection.addStatementEventListener(null); pooledConnection.removeStatementEventListener(null); } }
7,331
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/jdbc/ResultSetMetaDataTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.jdbc; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.aws.neptune.jdbc.helpers.HelperFunctions; import software.aws.neptune.jdbc.mock.MockResultSetMetaData; import software.aws.neptune.jdbc.mock.MockStatement; /** * Test for abstract ResultSetMetaData Object. */ public class ResultSetMetaDataTest { private java.sql.ResultSetMetaData resultSetMetaData; @BeforeEach void initialize() { resultSetMetaData = new MockResultSetMetaData(); } @Test void testWrap() { HelperFunctions .expectFunctionDoesntThrow(() -> resultSetMetaData.isWrapperFor(MockResultSetMetaData.class), true); HelperFunctions.expectFunctionDoesntThrow(() -> resultSetMetaData.isWrapperFor(MockStatement.class), false); HelperFunctions.expectFunctionDoesntThrow(() -> resultSetMetaData.isWrapperFor(null), false); HelperFunctions.expectFunctionDoesntThrow(() -> resultSetMetaData.unwrap(MockResultSetMetaData.class), resultSetMetaData); HelperFunctions.expectFunctionThrows(() -> resultSetMetaData.unwrap(MockStatement.class)); } }
7,332
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/jdbc/StatementTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.jdbc; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.aws.neptune.jdbc.helpers.HelperFunctions; import software.aws.neptune.jdbc.mock.MockConnection; import software.aws.neptune.jdbc.mock.MockResultSet; import software.aws.neptune.jdbc.mock.MockStatement; import software.aws.neptune.opencypher.OpenCypherConnectionProperties; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLWarning; /** * Test for abstract Statement Object. */ public class StatementTest { private java.sql.Statement statement; private java.sql.Connection connection; @BeforeEach void initialize() throws SQLException { connection = new MockConnection(new OpenCypherConnectionProperties()); statement = new MockStatement(connection); } @Test void testSetGetIs() { HelperFunctions.expectFunctionThrows(() -> statement.setPoolable(false)); HelperFunctions.expectFunctionThrows(() -> statement.setCursorName("")); HelperFunctions.expectFunctionThrows(() -> statement.setFetchDirection(ResultSet.FETCH_REVERSE)); HelperFunctions.expectFunctionDoesntThrow(() -> statement.setFetchDirection(ResultSet.FETCH_FORWARD)); HelperFunctions.expectFunctionDoesntThrow(() -> statement.setEscapeProcessing(false)); HelperFunctions.expectFunctionThrows(() -> statement.setFetchSize(0)); HelperFunctions.expectFunctionDoesntThrow(() -> statement.setFetchSize(1)); HelperFunctions.expectFunctionThrows(() -> statement.setLargeMaxRows(-1)); HelperFunctions.expectFunctionDoesntThrow(() -> statement.setLargeMaxRows(1)); HelperFunctions.expectFunctionThrows(() -> statement.setMaxFieldSize(-1)); HelperFunctions.expectFunctionDoesntThrow(() -> statement.setMaxFieldSize(1)); HelperFunctions.expectFunctionThrows(() -> statement.setMaxRows(-1)); HelperFunctions.expectFunctionDoesntThrow(() -> statement.setMaxRows(1)); HelperFunctions.expectFunctionDoesntThrow(() -> statement.getConnection(), connection); HelperFunctions .expectFunctionDoesntThrow(() -> statement.getFetchDirection(), java.sql.ResultSet.FETCH_FORWARD); HelperFunctions.expectFunctionDoesntThrow(() -> statement.getFetchSize(), 0); HelperFunctions.expectFunctionThrows(() -> statement.getGeneratedKeys()); HelperFunctions.expectFunctionDoesntThrow(() -> statement.getLargeMaxRows(), (long) 1); HelperFunctions.expectFunctionDoesntThrow(() -> statement.getMaxFieldSize(), 1); HelperFunctions.expectFunctionDoesntThrow(() -> statement.getLargeUpdateCount(), (long) -1); HelperFunctions.expectFunctionDoesntThrow(() -> statement.getMaxRows(), 1); HelperFunctions.expectFunctionDoesntThrow(() -> statement.getMoreResults(), false); ((MockStatement) statement).setResultSet(new MockResultSet(statement)); HelperFunctions.expectFunctionDoesntThrow(() -> statement.execute("")); HelperFunctions.expectFunctionDoesntThrow(() -> statement.getMoreResults( java.sql.Statement.CLOSE_CURRENT_RESULT), false); HelperFunctions.expectFunctionDoesntThrow(() -> statement.getResultSet(), null); HelperFunctions.expectFunctionDoesntThrow(() -> statement.getResultSetConcurrency(), java.sql.ResultSet.CONCUR_READ_ONLY); HelperFunctions.expectFunctionDoesntThrow(() -> statement.getResultSetHoldability(), java.sql.ResultSet.CLOSE_CURSORS_AT_COMMIT); HelperFunctions.expectFunctionDoesntThrow(() -> statement.getResultSetType(), java.sql.ResultSet.TYPE_FORWARD_ONLY); HelperFunctions.expectFunctionDoesntThrow(() -> statement.getUpdateCount(), -1); HelperFunctions.expectFunctionDoesntThrow(() -> statement.closeOnCompletion()); HelperFunctions.expectFunctionDoesntThrow(() -> statement.isCloseOnCompletion(), true); HelperFunctions.expectFunctionDoesntThrow(() -> statement.isPoolable(), false); HelperFunctions.expectFunctionDoesntThrow(() -> statement.setLargeMaxRows(Long.MAX_VALUE)); HelperFunctions.expectFunctionDoesntThrow(() -> statement.getMaxRows(), Integer.MAX_VALUE); } @Test void testExecute() { HelperFunctions.expectFunctionDoesntThrow(() -> statement.execute(""), true); HelperFunctions.expectFunctionDoesntThrow(() -> statement.execute("", 0), true); HelperFunctions.expectFunctionDoesntThrow(() -> statement.execute("", new int[] {}), true); HelperFunctions.expectFunctionDoesntThrow(() -> statement.execute("", new String[] {}), true); HelperFunctions.expectFunctionThrows(() -> statement.executeBatch()); HelperFunctions.expectFunctionThrows(() -> statement.executeLargeBatch()); HelperFunctions.expectFunctionThrows(() -> statement.executeLargeUpdate("")); HelperFunctions.expectFunctionThrows(() -> statement.executeLargeUpdate("", 0)); HelperFunctions.expectFunctionThrows(() -> statement.executeLargeUpdate("", new int[] {})); HelperFunctions.expectFunctionThrows(() -> statement.executeLargeUpdate("", new String[] {})); HelperFunctions.expectFunctionThrows(() -> statement.executeUpdate("")); HelperFunctions.expectFunctionThrows(() -> statement.executeUpdate("", 0)); HelperFunctions.expectFunctionThrows(() -> statement.executeUpdate("", new int[] {})); HelperFunctions.expectFunctionThrows(() -> statement.executeUpdate("", new String[] {})); HelperFunctions.expectFunctionThrows(() -> statement.executeBatch()); } @Test void testMisc() { HelperFunctions.expectFunctionThrows(() -> statement.cancel()); HelperFunctions.expectFunctionThrows(() -> statement.addBatch("")); HelperFunctions.expectFunctionThrows(() -> statement.clearBatch()); } @Test void testClosed() { HelperFunctions.expectFunctionDoesntThrow(() -> statement.isClosed(), false); HelperFunctions.expectFunctionDoesntThrow(() -> statement.close()); HelperFunctions.expectFunctionDoesntThrow(() -> statement.isClosed(), true); HelperFunctions.expectFunctionThrows(() -> ((Statement) statement).verifyOpen()); HelperFunctions.expectFunctionDoesntThrow(() -> statement.close()); } @Test void testResultSetClose() { HelperFunctions.expectFunctionDoesntThrow(() -> statement.isClosed(), false); ((MockStatement) statement).setResultSet(new MockResultSet(statement)); HelperFunctions.expectFunctionDoesntThrow(() -> statement.execute("")); HelperFunctions.expectFunctionDoesntThrow(() -> statement.close()); HelperFunctions.expectFunctionDoesntThrow(() -> statement.isClosed(), true); HelperFunctions.expectFunctionThrows(() -> ((Statement) statement).verifyOpen()); HelperFunctions.expectFunctionDoesntThrow(() -> statement.close()); } @Test void testWrap() { HelperFunctions.expectFunctionDoesntThrow(() -> statement.isWrapperFor(MockStatement.class), true); HelperFunctions.expectFunctionDoesntThrow(() -> statement.isWrapperFor(MockConnection.class), false); HelperFunctions.expectFunctionDoesntThrow(() -> statement.isWrapperFor(null), false); HelperFunctions.expectFunctionDoesntThrow(() -> statement.unwrap(MockStatement.class), statement); HelperFunctions.expectFunctionThrows(() -> statement.unwrap(MockConnection.class)); } @Test void testWarnings() { HelperFunctions.expectFunctionDoesntThrow(() -> statement.getWarnings(), null); HelperFunctions.expectFunctionDoesntThrow(() -> statement.clearWarnings()); HelperFunctions.expectFunctionDoesntThrow(() -> statement.getWarnings(), null); HelperFunctions .expectFunctionDoesntThrow(() -> ((Statement) statement).addWarning(HelperFunctions.getNewWarning1())); final SQLWarning warning = HelperFunctions.getNewWarning1(); HelperFunctions.expectFunctionDoesntThrow(() -> statement.getWarnings(), warning); warning.setNextWarning(HelperFunctions.getNewWarning2()); HelperFunctions .expectFunctionDoesntThrow(() -> ((Statement) statement).addWarning(HelperFunctions.getNewWarning2())); HelperFunctions.expectFunctionDoesntThrow(() -> statement.getWarnings(), warning); HelperFunctions.expectFunctionDoesntThrow(() -> statement.clearWarnings()); HelperFunctions.expectFunctionDoesntThrow(() -> statement.getWarnings(), null); } }
7,333
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/jdbc/ResultSetTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.jdbc; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.aws.neptune.jdbc.helpers.HelperFunctions; import software.aws.neptune.jdbc.mock.MockConnection; import software.aws.neptune.jdbc.mock.MockResultSet; import software.aws.neptune.jdbc.mock.MockStatement; import software.aws.neptune.opencypher.OpenCypherConnectionProperties; import java.io.InputStream; import java.io.Reader; import java.sql.Blob; import java.sql.Clob; import java.sql.NClob; import java.sql.SQLException; import java.sql.SQLWarning; import java.util.Map; /** * Test for abstract ResultSet Object. */ public class ResultSetTest { private java.sql.ResultSet resultSet; private java.sql.Statement statement; @BeforeEach void initialize() throws SQLException { statement = new MockStatement(new MockConnection(new OpenCypherConnectionProperties())); resultSet = new MockResultSet(statement); } @Test void testGetType() { HelperFunctions.expectFunctionThrows(() -> resultSet.getArray(0)); HelperFunctions.expectFunctionThrows(() -> resultSet.getArray("")); HelperFunctions.expectFunctionThrows(() -> resultSet.getAsciiStream(0)); HelperFunctions.expectFunctionThrows(() -> resultSet.getAsciiStream("")); HelperFunctions.expectFunctionThrows(() -> resultSet.getBigDecimal(0)); HelperFunctions.expectFunctionThrows(() -> resultSet.getBigDecimal(0, 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.getBigDecimal("")); HelperFunctions.expectFunctionThrows(() -> resultSet.getBigDecimal("", 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.getBinaryStream(0)); HelperFunctions.expectFunctionThrows(() -> resultSet.getBinaryStream("")); HelperFunctions.expectFunctionThrows(() -> resultSet.getBlob(0)); HelperFunctions.expectFunctionThrows(() -> resultSet.getBlob("")); HelperFunctions.expectFunctionThrows(() -> resultSet.getBoolean(0)); HelperFunctions.expectFunctionThrows(() -> resultSet.getBoolean("")); HelperFunctions.expectFunctionThrows(() -> resultSet.getByte(0)); HelperFunctions.expectFunctionThrows(() -> resultSet.getByte("")); HelperFunctions.expectFunctionThrows(() -> resultSet.getBytes(0)); HelperFunctions.expectFunctionThrows(() -> resultSet.getBytes("")); HelperFunctions.expectFunctionThrows(() -> resultSet.getCharacterStream(0)); HelperFunctions.expectFunctionThrows(() -> resultSet.getCharacterStream("")); HelperFunctions.expectFunctionThrows(() -> resultSet.getClob(0)); HelperFunctions.expectFunctionThrows(() -> resultSet.getClob("")); HelperFunctions.expectFunctionThrows(() -> resultSet.getDate(0)); HelperFunctions.expectFunctionThrows(() -> resultSet.getDate("")); HelperFunctions.expectFunctionThrows(() -> resultSet.getDate(0, null)); HelperFunctions.expectFunctionThrows(() -> resultSet.getDate("", null)); HelperFunctions.expectFunctionThrows(() -> resultSet.getDouble(0)); HelperFunctions.expectFunctionThrows(() -> resultSet.getDouble("")); HelperFunctions.expectFunctionThrows(() -> resultSet.getFloat(0)); HelperFunctions.expectFunctionThrows(() -> resultSet.getFloat("")); HelperFunctions.expectFunctionThrows(() -> resultSet.getInt(0)); HelperFunctions.expectFunctionThrows(() -> resultSet.getInt("")); HelperFunctions.expectFunctionThrows(() -> resultSet.getLong(0)); HelperFunctions.expectFunctionThrows(() -> resultSet.getLong("")); HelperFunctions.expectFunctionThrows(() -> resultSet.getNCharacterStream(0)); HelperFunctions.expectFunctionThrows(() -> resultSet.getNCharacterStream("")); HelperFunctions.expectFunctionThrows(() -> resultSet.getNClob(0)); HelperFunctions.expectFunctionThrows(() -> resultSet.getNClob("")); HelperFunctions.expectFunctionThrows(() -> resultSet.getNString(0)); HelperFunctions.expectFunctionThrows(() -> resultSet.getNString("")); HelperFunctions.expectFunctionThrows(() -> resultSet.getObject(0)); HelperFunctions.expectFunctionThrows(() -> resultSet.getObject("")); HelperFunctions.expectFunctionThrows(() -> resultSet.getObject(0, (Class<?>) null)); HelperFunctions.expectFunctionThrows(() -> resultSet.getObject("", (Class<?>) null)); HelperFunctions.expectFunctionThrows(() -> resultSet.getObject(0, (Map<String, Class<?>>) null)); HelperFunctions.expectFunctionThrows(() -> resultSet.getObject("", (Map<String, Class<?>>) null)); HelperFunctions.expectFunctionThrows(() -> resultSet.getObject("")); HelperFunctions.expectFunctionThrows(() -> resultSet.getRef(0)); HelperFunctions.expectFunctionThrows(() -> resultSet.getRef("")); HelperFunctions.expectFunctionThrows(() -> resultSet.getRowId(0)); HelperFunctions.expectFunctionThrows(() -> resultSet.getRowId("")); HelperFunctions.expectFunctionThrows(() -> resultSet.getShort(0)); HelperFunctions.expectFunctionThrows(() -> resultSet.getShort("")); HelperFunctions.expectFunctionThrows(() -> resultSet.getSQLXML(0)); HelperFunctions.expectFunctionThrows(() -> resultSet.getSQLXML("")); HelperFunctions.expectFunctionThrows(() -> resultSet.getString(0)); HelperFunctions.expectFunctionThrows(() -> resultSet.getString("")); HelperFunctions.expectFunctionThrows(() -> resultSet.getTime(0)); HelperFunctions.expectFunctionThrows(() -> resultSet.getTime("")); HelperFunctions.expectFunctionThrows(() -> resultSet.getTime(0, null)); HelperFunctions.expectFunctionThrows(() -> resultSet.getTime("", null)); HelperFunctions.expectFunctionThrows(() -> resultSet.getTimestamp(0)); HelperFunctions.expectFunctionThrows(() -> resultSet.getTimestamp("")); HelperFunctions.expectFunctionThrows(() -> resultSet.getTimestamp(0, null)); HelperFunctions.expectFunctionThrows(() -> resultSet.getTimestamp("", null)); HelperFunctions.expectFunctionThrows(() -> resultSet.getUnicodeStream(0)); HelperFunctions.expectFunctionThrows(() -> resultSet.getUnicodeStream("")); HelperFunctions.expectFunctionThrows(() -> resultSet.getURL(0)); HelperFunctions.expectFunctionThrows(() -> resultSet.getURL("")); } @Test void testUpdate() { HelperFunctions.expectFunctionThrows(() -> resultSet.updateArray(0, null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateArray("", null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateAsciiStream(0, null, (long) 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateAsciiStream("", null, (long) 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateAsciiStream(0, null, 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateAsciiStream("", null, 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateAsciiStream(0, null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateAsciiStream("", null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateBigDecimal(0, null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateBigDecimal("", null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateBinaryStream(0, null, (long) 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateBinaryStream("", null, (long) 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateBinaryStream(0, null, 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateBinaryStream("", null, 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateBinaryStream(0, null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateBinaryStream("", null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateBlob(0, (Blob) null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateBlob("", (Blob) null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateBlob(0, null, 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateBlob("", null, 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateBlob(0, (InputStream) null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateBlob("", (InputStream) null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateBoolean(0, false)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateBoolean("", false)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateByte(0, (byte) 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateByte("", (byte) 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateBytes(0, null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateBytes("", null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateCharacterStream(0, null, (long) 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateCharacterStream("", null, (long) 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateCharacterStream(0, null, 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateCharacterStream("", null, 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateCharacterStream(0, null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateCharacterStream("", null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateClob(0, (Clob) null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateClob("", (Clob) null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateClob(0, null, 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateClob("", null, 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateClob(0, (Reader) null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateClob("", (Reader) null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateDate(0, null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateDate("", null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateDouble(0, 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateDouble("", 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateFloat(0, 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateFloat("", 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateInt(0, 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateInt("", 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateLong(0, 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateLong("", 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateNCharacterStream(0, null, 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateNCharacterStream("", null, 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateNCharacterStream(0, null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateNCharacterStream("", null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateNClob(0, (NClob) null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateNClob("", (NClob) null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateNClob(0, null, 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateNClob("", null, 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateNClob(0, (Reader) null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateNClob("", (Reader) null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateNString(0, null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateNString("", null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateNull(0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateNull("")); HelperFunctions.expectFunctionThrows(() -> resultSet.updateObject(0, null, 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateObject(0, null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateObject("", null, 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateObject("", null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateRef(0, null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateRef("", null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateRow()); HelperFunctions.expectFunctionThrows(() -> resultSet.updateRowId(0, null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateRowId("", null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateSQLXML(0, null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateSQLXML("", null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateShort(0, (short) 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateShort("", (short) 0)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateString(0, null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateString("", null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateTime(0, null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateTime("", null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateTimestamp(0, null)); HelperFunctions.expectFunctionThrows(() -> resultSet.updateTimestamp("", null)); } @Test void testRow() { HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.rowDeleted(), false); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.rowInserted(), false); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.rowUpdated(), false); resultSet = new MockResultSet(statement); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.next(), true); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.relative(1), true); resultSet = new MockResultSet(statement); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.next(), true); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.relative(10), false); HelperFunctions.expectFunctionThrows(() -> resultSet.relative(-1)); HelperFunctions.expectFunctionThrows(() -> resultSet.moveToCurrentRow()); HelperFunctions.expectFunctionThrows(() -> resultSet.refreshRow()); HelperFunctions.expectFunctionThrows(() -> resultSet.previous()); HelperFunctions.expectFunctionThrows(() -> resultSet.insertRow()); HelperFunctions.expectFunctionThrows(() -> resultSet.moveToInsertRow()); HelperFunctions.expectFunctionThrows(() -> resultSet.deleteRow()); HelperFunctions.expectFunctionThrows(() -> resultSet.cancelRowUpdates()); resultSet = new MockResultSet(statement); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.next(), true); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.isAfterLast(), false); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.isBeforeFirst(), false); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.isFirst(), true); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.isLast(), false); resultSet = new MockResultSet(statement); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.isBeforeFirst(), true); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.isFirst(), false); resultSet = new MockResultSet(statement); for (int i = 0; i < 10; i++) { HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.next(), true); } HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.isLast(), true); resultSet = new MockResultSet(statement); for (int i = 0; i < 10; i++) { HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.next(), true); } HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.next(), false); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.isAfterLast(), true); resultSet = new MockResultSet(statement); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.next(), true); HelperFunctions.expectFunctionThrows(() -> resultSet.first()); HelperFunctions.expectFunctionThrows(() -> resultSet.last()); HelperFunctions.expectFunctionThrows(() -> resultSet.beforeFirst()); HelperFunctions.expectFunctionThrows(() -> resultSet.afterLast()); resultSet = new MockResultSet(statement); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.next(), true); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.getRow(), 1); HelperFunctions.expectFunctionThrows(() -> resultSet.absolute(-1)); HelperFunctions.expectFunctionThrows(() -> resultSet.absolute(0)); resultSet = new MockResultSet(statement); for (int i = 0; i < 10; i++) { HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.next(), true); } HelperFunctions.expectFunctionThrows(() -> resultSet.absolute(0)); HelperFunctions.expectFunctionThrows(() -> resultSet.absolute(5)); resultSet = new MockResultSet(statement); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.next(), true); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.absolute(5), true); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.absolute(10), false); } @Test void testFetch() { HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.setFetchDirection(java.sql.ResultSet.FETCH_FORWARD)); HelperFunctions.expectFunctionThrows(() -> resultSet.setFetchDirection(java.sql.ResultSet.FETCH_REVERSE)); HelperFunctions.expectFunctionThrows(() -> resultSet.setFetchDirection(java.sql.ResultSet.FETCH_UNKNOWN)); HelperFunctions .expectFunctionDoesntThrow(() -> resultSet.getFetchDirection(), java.sql.ResultSet.FETCH_FORWARD); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.getType(), java.sql.ResultSet.TYPE_FORWARD_ONLY); HelperFunctions .expectFunctionDoesntThrow(() -> resultSet.getConcurrency(), java.sql.ResultSet.CONCUR_READ_ONLY); HelperFunctions.expectFunctionThrows(() -> resultSet.getCursorName()); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.getFetchSize(), 0); HelperFunctions.expectFunctionThrows(() -> resultSet.setFetchSize(-1)); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.setFetchSize(0)); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.setFetchSize(1)); } @Test void testGetStatement() { HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.getStatement(), statement); } @Test void testWrap() { HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.isWrapperFor(MockResultSet.class), true); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.isWrapperFor(MockStatement.class), false); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.isWrapperFor(null), false); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.unwrap(MockResultSet.class), resultSet); HelperFunctions.expectFunctionThrows(() -> resultSet.unwrap(MockStatement.class)); } @Test void testClosed() { HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.isClosed(), false); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.close()); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.isClosed(), true); HelperFunctions.expectFunctionThrows(() -> ((ResultSet) resultSet).verifyOpen()); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.close()); } @Test void testWarnings() { HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.getWarnings(), null); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.clearWarnings()); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.getWarnings(), null); HelperFunctions .expectFunctionDoesntThrow(() -> ((ResultSet) resultSet).addWarning(HelperFunctions.getNewWarning1())); final SQLWarning warning = HelperFunctions.getNewWarning1(); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.getWarnings(), warning); warning.setNextWarning(HelperFunctions.getNewWarning2()); HelperFunctions .expectFunctionDoesntThrow(() -> ((ResultSet) resultSet).addWarning(HelperFunctions.getNewWarning2())); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.getWarnings(), warning); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.clearWarnings()); HelperFunctions.expectFunctionDoesntThrow(() -> resultSet.getWarnings(), null); } }
7,334
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/jdbc/ConnectionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.jdbc; import com.google.common.collect.ImmutableMap; import org.apache.log4j.Level; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.aws.neptune.jdbc.helpers.HelperFunctions; import software.aws.neptune.jdbc.mock.MockConnection; import software.aws.neptune.jdbc.mock.MockStatement; import software.aws.neptune.jdbc.utilities.AuthScheme; import software.aws.neptune.jdbc.utilities.ConnectionProperties; import software.aws.neptune.jdbc.utilities.SqlError; import software.aws.neptune.opencypher.OpenCypherConnectionProperties; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLWarning; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * Test for abstract Connection Object. */ public class ConnectionTest { private static final Properties PROPERTIES = new Properties(); private static final String TEST_SCHEMA = "schema"; private static final String TEST_CATALOG = "catalog"; private static final String TEST_NATIVE_SQL = "native sql"; private static final String TEST_PROP_KEY_UNSUPPORTED = "unsupported"; private static final String TEST_PROP_VAL_UNSUPPORTED = "unsupported"; private static final String TEST_PROP_KEY = ConnectionProperties.LOG_LEVEL_KEY; private static final Level TEST_PROP_VAL = Level.OFF; private static final Properties TEST_PROP = new Properties(); private static final Properties TEST_PROP_INITIAL = new Properties(); private static final Properties TEST_PROP_MODIFIED = new Properties(); private static final Map<String, Class<?>> TEST_TYPE_MAP = new ImmutableMap.Builder<String, Class<?>>().put("String", String.class).build(); private java.sql.Connection connection; @BeforeEach void initialize() throws SQLException { PROPERTIES.put(ConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.None); // set default to None connection = new MockConnection(new OpenCypherConnectionProperties(PROPERTIES)); TEST_PROP.put(TEST_PROP_KEY, TEST_PROP_VAL); TEST_PROP_INITIAL.put(ConnectionProperties.APPLICATION_NAME_KEY, Driver.APPLICATION_NAME); TEST_PROP_INITIAL.putAll(ConnectionProperties.DEFAULT_PROPERTIES_MAP); TEST_PROP_INITIAL.putAll(PROPERTIES); TEST_PROP_MODIFIED.putAll(TEST_PROP_INITIAL); TEST_PROP_MODIFIED.remove(TEST_PROP_KEY); } @Test void testTransactions() { // Transaction isolation. HelperFunctions .expectFunctionDoesntThrow(() -> connection.setTransactionIsolation(Connection.TRANSACTION_NONE)); HelperFunctions .expectFunctionThrows(() -> connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED)); HelperFunctions.expectFunctionThrows( () -> connection.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED)); HelperFunctions .expectFunctionThrows(() -> connection.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ)); HelperFunctions .expectFunctionThrows(() -> connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE)); HelperFunctions .expectFunctionDoesntThrow(() -> connection.getTransactionIsolation(), Connection.TRANSACTION_NONE); // Savepoint. HelperFunctions.expectFunctionThrows(() -> connection.setSavepoint()); HelperFunctions.expectFunctionThrows(() -> connection.setSavepoint(null)); HelperFunctions.expectFunctionThrows(() -> connection.releaseSavepoint(null)); // Rollback. HelperFunctions.expectFunctionThrows(() -> connection.rollback(null)); HelperFunctions.expectFunctionThrows(() -> connection.rollback()); // Commit. HelperFunctions.expectFunctionThrows(() -> connection.commit()); // Abort. HelperFunctions.expectFunctionThrows(() -> connection.abort(null)); // Holdability. HelperFunctions.expectFunctionThrows(() -> connection.setHoldability(0)); HelperFunctions.expectFunctionDoesntThrow(() -> connection.getHoldability(), ResultSet.CLOSE_CURSORS_AT_COMMIT); } @Test void testStatements() { // Statement without transaction. HelperFunctions.expectFunctionDoesntThrow(() -> connection.createStatement()); HelperFunctions.expectFunctionDoesntThrow(() -> connection.createStatement(0, 0)); // Statement with transaction. HelperFunctions.expectFunctionThrows(() -> connection.createStatement(0, 0, 0)); // Prepared statements. HelperFunctions.expectFunctionDoesntThrow(() -> connection.prepareStatement(null)); HelperFunctions.expectFunctionThrows(() -> connection.prepareStatement(null, 0)); HelperFunctions.expectFunctionThrows(() -> connection.prepareStatement(null, 0, 0)); HelperFunctions.expectFunctionThrows(() -> connection.prepareStatement(null, 0, 0, 0)); HelperFunctions.expectFunctionThrows(() -> connection.prepareStatement(null, new int[] {})); HelperFunctions.expectFunctionThrows(() -> connection.prepareStatement(null, new String[] {})); // Callable statements. HelperFunctions.expectFunctionThrows(() -> connection.prepareCall(null)); HelperFunctions.expectFunctionThrows(() -> connection.prepareCall(null, 0, 0)); HelperFunctions.expectFunctionThrows(() -> connection.prepareCall(null, 0, 0, 0)); } @Test void testClientInfo() { HelperFunctions.expectFunctionDoesntThrow(() -> connection.getClientInfo(), TEST_PROP_INITIAL); HelperFunctions.expectFunctionDoesntThrow(() -> connection.setClientInfo(null)); HelperFunctions.expectFunctionDoesntThrow(() -> connection.getClientInfo(null), null); HelperFunctions.expectFunctionDoesntThrow(() -> connection.getClientInfo(), TEST_PROP_INITIAL); HelperFunctions.expectFunctionDoesntThrow(() -> connection.getClientInfo(), TEST_PROP_INITIAL); HelperFunctions.expectFunctionDoesntThrow( () -> connection.setClientInfo(TEST_PROP_KEY, String.valueOf(TEST_PROP_VAL))); HelperFunctions.expectFunctionDoesntThrow(() -> connection.getClientInfo(TEST_PROP_KEY), String.valueOf(TEST_PROP_VAL)); HelperFunctions.expectFunctionDoesntThrow(() -> connection.setClientInfo(TEST_PROP_KEY, "")); HelperFunctions.expectFunctionDoesntThrow(() -> connection.getClientInfo(), TEST_PROP_INITIAL); HelperFunctions.expectFunctionDoesntThrow(() -> connection.setClientInfo(TEST_PROP)); HelperFunctions.expectFunctionDoesntThrow(() -> connection.getClientInfo(TEST_PROP_KEY), String.valueOf(TEST_PROP_VAL)); HelperFunctions.expectFunctionDoesntThrow(() -> connection.setClientInfo(TEST_PROP_KEY, null)); HelperFunctions.expectFunctionDoesntThrow(() -> connection.getClientInfo(), TEST_PROP_MODIFIED); HelperFunctions.expectFunctionThrows( SqlError.lookup(SqlError.INVALID_CONNECTION_PROPERTY, TEST_PROP_KEY_UNSUPPORTED, ""), () -> connection.setClientInfo(TEST_PROP_KEY_UNSUPPORTED, "")); HelperFunctions.expectFunctionThrows( SqlError.lookup(SqlError.INVALID_CONNECTION_PROPERTY, TEST_PROP_KEY, TEST_PROP_VAL_UNSUPPORTED), () -> connection.setClientInfo(TEST_PROP_KEY, TEST_PROP_VAL_UNSUPPORTED)); HelperFunctions.expectFunctionDoesntThrow(() -> connection.close()); HelperFunctions.expectFunctionThrows( SqlError.CONN_CLOSED, () -> connection.setClientInfo(TEST_PROP_KEY, String.valueOf(TEST_PROP_VAL))); HelperFunctions.expectFunctionThrows( SqlError.CONN_CLOSED, () -> connection.setClientInfo(TEST_PROP)); } @Test void testDataTypes() { HelperFunctions.expectFunctionThrows(() -> connection.createBlob()); HelperFunctions.expectFunctionThrows(() -> connection.createClob()); HelperFunctions.expectFunctionThrows(() -> connection.createNClob()); HelperFunctions.expectFunctionThrows(() -> connection.createSQLXML()); HelperFunctions.expectFunctionThrows(() -> connection.createArrayOf(null, new Object[] {})); HelperFunctions.expectFunctionThrows(() -> connection.createStruct(null, new Object[] {})); } @Test void testCatalog() { HelperFunctions.expectFunctionDoesntThrow(() -> connection.getCatalog(), null); HelperFunctions.expectFunctionDoesntThrow(() -> connection.setCatalog(TEST_CATALOG)); HelperFunctions.expectFunctionDoesntThrow(() -> connection.getCatalog(), null); } @Test void testSchema() { HelperFunctions.expectFunctionDoesntThrow(() -> connection.getSchema(), null); HelperFunctions.expectFunctionDoesntThrow(() -> connection.getSchema(), null); HelperFunctions.expectFunctionDoesntThrow(() -> connection.setSchema(TEST_SCHEMA)); } @Test void testWarnings() { HelperFunctions.expectFunctionDoesntThrow(() -> connection.getWarnings(), null); HelperFunctions.expectFunctionDoesntThrow(() -> connection.clearWarnings()); HelperFunctions.expectFunctionDoesntThrow(() -> connection.getWarnings(), null); HelperFunctions.expectFunctionDoesntThrow( () -> ((Connection) connection).addWarning(HelperFunctions.getNewWarning1())); final SQLWarning warning = HelperFunctions.getNewWarning1(); HelperFunctions.expectFunctionDoesntThrow(() -> connection.getWarnings(), warning); warning.setNextWarning(HelperFunctions.getNewWarning2()); HelperFunctions.expectFunctionDoesntThrow( () -> ((Connection) connection).addWarning(HelperFunctions.getNewWarning2())); HelperFunctions.expectFunctionDoesntThrow(() -> connection.getWarnings(), warning); HelperFunctions.expectFunctionDoesntThrow(() -> connection.clearWarnings()); HelperFunctions.expectFunctionDoesntThrow(() -> connection.getWarnings(), null); } @Test void testReadOnly() { HelperFunctions.expectFunctionDoesntThrow(() -> connection.setReadOnly(true)); HelperFunctions.expectFunctionThrows(() -> connection.setReadOnly(false)); HelperFunctions.expectFunctionDoesntThrow(() -> connection.isReadOnly(), true); } @Test void testAutoCommit() { HelperFunctions.expectFunctionDoesntThrow(() -> connection.setAutoCommit(true)); HelperFunctions.expectFunctionDoesntThrow(() -> connection.setAutoCommit(false)); HelperFunctions.expectFunctionDoesntThrow(() -> connection.getAutoCommit(), true); } @Test void testClosed() { HelperFunctions.expectFunctionDoesntThrow(() -> connection.isClosed(), false); HelperFunctions.expectFunctionDoesntThrow(() -> connection.close()); HelperFunctions.expectFunctionDoesntThrow(() -> connection.isClosed(), true); HelperFunctions.expectFunctionThrows(() -> ((Connection) connection).verifyOpen()); HelperFunctions.expectFunctionDoesntThrow(() -> connection.close()); } @Test void testWrap() { HelperFunctions.expectFunctionDoesntThrow(() -> connection.isWrapperFor(MockConnection.class), true); HelperFunctions.expectFunctionDoesntThrow(() -> connection.isWrapperFor(MockStatement.class), false); HelperFunctions.expectFunctionDoesntThrow(() -> connection.isWrapperFor(null), false); HelperFunctions.expectFunctionDoesntThrow(() -> connection.unwrap(MockConnection.class), connection); HelperFunctions.expectFunctionThrows(() -> connection.unwrap(MockStatement.class)); } @Test void testTypeMap() { HelperFunctions.expectFunctionDoesntThrow(() -> connection.getTypeMap(), new HashMap<>()); HelperFunctions.expectFunctionDoesntThrow(() -> connection.setTypeMap(TEST_TYPE_MAP)); HelperFunctions.expectFunctionDoesntThrow(() -> connection.getTypeMap(), TEST_TYPE_MAP); HelperFunctions.expectFunctionDoesntThrow(() -> connection.setTypeMap(null)); HelperFunctions.expectFunctionDoesntThrow(() -> connection.getTypeMap(), new HashMap<>()); } @Test void testNativeSQL() { HelperFunctions.expectFunctionDoesntThrow(() -> connection.nativeSQL(TEST_NATIVE_SQL), TEST_NATIVE_SQL); } }
7,335
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/jdbc
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/jdbc/mock/MockStatement.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.jdbc.mock; import software.aws.neptune.jdbc.Statement; import java.sql.Connection; import java.sql.SQLException; /** * Mock implementation for Statement object so it can be instantiated and tested. */ public class MockStatement extends Statement implements java.sql.Statement { private java.sql.ResultSet resultSet = null; /** * Constructor for MockStatement. * * @param connection Connection to pass to Statement. */ public MockStatement(final Connection connection) throws SQLException { super(connection, new MockQueryExecutor()); } public void setResultSet(final java.sql.ResultSet resultSet) { this.resultSet = resultSet; } }
7,336
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/jdbc
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/jdbc/mock/MockPreparedStatement.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.jdbc.mock; import software.aws.neptune.jdbc.PreparedStatement; import java.sql.Connection; import java.sql.SQLException; /** * Mock implementation for PreparedStatement object so it can be instantiated and tested. */ public class MockPreparedStatement extends PreparedStatement implements java.sql.PreparedStatement { /** * Constructor for seeding the prepared statement with the parent connection. * * @param connection The parent connection. * @param sql The sql query. * @throws SQLException if error occurs when get type map of connection. */ public MockPreparedStatement(final Connection connection, final String sql) throws SQLException { super(connection, sql, new MockQueryExecutor()); } }
7,337
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/jdbc
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/jdbc/mock/MockDriver.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.jdbc.mock; import software.aws.neptune.jdbc.Driver; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; /** * Mock implementation for Driver object so it can be instantiated and tested. */ public class MockDriver extends Driver implements java.sql.Driver { @Override public Connection connect(final String url, final Properties info) throws SQLException { return null; } @Override public boolean acceptsURL(final String url) throws SQLException { return false; } }
7,338
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/jdbc
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/jdbc/mock/MockDatabaseMetadata.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.jdbc.mock; import software.aws.neptune.jdbc.DatabaseMetaData; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; /** * Mock implementation for DatabaseMetadata object so it can be instantiated and tested. */ public class MockDatabaseMetadata extends DatabaseMetaData implements java.sql.DatabaseMetaData { /** * MockDatabaseMetadata constructor. * * @param connection Connection Object. */ public MockDatabaseMetadata(final Connection connection) { super(connection); } @Override public String getURL() throws SQLException { return null; } @Override public String getUserName() throws SQLException { return null; } @Override public String getDatabaseProductName() throws SQLException { return null; } @Override public String getDatabaseProductVersion() throws SQLException { return null; } @Override public String getDriverName() throws SQLException { return null; } @Override public String getSQLKeywords() throws SQLException { return null; } @Override public String getNumericFunctions() throws SQLException { return null; } @Override public String getStringFunctions() throws SQLException { return null; } @Override public String getSystemFunctions() throws SQLException { return null; } @Override public String getTimeDateFunctions() throws SQLException { return null; } @Override public String getSearchStringEscape() throws SQLException { return null; } @Override public String getExtraNameCharacters() throws SQLException { return null; } @Override public String getCatalogTerm() throws SQLException { return null; } @Override public String getCatalogSeparator() throws SQLException { return null; } @Override public int getMaxRowSize() throws SQLException { return 0; } @Override public ResultSet getProcedures(final String catalog, final String schemaPattern, final String procedureNamePattern) throws SQLException { return null; } @Override public ResultSet getTables(final String catalog, final String schemaPattern, final String tableNamePattern, final String[] types) throws SQLException { return null; } @Override public ResultSet getSchemas() throws SQLException { return null; } @Override public ResultSet getCatalogs() throws SQLException { return null; } @Override public ResultSet getTableTypes() throws SQLException { return null; } @Override public ResultSet getColumns(final String catalog, final String schemaPattern, final String tableNamePattern, final String columnNamePattern) throws SQLException { return null; } @Override public ResultSet getColumnPrivileges(final String catalog, final String schema, final String table, final String columnNamePattern) throws SQLException { return null; } @Override public ResultSet getBestRowIdentifier(final String catalog, final String schema, final String table, final int scope, final boolean nullable) throws SQLException { return null; } @Override public ResultSet getPrimaryKeys(final String catalog, final String schema, final String table) throws SQLException { return null; } @Override public ResultSet getImportedKeys(final String catalog, final String schema, final String table) throws SQLException { return null; } @Override public ResultSet getTypeInfo() throws SQLException { return null; } @Override public ResultSet getIndexInfo(final String catalog, final String schema, final String table, final boolean unique, final boolean approximate) throws SQLException { return null; } @Override public ResultSet getAttributes(final String catalog, final String schemaPattern, final String typeNamePattern, final String attributeNamePattern) throws SQLException { return null; } @Override public int getDatabaseMajorVersion() throws SQLException { return 0; } @Override public int getDatabaseMinorVersion() throws SQLException { return 0; } @Override public int getJDBCMajorVersion() throws SQLException { return 0; } @Override public int getJDBCMinorVersion() throws SQLException { return 0; } @Override public ResultSet getSchemas(final String catalog, final String schemaPattern) throws SQLException { return null; } @Override public ResultSet getClientInfoProperties() throws SQLException { return null; } }
7,339
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/jdbc
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/jdbc/mock/MockConnection.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.jdbc.mock; import lombok.NonNull; import software.aws.neptune.jdbc.Connection; import software.aws.neptune.jdbc.utilities.ConnectionProperties; import software.aws.neptune.jdbc.utilities.QueryExecutor; import java.sql.DatabaseMetaData; import java.sql.SQLException; /** * Mock implementation for Connection object so it can be instantiated and tested. */ public class MockConnection extends Connection implements java.sql.Connection { /** * Constructor for MockConnection. * * @param connectionProperties Properties to pass to Connection. */ public MockConnection( final @NonNull ConnectionProperties connectionProperties) throws SQLException { super(connectionProperties); } @Override public QueryExecutor getQueryExecutor() { return new MockQueryExecutor(); } @Override protected void doClose() { } @Override public DatabaseMetaData getMetaData() throws SQLException { return null; } }
7,340
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/jdbc
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/jdbc/mock/MockQueryExecutor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.jdbc.mock; import software.aws.neptune.jdbc.utilities.QueryExecutor; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class MockQueryExecutor extends QueryExecutor { @Override public int getMaxFetchSize() { return 0; } @Override public boolean isValid(final int timeout) { return false; } @Override public ResultSet executeQuery(final String sql, final Statement statement) throws SQLException { return null; } @Override public ResultSet executeGetTables(final Statement statement, final String tableName) throws SQLException { return null; } @Override public ResultSet executeGetSchemas(final Statement statement) throws SQLException { return null; } @Override public ResultSet executeGetCatalogs(final Statement statement) throws SQLException { return null; } @Override public ResultSet executeGetTableTypes(final Statement statement) throws SQLException { return null; } @Override public ResultSet executeGetColumns(final Statement statement, final String nodes) throws SQLException { return null; } @Override public ResultSet executeGetTypeInfo(final Statement statement) throws SQLException { return null; } @Override protected <T> T runQuery(final String query) throws SQLException { return null; } @Override protected void performCancel() throws SQLException { } }
7,341
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/jdbc
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/jdbc/mock/MockPooledConnection.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.jdbc.mock; import software.aws.neptune.jdbc.PooledConnection; import java.sql.Connection; import java.sql.SQLException; /** * Mock implementation for PooledConnection object so it can be instantiated and tested. */ public class MockPooledConnection extends PooledConnection implements javax.sql.PooledConnection { /** * MockPooledConnection constructor. * * @param connection Connection Object. */ public MockPooledConnection(final Connection connection) { super(connection); } @Override public Connection getConnection() throws SQLException { return null; } }
7,342
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/jdbc
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/jdbc/mock/MockResultSet.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.jdbc.mock; import software.aws.neptune.jdbc.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; /** * Mock implementation for ResultSet object so it can be instantiated and tested. */ public class MockResultSet extends ResultSet implements java.sql.ResultSet { private static final int ROW_COUNT = 10; private static final int COL_COUNT = 10; private int rowIndex = 0; /** * Constructor for MockResultSet. * * @param statement Statement Object. */ public MockResultSet(final Statement statement) { super(statement, new ArrayList<>(10), ROW_COUNT); } @Override protected void doClose() throws SQLException { } @Override protected int getDriverFetchSize() throws SQLException { return 0; } @Override protected void setDriverFetchSize(final int rows) { } @Override protected Object getConvertedValue(final int columnIndex) throws SQLException { if (columnIndex == 0 || columnIndex > COL_COUNT) { throw new SQLException("Index out of bounds."); } return null; } @Override protected ResultSetMetaData getResultMetadata() throws SQLException { return null; } @Override public boolean wasNull() throws SQLException { return false; } public void setRowIdx(final int idx) { this.rowIndex = idx; } }
7,343
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/jdbc
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/jdbc/mock/MockDataSource.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.jdbc.mock; import software.aws.neptune.jdbc.DataSource; import javax.sql.PooledConnection; import java.sql.Connection; import java.sql.SQLException; /** * Mock implementation for DataSource object so it can be instantiated and tested. */ public class MockDataSource extends DataSource implements javax.sql.DataSource { @Override public PooledConnection getPooledConnection() throws SQLException { return null; } @Override public PooledConnection getPooledConnection(final String user, final String password) throws SQLException { return null; } @Override public Connection getConnection() throws SQLException { return null; } @Override public Connection getConnection(final String username, final String password) throws SQLException { return null; } @Override public int getLoginTimeout() throws SQLException { return 0; } @Override public void setLoginTimeout(final int seconds) throws SQLException { } }
7,344
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/jdbc
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/jdbc/mock/MockResultSetMetaData.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.jdbc.mock; import software.aws.neptune.jdbc.ResultSetMetaData; import java.sql.SQLException; /** * Mock implementation for ResultSetMetaData object so it can be instantiated and tested. */ public class MockResultSetMetaData extends ResultSetMetaData implements java.sql.ResultSetMetaData { /** * Constructor for MockResultSetMetadata. */ public MockResultSetMetaData() { super(null); } @Override public int getColumnCount() throws SQLException { return 0; } @Override public boolean isAutoIncrement(final int column) throws SQLException { return false; } @Override public boolean isCaseSensitive(final int column) throws SQLException { return false; } @Override public boolean isSearchable(final int column) throws SQLException { return false; } @Override public boolean isCurrency(final int column) throws SQLException { return false; } @Override public int isNullable(final int column) throws SQLException { return 0; } @Override public boolean isSigned(final int column) throws SQLException { return false; } @Override public int getColumnDisplaySize(final int column) throws SQLException { return 0; } @Override public String getColumnLabel(final int column) throws SQLException { return null; } @Override public String getColumnName(final int column) throws SQLException { return null; } @Override public String getSchemaName(final int column) throws SQLException { return null; } @Override public int getPrecision(final int column) throws SQLException { return 0; } @Override public int getScale(final int column) throws SQLException { return 0; } @Override public String getTableName(final int column) throws SQLException { return null; } @Override public String getCatalogName(final int column) throws SQLException { return null; } @Override public int getColumnType(final int column) throws SQLException { return 0; } @Override public String getColumnTypeName(final int column) throws SQLException { return null; } @Override public boolean isReadOnly(final int column) throws SQLException { return false; } @Override public boolean isWritable(final int column) throws SQLException { return false; } @Override public boolean isDefinitelyWritable(final int column) throws SQLException { return false; } @Override public String getColumnClassName(final int column) throws SQLException { return null; } }
7,345
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/jdbc
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/jdbc/helpers/HelperFunctions.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.jdbc.helpers; import org.junit.jupiter.api.Assertions; import software.aws.neptune.jdbc.utilities.SqlError; import software.aws.neptune.jdbc.utilities.Warning; import java.sql.SQLException; import java.sql.SQLWarning; import java.util.Random; import java.util.concurrent.atomic.AtomicReference; public class HelperFunctions { public static final String TEST_WARNING_REASON_1 = "warning_1"; public static final String TEST_WARNING_REASON_2 = "warning_2"; public static final String TEST_WARNING_UNSUPPORTED = "unsupported"; public static final String TEST_WARNING_STATE = "state"; public static final SQLWarning TEST_SQL_WARNING_UNSUPPORTED = new SQLWarning(Warning.lookup(Warning.UNSUPPORTED_PROPERTY, TEST_WARNING_UNSUPPORTED)); /** * Function to verify that function passed in throws an exception. * * @param f function to check. */ public static void expectFunctionThrows(final VerifyThrowInterface f) { Assertions.assertThrows(SQLException.class, f::function); } /** * Function to verify that function passed in throws an exception with specified error message. * * @param error specific error message. * @param f function to check. */ public static void expectFunctionThrows(final String error, final VerifyThrowInterface f) { final Exception exception = Assertions.assertThrows(SQLException.class, f::function); Assertions.assertEquals(error, exception.getMessage()); } /** * Function to verify that function passed in throws an exception with specified error key. Error arguments are not supported. * * @param key specific error code. * @param f function to check. */ public static void expectFunctionThrows(final SqlError key, final VerifyThrowInterface f) { expectFunctionThrows(SqlError.lookup(key), f); } /** * Function to verify that function passed in doesn't throw an exception. * * @param f function to check. */ public static void expectFunctionDoesntThrow(final VerifyThrowInterface f) { Assertions.assertDoesNotThrow(f::function); } /** * Function to verify that function passed in doesn't throw an exception and has correct output value. * * @param f function to check. * @param expected expected value. */ public static void expectFunctionDoesntThrow(final VerifyValueInterface<?> f, final Object expected) { final AtomicReference<Object> actual = new AtomicReference<>(); Assertions.assertDoesNotThrow(() -> actual.set(f.function())); if (actual.get() instanceof SQLWarning) { SQLWarning actualWarning = (SQLWarning) actual.get(); SQLWarning expectedWarning = (SQLWarning) expected; do { Assertions.assertNotNull(actualWarning); Assertions.assertEquals(expectedWarning.getMessage(), actualWarning.getMessage()); actualWarning = actualWarning.getNextWarning(); expectedWarning = expectedWarning.getNextWarning(); // Dummy is used because end points to itself infinitely. // Make sure we don't see same warning multiple times in a row. } while (expectedWarning != null); } else { Assertions.assertEquals(expected, actual.get()); } } public static SQLWarning getNewWarning1() { return new SQLWarning(TEST_WARNING_REASON_1, TEST_WARNING_STATE); } public static SQLWarning getNewWarning2() { return new SQLWarning(TEST_WARNING_REASON_2, TEST_WARNING_STATE); } /** * Generates random positive integer value. * * @param maxValue Maximum integer value. * @return Random integer value. */ public static int randomPositiveIntValue(final int maxValue) { final Random random = new Random(); int randomValue = 0; while (randomValue == 0) { final int nextInt = random.nextInt(maxValue); randomValue = nextInt < 0 ? (-1) * nextInt : nextInt; } return randomValue; } /** * Simple interface to pass to functions below. * * @param <R> Template type. */ public interface VerifyValueInterface<R> { /** * Function to execute. * * @return Template type. * @throws SQLException Exception thrown. */ R function() throws SQLException; } /** * Simple interface to pass to functions below. */ public interface VerifyThrowInterface { /** * Function to execute. * * @throws SQLException Exception thrown. */ void function() throws SQLException; } }
7,346
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/common
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/common/gremlindatamodel/MetadataCacheTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.common.gremlindatamodel; import org.apache.calcite.util.Pair; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; import software.aws.neptune.gremlin.adapter.converter.schema.calcite.GremlinSchema; import software.aws.neptune.gremlin.adapter.converter.schema.gremlin.GremlinEdgeTable; import software.aws.neptune.gremlin.adapter.converter.schema.gremlin.GremlinProperty; import software.aws.neptune.gremlin.adapter.converter.schema.gremlin.GremlinVertexTable; import java.lang.reflect.Method; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; public class MetadataCacheTest { private static final String ENDPOINT = "mockEndpoint"; @Test void testMetadataCacheFiltering() throws SQLException { // Set up four tables, two vertex table with label "vertex" and "vertexBeta", and two edge tables with labels "edge", "edgeBeta". final GremlinVertexTable testTableVertex = new GremlinVertexTable("vertex", new ArrayList<>(Collections.singletonList(new GremlinProperty("testVertex", "string"))), new ArrayList<>(Collections.singletonList("edgeIn")), new ArrayList<>(Collections.singletonList("edgeOut"))); final GremlinVertexTable testTableVertexBeta = new GremlinVertexTable("vertexBeta", new ArrayList<>(Collections.singletonList(new GremlinProperty("testVertex", "string"))), new ArrayList<>(Collections.singletonList("edgeIn")), new ArrayList<>(Collections.singletonList("edgeOut"))); final GremlinEdgeTable testTableEdge = new GremlinEdgeTable("edge", new ArrayList<>(Collections.singletonList(new GremlinProperty("testEdge", "string"))), new ArrayList<>(Collections.singletonList(new Pair<>("vertexIn", "vertexOut")))); final GremlinEdgeTable testTableEdgeBeta = new GremlinEdgeTable("edgeBeta", new ArrayList<>(Collections.singletonList(new GremlinProperty("testEdge", "string"))), new ArrayList<>(Collections.singletonList(new Pair<>("vertexIn", "vertexOut")))); // Create a full schema to call the method on. final GremlinSchema testFullSchema = new GremlinSchema(new ArrayList<>(Arrays.asList(testTableVertex, testTableVertexBeta)), new ArrayList<>(Arrays.asList(testTableEdge, testTableEdgeBeta))); try (MockedStatic<MetadataCache> mockMetadataCache = Mockito.mockStatic(MetadataCache.class, invocation -> { final Method method = invocation.getMethod(); if ("getGremlinSchemas".equals(method.getName())) { return invocation.getMock(); } else { return invocation.callRealMethod(); } })) { final Map<String, GremlinSchema> schemaMap = new HashMap<>(); schemaMap.put(ENDPOINT, testFullSchema); mockMetadataCache.when(MetadataCache::getGremlinSchemas).thenReturn(schemaMap); Assertions.assertEquals(schemaMap, MetadataCache.getGremlinSchemas()); // Assert that filtering based label only gets the specified table. final GremlinSchema generatedVertexSchema = MetadataCache.getFilteredCacheNodeColumnInfos("vertex", ENDPOINT); Assertions.assertEquals("vertex", generatedVertexSchema.getVertices().get(0).getLabel()); Assertions.assertEquals(testTableVertex, generatedVertexSchema.getVertices().get(0)); Assertions.assertEquals(1, generatedVertexSchema.getVertices().size()); Assertions.assertEquals(0, generatedVertexSchema.getEdges().size()); final GremlinSchema generatedVertexBetaSchema = MetadataCache.getFilteredCacheNodeColumnInfos("vertexBeta", ENDPOINT); Assertions.assertEquals("vertexBeta", generatedVertexBetaSchema.getVertices().get(0).getLabel()); Assertions.assertEquals(testTableVertexBeta, generatedVertexBetaSchema.getVertices().get(0)); Assertions.assertEquals(1, generatedVertexBetaSchema.getVertices().size()); Assertions.assertEquals(0, generatedVertexBetaSchema.getEdges().size()); final GremlinSchema generatedEdgeSchema = MetadataCache.getFilteredCacheNodeColumnInfos("edge", ENDPOINT); Assertions.assertEquals("edge", generatedEdgeSchema.getEdges().get(0).getLabel()); Assertions.assertEquals(testTableEdge, generatedEdgeSchema.getEdges().get(0)); Assertions.assertEquals(0, generatedEdgeSchema.getVertices().size()); Assertions.assertEquals(1, generatedEdgeSchema.getEdges().size()); final GremlinSchema generatedEdgeBetaSchema = MetadataCache.getFilteredCacheNodeColumnInfos("edgeBeta", ENDPOINT); Assertions.assertEquals("edgeBeta", generatedEdgeBetaSchema.getEdges().get(0).getLabel()); Assertions.assertEquals(testTableEdgeBeta, generatedEdgeBetaSchema.getEdges().get(0)); Assertions.assertEquals(0, generatedEdgeBetaSchema.getVertices().size()); Assertions.assertEquals(1, generatedEdgeBetaSchema.getEdges().size()); } } }
7,347
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/opencypher/OpenCypherManualIAMTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.opencypher; import com.google.common.util.concurrent.ThreadFactoryBuilder; import lombok.AllArgsConstructor; import lombok.SneakyThrows; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.time.Duration; import java.time.Instant; import java.util.AbstractMap; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class OpenCypherManualIAMTest { private static final int PORT = 8182; private static final String HOSTNAME = "jdbc-bug-bash-iam-instance-1.cdubgfjknn5r.us-east-1.neptune.amazonaws.com"; private static final String ENDPOINT = String.format("bolt://%s:%d", HOSTNAME, PORT); private static final String REGION = "us-east-1"; private static final String AUTH = "IamSigV4"; private static final String ENCRYPTION = "TRUE"; private static final String CONNECTION_STRING = String.format("jdbc:neptune:opencypher://%s;useEncryption=%s;authScheme=%s;serviceRegion=%s;", ENDPOINT, ENCRYPTION, AUTH, REGION); private static final String CREATE_NODES = String.format("CREATE (:%s %s)", "Person:Developer", "{hello:'world'}") + String.format(" CREATE (:%s %s)", "Person", "{person:1234}") + String.format(" CREATE (:%s %s)", "Human", "{hello:'world'}") + String.format(" CREATE (:%s %s)", "Human", "{hello:123}") + String.format(" CREATE (:%s %s)", "Developer", "{hello:123}") + String.format(" CREATE (:%s %s)", "Person", "{p1:true}") + String.format(" CREATE (:%s %s)", "Person", "{p1:1.0}") + " CREATE (:Foo {foo:'foo'})-[:Rel {rel:'rel'}]->(:Bar {bar:'bar'})"; private final Map<String, List<Map.Entry<String, String>>> tableMap = new HashMap<>(); @Disabled @Test void testBasicIamAuth() throws Exception { final Connection connection = DriverManager.getConnection(CONNECTION_STRING); Assertions.assertTrue(connection.isValid(1)); } @Disabled @Test void testLongRunningQuery() throws Exception { final Properties properties = new Properties(); properties.put(OpenCypherConnectionProperties.ENDPOINT_KEY, ENDPOINT); properties.put(OpenCypherConnectionProperties.AUTH_SCHEME_KEY, AUTH); properties.put(OpenCypherConnectionProperties.SERVICE_REGION_KEY, REGION); final Connection connection = new OpenCypherConnection(new OpenCypherConnectionProperties(properties)); Assertions.assertTrue(connection.isValid(1)); final Statement statement = connection.createStatement(); final Instant start = Instant.now(); try { launchCancelThread(statement, 1000); final ResultSet resultSet = statement.executeQuery(createLongQuery()); } catch (final SQLException e) { System.out.println("Encountered exception: " + e); } final Instant end = Instant.now(); System.out.println("Time diff: " + Duration.between(start, end).toMillis() + " ms"); } @Disabled @Test void testGetColumns() throws SQLException { final Connection connection = DriverManager.getConnection(CONNECTION_STRING); final DatabaseMetaData databaseMetaData = connection.getMetaData(); final ResultSet resultSet = databaseMetaData.getColumns(null, null, null, null); Assertions.assertTrue(resultSet.next()); do { final String table = resultSet.getString("TABLE_NAME"); final String column = resultSet.getString("COLUMN_NAME"); final String type = resultSet.getString("TYPE_NAME"); if (!tableMap.containsKey(table)) { tableMap.put(table, new ArrayList<>()); } tableMap.get(table).add(new AbstractMap.SimpleImmutableEntry<String, String>(column, type) { }); } while (resultSet.next()); for (final Map.Entry<String, List<Map.Entry<String, String>>> entry : tableMap.entrySet()) { System.out.println("Table: " + entry.getKey()); for (final Map.Entry<String, String> columnTypePair : entry.getValue()) { System.out.println("\tColumn: " + columnTypePair.getKey() + ",\t Type: " + columnTypePair.getValue()); } } } @Disabled @Test void testGetTables() throws SQLException { final Connection connection = DriverManager.getConnection(CONNECTION_STRING); final DatabaseMetaData databaseMetaData = connection.getMetaData(); final ResultSet resultSet = databaseMetaData.getTables(null, null, null, null); Assertions.assertTrue(resultSet.next()); do { final int columnCount = resultSet.getMetaData().getColumnCount(); System.out.println("Table: " + resultSet.getString("TABLE_NAME")); for (int i = 0; i < columnCount; i++) { final String columnName = resultSet.getMetaData().getColumnName(i + 1); if (!"TABLE_NAME".equals(columnName)) { System.out.println("\t" + resultSet.getMetaData().getColumnName(i + 1) + " - '" + resultSet.getString(i + 1) + "'"); } } } while (resultSet.next()); } String createLongQuery() { final int nodeCount = 1000; final StringBuilder createStatement = new StringBuilder(); for (int i = 0; i < nodeCount; i++) { createStatement.append(String.format("CREATE (node%d:Foo)", i)); if (i != (nodeCount - 1)) { createStatement.append(" "); } } return createStatement.toString(); } void launchCancelThread(final Statement statement, final int waitTime) { final ExecutorService cancelThread = Executors.newSingleThreadExecutor( new ThreadFactoryBuilder().setNameFormat("cancelThread").setDaemon(true).build()); cancelThread.execute(new Cancel(statement, waitTime)); } /** * Class to cancel query in a separate thread. */ @AllArgsConstructor public static class Cancel implements Runnable { private final Statement statement; private final int waitTime; @SneakyThrows @Override public void run() { try { Thread.sleep(waitTime); statement.cancel(); } catch (final SQLException e) { System.out.println("Cancel exception: " + e); } } } }
7,348
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/opencypher/OpenCypherDataSourceTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.opencypher; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import software.aws.neptune.NeptuneDriverTestWithEncryption; import software.aws.neptune.jdbc.helpers.HelperFunctions; import software.aws.neptune.jdbc.utilities.AuthScheme; import software.aws.neptune.jdbc.utilities.SqlError; import software.aws.neptune.opencypher.mock.MockOpenCypherDatabase; import java.sql.SQLException; class OpenCypherDataSourceTest { private static MockOpenCypherDatabase database; private static String validEndpoint; private OpenCypherDataSource dataSource; /** * Function to get a random available port and initialize database before testing. */ @BeforeAll public static void initializeDatabase() { database = MockOpenCypherDatabase.builder("localhost", NeptuneDriverTestWithEncryption.class.getName()).build(); validEndpoint = String.format("bolt://%s:%d", "localhost", database.getPort()); } /** * Function to get a shutdown database after testing. */ @AfterAll public static void shutdownDatabase() { database.shutdown(); } @BeforeEach void initialize() throws SQLException { dataSource = new OpenCypherDataSource(); } @Test @Disabled void testGetConnectionSuccess() throws SQLException { dataSource.setEndpoint(validEndpoint); Assertions.assertTrue(dataSource.getConnection() instanceof OpenCypherConnection); Assertions.assertTrue(dataSource.getPooledConnection() instanceof OpenCypherPooledConnection); } @Test void testGetConnectionFailure() throws SQLException { HelperFunctions .expectFunctionThrows(SqlError.FEATURE_NOT_SUPPORTED, () -> dataSource.getConnection("name", "psw")); HelperFunctions.expectFunctionThrows(SqlError.FEATURE_NOT_SUPPORTED, () -> dataSource.getPooledConnection("name", "psw")); } @Test void testSupportedProperties() throws SQLException { Assertions.assertDoesNotThrow(() -> dataSource.setEndpoint(validEndpoint)); Assertions.assertEquals(validEndpoint, dataSource.getEndpoint()); Assertions.assertDoesNotThrow(() -> dataSource.setApplicationName("appName")); Assertions.assertEquals("appName", dataSource.getApplicationName()); Assertions.assertDoesNotThrow(() -> dataSource.setAuthScheme(AuthScheme.None)); Assertions.assertEquals(AuthScheme.None, dataSource.getAuthScheme()); Assertions.assertDoesNotThrow(() -> dataSource.setAwsCredentialsProviderClass("aws")); Assertions.assertEquals("aws", dataSource.getAwsCredentialsProviderClass()); Assertions.assertDoesNotThrow(() -> dataSource.setCustomCredentialsFilePath("path")); Assertions.assertEquals("path", dataSource.getCustomCredentialsFilePath()); Assertions.assertDoesNotThrow(() -> dataSource.setConnectionRetryCount(5)); Assertions.assertEquals(5, dataSource.getConnectionRetryCount()); Assertions.assertDoesNotThrow(() -> dataSource.setConnectionTimeoutMillis(1000)); Assertions.assertEquals(1000, dataSource.getConnectionTimeoutMillis()); Assertions.assertDoesNotThrow(() -> dataSource.setLoginTimeout(50)); Assertions.assertEquals(50, dataSource.getLoginTimeout()); Assertions.assertDoesNotThrow(() -> dataSource.setUseEncryption(true)); Assertions.assertEquals(true, dataSource.getUseEncryption()); } }
7,349
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/opencypher/OpenCypherPreparedStatementTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.opencypher; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import software.aws.neptune.NeptunePreparedStatementTestHelper; import software.aws.neptune.jdbc.utilities.AuthScheme; import software.aws.neptune.opencypher.mock.MockOpenCypherDatabase; import java.sql.SQLException; import java.util.Properties; // TODO AN-887: Fix query cancellation issue and enable tests. @Disabled public class OpenCypherPreparedStatementTest extends OpenCypherStatementTestBase { private static final String HOSTNAME = "localhost"; private static final Properties PROPERTIES = new Properties(); private static MockOpenCypherDatabase database; private NeptunePreparedStatementTestHelper neptunePreparedStatementTestHelper; /** * Function to get a random available port and initialize database before testing. */ @BeforeAll public static void initializeDatabase() throws SQLException { database = MockOpenCypherDatabase.builder(HOSTNAME, OpenCypherPreparedStatementTest.class.getName()).build(); PROPERTIES.put(OpenCypherConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.None); // reverse default to None PROPERTIES.putIfAbsent(OpenCypherConnectionProperties.ENDPOINT_KEY, String.format("bolt://%s:%d", HOSTNAME, database.getPort())); } /** * Function to get a shutdown database after testing. */ @AfterAll public static void shutdownDatabase() { database.shutdown(); } @BeforeEach void initialize() throws SQLException { final java.sql.Connection connection = new OpenCypherConnection(new OpenCypherConnectionProperties(PROPERTIES)); neptunePreparedStatementTestHelper = new NeptunePreparedStatementTestHelper(connection.prepareStatement(""), connection.prepareStatement(LONG_QUERY), connection.prepareStatement(QUICK_QUERY)); } @Test void testCancelQueryWithoutExecute() { neptunePreparedStatementTestHelper.testCancelQueryWithoutExecute(); } @Test void testCancelQueryWhileExecuteInProgress() { neptunePreparedStatementTestHelper.testCancelQueryWhileExecuteInProgress(); } @Test void testCancelQueryTwice() { // TODO: This is currently failing irrelevantly. Will fix later. // neptunePreparedStatementTestHelper.testCancelQueryTwice(); } @Test void testCancelQueryAfterExecuteComplete() { neptunePreparedStatementTestHelper.testCancelQueryAfterExecuteComplete(); } @Test void testMisc() { neptunePreparedStatementTestHelper.testMisc(); } @Test void testSet() { neptunePreparedStatementTestHelper.testSet(); } }
7,350
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/opencypher/OpenCypherStatementTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.opencypher; public class OpenCypherStatementTestBase { protected static final String QUICK_QUERY; protected static final String LONG_QUERY; protected static final int LONG_QUERY_NODE_COUNT = 1200; private static int currentIndex = 0; static { QUICK_QUERY = "CREATE (quick:Foo) RETURN quick"; final StringBuilder stringBuilder = new StringBuilder(); for (int i = currentIndex; i < (currentIndex + LONG_QUERY_NODE_COUNT); i++) { stringBuilder.append(String.format("CREATE (node%d:Foo) ", i)); } stringBuilder.append("RETURN "); for (int i = currentIndex; i < (currentIndex + LONG_QUERY_NODE_COUNT); i++) { if (i != currentIndex) { stringBuilder.append(", "); } stringBuilder.append(String.format("node%d", i)); } currentIndex += LONG_QUERY_NODE_COUNT; LONG_QUERY = stringBuilder.toString(); } }
7,351
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/opencypher/OpenCypherResultSetGetColumnsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.opencypher; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import software.aws.neptune.common.gremlindatamodel.resultset.ResultSetGetTables; import software.aws.neptune.jdbc.utilities.AuthScheme; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.Properties; public class OpenCypherResultSetGetColumnsTest { protected static final Properties PROPERTIES = new Properties(); private static final Map<String, Map<String, Map<String, Object>>> COLUMNS = new HashMap<>(); private static java.sql.Statement statement; static { COLUMNS.put(ResultSetGetTables.nodeListToString(ImmutableList.of("A", "B", "C")), ImmutableMap.of( "name", ImmutableMap.of( "dataType", "String", "isMultiValue", false, "isNullable", false), "email", ImmutableMap.of( "dataType", "String", "isMultiValue", false, "isNullable", false))); COLUMNS.put(ResultSetGetTables.nodeListToString(ImmutableList.of("A", "B", "C", "D")), ImmutableMap.of( "age", ImmutableMap.of( "dataType", "Integer", "isMultiValue", false, "isNullable", false), "email", ImmutableMap.of( "dataType", "String", "isMultiValue", false, "isNullable", false))); } /** * Function to initialize java.sql.Statement for use in tests. * * @throws SQLException Thrown if initialization fails. */ @BeforeAll public static void initialize() throws SQLException { PROPERTIES.put(OpenCypherConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.None); // reverse default to None // Make up fake endpoint since we aren't actually connection. PROPERTIES.putIfAbsent(OpenCypherConnectionProperties.ENDPOINT_KEY, String.format("bolt://%s:%d", "localhost", 123)); final java.sql.Connection connection = new OpenCypherConnection(new OpenCypherConnectionProperties(PROPERTIES)); statement = connection.createStatement(); } void verifyResultSet(final ResultSet resultSet) throws SQLException { Assertions.assertTrue(resultSet.next()); final int i = 1; do { Assertions.assertEquals("catalog", resultSet.getString(1)); Assertions.assertEquals("gremlin", resultSet.getString(2)); final String tableName = resultSet.getString(3); Assertions.assertTrue(COLUMNS.containsKey(tableName)); final Map<String, Map<String, Object>> columnNameInfo = COLUMNS.get(tableName); final String columnName = resultSet.getString(4); Assertions.assertTrue(columnNameInfo.containsKey(columnName)); final Map<String, Object> columnInfo = columnNameInfo.get(columnName); // TODO: validate JDBC type. (idx 5) Assertions.assertEquals(columnInfo.get("dataType"), resultSet.getString(6)); // TODO: Determine what to do with column size. (idx 7) Assertions.assertNull(resultSet.getString(8)); Assertions.assertNull(resultSet.getString(9)); Assertions.assertEquals(10, resultSet.getInt(10)); Assertions.assertEquals((Boolean) columnInfo.get("isNullable") ? DatabaseMetaData.columnNullable : DatabaseMetaData.columnNoNulls, resultSet.getInt(11)); Assertions.assertNull(resultSet.getString(12)); Assertions.assertNull(resultSet.getString(13)); Assertions.assertNull(resultSet.getString(14)); Assertions.assertNull(resultSet.getString(15)); if ("String".equals(resultSet.getString(6))) { Assertions.assertEquals(Integer.MAX_VALUE, resultSet.getInt(16)); } else { Assertions.assertEquals(0, resultSet.getInt(16)); Assertions.assertTrue(resultSet.wasNull()); } // Assertions.assertEquals(i++, resultSet.getInt(17)); TODO: Collect and make sure all come out. Assertions.assertEquals((Boolean) columnInfo.get("isNullable") ? "YES" : "NO", resultSet.getString(18)); Assertions.assertNull(resultSet.getString(19)); Assertions.assertNull(resultSet.getString(20)); Assertions.assertNull(resultSet.getString(21)); Assertions.assertNull(resultSet.getString(22)); Assertions.assertEquals("NO", resultSet.getString(23)); Assertions.assertEquals("NO", resultSet.getString(24)); } while (resultSet.next()); } }
7,352
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/opencypher/OpenCypherSignatureVerifier.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.opencypher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import picocli.CommandLine; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.Properties; import java.util.concurrent.Callable; /** * This class can be used to make a query to a real Neptune instance using IAM auth. * The query is not supposed to return any result, but if there is a problem with the * signature, an exception will be thrown. * <p> * 1. Run with the parameters --host and --region. If you're using SSH tunneling, * configure your environment as described in markdown/setup/configuration.md, * and include parameters --ssh-file and --ssh-host. * 2. Set environment variables AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and if using * temporary credentials, AWS_SESSION_TOKEN. * <p> * You can run this class without any parameters to see its usage. */ class OpenCypherSignatureVerifier implements Callable<Integer> { private static final Logger LOGGER = LoggerFactory.getLogger(OpenCypherSignatureVerifier.class); @CommandLine.Option(names = {"--host"}, description = "Neptune hostname") private String host; @CommandLine.Option(names = {"--region"}, description = "AWS region for Neptune cluster") private String region; @CommandLine.ArgGroup(exclusive = false, multiplicity = "0..1") private Ssh ssh; @Override public Integer call() { final String connString = String.format("jdbc:neptune:opencypher://bolt://%s:8182", host); try (Connection connection = DriverManager.getConnection(connString, connectionProperties())) { LOGGER.info("Connection created"); final Statement statement = connection.createStatement(); LOGGER.info("Statement created"); final String query = "match (n) where id(n) = '1' return n.prop"; final ResultSet results = statement.executeQuery(query); LOGGER.info("Statement executed"); while (results.next()) { LOGGER.info("Start result"); final String rd = results.getString(1); LOGGER.info(rd); LOGGER.info("End result"); } } catch (Exception e) { return 1; } return 0; } private Properties connectionProperties() { final Properties properties = new Properties(); properties.put("authScheme", "IAMSigV4"); properties.put("serviceRegion", region); properties.put("useEncryption", true); properties.put("LogLevel", "DEBUG"); if (ssh != null) { properties.put("sshUser", ssh.user); properties.put("sshHost", ssh.host); properties.put("sshPrivateKeyFile", ssh.privateKeyFile); } return properties; } private static class Ssh { @CommandLine.Option(names = {"--ssh-user"}, required = false, description = "username for the internal SSH tunnel") private String user = "ec2-user"; @CommandLine.Option(names = {"--ssh-host"}, description = "host name for the internal SSH tunnel") private String host; @CommandLine.Option(names = {"--ssh-file"}, description = "path to the private key file for the internal SSH tunnel") private String privateKeyFile; } public static void main(final String[] args) { final int exitCode = new CommandLine(new OpenCypherSignatureVerifier()).execute(args); System.exit(exitCode); } }
7,353
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/opencypher/OpenCypherStatementTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.opencypher; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import software.aws.neptune.NeptuneStatementTestHelper; import software.aws.neptune.jdbc.utilities.AuthScheme; import software.aws.neptune.opencypher.mock.MockOpenCypherDatabase; import java.sql.SQLException; import java.util.Properties; // TODO AN-887: Fix query cancellation issue and enable tests. @Disabled public class OpenCypherStatementTest extends OpenCypherStatementTestBase { protected static final String HOSTNAME = "localhost"; protected static final Properties PROPERTIES = new Properties(); private static MockOpenCypherDatabase database; private static NeptuneStatementTestHelper neptuneStatementTestHelper; /** * Function to get a random available port and initialize database before testing. */ @BeforeAll public static void initializeDatabase() throws SQLException { database = MockOpenCypherDatabase.builder(HOSTNAME, OpenCypherStatementTest.class.getName()).build(); PROPERTIES.put(OpenCypherConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.None); // reverse default to None PROPERTIES.putIfAbsent(OpenCypherConnectionProperties.ENDPOINT_KEY, String.format("bolt://%s:%d", HOSTNAME, database.getPort())); final java.sql.Connection connection = new OpenCypherConnection(new OpenCypherConnectionProperties(PROPERTIES)); neptuneStatementTestHelper = new NeptuneStatementTestHelper(connection.createStatement(), LONG_QUERY, QUICK_QUERY); } /** * Function to get a shutdown database after testing. */ @AfterAll public static void shutdownDatabase() { database.shutdown(); } @Test void testCancelQueryWithoutExecute() { neptuneStatementTestHelper.testCancelQueryWithoutExecute(); } @Test void testCancelQueryWhileExecuteInProgress() { neptuneStatementTestHelper.testCancelQueryWhileExecuteInProgress(); } @Test void testCancelQueryTwice() { neptuneStatementTestHelper.testCancelQueryTwice(); } @Test void testCancelQueryAfterExecuteComplete() { neptuneStatementTestHelper.testCancelQueryAfterExecuteComplete(); } }
7,354
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/opencypher/OpenCypherResultSetTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.opencypher; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.aws.neptune.jdbc.utilities.AuthScheme; import software.aws.neptune.opencypher.mock.MockOpenCypherDatabase; import java.sql.SQLException; import java.time.LocalDateTime; import java.util.Properties; public class OpenCypherResultSetTest { private static final String HOSTNAME = "localhost"; private static final Properties PROPERTIES = new Properties(); private static MockOpenCypherDatabase database; private static java.sql.Statement statement; /** * Function to get a random available port and initiaize database before testing. */ @BeforeAll public static void initializeDatabase() throws SQLException { database = MockOpenCypherDatabase.builder(HOSTNAME, OpenCypherResultSetTest.class.getName()).build(); PROPERTIES.put(OpenCypherConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.None); // reverse default to None PROPERTIES.putIfAbsent(OpenCypherConnectionProperties.ENDPOINT_KEY, String.format("bolt://%s:%d", HOSTNAME, database.getPort())); final java.sql.Connection connection = new OpenCypherConnection(new OpenCypherConnectionProperties(PROPERTIES)); statement = connection.createStatement(); } /** * Function to get a shutdown database after testing. */ @AfterAll public static void shutdownDatabase() { database.shutdown(); } @BeforeEach void initialize() throws SQLException { } // Primitive types. @Test void testNullType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery("RETURN null as x"); Assertions.assertTrue(resultSet.next()); Assertions.assertFalse(resultSet.getBoolean(1)); Assertions.assertTrue(resultSet.wasNull()); Assertions.assertEquals((byte) 0, resultSet.getByte(1)); Assertions.assertTrue(resultSet.wasNull()); Assertions.assertEquals((short) 0, resultSet.getShort(1)); Assertions.assertTrue(resultSet.wasNull()); Assertions.assertEquals(0, resultSet.getInt(1)); Assertions.assertTrue(resultSet.wasNull()); Assertions.assertEquals(0, resultSet.getLong(1)); Assertions.assertTrue(resultSet.wasNull()); Assertions.assertEquals(0.0f, resultSet.getFloat(1)); Assertions.assertTrue(resultSet.wasNull()); Assertions.assertEquals(0.0, resultSet.getDouble(1)); Assertions.assertTrue(resultSet.wasNull()); Assertions.assertNull(resultSet.getString(1)); Assertions.assertTrue(resultSet.wasNull()); Assertions.assertNull(resultSet.getDate(1)); Assertions.assertTrue(resultSet.wasNull()); Assertions.assertNull(resultSet.getTime(1)); Assertions.assertTrue(resultSet.wasNull()); Assertions.assertNull(resultSet.getTimestamp(1)); Assertions.assertTrue(resultSet.wasNull()); } @Test void testBooleanType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery("RETURN true as x"); Assertions.assertTrue(resultSet.next()); Assertions.assertTrue(resultSet.getBoolean(1)); Assertions.assertEquals(((Boolean) true).toString(), resultSet.getString(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getByte(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getShort(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getInt(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getLong(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDate(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTime(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTimestamp(1)); } @Test void testSimpleNumericType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery("RETURN 1 as x"); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(1L, resultSet.getLong(1)); Assertions.assertEquals(1, resultSet.getInt(1)); Assertions.assertEquals((short) 1, resultSet.getShort(1)); Assertions.assertEquals((byte) 1, resultSet.getByte(1)); Assertions.assertEquals(((Integer) 1).toString(), resultSet.getString(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDate(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTime(1).toLocalTime()); Assertions.assertThrows(SQLException.class, () -> resultSet.getTimestamp(1)); } @Test void testLargeNumericType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery("RETURN 4147483647 as x"); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(4147483647L, resultSet.getLong(1)); Assertions.assertEquals(0, resultSet.getInt(1)); Assertions.assertEquals(0, resultSet.getShort(1)); Assertions.assertEquals(0, resultSet.getByte(1)); Assertions.assertEquals(((Long) 4147483647L).toString(), resultSet.getString(1)); Assertions.assertThrows(java.sql.SQLException.class, () -> resultSet.getBoolean(1)); Assertions.assertThrows(java.sql.SQLException.class, () -> resultSet.getDate(1)); Assertions.assertThrows(java.sql.SQLException.class, () -> resultSet.getTime(1).toLocalTime()); Assertions.assertThrows(java.sql.SQLException.class, () -> resultSet.getTimestamp(1)); } @Test void testFloatingPointType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery("RETURN 1.0 as x"); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(1.0f, resultSet.getFloat(1)); Assertions.assertEquals(1.0, resultSet.getDouble(1)); Assertions.assertEquals((byte) 1.0, resultSet.getByte(1)); Assertions.assertEquals((short) 1.0, resultSet.getShort(1)); Assertions.assertEquals((int) 1.0, resultSet.getInt(1)); Assertions.assertEquals((long) 1.0, resultSet.getLong(1)); Assertions.assertEquals(((Double) 1.0).toString(), resultSet.getString(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDate(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTime(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTimestamp(1)); } @Test void testStringType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery("RETURN 'hello' as x"); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(resultSet.getString(1), "hello"); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getByte(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getShort(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getInt(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getLong(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getFloat(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDouble(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDate(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTime(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTimestamp(1)); } @Test void testNumericStringType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery("RETURN '1.0' as x"); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(resultSet.getString(1), "1.0"); Assertions.assertEquals(resultSet.getString(1), ((Double) 1.0).toString()); Assertions.assertThrows(SQLException.class, () -> resultSet.getByte(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getShort(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getFloat(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDouble(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getInt(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getLong(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDate(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTime(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTimestamp(1)); } // Composite types @Test void testArrayType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery("RETURN ['hello', 'world'] as x"); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals("[hello, world]", resultSet.getString(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getByte(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getShort(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getInt(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getLong(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getFloat(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDouble(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDate(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTime(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTimestamp(1)); } @Test void testMapType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery("RETURN ({hello:'world'}) as x"); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals("{hello=world}", resultSet.getString(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getByte(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getShort(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getInt(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getLong(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getFloat(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDouble(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDate(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTime(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTimestamp(1)); } @Test void testNodeType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery("CREATE (node:Foo {hello:'world'}) RETURN node"); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(String.format("(%s : %s)", "[Foo]", "{hello=world}"), resultSet.getString(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDate(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTime(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTimestamp(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getByte(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getShort(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getInt(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getLong(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getFloat(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDouble(1)); } @Test void testRelationshipType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery("CREATE (node1:Foo)-[rel:Rel {hello:'world'}]->(node2:Bar) RETURN rel"); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(String.format("[%s : %s]", "Rel", "{hello=world}"), resultSet.getString(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDate(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTime(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTimestamp(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getByte(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getShort(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getInt(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getLong(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getFloat(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDouble(1)); } @Test void testBiDirectionalPathType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery( "CREATE p=(lyn:Person { name:'Lyndon'})-[:WORKS {position:'developer'}]->(bqt:Company {product:'software'})<-[:WORKS {position:'developer'}]-(val:Person { name:'Valentina'}) RETURN p"); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(String.format("(%s)-[%s]->(%s)<-[%s]-(%s)", "[Person] : {name=Lyndon}", "WORKS : {position=developer}", "[Company] : {product=software}", "WORKS : {position=developer}", "[Person] : {name=Valentina}"), resultSet.getString(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDate(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTime(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTimestamp(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getByte(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getShort(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getInt(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getLong(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getFloat(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDouble(1)); } @Test void testReverseDirectionalPathType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery( "CREATE p=(node1:Foo)<-[rel:Rel]-(node2:Bar) RETURN p"); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(String.format("(%s)<-[%s]-(%s)", "[Foo] : {}", "Rel : {}", "[Bar] : {}"), resultSet.getString(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDate(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTime(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTimestamp(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getByte(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getShort(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getInt(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getLong(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getFloat(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDouble(1)); } @Test void testForwardDirectionalPathType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery( "CREATE p=(node1:Foo)-[rel:Rel]->(node2:Bar) RETURN p"); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(String.format("(%s)-[%s]->(%s)", "[Foo] : {}", "Rel : {}", "[Bar] : {}"), resultSet.getString(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDate(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTime(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTimestamp(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getByte(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getShort(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getInt(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getLong(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getFloat(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDouble(1)); } @Test void test2DPointType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery("RETURN point({ x:0, y:1 }) AS n"); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(String.format("(%f, %f)", 0f, 1f), resultSet.getString(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDate(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTime(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTimestamp(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getByte(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getShort(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getInt(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getLong(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getFloat(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDouble(1)); } @Test void test3DPointType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery("RETURN point({ x:0, y:1, z:2 }) AS n"); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(String.format("(%f, %f, %f)", 0f, 1f, 2f), resultSet.getString(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDate(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTime(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getTimestamp(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getByte(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getShort(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getInt(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getLong(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getFloat(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDouble(1)); } @Test void testDateType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery("RETURN date(\"1993-03-30\") AS n"); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(java.sql.Date.valueOf("1993-03-30"), resultSet.getDate(1)); Assertions.assertEquals(java.sql.Timestamp.valueOf(LocalDateTime.of(1993, 3, 30, 0, 0)), resultSet.getTimestamp(1)); Assertions.assertEquals(java.sql.Time.valueOf("00:00:00").toString(), resultSet.getTime(1).toString()); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getByte(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getShort(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getInt(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getLong(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getFloat(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDouble(1)); } @Test void testTimeType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery("RETURN time(\"12:10:10\") AS n"); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(java.sql.Time.valueOf("12:10:10"), resultSet.getTime(1)); Assertions.assertEquals(java.sql.Timestamp.valueOf(LocalDateTime.of(1970, 1, 1, 12, 10, 10)), resultSet.getTimestamp(1)); Assertions.assertEquals(java.sql.Time.valueOf("12:10:10").toString() + "Z", resultSet.getString(1)); Assertions.assertEquals(java.sql.Date.valueOf("1970-01-01").toString(), resultSet.getDate(1).toString()); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getByte(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getShort(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getInt(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getLong(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getFloat(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDouble(1)); } @Test void testLocalTimeType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery("RETURN localtime(\"12:10:10\") AS n"); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(java.sql.Time.valueOf("12:10:10"), resultSet.getTime(1)); Assertions.assertEquals(java.sql.Timestamp.valueOf(LocalDateTime.of(1970, 1, 1, 12, 10, 10)), resultSet.getTimestamp(1)); Assertions.assertEquals(java.sql.Time.valueOf("12:10:10").toString(), resultSet.getString(1)); Assertions.assertEquals(java.sql.Date.valueOf("1970-01-01").toString(), resultSet.getDate(1).toString()); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getByte(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getShort(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getInt(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getLong(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getFloat(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDouble(1)); } @Test void testDatetimeType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery("RETURN datetime(\"1993-03-30T12:10:10.000000225+0100\") AS n"); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals("1993-03-30T12:10:10.000000225+01:00", resultSet.getString(1)); Assertions.assertEquals(java.sql.Timestamp.valueOf(LocalDateTime.of(1993, 3, 30, 12, 10, 10, 225)).toString(), resultSet.getTimestamp(1).toString()); Assertions.assertEquals(java.sql.Date.valueOf("1993-03-30").toString(), resultSet.getDate(1).toString()); Assertions.assertEquals(java.sql.Time.valueOf("12:10:10").toString(), resultSet.getTime(1).toString()); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getByte(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getShort(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getInt(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getLong(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getFloat(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDouble(1)); } @Test void testLocalDatetimeType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery("RETURN localdatetime(\"1993-03-30T12:10:10.000000225\") AS n"); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals("1993-03-30T12:10:10.000000225", resultSet.getString(1)); Assertions.assertEquals(java.sql.Date.valueOf("1993-03-30").toString(), resultSet.getDate(1).toString()); Assertions.assertEquals(java.sql.Time.valueOf("12:10:10").toString(), resultSet.getTime(1).toString()); Assertions.assertEquals(java.sql.Timestamp.valueOf(LocalDateTime.of(1993, 3, 30, 12, 10, 10, 225)).toString(), resultSet.getTimestamp(1).toString()); Assertions.assertThrows(SQLException.class, () -> resultSet.getBoolean(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getByte(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getShort(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getInt(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getLong(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getFloat(1)); Assertions.assertThrows(SQLException.class, () -> resultSet.getDouble(1)); } @Test void testDurationType() throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery("RETURN duration(\"P5M1.5D\") as n"); Assertions.assertTrue(resultSet.next()); } }
7,355
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/opencypher/OpenCypherResultSetMetadataTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.opencypher; import com.google.common.collect.ImmutableList; import lombok.AllArgsConstructor; import lombok.Getter; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.neo4j.driver.internal.types.InternalTypeSystem; import software.aws.neptune.jdbc.utilities.AuthScheme; import software.aws.neptune.opencypher.mock.MockOpenCypherDatabase; import software.aws.neptune.opencypher.mock.OpenCypherQueryLiterals; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Types; import java.util.List; import java.util.Properties; public class OpenCypherResultSetMetadataTest { private static final String HOSTNAME = "localhost"; private static final Properties PROPERTIES = new Properties(); private static final List<MetadataTestHelper> METADATA_TEST_HELPER = ImmutableList.of( new MetadataTestHelper(OpenCypherQueryLiterals.NULL, 0, 0, 0, false, false, Types.NULL, Object.class.getTypeName(), InternalTypeSystem.TYPE_SYSTEM.NULL().name()), new MetadataTestHelper(OpenCypherQueryLiterals.POS_INTEGER, 20, 20, 0, false, true, java.sql.Types.BIGINT, Long.class.getTypeName(), InternalTypeSystem.TYPE_SYSTEM.INTEGER().name()), new MetadataTestHelper(OpenCypherQueryLiterals.NON_EMPTY_STRING, Integer.MAX_VALUE, Integer.MAX_VALUE, 0, true, false, java.sql.Types.VARCHAR, String.class.getTypeName(), InternalTypeSystem.TYPE_SYSTEM.STRING().name()), new MetadataTestHelper(OpenCypherQueryLiterals.TRUE, 1, 1, 0, false, false, java.sql.Types.BIT, Boolean.class.getTypeName(), InternalTypeSystem.TYPE_SYSTEM.BOOLEAN().name()), new MetadataTestHelper(OpenCypherQueryLiterals.POS_DOUBLE, 25, 15, 15, false, true, java.sql.Types.DOUBLE, Double.class.getTypeName(), InternalTypeSystem.TYPE_SYSTEM.FLOAT().name()), new MetadataTestHelper(OpenCypherQueryLiterals.NON_EMPTY_MAP, Integer.MAX_VALUE, Integer.MAX_VALUE, 0, true, false, java.sql.Types.VARCHAR, String.class.getTypeName(), InternalTypeSystem.TYPE_SYSTEM.MAP().name()), new MetadataTestHelper(OpenCypherQueryLiterals.NON_EMPTY_LIST, Integer.MAX_VALUE, Integer.MAX_VALUE, 0, true, false, java.sql.Types.VARCHAR, String.class.getTypeName(), InternalTypeSystem.TYPE_SYSTEM.LIST().name()), new MetadataTestHelper(OpenCypherQueryLiterals.DATE, 24, 24, 0, false, false, java.sql.Types.DATE, java.sql.Date.class.getTypeName(), InternalTypeSystem.TYPE_SYSTEM.DATE().name()), new MetadataTestHelper(OpenCypherQueryLiterals.TIME, 24, 24, 0, false, false, java.sql.Types.TIME, java.sql.Time.class.getTypeName(), InternalTypeSystem.TYPE_SYSTEM.TIME().name()), new MetadataTestHelper(OpenCypherQueryLiterals.LOCAL_TIME, 24, 24, 0, false, false, java.sql.Types.TIME, java.sql.Time.class.getTypeName(), InternalTypeSystem.TYPE_SYSTEM.LOCAL_TIME().name()), new MetadataTestHelper(OpenCypherQueryLiterals.DATE_TIME, 24, 24, 0, false, false, java.sql.Types.TIMESTAMP, java.sql.Timestamp.class.getTypeName(), InternalTypeSystem.TYPE_SYSTEM.DATE_TIME().name()), new MetadataTestHelper(OpenCypherQueryLiterals.LOCAL_DATE_TIME, 24, 24, 0, false, false, java.sql.Types.TIMESTAMP, java.sql.Timestamp.class.getTypeName(), InternalTypeSystem.TYPE_SYSTEM.LOCAL_DATE_TIME().name()), new MetadataTestHelper(OpenCypherQueryLiterals.DURATION, Integer.MAX_VALUE, Integer.MAX_VALUE, 0, true, false, java.sql.Types.VARCHAR, String.class.getTypeName(), InternalTypeSystem.TYPE_SYSTEM.DURATION().name()), new MetadataTestHelper(OpenCypherQueryLiterals.NODE, Integer.MAX_VALUE, Integer.MAX_VALUE, 0, true, false, java.sql.Types.VARCHAR, String.class.getTypeName(), InternalTypeSystem.TYPE_SYSTEM.NODE().name()), new MetadataTestHelper(OpenCypherQueryLiterals.RELATIONSHIP, Integer.MAX_VALUE, Integer.MAX_VALUE, 0, true, false, java.sql.Types.VARCHAR, String.class.getTypeName(), InternalTypeSystem.TYPE_SYSTEM.RELATIONSHIP().name()), new MetadataTestHelper(OpenCypherQueryLiterals.PATH, Integer.MAX_VALUE, Integer.MAX_VALUE, 0, true, false, java.sql.Types.VARCHAR, String.class.getTypeName(), InternalTypeSystem.TYPE_SYSTEM.PATH().name()), new MetadataTestHelper(OpenCypherQueryLiterals.POINT_2D, Integer.MAX_VALUE, Integer.MAX_VALUE, 0, true, false, java.sql.Types.VARCHAR, String.class.getTypeName(), InternalTypeSystem.TYPE_SYSTEM.POINT().name()), new MetadataTestHelper(OpenCypherQueryLiterals.POINT_3D, Integer.MAX_VALUE, Integer.MAX_VALUE, 0, true, false, java.sql.Types.VARCHAR, String.class.getTypeName(), InternalTypeSystem.TYPE_SYSTEM.POINT().name()) ); private static MockOpenCypherDatabase database; private static java.sql.Statement statement; /** * Function to get a random available port and initiaize database before testing. */ @BeforeAll public static void initializeDatabase() throws SQLException { database = MockOpenCypherDatabase.builder(HOSTNAME, OpenCypherResultSetMetadataTest.class.getName()).build(); PROPERTIES.put(OpenCypherConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.None); // reverse default to None PROPERTIES.putIfAbsent(OpenCypherConnectionProperties.ENDPOINT_KEY, String.format("bolt://%s:%d", HOSTNAME, database.getPort())); final java.sql.Connection connection = new OpenCypherConnection(new OpenCypherConnectionProperties(PROPERTIES)); statement = connection.createStatement(); } /** * Function to get a shutdown database after testing. */ @AfterAll public static void shutdownDatabase() { database.shutdown(); } ResultSetMetaData getResultSetMetaData(final String query) throws SQLException { final java.sql.ResultSet resultSet = statement.executeQuery(query); return resultSet.getMetaData(); } @Test void testGetColumnCount() throws SQLException { Assertions.assertEquals(1, getResultSetMetaData("MATCH (n) RETURN n").getColumnCount()); Assertions.assertEquals(1, getResultSetMetaData("RETURN true AS l1").getColumnCount()); Assertions.assertEquals(3, getResultSetMetaData("MATCH (n) RETURN n.foo, n.bar, n.baz").getColumnCount()); } @Test void testGetColumnDisplaySize() throws SQLException { for (final MetadataTestHelper helper : METADATA_TEST_HELPER) { Assertions.assertEquals(helper.getDisplaySize(), getResultSetMetaData(helper.getQuery()).getColumnDisplaySize(1), "For query: " + helper.getQuery()); } } @Test void testGetPrecision() throws SQLException { for (final MetadataTestHelper helper : METADATA_TEST_HELPER) { Assertions.assertEquals(helper.getPrecision(), getResultSetMetaData(helper.getQuery()).getPrecision(1), "For query: " + helper.getQuery()); } } @Test void testGetScale() throws SQLException { for (final MetadataTestHelper helper : METADATA_TEST_HELPER) { Assertions.assertEquals(helper.getScale(), getResultSetMetaData(helper.getQuery()).getScale(1), "For query: " + helper.getQuery()); } } @Test void testIsAutoIncrement() throws SQLException { Assertions.assertFalse(getResultSetMetaData("RETURN 'foo' as n").isAutoIncrement(1)); Assertions.assertFalse(getResultSetMetaData("RETURN 1 as n").isAutoIncrement(1)); } @Test void testIsCaseSensitive() throws SQLException { Assertions.assertTrue(getResultSetMetaData("RETURN 'foo' as n").isCaseSensitive(1)); Assertions.assertFalse(getResultSetMetaData("RETURN 1 as n").isCaseSensitive(1)); } @Test void testIsSearchable() throws SQLException { Assertions.assertFalse(getResultSetMetaData("RETURN 'foo' as n").isSearchable(1)); } @Test void testIsCurrency() throws SQLException { Assertions.assertFalse(getResultSetMetaData("RETURN 'foo' as n").isCurrency(1)); Assertions.assertFalse(getResultSetMetaData("RETURN 1 as n").isCurrency(1)); } @Test void testIsNullable() throws SQLException { Assertions.assertEquals(ResultSetMetaData.columnNullableUnknown, getResultSetMetaData("RETURN 'foo' as n").isNullable(1)); Assertions.assertEquals(ResultSetMetaData.columnNullableUnknown, getResultSetMetaData("RETURN 1 as n").isNullable(1)); Assertions.assertEquals(ResultSetMetaData.columnNullableUnknown, getResultSetMetaData("RETURN true as n").isNullable(1)); } @Test void testIsSigned() throws SQLException { for (final MetadataTestHelper helper : METADATA_TEST_HELPER) { Assertions.assertEquals(helper.isSigned(), getResultSetMetaData(helper.getQuery()).isSigned(1), "For query: " + helper.getQuery()); } } @Test void testGetColumnLabel() throws SQLException { Assertions.assertEquals("n", getResultSetMetaData("Return 1 as n").getColumnName(1)); } @Test void testGetColumnName() throws SQLException { Assertions.assertEquals("n", getResultSetMetaData("Return 1 as n").getColumnName(1)); } @Test void testGetColumnType() throws SQLException { for (final MetadataTestHelper helper : METADATA_TEST_HELPER) { Assertions.assertEquals(helper.getJdbcType(), getResultSetMetaData(helper.getQuery()).getColumnType(1), "For query: " + helper.getQuery()); } } @Test void testGetColumnTypeName() throws SQLException { for (final MetadataTestHelper helper : METADATA_TEST_HELPER) { Assertions.assertEquals(helper.getInternalColumnClassName(), getResultSetMetaData(helper.getQuery()).getColumnTypeName(1), "For query: " + helper.getQuery()); } } @Test void testGetColumnClassName() throws SQLException { for (final MetadataTestHelper helper : METADATA_TEST_HELPER) { Assertions.assertEquals(helper.getColumnClassName(), getResultSetMetaData(helper.getQuery()).getColumnClassName(1), "For query: " + helper.getQuery()); } } @Test void testIsReadOnly() throws SQLException { Assertions.assertTrue(getResultSetMetaData("RETURN 'foo' as n").isReadOnly(1)); } @Test void testIsWritable() throws SQLException { Assertions.assertFalse(getResultSetMetaData("RETURN 'foo' as n").isWritable(1)); } @Test void testIsDefinitelyWritable() throws SQLException { Assertions.assertFalse(getResultSetMetaData("RETURN 'foo' as n").isDefinitelyWritable(1)); } @Test void testGetTableName() throws SQLException { Assertions.assertEquals("", getResultSetMetaData("RETURN 'foo' as n").getTableName(1)); } @Test void testGetSchemaName() throws SQLException { Assertions.assertEquals("", getResultSetMetaData("RETURN 'foo' as n").getSchemaName(1)); } @Test void testGetCatalogName() throws SQLException { Assertions.assertEquals("", getResultSetMetaData("RETURN 'foo' as n").getCatalogName(1)); } @AllArgsConstructor @Getter static class MetadataTestHelper { private final String query; private final int displaySize; private final int precision; private final int scale; private final boolean caseSensitive; private final boolean signed; private final int jdbcType; private final String columnClassName; private final String internalColumnClassName; } }
7,356
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/opencypher/OpenCypherManualNeptuneVerificationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.opencypher; import org.junit.Assert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import software.aws.neptune.jdbc.utilities.AuthScheme; import software.aws.neptune.opencypher.utilities.OpenCypherGetColumnUtilities; import java.sql.SQLException; import java.util.Properties; import static software.aws.neptune.jdbc.utilities.ConnectionProperties.SSH_HOSTNAME; import static software.aws.neptune.jdbc.utilities.ConnectionProperties.SSH_PRIVATE_KEY_FILE; import static software.aws.neptune.jdbc.utilities.ConnectionProperties.SSH_STRICT_HOST_KEY_CHECKING; import static software.aws.neptune.jdbc.utilities.ConnectionProperties.SSH_USER; @Disabled public class OpenCypherManualNeptuneVerificationTest { private static final String HOSTNAME = "database-1.cluster-cdffsmv2nzf7.us-east-2.neptune.amazonaws.com"; private static final Properties PROPERTIES = new Properties(); private static final String CREATE_NODES; private static java.sql.Connection connection; private static java.sql.DatabaseMetaData databaseMetaData; static { CREATE_NODES = String.format("CREATE (:%s %s)", "Person:Developer", "{hello:'world'}") + String.format(" CREATE (:%s %s)", "Person", "{person:1234}") + String.format(" CREATE (:%s %s)", "Human", "{hello:'world'}") + String.format(" CREATE (:%s %s)", "Human", "{hello:123}") + String.format(" CREATE (:%s %s)", "Developer", "{hello:123}") + // String.format(" CREATE (:%s %s)", "Person", "{person:'1234'}") + String.format(" CREATE (:%s %s)", "Person", "{p1:true}") + String.format(" CREATE (:%s %s)", "Person", "{p1:1.0}") + " CREATE (:Foo {foo:'foo'})-[:Rel {rel:'rel'}]->(:Bar {bar:'bar'})"; } @BeforeAll static void initialize() throws SQLException { final String endpoint = String.format("bolt://%s:%d", HOSTNAME, 8182); PROPERTIES.put(SSH_USER, "ec2-user"); PROPERTIES.put(SSH_HOSTNAME, "52.14.185.245"); PROPERTIES.put(SSH_PRIVATE_KEY_FILE, "~/Downloads/EC2/neptune-test.pem"); PROPERTIES.put(SSH_STRICT_HOST_KEY_CHECKING, "false"); PROPERTIES.put(OpenCypherConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.None); // reverse default to None PROPERTIES.putIfAbsent(OpenCypherConnectionProperties.ENDPOINT_KEY, endpoint); connection = new OpenCypherConnection(new OpenCypherConnectionProperties(PROPERTIES)); final java.sql.Statement statement = connection.createStatement(); statement.execute(CREATE_NODES); databaseMetaData = connection.getMetaData(); } @Disabled @Test void testGetColumns() throws SQLException { Assert.assertTrue(connection.isValid(1)); final java.sql.ResultSet resultSet = databaseMetaData.getColumns(null, null, null, null); Assertions.assertTrue(resultSet.next()); do { for (final String columnName : OpenCypherGetColumnUtilities.COLUMN_NAMES) { System.out.println(columnName + " - " + resultSet.getString(columnName)); } } while (resultSet.next()); } @Disabled @Test void testGetColumnsHuman() throws SQLException { final java.sql.ResultSet resultSet = databaseMetaData.getColumns(null, null, "Human", null); Assertions.assertTrue(resultSet.next()); do { for (final String columnName : OpenCypherGetColumnUtilities.COLUMN_NAMES) { System.out.println(columnName + " - " + resultSet.getString(columnName)); } } while (resultSet.next()); } @Disabled @Test void testGetColumnsHumanDeveloper() throws SQLException { final java.sql.ResultSet resultSet = databaseMetaData.getColumns(null, null, "Human:Developer", null); Assertions.assertFalse(resultSet.next()); } @Disabled @Test void testIsValid() throws SQLException { Assertions.assertTrue(connection.isValid(1)); } }
7,357
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/opencypher/OpenCypherConnectionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.opencypher; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.aws.neptune.jdbc.Driver; import software.aws.neptune.jdbc.helpers.HelperFunctions; import software.aws.neptune.jdbc.utilities.AuthScheme; import software.aws.neptune.jdbc.utilities.ConnectionProperties; import software.aws.neptune.jdbc.utilities.SqlError; import software.aws.neptune.opencypher.mock.MockOpenCypherDatabase; import software.aws.neptune.opencypher.mock.MockOpenCypherNodes; import software.aws.neptune.opencypher.resultset.OpenCypherResultSet; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; import java.util.concurrent.atomic.AtomicReference; public class OpenCypherConnectionTest { private static final String HOSTNAME = "localhost"; private static final String QUERY = "MATCH (p1:Person)-[:KNOWS]->(p2:Person)-[:GIVES_PETS_TO]->(k:Kitty) WHERE k.name = 'tootsie' RETURN p1, p2, k"; private static final Properties PROPERTIES = new Properties(); private static final String TEST_PROP_KEY_UNSUPPORTED = "unsupported"; private static final String TEST_PROP_VAL_UNSUPPORTED = "unsupported"; private static final String TEST_PROP_KEY = "connectionTimeout"; private static final String TEST_PROP_VAL = "1"; private static final Properties TEST_PROP = new Properties(); private static final Properties TEST_PROP_INITIAL = new Properties(); private static final Properties TEST_PROP_MODIFIED = new Properties(); private static MockOpenCypherDatabase database; private java.sql.Connection connection; /** * Function to get a random available port and initialize database before testing. */ @BeforeAll public static void initializeDatabase() { database = MockOpenCypherDatabase.builder(HOSTNAME, OpenCypherConnectionTest.class.getName()) .withNode(MockOpenCypherNodes.LYNDON) .withNode(MockOpenCypherNodes.VALENTINA) .withNode(MockOpenCypherNodes.VINNY) .withNode(MockOpenCypherNodes.TOOTSIE) .withRelationship(MockOpenCypherNodes.LYNDON, MockOpenCypherNodes.VALENTINA, "KNOWS", "KNOWS") .withRelationship(MockOpenCypherNodes.LYNDON, MockOpenCypherNodes.VINNY, "GIVES_PETS_TO", "GETS_PETS_FROM") .withRelationship(MockOpenCypherNodes.VALENTINA, MockOpenCypherNodes.TOOTSIE, "GIVES_PETS_TO", "GETS_PETS_FROM") .build(); PROPERTIES.putIfAbsent(OpenCypherConnectionProperties.ENDPOINT_KEY, String.format("bolt://%s:%d", HOSTNAME, database.getPort())); } /** * Function to get a shutdown database after testing. */ @AfterAll public static void shutdownDatabase() { database.shutdown(); } @BeforeEach void initialize() throws SQLException { PROPERTIES.put(ConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.None); // set default to None connection = new OpenCypherConnection(new OpenCypherConnectionProperties(PROPERTIES)); TEST_PROP.put(TEST_PROP_KEY, TEST_PROP_VAL); TEST_PROP_INITIAL.put(ConnectionProperties.APPLICATION_NAME_KEY, Driver.APPLICATION_NAME); TEST_PROP_INITIAL.putAll(ConnectionProperties.DEFAULT_PROPERTIES_MAP); TEST_PROP_INITIAL.putAll(OpenCypherConnectionProperties.DEFAULT_PROPERTIES_MAP); TEST_PROP_INITIAL.putAll(PROPERTIES); TEST_PROP_MODIFIED.putAll(TEST_PROP_INITIAL); TEST_PROP_MODIFIED.remove(TEST_PROP_KEY); } @Test void testOpenCypherConnectionPrepareStatementType() { final AtomicReference<PreparedStatement> statement = new AtomicReference<>(); Assertions.assertDoesNotThrow(() -> statement.set(connection.prepareStatement(QUERY))); Assertions.assertTrue(statement.get() instanceof software.aws.neptune.jdbc.PreparedStatement); final AtomicReference<ResultSet> openCypherResultSet = new AtomicReference<>(); Assertions.assertDoesNotThrow(() -> openCypherResultSet.set(statement.get().executeQuery())); Assertions.assertTrue(openCypherResultSet.get() instanceof OpenCypherResultSet); } @Test void testOpenCypherConnectionStatementType() { final AtomicReference<Statement> statement = new AtomicReference<>(); Assertions.assertDoesNotThrow(() -> statement.set(connection.createStatement())); Assertions.assertTrue(statement.get() instanceof software.aws.neptune.jdbc.Statement); final AtomicReference<ResultSet> openCypherResultSet = new AtomicReference<>(); Assertions.assertDoesNotThrow(() -> openCypherResultSet.set(statement.get().executeQuery(QUERY))); Assertions.assertTrue(openCypherResultSet.get() instanceof OpenCypherResultSet); } @Test void testClientInfo() { HelperFunctions.expectFunctionDoesntThrow(() -> connection.getClientInfo(), TEST_PROP_INITIAL); HelperFunctions.expectFunctionDoesntThrow(() -> connection.setClientInfo(null)); HelperFunctions.expectFunctionDoesntThrow(() -> connection.getClientInfo(null), null); HelperFunctions.expectFunctionDoesntThrow(() -> connection.getClientInfo(), TEST_PROP_INITIAL); HelperFunctions.expectFunctionDoesntThrow(() -> connection.getClientInfo(), TEST_PROP_INITIAL); HelperFunctions.expectFunctionDoesntThrow(() -> connection.setClientInfo(TEST_PROP_KEY, TEST_PROP_VAL)); HelperFunctions.expectFunctionDoesntThrow(() -> connection.getClientInfo(TEST_PROP_KEY), TEST_PROP_VAL); HelperFunctions.expectFunctionDoesntThrow(() -> connection.setClientInfo(TEST_PROP_KEY, "")); HelperFunctions.expectFunctionDoesntThrow(() -> connection.getClientInfo(), TEST_PROP_INITIAL); HelperFunctions.expectFunctionDoesntThrow(() -> connection.setClientInfo(TEST_PROP)); HelperFunctions.expectFunctionDoesntThrow(() -> connection.getClientInfo(TEST_PROP_KEY), TEST_PROP_VAL); HelperFunctions.expectFunctionDoesntThrow(() -> connection.setClientInfo(TEST_PROP_KEY, null)); HelperFunctions.expectFunctionDoesntThrow(() -> connection.getClientInfo(), TEST_PROP_MODIFIED); HelperFunctions.expectFunctionThrows( SqlError.lookup(SqlError.INVALID_CONNECTION_PROPERTY, TEST_PROP_KEY_UNSUPPORTED, ""), () -> connection.setClientInfo(TEST_PROP_KEY_UNSUPPORTED, "")); HelperFunctions.expectFunctionThrows( SqlError.lookup(SqlError.INVALID_CONNECTION_PROPERTY, TEST_PROP_KEY, TEST_PROP_VAL_UNSUPPORTED), () -> connection.setClientInfo(TEST_PROP_KEY, TEST_PROP_VAL_UNSUPPORTED)); HelperFunctions.expectFunctionDoesntThrow(() -> connection.close()); HelperFunctions.expectFunctionThrows( SqlError.CONN_CLOSED, () -> connection.setClientInfo(TEST_PROP_KEY, TEST_PROP_VAL)); HelperFunctions.expectFunctionThrows( SqlError.CONN_CLOSED, () -> connection.setClientInfo(TEST_PROP)); } }
7,358
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/opencypher/OpenCypherConnectionPropertiesTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.opencypher; import com.google.common.collect.ImmutableList; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import software.aws.neptune.ConnectionPropertiesTestBase; import software.aws.neptune.jdbc.utilities.AuthScheme; import software.aws.neptune.jdbc.utilities.ConnectionProperties; import java.sql.SQLClientInfoException; import java.sql.SQLException; import java.util.Properties; /** * Test for OpenCypherConnectionProperties. */ class OpenCypherConnectionPropertiesTest extends ConnectionPropertiesTestBase { private OpenCypherConnectionProperties connectionProperties; protected void assertDoesNotThrowOnNewConnectionProperties(final Properties properties) { Assertions.assertDoesNotThrow(() -> { // Since we have added the check for service region and IAMSigV4 is set by default, we need to add a mock // region property here in case the system running these tests does not have SERVICE_REGION variable set. properties.put("serviceRegion", "mock-region"); connectionProperties = new OpenCypherConnectionProperties(properties); }); } protected void assertThrowsOnNewConnectionProperties(final Properties properties) { Assertions.assertThrows(SQLException.class, () -> connectionProperties = new OpenCypherConnectionProperties(properties)); } protected <T> void assertPropertyValueEqualsToExpected(final String key, final T expectedValue) { Assertions.assertEquals(expectedValue, connectionProperties.get(key)); } @Test void testDefaultValues() throws SQLException { connectionProperties = new OpenCypherConnectionProperties(); Assertions.assertEquals("", connectionProperties.getEndpoint()); Assertions.assertEquals(OpenCypherConnectionProperties.DEFAULT_CONNECTION_TIMEOUT_MILLIS, connectionProperties.getConnectionTimeoutMillis()); Assertions.assertEquals(OpenCypherConnectionProperties.DEFAULT_CONNECTION_RETRY_COUNT, connectionProperties.getConnectionRetryCount()); Assertions.assertEquals(OpenCypherConnectionProperties.DEFAULT_CONNECTION_POOL_SIZE, connectionProperties.getConnectionPoolSize()); Assertions .assertEquals(OpenCypherConnectionProperties.DEFAULT_AUTH_SCHEME, connectionProperties.getAuthScheme()); Assertions.assertEquals(OpenCypherConnectionProperties.DEFAULT_USE_ENCRYPTION, connectionProperties.getUseEncryption()); Assertions.assertEquals(OpenCypherConnectionProperties.DEFAULT_SERVICE_REGION, connectionProperties.getServiceRegion()); } @Test void testApplicationName() throws SQLException { testStringPropertyViaConstructor( OpenCypherConnectionProperties.APPLICATION_NAME_KEY); final String testValue = "test application name"; connectionProperties = new OpenCypherConnectionProperties(); connectionProperties.setApplicationName(testValue); Assertions.assertEquals(testValue, connectionProperties.getApplicationName()); } @Test void testEndpoint() throws SQLException { testStringPropertyViaConstructor( OpenCypherConnectionProperties.ENDPOINT_KEY, DEFAULT_EMPTY_STRING); final String testValue = "test endpoint"; connectionProperties = new OpenCypherConnectionProperties(); connectionProperties.setEndpoint(testValue); Assertions.assertEquals(testValue, connectionProperties.getEndpoint()); } @Test void testRegion() throws SQLException { final Properties initProperties = new Properties(); initProperties.put(ConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.None); // reset to None assertDoesNotThrowOnNewConnectionProperties(initProperties); final String testValue = "test region"; connectionProperties.setServiceRegion(testValue); Assertions.assertEquals(testValue, connectionProperties.getServiceRegion()); connectionProperties.setServiceRegion("us-east-1"); Assertions.assertEquals("us-east-1", connectionProperties.getServiceRegion()); } @Test void testAwsCredentialsProviderClass() throws SQLException { testStringPropertyViaConstructor( OpenCypherConnectionProperties.AWS_CREDENTIALS_PROVIDER_CLASS_KEY); connectionProperties = new OpenCypherConnectionProperties(); final String testValue = "test AwsCredentialsProviderClass"; connectionProperties.setAwsCredentialsProviderClass(testValue); Assertions.assertEquals(testValue, connectionProperties.getAwsCredentialsProviderClass()); } @Test void testCustomCredentialsFilePath() throws SQLException { testStringPropertyViaConstructor( OpenCypherConnectionProperties.CUSTOM_CREDENTIALS_FILE_PATH_KEY); connectionProperties = new OpenCypherConnectionProperties(); final String testValue = "test CustomCredentialsFilePath"; connectionProperties.setCustomCredentialsFilePath(testValue); Assertions.assertEquals(testValue, connectionProperties.getCustomCredentialsFilePath()); } @Test void testConnectionTimeout() throws SQLException { testIntegerPropertyViaConstructor( OpenCypherConnectionProperties.CONNECTION_TIMEOUT_MILLIS_KEY, OpenCypherConnectionProperties.DEFAULT_CONNECTION_TIMEOUT_MILLIS); connectionProperties = new OpenCypherConnectionProperties(); connectionProperties.setConnectionTimeoutMillis(10); Assertions.assertEquals(10, connectionProperties.getConnectionTimeoutMillis()); } @Test void testConnectionRetryCount() throws SQLException { testIntegerPropertyViaConstructor( OpenCypherConnectionProperties.CONNECTION_RETRY_COUNT_KEY, OpenCypherConnectionProperties.DEFAULT_CONNECTION_RETRY_COUNT); connectionProperties = new OpenCypherConnectionProperties(); connectionProperties.setConnectionRetryCount(10); Assertions.assertEquals(10, connectionProperties.getConnectionRetryCount()); } @Test void testConnectionPoolSize() throws SQLException { testIntegerPropertyViaConstructor( OpenCypherConnectionProperties.CONNECTION_POOL_SIZE_KEY, OpenCypherConnectionProperties.DEFAULT_CONNECTION_POOL_SIZE); connectionProperties = new OpenCypherConnectionProperties(); connectionProperties.setConnectionPoolSize(10); Assertions.assertEquals(10, connectionProperties.getConnectionPoolSize()); } @Test void testAuthScheme() throws SQLException { testAuthSchemeViaConstructor(); connectionProperties = new OpenCypherConnectionProperties(); connectionProperties.setAuthScheme(AuthScheme.None); Assertions.assertEquals(AuthScheme.None, connectionProperties.getAuthScheme()); } @Test void testUseEncryption() throws SQLException { Properties properties = new Properties(); properties.put(ConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.None); // reset to None testBooleanPropertyViaConstructor( properties, OpenCypherConnectionProperties.USE_ENCRYPTION_KEY, OpenCypherConnectionProperties.DEFAULT_USE_ENCRYPTION); // new set of properties properties = new Properties(); properties.put(ConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.None); // reset to None properties.put("serviceRegion", "mock-region"); assertDoesNotThrowOnNewConnectionProperties(properties); final ImmutableList<Boolean> boolValues = ImmutableList.of(true, false); for (final Boolean boolValue : boolValues) { connectionProperties.setUseEncryption(boolValue); Assertions.assertEquals(boolValue, connectionProperties.getUseEncryption()); } } @Test void testDisableEncryptionWithIAMSigV4() throws SQLException { final Properties properties = new Properties(); properties.put("authScheme", "IAMSigV4"); properties.put("useEncryption", true); properties.put("serviceRegion", "mock-region"); connectionProperties = new OpenCypherConnectionProperties(properties); Assertions.assertTrue(connectionProperties.getUseEncryption()); Assertions.assertEquals(connectionProperties.getAuthScheme(), AuthScheme.IAMSigV4); Assertions.assertThrows(SQLClientInfoException.class, () -> connectionProperties.setUseEncryption(false)); Assertions.assertDoesNotThrow(() -> connectionProperties.setAuthScheme(AuthScheme.None)); Assertions.assertDoesNotThrow(() -> connectionProperties.setUseEncryption(false)); } @Test void testEnableIAMSigV4WithoutEncrpytion() throws SQLException { final Properties properties = new Properties(); properties.put("authScheme", "None"); properties.put("useEncryption", false); connectionProperties = new OpenCypherConnectionProperties(properties); Assertions.assertFalse(connectionProperties.getUseEncryption()); Assertions.assertEquals(connectionProperties.getAuthScheme(), AuthScheme.None); Assertions.assertThrows(SQLClientInfoException.class, () -> connectionProperties.setAuthScheme(AuthScheme.IAMSigV4)); Assertions.assertDoesNotThrow(() -> connectionProperties.setUseEncryption(true)); Assertions.assertDoesNotThrow(() -> connectionProperties.setAuthScheme(AuthScheme.IAMSigV4)); } }
7,359
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/opencypher/OpenCypherIAMRequestGeneratorTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.opencypher; import com.amazonaws.http.HttpMethodName; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.neo4j.driver.AuthToken; import org.neo4j.driver.Value; import org.neo4j.driver.internal.security.InternalAuthToken; import java.lang.reflect.Type; import java.net.URI; import java.time.Duration; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.amazonaws.auth.internal.SignerConstants.AUTHORIZATION; import static com.amazonaws.auth.internal.SignerConstants.HOST; import static com.amazonaws.auth.internal.SignerConstants.X_AMZ_DATE; import static com.amazonaws.auth.internal.SignerConstants.X_AMZ_SECURITY_TOKEN; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.neo4j.driver.Values.value; import static org.neo4j.driver.internal.security.InternalAuthToken.CREDENTIALS_KEY; import static org.neo4j.driver.internal.security.InternalAuthToken.PRINCIPAL_KEY; import static org.neo4j.driver.internal.security.InternalAuthToken.REALM_KEY; import static org.neo4j.driver.internal.security.InternalAuthToken.SCHEME_KEY; import static software.aws.neptune.opencypher.OpenCypherIAMRequestGenerator.DUMMY_USERNAME; import static software.aws.neptune.opencypher.OpenCypherIAMRequestGenerator.HTTP_METHOD_HDR; import static software.aws.neptune.opencypher.OpenCypherIAMRequestGenerator.SERVICE_NAME; class OpenCypherIAMRequestGeneratorTest { private static final String DUMMY_ACCESS_KEY_ID = "xxx"; private static final String DUMMY_SESSION_TOKEN = "zzz"; @BeforeAll public static void beforeAll() { System.setProperty("aws.accessKeyId", DUMMY_ACCESS_KEY_ID); System.setProperty("aws.secretKey", "yyy"); } @AfterAll public static void afterAll() { System.clearProperty("aws.accessKeyId"); System.clearProperty("aws.secretKey"); } @AfterEach public void afterEach() { System.clearProperty("aws.sessionToken"); } @Test public void testCreateAuthToken() { verifyAuthToken(false); } @Test public void testCreateAuthTokenWithTempCreds() { System.setProperty("aws.sessionToken", DUMMY_SESSION_TOKEN); verifyAuthToken(true); } private void verifyAuthToken(final boolean useTempCreds) { final String url = "bolt://somehost.com:58763"; final String region = "us-west-2"; final AuthToken authToken = OpenCypherIAMRequestGenerator.createAuthToken(url, region); assertTrue(authToken instanceof InternalAuthToken); final Map<String, Value> internalAuthToken = ((InternalAuthToken) authToken).toMap(); assertEquals(value("basic"), internalAuthToken.get(SCHEME_KEY)); assertEquals(value(DUMMY_USERNAME), internalAuthToken.get(PRINCIPAL_KEY)); assertFalse(internalAuthToken.containsKey(REALM_KEY)); assertTrue(internalAuthToken.containsKey(CREDENTIALS_KEY)); final Value credentialsValue = internalAuthToken.get(CREDENTIALS_KEY); final Type type = new TypeToken<Map<String, String>>() { }.getType(); final Map<String, String> credentials = new Gson().fromJson(credentialsValue.asString(), type); assertNotNull(credentials.get(X_AMZ_DATE)); final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX"); final ZonedDateTime xAmzDate = ZonedDateTime.parse(credentials.get(X_AMZ_DATE), formatter); final ZonedDateTime refDateTime = ZonedDateTime.now(ZoneOffset.UTC); final long dateTimeDiff = Duration.between(xAmzDate, refDateTime).getSeconds(); assertTrue(dateTimeDiff >= 0 && dateTimeDiff < 60); final URI uri = URI.create(url); assertEquals(String.format("%s:%d", uri.getHost(), uri.getPort()), credentials.get(HOST)); assertEquals(HttpMethodName.GET.name(), credentials.get(HTTP_METHOD_HDR)); assertEquals(useTempCreds ? DUMMY_SESSION_TOKEN : null, credentials.get(X_AMZ_SECURITY_TOKEN)); final String auth = credentials.get(AUTHORIZATION); assertNotNull(auth); assertTrue(auth.startsWith("AWS4-HMAC-SHA256")); final Pattern pattern = Pattern.compile("([^,\\s]+)=([^,\\s]+)"); final Matcher matcher = pattern.matcher(auth); final Map<String, String> keyValues = new HashMap<>(); while (matcher.find()) { assertEquals(2, matcher.groupCount()); final String key = matcher.group(1); final String value = matcher.group(2); keyValues.put(key, value); } assertNotNull(keyValues.get("Signature")); assertEquals( String.format( "%s/%s/%s/%s/aws4_request", DUMMY_ACCESS_KEY_ID, DateTimeFormatter.ofPattern("yyyyMMdd").format(refDateTime), region, SERVICE_NAME ), keyValues.get("Credential") ); final String signedHeaders = keyValues.get("SignedHeaders"); assertNotNull(signedHeaders); final List<String> headers = Arrays.asList(signedHeaders.split(";")); assertTrue(headers.contains(HOST.toLowerCase())); assertTrue(headers.contains(X_AMZ_DATE.toLowerCase())); assertEquals(useTempCreds, headers.contains(X_AMZ_SECURITY_TOKEN.toLowerCase())); } }
7,360
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/opencypher/OpenCypherDatabaseMetadataTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.opencypher; import com.google.common.collect.ImmutableSet; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import software.aws.neptune.jdbc.utilities.AuthScheme; import software.aws.neptune.opencypher.mock.MockOpenCypherDatabase; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.Arrays; import java.util.HashSet; import java.util.Properties; import java.util.Set; public class OpenCypherDatabaseMetadataTest { private static final String HOSTNAME = "localhost"; private static final Properties PROPERTIES = new Properties(); private static final Set<Set<String>> GET_TABLES_NODE_SET = ImmutableSet.of( ImmutableSet.of("Person"), ImmutableSet.of("Person", "Developer"), ImmutableSet.of("Person", "Human"), ImmutableSet.of("Person", "Developer", "Human"), ImmutableSet.of("Human", "Developer"), ImmutableSet.of("Dog"), ImmutableSet.of("Cat")); private static final Set<Set<String>> GET_TABLES_PERSON_NODE_SET = ImmutableSet.of( ImmutableSet.of("Person"), ImmutableSet.of("Person", "Developer"), ImmutableSet.of("Person", "Human"), ImmutableSet.of("Person", "Developer", "Human")); private static final String CREATE_NODES; private static final Set<String> GET_TABLES_NULL_SET = ImmutableSet.of( "TABLE_CAT", "TABLE_SCHEM", "TYPE_CAT", "TYPE_SCHEM", "TYPE_NAME", "SELF_REFERENCING_COL_NAME", "REF_GENERATION"); private static MockOpenCypherDatabase database; private static java.sql.DatabaseMetaData databaseMetaData; static { final StringBuilder stringBuilder = new StringBuilder(); GET_TABLES_NODE_SET.forEach(n -> stringBuilder.append(String.format(" CREATE (:%s {})", String.join(":", n)))); CREATE_NODES = stringBuilder.replace(0, 1, "").toString(); } /** * Function to get a random available port and initialize database before testing. */ @BeforeAll public static void initializeDatabase() throws SQLException { database = MockOpenCypherDatabase.builder(HOSTNAME, OpenCypherDatabaseMetadataTest.class.getName()).build(); PROPERTIES.put(OpenCypherConnectionProperties.AUTH_SCHEME_KEY, AuthScheme.None); // reverse default to None PROPERTIES.putIfAbsent(OpenCypherConnectionProperties.ENDPOINT_KEY, String.format("bolt://%s:%d", HOSTNAME, database.getPort())); final java.sql.Connection connection = new OpenCypherConnection(new OpenCypherConnectionProperties(PROPERTIES)); final java.sql.Statement statement = connection.createStatement(); statement.execute(CREATE_NODES); databaseMetaData = connection.getMetaData(); } /** * Function to get a shutdown database after testing. */ @AfterAll public static void shutdownDatabase() { database.shutdown(); } @Disabled @Test void testGetTables() throws SQLException { final java.sql.ResultSet resultSet = databaseMetaData.getTables(null, null, null, null); Assertions.assertTrue(resultSet.next()); final ResultSetMetaData metaData = resultSet.getMetaData(); final int columnCount = metaData.getColumnCount(); final Set<Set<String>> expectedTables = new HashSet<>(GET_TABLES_NODE_SET); do { for (int i = 1; i <= columnCount; i++) { final String columnName = metaData.getColumnName(i); if (GET_TABLES_NULL_SET.contains(columnName)) { Assertions.assertNull(resultSet.getString(i)); } else if ("TABLE_NAME".equals(columnName)) { final Set<String> labels = new HashSet<>(Arrays.asList(resultSet.getString(i).split(":"))); Assertions.assertTrue(expectedTables.contains(labels), String.format("Table name set '%s' is not in the expected tables set.", labels.toString())); expectedTables.remove(labels); } else if ("TABLE_TYPE".equals(columnName)) { Assertions.assertEquals("TABLE", resultSet.getString(i)); } else if ("REMARKS".equals(columnName)) { Assertions.assertEquals("", resultSet.getString(i)); } else { Assertions.fail( String.format("Unexpected column name '%s' encountered for table metadata.", columnName)); } } } while (resultSet.next()); } @Disabled @Test void testGetTablesPersonOnly() throws SQLException { final java.sql.ResultSet resultSet = databaseMetaData.getTables(null, null, "Person", null); Assertions.assertTrue(resultSet.next()); final ResultSetMetaData metaData = resultSet.getMetaData(); final int columnCount = metaData.getColumnCount(); final Set<Set<String>> expectedTables = new HashSet<>(GET_TABLES_PERSON_NODE_SET); do { for (int i = 1; i <= columnCount; i++) { final String columnName = metaData.getColumnName(i); if (GET_TABLES_NULL_SET.contains(columnName)) { Assertions.assertNull(resultSet.getString(i)); } else if ("TABLE_NAME".equals(columnName)) { final Set<String> labels = new HashSet<>(Arrays.asList(resultSet.getString(i).split(":"))); Assertions.assertTrue(expectedTables.contains(labels), String.format("Table name set '%s' is not in the expected tables set.", labels.toString())); expectedTables.remove(labels); } else if ("TABLE_TYPE".equals(columnName)) { Assertions.assertEquals("TABLE", resultSet.getString(i)); } else if ("REMARKS".equals(columnName)) { Assertions.assertEquals("", resultSet.getString(i)); } else { Assertions.fail( String.format("Unexpected column name '%s' encountered for table metadata.", columnName)); } } } while (resultSet.next()); } @Test void testGetCatalogs() throws SQLException { final java.sql.ResultSet resultSet = databaseMetaData.getCatalogs(); // Catalog is not currently supported Assertions.assertFalse(resultSet.next()); } @Test void testGetSchemas() throws SQLException { final java.sql.ResultSet resultSet = databaseMetaData.getSchemas(); Assertions.assertTrue(resultSet.next()); // TODO: Fix this to check the value later. } @Test void testGetTableTypes() throws SQLException { final java.sql.ResultSet resultSet = databaseMetaData.getTableTypes(); Assertions.assertTrue(resultSet.next()); final ResultSetMetaData metaData = resultSet.getMetaData(); final int columnCount = metaData.getColumnCount(); Assertions.assertEquals(1, columnCount); Assertions.assertEquals("TABLE", resultSet.getString(1)); Assertions.assertFalse(resultSet.next()); } @Test void testGetTypeInfo() throws SQLException { final java.sql.ResultSet resultSet = databaseMetaData.getTypeInfo(); Assertions.assertTrue(resultSet.next()); final ResultSetMetaData metaData = resultSet.getMetaData(); final int columnCount = metaData.getColumnCount(); Assertions.assertEquals(18, columnCount); Assertions.assertEquals("BOOLEAN", resultSet.getString(1)); Assertions.assertTrue(resultSet.next()); } }
7,361
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/opencypher
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/opencypher/mock/MockOpenCypherNode.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.opencypher.mock; public interface MockOpenCypherNode { /** * Info for CREATE functions. * Example: NodeType {node_param: 'node_value'} * * @return Info for CREATE functions. */ String getInfo(); /** * Annotation for CREATE functions. * * @return Annotation for CREATE functions. */ String getAnnotation(); /** * Index for CREATE INDEX functions. * Example: NodeType (node_param) * * @return Index for CREATE INDEX functions. */ String getIndex(); }
7,362
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/opencypher
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/opencypher/mock/MockOpenCypherNodes.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.opencypher.mock; import lombok.AllArgsConstructor; import java.util.concurrent.atomic.AtomicInteger; public class MockOpenCypherNodes { private static final AtomicInteger ANNOTATION_IDX = new AtomicInteger(); public static final MockOpenCypherNode LYNDON = getPerson("lyndon", "bauto"); public static final MockOpenCypherNode VALENTINA = getPerson("valentina", "bozanovic"); public static final MockOpenCypherNode VINNY = getKitty("vinny"); public static final MockOpenCypherNode TOOTSIE = getKitty("tootsie"); static String getNextAnnotation() { return String.format("a%d", ANNOTATION_IDX.getAndIncrement()); } /** * Function to get a Person Node with the provided parameters. * * @param firstName First name. * @param lastName Last name. * @return Person Node. */ public static MockOpenCypherNode getPerson(final String firstName, final String lastName) { return new Person(firstName, lastName, getNextAnnotation()); } /** * Function to get a Kitty Node with the provided parameters. * * @param name Name. * @return Kitty Node. */ public static MockOpenCypherNode getKitty(final String name) { return new Kitty(name, getNextAnnotation()); } @AllArgsConstructor private static class Person implements MockOpenCypherNode { private final String firstName; private final String lastName; private final String annotation; @Override public String getInfo() { return String.format("Person {first_name: '%s', last_name: '%s'}", firstName, lastName); } @Override public String getAnnotation() { return annotation; } @Override public String getIndex() { return "Person (first_name, last_name)"; } } @AllArgsConstructor private static class Kitty implements MockOpenCypherNode { private final String name; private final String annotation; @Override public String getInfo() { return String.format("Kitty {name: '%s'}", name); } @Override public String getAnnotation() { return annotation; } @Override public String getIndex() { return "Kitty (name)"; } } }
7,363
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/opencypher
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/opencypher/mock/OpenCypherQueryLiterals.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.opencypher.mock; public class OpenCypherQueryLiterals { // Primitive public static final String NULL = "RETURN null as n"; public static final String POS_INTEGER = "RETURN 1 AS n"; public static final String NEG_INTEGER = "RETURN -1 AS n"; public static final String ZERO_INTEGER = "RETURN 0 AS n"; public static final String NON_EMPTY_STRING = "RETURN 'hello' AS n"; public static final String EMPTY_STRING = "RETURN '' AS n"; public static final String TRUE = "RETURN true AS n"; public static final String FALSE = "RETURN false AS n"; public static final String POS_DOUBLE = "RETURN 1.0 AS n"; public static final String NEG_DOUBLE = "RETURN -1.0 AS n"; public static final String ZERO_DOUBLE = "RETURN 0.0 AS n"; // Composite public static final String EMPTY_MAP = "RETURN ({}) AS n"; public static final String NON_EMPTY_MAP = "RETURN ({hello:'world'}) AS n"; public static final String EMPTY_LIST = "RETURN [] AS n"; public static final String NON_EMPTY_LIST = "RETURN ['hello', 'world'] AS n"; // Date, time, point public static final String DATE = "RETURN date(\"1993-03-30\") AS n"; public static final String TIME = "RETURN time(\"12:10:10.225+0100\") AS n"; public static final String LOCAL_TIME = "RETURN localtime(\"12:10:10.225\") AS n"; public static final String DATE_TIME = "RETURN datetime(\"1993-03-30T12:10:10.225+0100\") AS n"; public static final String LOCAL_DATE_TIME = "RETURN localdatetime(\"1993-03-30T12:10:10.225\") AS n"; public static final String DURATION = "RETURN duration(\"P5M1.5D\") as n"; public static final String POINT_2D = "RETURN point({ x:0, y:1 }) AS n"; public static final String POINT_3D = "RETURN point({ x:0, y:1, z:2 }) AS n"; // Graph public static final String NODE = "CREATE (node:Foo) RETURN node"; public static final String RELATIONSHIP = "CREATE (node1:Foo)-[rel:Rel]->(node2:Bar) RETURN rel"; public static final String PATH = "CREATE (node1:Foo)-[rel:Rel]->(node2:Bar) " + "CREATE (node2)-[rel2:Rel]->(node3:Baz) " + "WITH (node1)-[:Rel*]->(node3) AS R " + "MATCH p = (node1)-[:Rel*]->(node3) " + "RETURN p"; }
7,364
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/opencypher
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/opencypher/mock/MockOpenCypherDatabase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.opencypher.mock; import lombok.Getter; import lombok.SneakyThrows; import org.junit.ClassRule; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.factory.GraphDatabaseBuilder; import org.neo4j.graphdb.factory.GraphDatabaseFactory; import org.neo4j.graphdb.factory.GraphDatabaseSettings; import org.neo4j.harness.junit.Neo4jRule; import org.neo4j.kernel.configuration.BoltConnector; import org.neo4j.kernel.configuration.Settings; import software.aws.neptune.opencypher.OpenCypherConnectionProperties; import java.io.File; import java.io.IOException; import java.net.ServerSocket; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import static org.neo4j.helpers.ListenSocketAddress.listenAddress; import static org.neo4j.kernel.configuration.BoltConnector.EncryptionLevel.DISABLED; import static org.neo4j.kernel.configuration.BoltConnector.EncryptionLevel.REQUIRED; import static org.neo4j.kernel.configuration.Connector.ConnectorType.BOLT; import static org.neo4j.kernel.configuration.Settings.FALSE; import static org.neo4j.kernel.configuration.Settings.STRING; import static org.neo4j.kernel.configuration.Settings.TRUE; public final class MockOpenCypherDatabase { private static final String DB_PATH = "target/neo4j-test/"; @ClassRule private static final Neo4jRule NEO4J_RULE = new Neo4jRule(); // Need lock to make sure we don't have port grab collisions (need to wait for binding). private static final Object LOCK = new Object(); private final GraphDatabaseService graphDb; @Getter private final String host; @Getter private final int port; /** * OpenCypherDatabase constructor. * * @param host Host to initialize with. * @param port Port to initialize with. * @param useEncryption Encryption usage to initialize with. */ private MockOpenCypherDatabase(final String host, final int port, final String path, final boolean useEncryption) throws IOException { this.host = host; this.port = port; final File dbPath = new File(DB_PATH + path); if (dbPath.isDirectory()) { Files.walk(dbPath.toPath()) .sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::delete); } graphDb = graphDbBuilder(dbPath, host, port, useEncryption) .newGraphDatabase(); } private static GraphDatabaseBuilder graphDbBuilder(final File dbPath, final String host, final int port, final boolean useEncryption) { final GraphDatabaseBuilder dbBuilder = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(dbPath); final BoltConnector boltConnector = new BoltConnector("bolt"); dbBuilder.setConfig(Settings.setting("dbms.directories.import", STRING, "data"), "../../data"); dbBuilder.setConfig(boltConnector.type, BOLT.name()); dbBuilder.setConfig(boltConnector.enabled, TRUE); dbBuilder.setConfig(boltConnector.listen_address, listenAddress(host, port)); if (useEncryption) { dbBuilder.setConfig(boltConnector.encryption_level, REQUIRED.name()); } else { dbBuilder.setConfig(boltConnector.encryption_level, DISABLED.name()); } dbBuilder.setConfig(GraphDatabaseSettings.auth_enabled, FALSE); return dbBuilder; } /** * Function to initiate builder for MockOpenCypherDatabase * * @param host Host to use. * @param callingClass Class calling builder (used for unique path). * @return Builder pattern for MockOpenCypherDatabase. */ @SneakyThrows public static MockOpenCypherDatabaseBuilder builder(final String host, final String callingClass) { return builder(host, callingClass, OpenCypherConnectionProperties.DEFAULT_USE_ENCRYPTION); } /** * Function to initiate builder for MockOpenCypherDatabase * * @param host Host to use. * @param callingClass Class calling builder (used for unique path). * @param useEncryption Indicates whether to use encryption. * @return Builder pattern for MockOpenCypherDatabase. */ @SneakyThrows public static MockOpenCypherDatabaseBuilder builder(final String host, final String callingClass, final boolean useEncryption) { synchronized (LOCK) { // Get random unassigned port. final ServerSocket socket = new ServerSocket(0); final int port = socket.getLocalPort(); socket.setReuseAddress(true); socket.close(); final MockOpenCypherDatabase db = new MockOpenCypherDatabase(host, port, callingClass, useEncryption); return new MockOpenCypherDatabaseBuilder(db); } } /** * Function to generate a create node query. * * @param mockNode Node to create. * @return Create node query. */ private static String createNode(final MockOpenCypherNode mockNode) { return String.format("CREATE (%s:%s)", mockNode.getAnnotation(), mockNode.getInfo()); } /** * Function to generate a create relationship query from (a)-[rel]->(b). * * @param mockNode1 Node to create relationship from (a). * @param mockNode2 Node to create relationship to (b). * @param relationship Relationship between notes [rel]. * @return Create relationship query. */ private static String createRelationship(final MockOpenCypherNode mockNode1, final MockOpenCypherNode mockNode2, final String relationship) { return String .format("CREATE (%s)-[%s:%s]->(%s)", mockNode1.getAnnotation(), MockOpenCypherNodes.getNextAnnotation(), relationship, mockNode2.getAnnotation()); } /** * Function to create an index query. * * @param mockNode Node to create index on. * @return Create index query. */ private static String createIndex(final MockOpenCypherNode mockNode) { return String.format("CREATE INDEX ON :%s", mockNode.getIndex()); } void executeQuery(final String query) { graphDb.execute(query); } /** * Function to shutdown the database. */ public void shutdown() { graphDb.shutdown(); } public static class MockOpenCypherDatabaseBuilder { private final MockOpenCypherDatabase db; private final List<String> indexes = new ArrayList<>(); private final List<String> nodes = new ArrayList<>(); private final List<String> relationships = new ArrayList<>(); MockOpenCypherDatabaseBuilder(final MockOpenCypherDatabase db) { this.db = db; } /** * Builder pattern node insert function. * * @param node Node to insert. * @return Builder. */ public MockOpenCypherDatabaseBuilder withNode(final MockOpenCypherNode node) { nodes.add(createNode(node)); if (!indexes.contains(createIndex(node))) { indexes.add(createIndex(node)); } return this; } /** * Builder pattern relationship insert (a)-[rel]->(b) * * @param node1 Node (a) to make relationship from. * @param node2 Node (b) to make relationship to. * @param relationship Relationship [rel] from (a) to (b). * @return Builder. */ public MockOpenCypherDatabaseBuilder withRelationship(final MockOpenCypherNode node1, final MockOpenCypherNode node2, final String relationship) { relationships.add(createRelationship(node1, node2, relationship)); return this; } /** * Builder pattern relationship insert (a)-[rel1]->(b) and (b)-[rel2]->(a) * * @param node1 Node (a) for relationship. * @param node2 Node (b) for relationship. * @param relationship1 Relationship [rel1] from (a) to (b). * @param relationship2 Relationship [rel2] from (b) to (b). * @return Builder. */ public MockOpenCypherDatabaseBuilder withRelationship(final MockOpenCypherNode node1, final MockOpenCypherNode node2, final String relationship1, final String relationship2) { relationships.add(createRelationship(node1, node2, relationship1)); relationships.add(createRelationship(node2, node1, relationship2)); return this; } /** * Function to build MockOpenCypherDatabase Object. * * @return Constructed database. */ public MockOpenCypherDatabase build() { if (!indexes.isEmpty()) { indexes.forEach(db::executeQuery); } String query = ""; if (!nodes.isEmpty()) { query = String.join(" ", nodes); if (!relationships.isEmpty()) { query += " " + String.join(" ", relationships); } } if (!query.isEmpty()) { db.executeQuery(query); } return db; } } }
7,365
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/opencypher
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/neptune/opencypher/utilities/OpenCypherGetColumnUtilities.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.opencypher.utilities; import java.util.ArrayList; import java.util.List; public class OpenCypherGetColumnUtilities { public static final List<String> COLUMN_NAMES = new ArrayList<>(); static { COLUMN_NAMES.add("TABLE_CAT"); COLUMN_NAMES.add("TABLE_SCHEM"); COLUMN_NAMES.add("TABLE_NAME"); COLUMN_NAMES.add("COLUMN_NAME"); COLUMN_NAMES.add("DATA_TYPE"); COLUMN_NAMES.add("TYPE_NAME"); COLUMN_NAMES.add("COLUMN_SIZE"); COLUMN_NAMES.add("BUFFER_LENGTH"); COLUMN_NAMES.add("DECIMAL_DIGITS"); COLUMN_NAMES.add("NUM_PREC_RADIX"); COLUMN_NAMES.add("NULLABLE"); COLUMN_NAMES.add("REMARKS"); COLUMN_NAMES.add("COLUMN_DEF"); COLUMN_NAMES.add("SQL_DATA_TYPE"); COLUMN_NAMES.add("SQL_DATETIME_SUB"); COLUMN_NAMES.add("CHAR_OCTET_LENGTH"); COLUMN_NAMES.add("ORDINAL_POSITION"); COLUMN_NAMES.add("IS_NULLABLE"); COLUMN_NAMES.add("SCOPE_CATALOG"); COLUMN_NAMES.add("SCOPE_SCHEMA"); COLUMN_NAMES.add("SCOPE_TABLE"); COLUMN_NAMES.add("SOURCE_DATA_TYPE"); COLUMN_NAMES.add("IS_AUTOINCREMENT"); COLUMN_NAMES.add("IS_GENERATEDCOLUMN"); } }
7,366
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/PerformanceTestUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.performance; import com.google.common.math.Quantiles; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.StringJoiner; import java.util.stream.Collectors; /** * Utility class for the performance tests. */ class PerformanceTestUtils { private static final String CSV_OUTPUT = "./performance-test-results-%s.csv"; private static final String getCsvFile(final String testName) { return String.format(CSV_OUTPUT, testName); } /** * Write the performance test metrics to a CSV file. * * @param executionMetric The {@link Metric} tracking execution times. * @param retrievalMetric The {@link Metric} tracking retrieval times. * @param testName Name of the performance test. * @throws IOException if an error occurred while creating the file. */ static void writeToCsv(final Metric executionMetric, final Metric retrievalMetric, final String testName) throws IOException { final File newFile = new File(getCsvFile(testName)); if (!newFile.exists()) { if (!newFile.createNewFile()) { System.out.println("Cannot create a new CSV file at the specified path."); return; } else { createNewCSVFile(testName); } } appendToCSVFile(executionMetric, retrievalMetric, testName); } /** * Append performance test metrics to the CSV. * * @param executionMetric The {@link Metric} tracking execution times. * @param retrievalMetric The {@link Metric} tracking retrieval times. * @param testName Name of the performance test. */ private static void appendToCSVFile(final Metric executionMetric, final Metric retrievalMetric, final String testName) { final List<Double> normalizedExecutionTimes = PerformanceTestUtils .normalizeTimes(executionMetric); final Map<Integer, Double> executionPercentiles = Quantiles.percentiles().indexes(50, 90, 95, 99) .compute(normalizedExecutionTimes); final List<Double> normalizedRetrievalTimes = PerformanceTestUtils .normalizeTimes(retrievalMetric); final Map<Integer, Double> retrievalPercentiles = Quantiles.percentiles().indexes(50, 90, 95, 99) .compute(normalizedRetrievalTimes); try (final Writer csv = new OutputStreamWriter(new FileOutputStream(getCsvFile(testName), true), StandardCharsets.UTF_8)) { final StringJoiner dataJoiner = new StringJoiner(","); dataJoiner.add(testName); dataJoiner.add(String.valueOf(retrievalMetric.getNumberOfRows())); dataJoiner.add(String .valueOf(PerformanceTestUtils.toMillis(executionMetric.getMinExecutionTime()))); dataJoiner.add(String .valueOf(PerformanceTestUtils.toMillis(executionMetric.getMaxExecutionTime()))); dataJoiner.add(String .valueOf(PerformanceTestUtils.toMillis(executionMetric.calculateAverageExecutionTime()))); dataJoiner.add(String.valueOf(executionPercentiles.get(50))); dataJoiner.add(String.valueOf(executionPercentiles.get(90))); dataJoiner.add(String.valueOf(executionPercentiles.get(95))); dataJoiner.add(String.valueOf(executionPercentiles.get(99))); dataJoiner.add(String .valueOf(PerformanceTestUtils.toMillis(retrievalMetric.getMinExecutionTime()))); dataJoiner.add(String .valueOf(PerformanceTestUtils.toMillis(retrievalMetric.getMaxExecutionTime()))); dataJoiner.add(String .valueOf(PerformanceTestUtils.toMillis(retrievalMetric.calculateAverageExecutionTime()))); dataJoiner.add(String.valueOf(retrievalPercentiles.get(50))); dataJoiner.add(String.valueOf(retrievalPercentiles.get(90))); dataJoiner.add(String.valueOf(retrievalPercentiles.get(95))); dataJoiner.add(String.valueOf(retrievalPercentiles.get(99))); csv.append(dataJoiner.toString()); csv.append("\n"); } catch (final IOException e) { System.out.println("Unable to save metrics to a csv file: " + e.getMessage()); } } /** * Creates a new CSV file tracking the performance metrics and add headers to the new CSV file. */ private static void createNewCSVFile(final String testName) { final StringJoiner joiner = new StringJoiner(","); try (final Writer csv = new OutputStreamWriter(new FileOutputStream(getCsvFile(testName)), StandardCharsets.UTF_8)) { joiner.add("Performance Test"); joiner.add("Number of Rows"); joiner.add("Min Execution Time"); joiner.add("Max Execution Time"); joiner.add("Average Execution Time"); joiner.add("Median Execution Time(P50)"); joiner.add("Execution Time P90"); joiner.add("Execution Time P95"); joiner.add("Execution Time P99"); joiner.add("Min Retrieval Time"); joiner.add("Max Retrieval Time"); joiner.add("Average Retrieval Time"); joiner.add("Median Retrieval Time(P50)"); joiner.add("Retrieval Time P90"); joiner.add("Retrieval Time P95"); joiner.add("Retrieval Time P99"); csv .append(joiner.toString()) .append("\n"); } catch (final IOException e) { System.out.println("Unable to save metrics to a csv file: " + e.getMessage()); } } /** * Normalize the running times. * * @param metric the performance test metric containing a list of running times. * @return the normalized running times. */ private static List<Double> normalizeTimes(final Metric metric) { final List<Double> normalizedRunningTimes = new ArrayList<>(metric.getExecutionTimes()); normalizedRunningTimes.remove(metric.getMaxExecutionTime()); normalizedRunningTimes.remove(metric.getMinExecutionTime()); normalizedRunningTimes.remove(metric.getMaxExecutionTime()); normalizedRunningTimes.remove(metric.getMinExecutionTime()); return normalizedRunningTimes.parallelStream().map(d -> d / 1000000).collect(Collectors.toList()); } /** * Converts nanoseconds to milliseconds. Not using {@link java.util.concurrent.TimeUnit} to * prevent truncation. * * @param nanoseconds The nanoseconds to convert. * @return milliseconds. */ private static double toMillis(final double nanoseconds) { return nanoseconds / 1000000; } }
7,367
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/Metric.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.performance; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; /** * Class tracking the execution time in nanoseconds from the performance tests. */ public class Metric { private final List<Double> executionTimes = new ArrayList<>(); private int numberOfRows; /** * Gets the maximum execution time. * * @return the maximum execution time. */ double getMaxExecutionTime() { return Collections.max(executionTimes); } /** * Gets the minimum execution time. * * @return the minimum execution time. */ double getMinExecutionTime() { return Collections.min(executionTimes); } /** * Gets the execution times. * * @return the list of execution times. */ List<Double> getExecutionTimes() { return executionTimes; } /** * Gets the total number of rows in the result set. * * @return the total number of rows in the result set. */ int getNumberOfRows() { return numberOfRows; } /** * Sets the total number of rows in the result set. * * @param numberOfRows The total number of rows in the result set. */ void setNumberOfRows(final int numberOfRows) { this.numberOfRows = numberOfRows; } /** * Track the execution time of the current iteration in the performance test. * * @param executionTime The execution time of an iteration in the performance test. */ void trackExecutionTime(final double executionTime) { executionTimes.add(executionTime); } /** * Calculate the average execution time of the test over all the runs. * * @return the average execution time. */ double calculateAverageExecutionTime() { final List<Double> normalizedExecutionTimes = new ArrayList<>(executionTimes); // Remove two extremes from each end normalizedExecutionTimes.remove(this.getMaxExecutionTime()); normalizedExecutionTimes.remove(this.getMinExecutionTime()); normalizedExecutionTimes.remove(this.getMaxExecutionTime()); normalizedExecutionTimes.remove(this.getMinExecutionTime()); return normalizedExecutionTimes .parallelStream() .collect(Collectors.averagingDouble(Double::doubleValue)); } }
7,368
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/DataTypePerformance.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.performance; import org.junit.jupiter.api.Test; import java.sql.SQLException; /** * Benchmark the driver's performance retrieving different amounts of data and data types. */ public abstract class DataTypePerformance { private static final int RUN_COUNT = 14; protected abstract PerformanceTestExecutor getPerformanceTestExecutor(); protected abstract String getAllDataQuery(); protected abstract String getNumberOfResultsQuery(); protected abstract String getTransformNumberOfIntegersQuery(); protected abstract String getTransformNumberOfStringsQuery(); protected abstract String getBaseTestName(); void runQuery(final String testName, final String query, final int runCount, final PerformanceTestExecutor.RetrieveType retrieveType) { getPerformanceTestExecutor().runTest(testName, query, runCount, retrieveType); } @Test void testGetAllData() throws SQLException { runQuery(getBaseTestName() + "-GetAllDataTest", getAllDataQuery(), RUN_COUNT, PerformanceTestExecutor.RetrieveType.OBJECT); } @Test void testGetNumberOfResults() throws SQLException { runQuery(getBaseTestName() + "-GetNumberResultsTest", getNumberOfResultsQuery(), RUN_COUNT, PerformanceTestExecutor.RetrieveType.OBJECT); } @Test void testTransformNumberOfIntegers() throws SQLException { runQuery(getBaseTestName() + "-GetTransformNumberIntegersTest", getTransformNumberOfIntegersQuery(), RUN_COUNT, PerformanceTestExecutor.RetrieveType.INTEGER); } @Test void testTransformNumberOfStrings() throws SQLException { runQuery(getBaseTestName() + "-GetTransformNumberStringTest", getTransformNumberOfStringsQuery(), RUN_COUNT, PerformanceTestExecutor.RetrieveType.STRING); } }
7,369
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/PerformanceTestExecutor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.performance; import lombok.SneakyThrows; import java.io.IOException; import java.util.AbstractMap; /** * Abstract class to handle performance test execution. */ public abstract class PerformanceTestExecutor { protected abstract Object execute(String query); protected abstract int retrieve(Object retrieveObject); protected abstract int retrieveString(Object retrieveObject); protected abstract int retrieveInteger(Object retrieveObject); /** * This function performs the test using the abstract functions. * * @param testName Name of the test. * @param query Query to run. * @param runs Number of times to execute. */ @SneakyThrows public void runTest(final String testName, final String query, final int runs, final RetrieveType retrieveType) { final Metric retrievalMetric = new Metric(); final Metric executionMetric = new Metric(); for (int i = 0; i < runs; i++) { final long startExecuteTime = System.nanoTime(); final Object data = execute(query); final long startRetrievalTime = System.nanoTime(); executionMetric.trackExecutionTime(System.nanoTime() - startExecuteTime); final int rowCount; switch (retrieveType) { case STRING: rowCount = retrieveString(data); break; case INTEGER: rowCount = retrieveInteger(data); break; case OBJECT: rowCount = retrieve(data); break; default: throw new Exception(String.format("Unknown retrieval type: %s", retrieveType.name())); } retrievalMetric.trackExecutionTime(System.nanoTime() - startRetrievalTime); if (i == 0) { retrievalMetric.setNumberOfRows(rowCount); } } handleMetrics(testName, new AbstractMap.SimpleEntry<>(retrievalMetric, executionMetric)); } /** * Handle the performance test metrics. * * @param testName Name of the performance test. * @param metrics The metric for executing the query and the metric for data retrieval. */ private void handleMetrics(final String testName, final AbstractMap.SimpleEntry<Metric, Metric> metrics) { final Metric retrievalMetric = metrics.getKey(); final Metric executionMetric = metrics.getValue(); try { PerformanceTestUtils.writeToCsv(executionMetric, retrievalMetric, testName); } catch (final IOException e) { System.out.println("Unable to save metrics to a csv file: " + e.getMessage()); } } enum RetrieveType { OBJECT, STRING, INTEGER } }
7,370
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations/PerformanceTestConstants.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.performance.implementations; import software.aws.neptune.jdbc.utilities.AuthScheme; public class PerformanceTestConstants { public static final String ENDPOINT = "no-auth-oc-enabled.cluster-cdubgfjknn5r.us-east-1.neptune.amazonaws.com"; public static final String REGION = "us-east-1"; public static final String SPARQL_ENDPOINT = "https://no-auth-oc-enabled.cluster-cdubgfjknn5r.us-east-1.neptune.amazonaws.com"; public static final String SPARQL_QUERY = "sparql"; public static final AuthScheme AUTH_SCHEME = AuthScheme.None; public static final int PORT = 8182; public static final int LIMIT_COUNT = 1000; public static final String SPARQL_ALL_DATA_QUERY = "SELECT ?s ?p ?o {?s ?p ?o}"; public static final String SPARQL_ALL_DATA_LIMIT_QUERY = String.format("%s LIMIT %d", SPARQL_ALL_DATA_QUERY, LIMIT_COUNT); public static final String SPARQL_NUMBER_QUERY = "PREFIX prop: <http://kelvinlawrence.net/air-routes/datatypeProperty/> " + "PREFIX class: <http://kelvinlawrence.net/air-routes/class/> " + "SELECT ?o " + "WHERE { " + " ?s a class:Airport . " + " ?s prop:elev ?o " + "} "; public static final String SPARQL_STRING_QUERY = "PREFIX prop: <http://kelvinlawrence.net/air-routes/datatypeProperty/> " + "PREFIX class: <http://kelvinlawrence.net/air-routes/class/> " + "SELECT ?s ?o " + "WHERE { " + " ?s a class:Airport . " + " ?s prop:code ?o " + "} "; public static final String GREMLIN_ALL_DATA_QUERY = "g.V().valueMap().with(WithOptions.tokens)"; public static final String GREMLIN_ALL_DATA_LIMIT_QUERY = String.format("%s.limit(%d)", GREMLIN_ALL_DATA_QUERY, LIMIT_COUNT); public static final String GREMLIN_NUMBER_QUERY = "g.V().hasLabel('airport').project('Elevation').by(values('elev'))"; public static final String GREMLIN_STRING_QUERY = "g.V().hasLabel('airport').project('Elevation').by(values('code'))"; public static final String OPENCYPHER_ALL_DATA_QUERY = "MATCH (n:airport) RETURN n"; public static final String OPENCYPHER_ALL_DATA_LIMIT_QUERY = String.format("%s LIMIT %d", OPENCYPHER_ALL_DATA_QUERY, LIMIT_COUNT); public static final String OPENCYPHER_NUMBER_QUERY = "MATCH (a:airport) RETURN a.elev as Elevation"; public static final String OPENCYPHER_STRING_QUERY = "MATCH (a:airport) RETURN a.code as Code"; }
7,371
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations/tests/SparqlJDBCTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.performance.implementations.tests; import lombok.SneakyThrows; import org.junit.jupiter.api.Disabled; import software.aws.performance.DataTypePerformance; import software.aws.performance.PerformanceTestExecutor; import software.aws.performance.implementations.executors.SparqlJDBCExecutor; import static software.aws.performance.implementations.PerformanceTestConstants.SPARQL_ALL_DATA_LIMIT_QUERY; import static software.aws.performance.implementations.PerformanceTestConstants.SPARQL_ALL_DATA_QUERY; import static software.aws.performance.implementations.PerformanceTestConstants.SPARQL_NUMBER_QUERY; import static software.aws.performance.implementations.PerformanceTestConstants.SPARQL_STRING_QUERY; @Disabled public class SparqlJDBCTest extends DataTypePerformance { @Override @SneakyThrows protected PerformanceTestExecutor getPerformanceTestExecutor() { return new SparqlJDBCExecutor(); } @Override // Get all airport data protected String getAllDataQuery() { return SPARQL_ALL_DATA_QUERY; } @Override protected String getNumberOfResultsQuery() { return SPARQL_ALL_DATA_LIMIT_QUERY; } @Override // Need to grab specific properties of certain nodes. protected String getTransformNumberOfIntegersQuery() { return SPARQL_NUMBER_QUERY; } @Override // Need to grab specific properties of certain nodes. protected String getTransformNumberOfStringsQuery() { return SPARQL_STRING_QUERY; } @Override protected String getBaseTestName() { return "SparqlJDBC"; } }
7,372
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations/tests/SqlGremlinJDBCTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.performance.implementations.tests; import lombok.SneakyThrows; import org.junit.jupiter.api.Disabled; import software.aws.performance.DataTypePerformance; import software.aws.performance.PerformanceTestExecutor; import software.aws.performance.implementations.executors.SqlGremlinJDBCExecutor; import static software.aws.performance.implementations.PerformanceTestConstants.LIMIT_COUNT; @Disabled public class SqlGremlinJDBCTest extends DataTypePerformance { @Override @SneakyThrows protected PerformanceTestExecutor getPerformanceTestExecutor() { return new SqlGremlinJDBCExecutor(); } @Override protected String getAllDataQuery() { return "SELECT * FROM `airport`"; } @Override protected String getNumberOfResultsQuery() { return String.format("%s LIMIT %d", getAllDataQuery(), LIMIT_COUNT); } @Override // Need to grab specific properties of certain nodes. protected String getTransformNumberOfIntegersQuery() { return "SELECT `airport`.`elev` AS `elev` FROM `airport`"; } @Override // Need to grab specific properties of certain nodes. protected String getTransformNumberOfStringsQuery() { return "SELECT `airport`.`code` AS `code` FROM `airport`"; } @Override protected String getBaseTestName() { return "SqlGremlinJDBC"; } }
7,373
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations/tests/OpenCypherJDBCTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.performance.implementations.tests; import lombok.SneakyThrows; import org.junit.jupiter.api.Disabled; import software.aws.performance.DataTypePerformance; import software.aws.performance.PerformanceTestExecutor; import software.aws.performance.implementations.executors.OpenCypherJDBCExecutor; import static software.aws.performance.implementations.PerformanceTestConstants.OPENCYPHER_ALL_DATA_LIMIT_QUERY; import static software.aws.performance.implementations.PerformanceTestConstants.OPENCYPHER_ALL_DATA_QUERY; import static software.aws.performance.implementations.PerformanceTestConstants.OPENCYPHER_NUMBER_QUERY; import static software.aws.performance.implementations.PerformanceTestConstants.OPENCYPHER_STRING_QUERY; @Disabled public class OpenCypherJDBCTest extends DataTypePerformance { @Override @SneakyThrows protected PerformanceTestExecutor getPerformanceTestExecutor() { return new OpenCypherJDBCExecutor(); } @Override protected String getAllDataQuery() { return OPENCYPHER_ALL_DATA_QUERY; } @Override protected String getNumberOfResultsQuery() { return OPENCYPHER_ALL_DATA_LIMIT_QUERY; } @Override // Need to grab specific properties of certain nodes. protected String getTransformNumberOfIntegersQuery() { return OPENCYPHER_NUMBER_QUERY; } @Override // Need to grab specific properties of certain nodes. protected String getTransformNumberOfStringsQuery() { return OPENCYPHER_STRING_QUERY; } @Override protected String getBaseTestName() { return "OpenCypherJDBC"; } }
7,374
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations/tests/SparqlBaselineTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.performance.implementations.tests; import org.junit.jupiter.api.Disabled; import software.aws.performance.DataTypePerformance; import software.aws.performance.PerformanceTestExecutor; import software.aws.performance.implementations.executors.SparqlBaselineExecutor; import static software.aws.performance.implementations.PerformanceTestConstants.SPARQL_ALL_DATA_LIMIT_QUERY; import static software.aws.performance.implementations.PerformanceTestConstants.SPARQL_ALL_DATA_QUERY; import static software.aws.performance.implementations.PerformanceTestConstants.SPARQL_NUMBER_QUERY; import static software.aws.performance.implementations.PerformanceTestConstants.SPARQL_STRING_QUERY; @Disabled public class SparqlBaselineTest extends DataTypePerformance { @Override protected PerformanceTestExecutor getPerformanceTestExecutor() { return new SparqlBaselineExecutor(); } @Override // Get all airport data protected String getAllDataQuery() { return SPARQL_ALL_DATA_QUERY; } @Override protected String getNumberOfResultsQuery() { return SPARQL_ALL_DATA_LIMIT_QUERY; } @Override // Need to grab specific properties of certain nodes. protected String getTransformNumberOfIntegersQuery() { return SPARQL_NUMBER_QUERY; } @Override // Need to grab specific properties of certain nodes. protected String getTransformNumberOfStringsQuery() { return SPARQL_STRING_QUERY; } @Override protected String getBaseTestName() { return "SparqlBaseline"; } }
7,375
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations/tests/GremlinBaselineTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.performance.implementations.tests; import lombok.SneakyThrows; import org.junit.jupiter.api.Disabled; import software.aws.performance.DataTypePerformance; import software.aws.performance.PerformanceTestExecutor; import software.aws.performance.implementations.executors.GremlinBaselineExecutor; import static software.aws.performance.implementations.PerformanceTestConstants.GREMLIN_ALL_DATA_LIMIT_QUERY; import static software.aws.performance.implementations.PerformanceTestConstants.GREMLIN_ALL_DATA_QUERY; import static software.aws.performance.implementations.PerformanceTestConstants.GREMLIN_NUMBER_QUERY; import static software.aws.performance.implementations.PerformanceTestConstants.GREMLIN_STRING_QUERY; @Disabled public class GremlinBaselineTest extends DataTypePerformance { @Override @SneakyThrows protected PerformanceTestExecutor getPerformanceTestExecutor() { return new GremlinBaselineExecutor(); } @Override protected String getAllDataQuery() { return GREMLIN_ALL_DATA_QUERY; } @Override protected String getNumberOfResultsQuery() { return GREMLIN_ALL_DATA_LIMIT_QUERY; } @Override // Need to grab specific properties of certain nodes. protected String getTransformNumberOfIntegersQuery() { return GREMLIN_NUMBER_QUERY; } @Override // Need to grab specific properties of certain nodes. protected String getTransformNumberOfStringsQuery() { return GREMLIN_STRING_QUERY; } @Override protected String getBaseTestName() { return "GremlinBaseline"; } }
7,376
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations/tests/OpenCypherBaselineTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.performance.implementations.tests; import lombok.SneakyThrows; import org.junit.jupiter.api.Disabled; import software.aws.performance.DataTypePerformance; import software.aws.performance.PerformanceTestExecutor; import software.aws.performance.implementations.executors.OpenCypherBaselineExecutor; import static software.aws.performance.implementations.PerformanceTestConstants.OPENCYPHER_ALL_DATA_LIMIT_QUERY; import static software.aws.performance.implementations.PerformanceTestConstants.OPENCYPHER_ALL_DATA_QUERY; import static software.aws.performance.implementations.PerformanceTestConstants.OPENCYPHER_NUMBER_QUERY; import static software.aws.performance.implementations.PerformanceTestConstants.OPENCYPHER_STRING_QUERY; @Disabled public class OpenCypherBaselineTest extends DataTypePerformance { @Override @SneakyThrows protected PerformanceTestExecutor getPerformanceTestExecutor() { return new OpenCypherBaselineExecutor(); } @Override protected String getAllDataQuery() { return OPENCYPHER_ALL_DATA_QUERY; } @Override protected String getNumberOfResultsQuery() { return OPENCYPHER_ALL_DATA_LIMIT_QUERY; } @Override // Need to grab specific properties of certain nodes. protected String getTransformNumberOfIntegersQuery() { return OPENCYPHER_NUMBER_QUERY; } @Override // Need to grab specific properties of certain nodes. protected String getTransformNumberOfStringsQuery() { return OPENCYPHER_STRING_QUERY; } @Override protected String getBaseTestName() { return "OpenCypherBaseline"; } }
7,377
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations/tests/GremlinJDBCTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.performance.implementations.tests; import lombok.SneakyThrows; import org.junit.jupiter.api.Disabled; import software.aws.performance.DataTypePerformance; import software.aws.performance.PerformanceTestExecutor; import software.aws.performance.implementations.executors.GremlinJDBCExecutor; import static software.aws.performance.implementations.PerformanceTestConstants.GREMLIN_ALL_DATA_LIMIT_QUERY; import static software.aws.performance.implementations.PerformanceTestConstants.GREMLIN_ALL_DATA_QUERY; import static software.aws.performance.implementations.PerformanceTestConstants.GREMLIN_NUMBER_QUERY; import static software.aws.performance.implementations.PerformanceTestConstants.GREMLIN_STRING_QUERY; @Disabled public class GremlinJDBCTest extends DataTypePerformance { @Override @SneakyThrows protected PerformanceTestExecutor getPerformanceTestExecutor() { return new GremlinJDBCExecutor(); } @Override protected String getAllDataQuery() { return GREMLIN_ALL_DATA_QUERY; } @Override protected String getNumberOfResultsQuery() { return GREMLIN_ALL_DATA_LIMIT_QUERY; } @Override // Need to grab specific properties of certain nodes. protected String getTransformNumberOfIntegersQuery() { return GREMLIN_NUMBER_QUERY; } @Override // Need to grab specific properties of certain nodes. protected String getTransformNumberOfStringsQuery() { return GREMLIN_STRING_QUERY; } @Override protected String getBaseTestName() { return "GremlinJDBC"; } }
7,378
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations/executors/SparqlJDBCExecutor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.performance.implementations.executors; import lombok.SneakyThrows; import software.aws.neptune.jdbc.utilities.ConnectionProperties; import software.aws.neptune.sparql.SparqlConnection; import software.aws.neptune.sparql.SparqlConnectionProperties; import software.aws.performance.implementations.PerformanceTestConstants; import java.sql.Statement; import java.util.Properties; public class SparqlJDBCExecutor extends JDBCExecutor { private final java.sql.Connection connection; /** * Constructor for SparqlJDBCExecutor. */ @SneakyThrows public SparqlJDBCExecutor() { final Properties properties = new Properties(); properties.put(ConnectionProperties.AUTH_SCHEME_KEY, PerformanceTestConstants.AUTH_SCHEME); properties.put(SparqlConnectionProperties.ENDPOINT_KEY, PerformanceTestConstants.SPARQL_ENDPOINT); properties.put(SparqlConnectionProperties.PORT_KEY, PerformanceTestConstants.PORT); properties.put(SparqlConnectionProperties.QUERY_ENDPOINT_KEY, PerformanceTestConstants.SPARQL_QUERY); connection = new SparqlConnection(new SparqlConnectionProperties(properties)); } @Override @SneakyThrows Statement getNewStatement() { return connection.createStatement(); } }
7,379
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations/executors/JDBCExecutor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.performance.implementations.executors; import lombok.SneakyThrows; import software.aws.performance.PerformanceTestExecutor; public abstract class JDBCExecutor extends PerformanceTestExecutor { abstract java.sql.Statement getNewStatement(); @Override @SneakyThrows protected Object execute(final String query) { return getNewStatement().executeQuery(query); } @Override @SneakyThrows protected int retrieve(final Object retrieveObject) { if (!(retrieveObject instanceof java.sql.ResultSet)) { throw new Exception("Error: expected a java.sql.ResultSet for data retrieval."); } final java.sql.ResultSet resultSet = (java.sql.ResultSet) retrieveObject; final int columnCount = resultSet.getMetaData().getColumnCount(); int rowCount = 0; while (resultSet.next()) { for (int i = 1; i <= columnCount; i++) { resultSet.getObject(i); } rowCount++; } return rowCount; } @Override @SneakyThrows protected int retrieveString(final Object retrieveObject) { if (!(retrieveObject instanceof java.sql.ResultSet)) { throw new Exception("Error: expected a java.sql.ResultSet for data retrieval."); } final java.sql.ResultSet resultSet = (java.sql.ResultSet) retrieveObject; final int columnCount = resultSet.getMetaData().getColumnCount(); int rowCount = 0; while (resultSet.next()) { for (int i = 1; i <= columnCount; i++) { resultSet.getString(i); } rowCount++; } return rowCount; } @Override @SneakyThrows protected int retrieveInteger(final Object retrieveObject) { if (!(retrieveObject instanceof java.sql.ResultSet)) { throw new Exception("Error: expected a java.sql.ResultSet for data retrieval."); } final java.sql.ResultSet resultSet = (java.sql.ResultSet) retrieveObject; final int columnCount = resultSet.getMetaData().getColumnCount(); int rowCount = 0; while (resultSet.next()) { for (int i = 1; i <= columnCount; i++) { resultSet.getInt(i); } rowCount++; } return rowCount; } }
7,380
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations/executors/OpenCypherBaselineExecutor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.performance.implementations.executors; import lombok.SneakyThrows; import org.neo4j.driver.AuthToken; import org.neo4j.driver.AuthTokens; import org.neo4j.driver.Config; import org.neo4j.driver.Driver; import org.neo4j.driver.GraphDatabase; import org.neo4j.driver.Record; import org.neo4j.driver.Session; import org.neo4j.driver.Value; import software.aws.neptune.jdbc.utilities.AuthScheme; import software.aws.neptune.opencypher.OpenCypherConnectionProperties; import software.aws.neptune.opencypher.OpenCypherIAMRequestGenerator; import software.aws.performance.PerformanceTestExecutor; import software.aws.performance.implementations.PerformanceTestConstants; import java.util.List; import java.util.Properties; import java.util.concurrent.TimeUnit; public class OpenCypherBaselineExecutor extends PerformanceTestExecutor { private final Session session; /** * Constructor for OpenCypherBaselineExecutor. */ @SneakyThrows public OpenCypherBaselineExecutor() { final Properties properties = new Properties(); properties.put(OpenCypherConnectionProperties.ENDPOINT_KEY, String.format("bolt://%s:%d", PerformanceTestConstants.ENDPOINT, PerformanceTestConstants.PORT)); properties.put(OpenCypherConnectionProperties.AUTH_SCHEME_KEY, PerformanceTestConstants.AUTH_SCHEME); properties.put(OpenCypherConnectionProperties.SERVICE_REGION_KEY, PerformanceTestConstants.REGION); final OpenCypherConnectionProperties openCypherConnectionProperties = new OpenCypherConnectionProperties(properties); final Config.ConfigBuilder configBuilder = Config.builder(); final boolean useEncryption = openCypherConnectionProperties.getUseEncryption(); if (useEncryption) { configBuilder.withEncryption(); configBuilder.withTrustStrategy(Config.TrustStrategy.trustAllCertificates()); } else { configBuilder.withoutEncryption(); } configBuilder.withMaxConnectionPoolSize(openCypherConnectionProperties.getConnectionPoolSize()); configBuilder .withConnectionTimeout(openCypherConnectionProperties.getConnectionTimeoutMillis(), TimeUnit.MILLISECONDS); AuthToken authToken = AuthTokens.none(); if (openCypherConnectionProperties.getAuthScheme().equals(AuthScheme.IAMSigV4)) { authToken = OpenCypherIAMRequestGenerator .createAuthToken(openCypherConnectionProperties.getEndpoint(), openCypherConnectionProperties.getServiceRegion()); } final Driver driver = GraphDatabase.driver(openCypherConnectionProperties.getEndpoint(), authToken, configBuilder.build()); session = driver.session(); } @Override protected Object execute(final String query) { return session.run(query).list(); } @Override @SneakyThrows protected int retrieve(final Object retrieveObject) { if (!(retrieveObject instanceof List)) { throw new Exception("Error: expected a Result for data retrieval."); } int rowCount = 0; final List<Record> recordList = (List<Record>) retrieveObject; for (final Record r : recordList) { final List<Value> values = r.values(); for (int i = 0; i < values.size(); i++) { values.get(i); } rowCount++; } return rowCount; } @Override @SneakyThrows protected int retrieveString(final Object retrieveObject) { if (!(retrieveObject instanceof List)) { throw new Exception("Error: expected a Result for data retrieval."); } int rowCount = 0; final List<Record> recordList = (List<Record>) retrieveObject; for (final Record r : recordList) { final List<Value> values = r.values(); for (int i = 0; i < values.size(); i++) { r.get(i).asString(); } rowCount++; } return rowCount; } @Override @SneakyThrows protected int retrieveInteger(final Object retrieveObject) { if (!(retrieveObject instanceof List)) { throw new Exception("Error: expected a Result for data retrieval."); } int rowCount = 0; final List<Record> recordList = (List<Record>) retrieveObject; for (final Record r : recordList) { final List<Value> values = r.values(); for (int i = 0; i < values.size(); i++) { r.get(i).asInt(); } rowCount++; } return rowCount; } }
7,381
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations/executors/SparqlBaselineExecutor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.performance.implementations.executors; import lombok.SneakyThrows; import org.apache.jena.query.QueryExecution; import org.apache.jena.query.QuerySolution; import org.apache.jena.query.ResultSet; import org.apache.jena.rdf.model.Literal; import org.apache.jena.rdf.model.RDFNode; import org.apache.jena.rdfconnection.RDFConnection; import software.aws.neptune.jdbc.utilities.ConnectionProperties; import software.aws.neptune.sparql.SparqlConnectionProperties; import software.aws.neptune.sparql.SparqlQueryExecutor; import software.aws.performance.PerformanceTestExecutor; import software.aws.performance.implementations.PerformanceTestConstants; import java.util.ArrayList; import java.util.List; import java.util.Properties; public class SparqlBaselineExecutor extends PerformanceTestExecutor { private final RDFConnection rdfConnection; private QueryExecution queryExecution; /** * Constructor for SparqlBaselineExecutor. */ @SneakyThrows public SparqlBaselineExecutor() { final Properties properties = new Properties(); properties.put(ConnectionProperties.AUTH_SCHEME_KEY, PerformanceTestConstants.AUTH_SCHEME); properties.put(SparqlConnectionProperties.ENDPOINT_KEY, PerformanceTestConstants.SPARQL_ENDPOINT); properties.put(SparqlConnectionProperties.PORT_KEY, PerformanceTestConstants.PORT); properties.put(SparqlConnectionProperties.QUERY_ENDPOINT_KEY, PerformanceTestConstants.SPARQL_QUERY); final SparqlConnectionProperties sparqlConnectionProperties = new SparqlConnectionProperties(properties); rdfConnection = SparqlQueryExecutor.createRDFBuilder(sparqlConnectionProperties).build(); } /** * We are testing SELECT queries only */ @Override @SneakyThrows protected Object execute(final String query) { final Object result; queryExecution = rdfConnection.query(query); result = queryExecution.execSelect(); return result; } @Override @SneakyThrows protected int retrieve(final Object retrieveObject) { if (!(retrieveObject instanceof ResultSet)) { throw new Exception("Error: expected a ResultSet for data retrieval."); } int rowCount = 0; final ResultSet result = (ResultSet) retrieveObject; final List<QuerySolution> selectRows = new ArrayList<>(); final List<String> columns = result.getResultVars(); while (result.hasNext()) { rowCount++; final QuerySolution row = result.next(); selectRows.add(row); for (final String column : columns) { row.get(column); } } // Need to close QueryExecution explicitly, else it remains open and will hit the max open HTTP client. // https://stackoverflow.com/questions/55368848/construct-query-hangs-in-fuseki-jena-after-executing-6-time queryExecution.close(); return rowCount; } @Override @SneakyThrows protected int retrieveString(final Object retrieveObject) { if (!(retrieveObject instanceof ResultSet)) { throw new Exception("Error: expected a ResultSet for data retrieval."); } int rowCount = 0; final ResultSet result = (ResultSet) retrieveObject; final List<QuerySolution> selectRows = new ArrayList<>(); final List<String> columns = result.getResultVars(); while (result.hasNext()) { rowCount++; final QuerySolution row = result.next(); selectRows.add(row); for (final String column : columns) { final RDFNode node = row.get(column); if (node.isLiteral()) { final Literal literal = node.asLiteral(); literal.getLexicalForm(); } else { node.toString(); } } } queryExecution.close(); return rowCount; } @Override @SneakyThrows protected int retrieveInteger(final Object retrieveObject) { if (!(retrieveObject instanceof ResultSet)) { throw new Exception("Error: expected a ResultSet for data retrieval."); } int rowCount = 0; final ResultSet result = (ResultSet) retrieveObject; final List<QuerySolution> selectRows = new ArrayList<>(); final List<String> columns = result.getResultVars(); while (result.hasNext()) { rowCount++; final QuerySolution row = result.next(); selectRows.add(row); for (final String column : columns) { final RDFNode node = row.get(column); if (node.isLiteral()) { final Literal literal = node.asLiteral(); if (!(literal.getValue() instanceof Number)) { Integer.parseInt(literal.getLexicalForm()); } } else { Integer.parseInt(node.toString()); } } } queryExecution.close(); return rowCount; } }
7,382
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations/executors/GremlinJDBCExecutor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.performance.implementations.executors; import lombok.SneakyThrows; import software.aws.neptune.gremlin.GremlinConnection; import software.aws.neptune.gremlin.GremlinConnectionProperties; import software.aws.performance.implementations.PerformanceTestConstants; import java.sql.Statement; import java.util.Properties; import static software.aws.neptune.gremlin.GremlinConnectionProperties.CONTACT_POINT_KEY; import static software.aws.neptune.gremlin.GremlinConnectionProperties.PORT_KEY; import static software.aws.neptune.jdbc.utilities.ConnectionProperties.AUTH_SCHEME_KEY; public class GremlinJDBCExecutor extends JDBCExecutor { private final java.sql.Connection connection; /** * Constructor for GremlinJDBCExecutor. */ @SneakyThrows public GremlinJDBCExecutor() { final Properties properties = new Properties(); properties.put(CONTACT_POINT_KEY, PerformanceTestConstants.ENDPOINT); properties.put(PORT_KEY, PerformanceTestConstants.PORT); properties.put(AUTH_SCHEME_KEY, PerformanceTestConstants.AUTH_SCHEME); connection = new GremlinConnection(new GremlinConnectionProperties(properties)); } @Override @SneakyThrows Statement getNewStatement() { return connection.createStatement(); } }
7,383
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations/executors/OpenCypherJDBCExecutor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.performance.implementations.executors; import lombok.SneakyThrows; import software.aws.neptune.opencypher.OpenCypherConnection; import software.aws.neptune.opencypher.OpenCypherConnectionProperties; import software.aws.performance.implementations.PerformanceTestConstants; import java.sql.Statement; import java.util.Properties; public class OpenCypherJDBCExecutor extends JDBCExecutor { private final java.sql.Connection connection; /** * Constructor for OpenCypherJDBCExecutor. */ @SneakyThrows public OpenCypherJDBCExecutor() { final Properties properties = new Properties(); properties.put(OpenCypherConnectionProperties.ENDPOINT_KEY, String.format("bolt://%s:%d", PerformanceTestConstants.ENDPOINT, PerformanceTestConstants.PORT)); properties.put(OpenCypherConnectionProperties.AUTH_SCHEME_KEY, PerformanceTestConstants.AUTH_SCHEME); properties.put(OpenCypherConnectionProperties.SERVICE_REGION_KEY, PerformanceTestConstants.REGION); connection = new OpenCypherConnection(new OpenCypherConnectionProperties(properties)); } @Override @SneakyThrows Statement getNewStatement() { return connection.createStatement(); } }
7,384
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations/executors/SqlGremlinJDBCExecutor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.performance.implementations.executors; import lombok.SneakyThrows; import software.aws.neptune.gremlin.GremlinConnectionProperties; import software.aws.neptune.gremlin.sql.SqlGremlinConnection; import software.aws.performance.implementations.PerformanceTestConstants; import java.sql.Statement; import java.util.Properties; import static software.aws.neptune.gremlin.GremlinConnectionProperties.CONTACT_POINT_KEY; import static software.aws.neptune.gremlin.GremlinConnectionProperties.PORT_KEY; import static software.aws.neptune.jdbc.utilities.ConnectionProperties.AUTH_SCHEME_KEY; public class SqlGremlinJDBCExecutor extends JDBCExecutor { private final java.sql.Connection connection; /** * Constructor for SqlGremlinJDBCExecutor. */ @SneakyThrows public SqlGremlinJDBCExecutor() { final Properties properties = new Properties(); properties.put(CONTACT_POINT_KEY, PerformanceTestConstants.ENDPOINT); properties.put(PORT_KEY, PerformanceTestConstants.PORT); properties.put(AUTH_SCHEME_KEY, PerformanceTestConstants.AUTH_SCHEME); connection = new SqlGremlinConnection(new GremlinConnectionProperties(properties)); // Invoking to force metadata grab so that it doesn't do it in the test. connection.getMetaData().getTables(null, null, null, null); } @Override @SneakyThrows Statement getNewStatement() { return connection.createStatement(); } }
7,385
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations
Create_ds/amazon-neptune-jdbc-driver/src/test/java/software/aws/performance/implementations/executors/GremlinBaselineExecutor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.performance.implementations.executors; import lombok.SneakyThrows; import org.apache.tinkerpop.gremlin.driver.Client; import org.apache.tinkerpop.gremlin.driver.Cluster; import org.apache.tinkerpop.gremlin.driver.Result; import software.aws.neptune.gremlin.GremlinConnectionProperties; import software.aws.neptune.gremlin.GremlinQueryExecutor; import software.aws.performance.PerformanceTestExecutor; import software.aws.performance.implementations.PerformanceTestConstants; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import static software.aws.neptune.gremlin.GremlinConnectionProperties.CONTACT_POINT_KEY; import static software.aws.neptune.gremlin.GremlinConnectionProperties.PORT_KEY; import static software.aws.neptune.jdbc.utilities.ConnectionProperties.AUTH_SCHEME_KEY; public class GremlinBaselineExecutor extends PerformanceTestExecutor { private final Client client; /** * Constructor for GremlinBaselineExecutor. */ @SneakyThrows public GremlinBaselineExecutor() { final Properties properties = new Properties(); properties.put(CONTACT_POINT_KEY, PerformanceTestConstants.ENDPOINT); properties.put(PORT_KEY, PerformanceTestConstants.PORT); properties.put(AUTH_SCHEME_KEY, PerformanceTestConstants.AUTH_SCHEME); final GremlinConnectionProperties gremlinConnectionProperties = new GremlinConnectionProperties(properties); final Cluster cluster = GremlinQueryExecutor.createClusterBuilder(gremlinConnectionProperties).create(); client = cluster.connect(); client.init(); } @Override @SneakyThrows protected Object execute(final String query) { return client.submit(query).all().get(); } @Override @SneakyThrows protected int retrieve(final Object retrieveObject) { if (!(retrieveObject instanceof List<?>)) { throw new Exception("Error: expected a List<?> for data retrieval."); } int rowCount = 0; final List<Result> results = (List<Result>) retrieveObject; for (final Result r : results) { rowCount++; if (!(r.getObject() instanceof LinkedHashMap)) { // Best way to handle it seems to be to issue a warning. throw new Exception("Error, data has unexpected format."); } final Map<?, ?> row = (LinkedHashMap<?, ?>) r.getObject(); final Set<?> keys = row.keySet(); for (final Object key : keys) { row.get(key); } } return rowCount; } @Override @SneakyThrows protected int retrieveString(final Object retrieveObject) { if (!(retrieveObject instanceof List<?>)) { throw new Exception("Error: expected a List<?> for data retrieval."); } int rowCount = 0; final List<Result> results = (List<Result>) retrieveObject; for (final Result r : results) { rowCount++; if (!(r.getObject() instanceof LinkedHashMap)) { // Best way to handle it seems to be to issue a warning. throw new Exception("Error, data has unexpected format."); } final Map<?, ?> row = (LinkedHashMap<?, ?>) r.getObject(); final Set<?> keys = row.keySet(); for (final Object key : keys) { Object data = row.get(key); if (!(row.get(key) instanceof String)) { data = data.toString(); } } } return rowCount; } @Override @SneakyThrows protected int retrieveInteger(final Object retrieveObject) { if (!(retrieveObject instanceof List<?>)) { throw new Exception("Error: expected a List<?> for data retrieval."); } int rowCount = 0; final List<Result> results = (List<Result>) retrieveObject; for (final Result r : results) { rowCount++; if (!(r.getObject() instanceof LinkedHashMap)) { // Best way to handle it seems to be to issue a warning. throw new Exception("Error, data has unexpected format."); } final Map<?, ?> row = (LinkedHashMap<?, ?>) r.getObject(); final Set<?> keys = row.keySet(); for (final Object key : keys) { Object data = row.get(key); if (!(row.get(key) instanceof Number)) { data = Integer.parseInt(data.toString()); } } } return rowCount; } }
7,386
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/sample
Create_ds/amazon-neptune-jdbc-driver/src/test/java/sample/applications/MetadataExamples.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package sample.applications; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; /** * This class provides some examples on how to get metadata on the database. Because Amazon Neptune is a Graph database * a mapping to a relational database is done. The distinct label sets of the nodes are provided as tables, and the * properties of the nodes are provided as columns in the tables. Clashing types on properties are resolved by promoting * the column to a String type. The getSchemas and getCatalogs functions return Empty {@java.sql.ResultSet}'s because * there is no mapping from a graph to either of these relational concepts. */ public class MetadataExamples { private final DatabaseMetaData databaseMetaData; /** * Constructor initializes connection and gets the {@link DatabaseMetaData}. * * @throws SQLException If creating the {@link Connection} or getting the {@link DatabaseMetaData} fails. */ MetadataExamples() throws SQLException { final Connection connection = AuthenticationExamples.createIAMAuthConnection(); databaseMetaData = connection.getMetaData(); } /** * This function retrieves and iterates over the {@link ResultSet} returned from * {@link DatabaseMetaData#getColumns(String, String, String, String)} * * @throws SQLException If getting the {@link ResultSet} from the {@link DatabaseMetaData} fails. */ public void getColumnsMetadataExample() throws SQLException { final ResultSet getColumnsResultSet = databaseMetaData.getColumns(null, null, null, null); if (!getColumnsResultSet.next()) { throw new SQLException( "This graph contains no columns (properties on any nodes with distinct label sets)."); } do { // Grab the table name, column name, and data type of column. Look here for more information: // https://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html#getColumns(java.lang.String,%20java.lang.String,%20java.lang.String,%20java.lang.String) final String tableName = getColumnsResultSet.getString("TABLE_NAME"); final String columnName = getColumnsResultSet.getString("COLUMN_NAME"); final String dataType = getColumnsResultSet.getString("DATA_TYPE"); } while (getColumnsResultSet.next()); } /** * This function retrieves and iterates over the {@link ResultSet} returned from * {@link DatabaseMetaData#getTables(String, String, String, String[])} * * @throws SQLException If getting the {@link ResultSet} from the {@link DatabaseMetaData} fails. */ public void getTablesMetadataExample() throws SQLException { final ResultSet getTablesResultSet = databaseMetaData.getTables(null, null, null, null); if (!getTablesResultSet.next()) { throw new SQLException("This graph contains no tables (nodes with distinct label sets)."); } do { // Grab the table name. Look here for more information: // https://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html#getTables(java.lang.String,%20java.lang.String,%20java.lang.String,%20java.lang.String[]) final String tableName = getTablesResultSet.getString("TABLE_NAME"); } while (getTablesResultSet.next()); } }
7,387
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/sample
Create_ds/amazon-neptune-jdbc-driver/src/test/java/sample/applications/ConnectionOptionsExamples.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package sample.applications; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; /** * This class provides an example on how to create a {@link Connection} with some extra config options. */ public class ConnectionOptionsExamples { /** * This function creates a {@link Connection} with additional config options. * * @return {@link Connection} with additional config options. * @throws SQLException If creating the {@link Connection} Object fails or is not valid. */ public static Connection createConnectionWithExtraConfigs() throws SQLException { // To enable IAM SigV4 authentication, set the AuthScheme to IAMSigV4 in the Properties map. final Properties properties = new Properties(); // To enable encryption, set the UseEncryption to true in the Properties map. properties.put("UseEncryption", "true"); // To set the connection timeout, set the ConnectionTimeout to an integer valued string (milliseconds) in the Properties map. properties.put("ConnectionTimeout", "1000"); // To set the connection retry count, set the ConnectionRetryCount to an integer valued string in the Properties map. properties.put("ConnectionRetryCount", "3"); // To set the connection pool size, set the ConnectionPoolSize to an integer valued string in the Properties map. properties.put("ConnectionPoolSize", "1000"); // To set the log level, set the LogLevel to a string value in the Properties map. properties.put("LogLevel", "DEBUG"); final Connection connection = DriverManager.getConnection(ExampleConfigs.getConnectionString(), properties); // Validate the connection with a timeout of 5 seconds. // If this line fails, create a {@link java.sql.Statement} and execute a literal query to check the error reported there. if (!connection.isValid(5)) { throw new SQLException( "Connection is not valid, verify that the url, port, and credentials are set correctly."); } return connection; } }
7,388
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/sample
Create_ds/amazon-neptune-jdbc-driver/src/test/java/sample/applications/ExampleConfigs.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package sample.applications; public class ExampleConfigs { private static final String JDBC_OPENCYPHER_CONNECTION_STRING = "jdbc:neptune:opencypher://bolt://%s:%d"; private static final String URL = "example-url.com"; private static final int PORT = 8182; public static String getConnectionString() { return String.format(JDBC_OPENCYPHER_CONNECTION_STRING, URL, PORT); } }
7,389
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/sample
Create_ds/amazon-neptune-jdbc-driver/src/test/java/sample/applications/QueryExecutionExamples.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package sample.applications; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * This class provides some examples on how to send queries to Amazon Neptune with the JDBC driver. */ public class QueryExecutionExamples { private final Connection connection; /** * Constructor initializes the {@link java.sql.Connection}. * * @throws SQLException If creating the {@link Connection} fails. */ QueryExecutionExamples() throws SQLException { connection = AuthenticationExamples.createIAMAuthConnection(); } /** * Helper function to execute queries. * * @param query Query to execute. * @return {@link java.sql.ResultSet} after executing query. * @throws SQLException If {@link java.sql.Statement} creation or query execution fails. */ ResultSet executeQuery(final String query) throws SQLException { final Statement statement = connection.createStatement(); final ResultSet resultSet = statement.executeQuery(query); statement.close(); return resultSet; } /** * This function sends a query with a Boolean literal and returns the value as a Boolean. * * @throws SQLException If {@link java.sql.Statement} creation or query execution fails. */ void queryLiteralBooleanExample() throws SQLException { final String query = "RETURN true AS n"; final ResultSet resultSet = executeQuery(query); // Value will be true. final Boolean value = resultSet.getBoolean(0); resultSet.close(); } /** * This function sends a query with a Integer literal and returns the value as a Integer. * * @throws SQLException If {@link java.sql.Statement} creation or query execution fails. */ void queryLiteralIntegerExample() throws SQLException { final String query = "RETURN 1 AS n"; final ResultSet resultSet = executeQuery(query); // Value will be 1. final Integer value = resultSet.getInt(0); resultSet.close(); } /** * This function sends a query with a Float literal and returns the value as a Float. * * @throws SQLException If {@link java.sql.Statement} creation or query execution fails. */ void queryLiteralFloatExample() throws SQLException { final String query = "RETURN 1.0 AS n"; final ResultSet resultSet = executeQuery(query); // Value will be 1.0. final Float value = resultSet.getFloat(0); resultSet.close(); } /** * This function sends a query with a String literal and returns the value as a String. * * @throws SQLException If {@link java.sql.Statement} creation or query execution fails. */ void queryLiteralStringExample() throws SQLException { final String query = "RETURN 'hello' AS n"; final ResultSet resultSet = executeQuery(query); // Value will be "hello". final String value = resultSet.getString(0); resultSet.close(); } /** * This function sends a query with a Date literal and returns the value as a Date. * * @throws SQLException If {@link java.sql.Statement} creation or query execution fails. */ void queryLiteralDateExample() throws SQLException { final String query = "RETURN date(\"1993-03-30\") AS n"; final ResultSet resultSet = executeQuery(query); // Value will be the date 1993-03-03 (yyyy-mm-dd). final java.sql.Date value = resultSet.getDate(0); resultSet.close(); } /** * This function sends a query with a node and returns the value as a String. * * @throws SQLException If {@link java.sql.Statement} creation or query execution fails. */ void queryNodeExample() throws SQLException { final String query = "CREATE (node:Foo {hello:'world'}) RETURN node"; final ResultSet resultSet = executeQuery(query); // Value will be the String "([Foo] : {hello=world})". final String value = resultSet.getString(0); resultSet.close(); } /** * This function sends a query with a relationship and returns the value as a String. * * @throws SQLException If {@link java.sql.Statement} creation or query execution fails. */ void queryRelationshipExample() throws SQLException { final String query = "CREATE (node1:Foo)-[rel:Rel {hello:'world'}]->(node2:Bar) RETURN rel"; final ResultSet resultSet = executeQuery(query); // Value will be the String "[Rel : {hello=world}]". final String value = resultSet.getString(0); resultSet.close(); } /** * This function sends a query with a path and returns the value as a String. * * @throws SQLException If {@link java.sql.Statement} creation or query execution fails. */ void queryPathExample() throws SQLException { final String query = "CREATE p=(l:Person { name:'Foo'})-[:WORKS {position:'developer'}]->(bqt:Company " + "{product:'software'})<-[:WORKS {position:'developer'}]-(v:Person { name:'Bar'}) RETURN p"; final ResultSet resultSet = executeQuery(query); // Value will be the String // "([Person] : {name=Foo})-[WORKS : {position=developer0}]->([Company] : {product=software}) // <-[WORKS : {position=developer}]-([Person] : {name=Bar})". final String value = resultSet.getString(0); resultSet.close(); } }
7,390
0
Create_ds/amazon-neptune-jdbc-driver/src/test/java/sample
Create_ds/amazon-neptune-jdbc-driver/src/test/java/sample/applications/AuthenticationExamples.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package sample.applications; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; /** * This class provides some examples on how to create a {@link Connection} with authentication for Amazon Neptune. */ public class AuthenticationExamples { /** * This function creates a {@link Connection} with IAM SigV4 authentication. * * @return {@link Connection} with IAM SigV4. * @throws SQLException If creating the {@link Connection} Object fails or is not valid. */ public static Connection createIAMAuthConnection() throws SQLException { // To enable IAM SigV4 authentication, set the AuthScheme to IAMSigV4 in the Properties map. final Properties properties = new Properties(); properties.put("AuthScheme", "IAMSigV4"); // Create the connection. IAM SigV4 authentication requires that the environment of the user is setup to // receive credentials. Notice, the SERVICE_REGION must be set appropriately as well. See // https://docs.aws.amazon.com/neptune/latest/userguide/iam-auth-connecting-gremlin-java.html for more information. // On Windows this can be done by settings the AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and SERVICE_REGION environment variables. // On Linux or Mac, a ~/.aws file can be created and populated with the credentials. // If TFA is setup on the account, follow the appropriate steps to set the session token for your environment as well. final Connection connection = DriverManager.getConnection(ExampleConfigs.getConnectionString(), properties); // Validate the connection with a timeout of 5 seconds. // If this line fails, create a {@link java.sql.Statement} and execute a literal query to check the error reported there. if (!connection.isValid(5)) { throw new SQLException( "Connection is not valid, verify that the url, port, and credentials are set correctly."); } return connection; } /** * This function creates a {@link Connection} without authentication. * * @return {@link Connection} without authentication. * @throws SQLException If creating the {@link Connection} Object fails or is not valid. */ public static Connection createNoAuthConnection() throws SQLException { // To create a connection without authentication, set AuthScheme to None in the Properties map. final Properties properties = new Properties(); properties.put("AuthScheme", "None"); final Connection connection = DriverManager.getConnection(ExampleConfigs.getConnectionString(), properties); // Validate the connection with a timeout of 5 seconds. // If this line fails, create a {@link java.sql.Statement} and execute a literal query to check the error reported there. if (!connection.isValid(5)) { throw new SQLException("Connection is not valid, verify that the url and port are set correctly."); } return connection; } }
7,391
0
Create_ds/amazon-neptune-jdbc-driver/src/main/java/software/aws
Create_ds/amazon-neptune-jdbc-driver/src/main/java/software/aws/neptune/NeptuneDatabaseMetadata.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune; import software.aws.neptune.jdbc.DatabaseMetaData; import java.sql.SQLException; public class NeptuneDatabaseMetadata extends DatabaseMetaData implements java.sql.DatabaseMetaData { private static final String DRIVER_NAME = "Amazon Neptune JDBC"; /** * NeptuneDatabaseMetadata constructor, initializes super class. * * @param connection Connection Object. */ public NeptuneDatabaseMetadata(final java.sql.Connection connection) { super(connection); } @Override public String getDatabaseProductName() throws SQLException { return "Neptune"; } @Override public String getDatabaseProductVersion() throws SQLException { return "1.0"; } @Override public String getCatalogTerm() throws SQLException { return ""; } @Override public String getCatalogSeparator() throws SQLException { return ""; } @Override public String getDriverName() { return DRIVER_NAME; } }
7,392
0
Create_ds/amazon-neptune-jdbc-driver/src/main/java/software/aws
Create_ds/amazon-neptune-jdbc-driver/src/main/java/software/aws/neptune/NeptuneDriver.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune; import com.google.common.collect.ImmutableList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.aws.neptune.gremlin.GremlinConnection; import software.aws.neptune.gremlin.GremlinConnectionProperties; import software.aws.neptune.gremlin.sql.SqlGremlinConnection; import software.aws.neptune.jdbc.Driver; import software.aws.neptune.jdbc.utilities.SqlError; import software.aws.neptune.jdbc.utilities.SqlState; import software.aws.neptune.opencypher.OpenCypherConnection; import software.aws.neptune.opencypher.OpenCypherConnectionProperties; import software.aws.neptune.sparql.SparqlConnection; import software.aws.neptune.sparql.SparqlConnectionProperties; import java.sql.DriverManager; import java.sql.SQLException; import java.util.List; import java.util.Properties; import java.util.regex.Pattern; public class NeptuneDriver extends Driver implements java.sql.Driver { public static final String CONN_STRING_PREFIX = "jdbc:neptune:"; private static final Logger LOGGER = LoggerFactory.getLogger(NeptuneDriver.class); private static final Pattern CONN_STRING_PATTERN = Pattern.compile(CONN_STRING_PREFIX + "(\\w+)://(.*)"); static { try { DriverManager.registerDriver(new NeptuneDriver()); } catch (final SQLException e) { LOGGER.error("Error registering driver: " + e.getMessage()); } } private static final List<String> LANGUAGE_LIST = ImmutableList.of( "opencypher", "gremlin", "sqlgremlin", "sparql"); @Override public boolean acceptsURL(final String url) throws SQLException { try { // TODO AN-550: Switch to map with class that holds Conn properties, key, query executor, etc. return url != null && url.startsWith(CONN_STRING_PREFIX) && LANGUAGE_LIST.contains(getLanguage(url, CONN_STRING_PATTERN)); } catch (final SQLException ignored) { } return false; } @Override public java.sql.Connection connect(final String url, final Properties info) throws SQLException { if (!acceptsURL(url)) { return null; } try { final DriverConnectionFactory connectionFactory = new DriverConnectionFactory(); return connectionFactory.getConnection(url, info); } catch (final Exception e) { if (e instanceof SQLException) { throw (SQLException) e; } LOGGER.error("Unexpected error while creating connection:", e); return null; } } private class DriverConnectionFactory { private final Pattern connStringPattern = Pattern.compile(CONN_STRING_PREFIX + "(\\w+)://(.*)"); private static final String OPENCYPHER = "opencypher"; private static final String GREMLIN = "gremlin"; private static final String SQL_GREMLIN = "sqlgremlin"; private static final String SPARQL = "sparql"; public java.sql.Connection getConnection(final String url, final Properties info) throws SQLException { final String language = getLanguage(url, connStringPattern); final String propertyString = getPropertyString(url, connStringPattern); final String firstPropertyKey = getFirstPropertyKey(language); final Properties properties = createProperties(propertyString, firstPropertyKey, info); switch (language.toLowerCase()) { case OPENCYPHER: return new OpenCypherConnection(new OpenCypherConnectionProperties(properties)); case GREMLIN: return new GremlinConnection(new GremlinConnectionProperties(properties)); case SQL_GREMLIN: return new SqlGremlinConnection(new GremlinConnectionProperties(properties)); case SPARQL: return new SparqlConnection(new SparqlConnectionProperties(properties)); default: LOGGER.error("Encountered Neptune JDBC connection string but failed to parse driver language."); throw SqlError.createSQLException( LOGGER, SqlState.CONNECTION_EXCEPTION, SqlError.INVALID_CONNECTION_PROPERTY); } } private Properties createProperties(final String propertyString, final String firstPropertyKey, final Properties info) { final Properties properties = parsePropertyString(propertyString, firstPropertyKey); if (info != null) { properties.putAll(info); } return properties; } private String getFirstPropertyKey(final String language) throws SQLException { if (OPENCYPHER.equalsIgnoreCase(language)) { return OpenCypherConnectionProperties.ENDPOINT_KEY; } if (GREMLIN.equalsIgnoreCase(language) || SQL_GREMLIN.equalsIgnoreCase(language)) { return GremlinConnectionProperties.CONTACT_POINT_KEY; } if (SPARQL.equalsIgnoreCase(language)) { return SparqlConnectionProperties.ENDPOINT_KEY; } LOGGER.error("Encountered Neptune JDBC connection string but failed to parse endpoint property."); throw SqlError.createSQLException( LOGGER, SqlState.CONNECTION_EXCEPTION, SqlError.INVALID_CONNECTION_PROPERTY); } } }
7,393
0
Create_ds/amazon-neptune-jdbc-driver/src/main/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/main/java/software/aws/neptune/gremlin/GremlinQueryExecutor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.gremlin; import lombok.NonNull; import lombok.SneakyThrows; import org.apache.tinkerpop.gremlin.driver.Client; import org.apache.tinkerpop.gremlin.driver.Cluster; import org.apache.tinkerpop.gremlin.driver.Result; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.aws.neptune.common.IAMHelper; import software.aws.neptune.common.gremlindatamodel.MetadataCache; import software.aws.neptune.gremlin.resultset.GremlinResultSet; import software.aws.neptune.gremlin.resultset.GremlinResultSetGetCatalogs; import software.aws.neptune.gremlin.resultset.GremlinResultSetGetColumns; import software.aws.neptune.gremlin.resultset.GremlinResultSetGetSchemas; import software.aws.neptune.gremlin.resultset.GremlinResultSetGetTableTypes; import software.aws.neptune.gremlin.resultset.GremlinResultSetGetTables; import software.aws.neptune.gremlin.resultset.GremlinResultSetGetTypeInfo; import software.aws.neptune.jdbc.utilities.AuthScheme; import software.aws.neptune.jdbc.utilities.QueryExecutor; import software.aws.neptune.jdbc.utilities.SqlError; import software.aws.neptune.jdbc.utilities.SqlState; import java.lang.reflect.Constructor; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; /** * Implementation of QueryExecutor for Gremlin. */ public class GremlinQueryExecutor extends QueryExecutor { private static final Logger LOGGER = LoggerFactory.getLogger(GremlinQueryExecutor.class); private static final Object CLUSTER_LOCK = new Object(); private static Cluster cluster = null; private static GremlinConnectionProperties previousGremlinConnectionProperties = null; private final Object completableFutureLock = new Object(); private final GremlinConnectionProperties gremlinConnectionProperties; private CompletableFuture<org.apache.tinkerpop.gremlin.driver.ResultSet> completableFuture; /** * GremlinQueryExecutor constructor. * * @param gremlinConnectionProperties GremlinConnectionProperties for use in the executor. */ public GremlinQueryExecutor(final GremlinConnectionProperties gremlinConnectionProperties) { this.gremlinConnectionProperties = gremlinConnectionProperties; } /** * Function to create a cluster builder for Gremlin. * * @param properties Connection properties to use. * @return Cluster builder based on connection properties. * @throws SQLException if internal functions in the properties fail. */ public static Cluster.Builder createClusterBuilder(final GremlinConnectionProperties properties) throws SQLException { final Cluster.Builder builder = Cluster.build(); if (properties.containsKey(GremlinConnectionProperties.CONTACT_POINT_KEY)) { builder.addContactPoint(properties.getContactPoint()); } if (properties.containsKey(GremlinConnectionProperties.PATH_KEY)) { builder.path(properties.getPath()); } if (properties.containsKey(GremlinConnectionProperties.PORT_KEY)) { builder.port(properties.getPort()); } if (properties.containsKey(GremlinConnectionProperties.SERIALIZER_KEY)) { if (properties.isSerializerObject()) { builder.serializer(properties.getSerializerObject()); } else if (properties.isSerializerEnum()) { builder.serializer(properties.getSerializerEnum()); } else if (properties.isChannelizerString()) { builder.serializer(properties.getSerializerString()); } } if (properties.containsKey(GremlinConnectionProperties.ENABLE_SSL_KEY)) { builder.enableSsl(properties.getEnableSsl()); } if (properties.containsKey(GremlinConnectionProperties.SSL_CONTEXT_KEY)) { builder.sslContext(properties.getSslContext()); } if (properties.containsKey(GremlinConnectionProperties.SSL_ENABLED_PROTOCOLS_KEY)) { builder.sslEnabledProtocols(properties.getSslEnabledProtocols()); } if (properties.containsKey(GremlinConnectionProperties.SSL_CIPHER_SUITES_KEY)) { builder.sslCipherSuites(properties.getSslCipherSuites()); } if (properties.containsKey(GremlinConnectionProperties.SSL_SKIP_VALIDATION_KEY)) { builder.sslSkipCertValidation(properties.getSslSkipCertValidation()); } if (properties.containsKey(GremlinConnectionProperties.KEY_STORE_KEY)) { builder.keyStore(properties.getKeyStore()); } if (properties.containsKey(GremlinConnectionProperties.KEY_STORE_PASSWORD_KEY)) { builder.keyStorePassword(properties.getKeyStorePassword()); } if (properties.containsKey(GremlinConnectionProperties.KEY_STORE_TYPE_KEY)) { builder.keyStoreType(properties.getKeyStoreType()); } if (properties.containsKey(GremlinConnectionProperties.TRUST_STORE_KEY)) { builder.trustStore(properties.getTrustStore()); } if (properties.containsKey(GremlinConnectionProperties.TRUST_STORE_PASSWORD_KEY)) { builder.trustStorePassword(properties.getTrustStorePassword()); } if (properties.containsKey(GremlinConnectionProperties.TRUST_STORE_TYPE_KEY)) { builder.trustStoreType(properties.getTrustStoreType()); } if (properties.containsKey(GremlinConnectionProperties.NIO_POOL_SIZE_KEY)) { builder.nioPoolSize(properties.getNioPoolSize()); } if (properties.containsKey(GremlinConnectionProperties.WORKER_POOL_SIZE_KEY)) { builder.workerPoolSize(properties.getWorkerPoolSize()); } if (properties.containsKey(GremlinConnectionProperties.MAX_CONNECTION_POOL_SIZE_KEY)) { builder.maxConnectionPoolSize(properties.getMaxConnectionPoolSize()); } if (properties.containsKey(GremlinConnectionProperties.MIN_CONNECTION_POOL_SIZE_KEY)) { builder.minConnectionPoolSize(properties.getMinConnectionPoolSize()); } if (properties.containsKey(GremlinConnectionProperties.MAX_IN_PROCESS_PER_CONNECTION_KEY)) { builder.maxInProcessPerConnection(properties.getMaxInProcessPerConnection()); } if (properties.containsKey(GremlinConnectionProperties.MIN_IN_PROCESS_PER_CONNECTION_KEY)) { builder.minInProcessPerConnection(properties.getMinInProcessPerConnection()); } if (properties.containsKey(GremlinConnectionProperties.MAX_SIMULT_USAGE_PER_CONNECTION_KEY)) { builder.maxSimultaneousUsagePerConnection(properties.getMaxSimultaneousUsagePerConnection()); } if (properties.containsKey(GremlinConnectionProperties.MIN_SIMULT_USAGE_PER_CONNECTION_KEY)) { builder.minSimultaneousUsagePerConnection(properties.getMinSimultaneousUsagePerConnection()); } if (properties.getAuthScheme() == AuthScheme.IAMSigV4) { IAMHelper.addHandshakeInterceptor(builder); } else if (properties.containsKey(GremlinConnectionProperties.CHANNELIZER_KEY)) { if (properties.isChannelizerGeneric()) { builder.channelizer(properties.getChannelizerGeneric()); } else if (properties.isChannelizerString()) { builder.channelizer(properties.getChannelizerString()); } } if (properties.containsKey(GremlinConnectionProperties.KEEPALIVE_INTERVAL_KEY)) { builder.keepAliveInterval(properties.getKeepAliveInterval()); } if (properties.containsKey(GremlinConnectionProperties.RESULT_ITERATION_BATCH_SIZE_KEY)) { builder.resultIterationBatchSize(properties.getResultIterationBatchSize()); } if (properties.containsKey(GremlinConnectionProperties.MAX_WAIT_FOR_CONNECTION_KEY)) { builder.maxWaitForConnection(properties.getMaxWaitForConnection()); } if (properties.containsKey(GremlinConnectionProperties.MAX_WAIT_FOR_CLOSE_KEY)) { builder.maxWaitForClose(properties.getMaxWaitForClose()); } if (properties.containsKey(GremlinConnectionProperties.MAX_CONTENT_LENGTH_KEY)) { builder.maxContentLength(properties.getMaxContentLength()); } if (properties.containsKey(GremlinConnectionProperties.VALIDATION_REQUEST_KEY)) { builder.validationRequest(properties.getValidationRequest()); } if (properties.containsKey(GremlinConnectionProperties.RECONNECT_INTERVAL_KEY)) { builder.reconnectInterval(properties.getReconnectInterval()); } if (properties.containsKey(GremlinConnectionProperties.LOAD_BALANCING_STRATEGY_KEY)) { builder.loadBalancingStrategy(properties.getLoadBalancingStrategy()); } return builder; } protected static Cluster getCluster(final GremlinConnectionProperties gremlinConnectionProperties) throws SQLException { if (cluster == null || !propertiesEqual(previousGremlinConnectionProperties, gremlinConnectionProperties)) { previousGremlinConnectionProperties = gremlinConnectionProperties; return createClusterBuilder(gremlinConnectionProperties).create(); } return cluster; } /** * Function to close down the cluster. */ public static void close() { synchronized (CLUSTER_LOCK) { if (cluster != null) { cluster.close(); cluster = null; } } } protected static Client getClient(final GremlinConnectionProperties gremlinConnectionProperties) throws SQLException { synchronized (CLUSTER_LOCK) { cluster = getCluster(gremlinConnectionProperties); return cluster.connect().init(); } } /** * Function to return max fetch size. * * @return Max fetch size (Integer max value). */ @Override public int getMaxFetchSize() { return Integer.MAX_VALUE; } /** * Verify that connection to database is functional. * * @param timeout Time in seconds to wait for the database operation used to validate the connection to complete. * @return true if the connection is valid, otherwise false. */ @Override @SneakyThrows public boolean isValid(final int timeout) { LOGGER.info("Checking timeout " + timeout + "."); final Cluster tempCluster = GremlinQueryExecutor.createClusterBuilder(gremlinConnectionProperties).maxWaitForConnection(timeout * 1000) .create(); final Client tempClient = tempCluster.connect(); try { tempClient.init(); // Neptune doesn't support arbitrary math queries, but the below command is valid in Gremlin and is basically // saying return 0. final CompletableFuture<List<Result>> tempCompletableFuture = tempClient.submit("g.inject(0)").all(); tempCompletableFuture.get(timeout, TimeUnit.SECONDS); return true; } catch (final Exception e) { LOGGER.error("Connecting to database failed.", e); } finally { tempClient.close(); tempCluster.close(); } return false; } /** * Function to execute query. * * @param sql Query to execute. * @param statement java.sql.Statement Object required for result set. * @return java.sql.ResultSet object returned from query execution. * @throws SQLException if query execution fails, or it was cancelled. */ @Override public ResultSet executeQuery(final String sql, final Statement statement) throws SQLException { LOGGER.info("GremlinQueryExecutor executeQuery"); final Constructor<?> constructor; try { constructor = GremlinResultSet.class .getConstructor(java.sql.Statement.class, GremlinResultSet.ResultSetInfoWithRows.class); } catch (final NoSuchMethodException e) { throw SqlError.createSQLException( LOGGER, SqlState.INVALID_QUERY_EXPRESSION, SqlError.QUERY_FAILED, e); } return runCancellableQuery(constructor, statement, sql); } /** * Function to get tables. * * @param statement java.sql.Statement Object required for result set. * @param tableName String table name with colon delimits. * @return java.sql.ResultSet object returned from query execution. * @throws SQLException if query execution fails, or it was cancelled. */ @Override public java.sql.ResultSet executeGetTables(final java.sql.Statement statement, final String tableName) throws SQLException { LOGGER.info("GremlinQueryExecutor executeGetTables"); final String endpoint = this.gremlinConnectionProperties.getContactPoint(); if (!MetadataCache.isMetadataCached(endpoint)) { // TODO AN-576: Temp isValid check. Find a better solution inside the export tool to check if connection is valid. if (!statement.getConnection().isValid(3000)) { throw new SQLException("Failed to execute getTables, could not connect to database."); } } MetadataCache.updateCacheIfNotUpdated(gremlinConnectionProperties); return new GremlinResultSetGetTables(statement, MetadataCache.getFilteredCacheNodeColumnInfos(tableName, endpoint), MetadataCache.getFilteredResultSetInfoWithoutRowsForTables(tableName, endpoint)); } /** * Function to get schema. * * @param statement java.sql.Statement Object required for result set. * @return java.sql.ResultSet Object containing schemas. * @throws SQLException if query execution fails, or it was cancelled. */ @Override public java.sql.ResultSet executeGetSchemas(final java.sql.Statement statement) throws SQLException { LOGGER.info("GremlinQueryExecutor executeGetSchemas"); return new GremlinResultSetGetSchemas(statement); } /** * Function to get catalogs. * * @param statement java.sql.Statement Object required for result set. * @return java.sql.ResultSet Object containing catalogs. */ @Override public java.sql.ResultSet executeGetCatalogs(final java.sql.Statement statement) { LOGGER.info("GremlinQueryExecutor executeGetCatalogs"); return new GremlinResultSetGetCatalogs(statement); } /** * Function to get table types. * * @param statement java.sql.Statement Object required for result set. * @return java.sql.ResultSet Object containing table types. */ @Override public java.sql.ResultSet executeGetTableTypes(final java.sql.Statement statement) { LOGGER.info("GremlinQueryExecutor executeGetTableTypes"); return new GremlinResultSetGetTableTypes(statement); } /** * Function to get table types. * * @param statement java.sql.Statement Object required for result set. * @param nodes String containing nodes to get schema for. * @return java.sql.ResultSet Object containing columns. */ @Override public java.sql.ResultSet executeGetColumns(final java.sql.Statement statement, final String nodes) throws SQLException { LOGGER.info("GremlinQueryExecutor executeGetColumns"); final String endpoint = this.gremlinConnectionProperties.getContactPoint(); if (!MetadataCache.isMetadataCached(endpoint)) { // TODO AN-576: Temp isValid check. Find a better solution inside the export tool to check if connection is valid. if (!statement.getConnection().isValid(3000)) { throw new SQLException("Failed to execute getTables, could not connect to database."); } } MetadataCache.updateCacheIfNotUpdated(gremlinConnectionProperties); return new GremlinResultSetGetColumns(statement, MetadataCache.getFilteredCacheNodeColumnInfos(nodes, endpoint), MetadataCache.getFilteredResultSetInfoWithoutRowsForColumns(nodes, endpoint)); } /** * Function to get type info. * * @param statement java.sql.Statement Object required for result set. * @return java.sql.ResultSet Object containing type info. */ @Override public java.sql.ResultSet executeGetTypeInfo(final java.sql.Statement statement) throws SQLException { LOGGER.info("GremlinQueryExecutor executeGetTypeInfo"); return new GremlinResultSetGetTypeInfo(statement); } @SneakyThrows @Override @SuppressWarnings("unchecked") protected <T> T runQuery(final String query) throws SQLException { final Client client = getClient(gremlinConnectionProperties); synchronized (completableFutureLock) { completableFuture = client.submitAsync(query); } final List<Result> results = completableFuture.get().all().get(); final List<Map<String, Object>> rows = new ArrayList<>(); final Map<String, Class<?>> columns = new HashMap<>(); long unnamedColumnIndex = 0L; for (final Object result : results.stream().map(Result::getObject).collect(Collectors.toList())) { if (result instanceof LinkedHashMap) { // We don't know key or value types, so pull it out raw. final Map<?, ?> uncastedRow = (LinkedHashMap<?, ?>) result; // Convert generic key types to string and insert in new map with corresponding value. final Map<String, Object> row = new HashMap<>(); uncastedRow.forEach((key, value) -> row.put(key.toString(), value)); // Add row to List of rows. rows.add(row); // Get columns from row and put in columns List if they aren't already in there. for (final String key : row.keySet()) { if (!columns.containsKey(key)) { final Object value = row.get(key); if (GremlinTypeMapping.checkContains(value.getClass())) { columns.put(key, value.getClass()); } else { columns.put(key, String.class); } } else if (columns.get(key) != row.get(key)) { columns.put(key, String.class); } } } else if (GremlinTypeMapping.checkContains(result.getClass())) { // Result is scalar - generate a new key for the column unnamedColumnIndex = findNextValidColumnIndex(columns, unnamedColumnIndex); final String key = generateColumnKey(unnamedColumnIndex); columns.put(key, result.getClass()); // Create and add new row with generated key final Map<String, Object> row = new HashMap<>(); row.put(key, result); rows.add(row); } else { // If not a map nor scalar best way to handle it seems to be to issue a warning. LOGGER.warn(String.format("Result of type '%s' is not convertible to a Map or Scalar of supported type and will be skipped.", result.getClass().getCanonicalName())); } } final List<String> listColumns = new ArrayList<>(columns.keySet()); return (T) new GremlinResultSet.ResultSetInfoWithRows(rows, columns, listColumns); } @Override protected void performCancel() throws SQLException { synchronized (completableFutureLock) { if (completableFuture != null && !completableFuture.isDone()) { completableFuture.cancel(true); } } } private long findNextValidColumnIndex(@NonNull final Map<String, Class<?>> columns, final long currentIndex) throws SQLException { long index = currentIndex; // While there is a conflict with an existing key increment and regenerate the column key while (columns.containsKey(generateColumnKey(index))) { if (index == Long.MAX_VALUE) { LOGGER.error(String.format("Reached the maximum number of column keys available for scalar columns: %d", index)); throw SqlError.createSQLException( LOGGER, SqlState.NUMERIC_VALUE_OUT_OF_RANGE, SqlError.INVALID_MAX_FIELD_SIZE); } index++; } return index; } private String generateColumnKey(@NonNull final Long unnamedColumnIndex) { return String.format("_col%d", unnamedColumnIndex); } }
7,394
0
Create_ds/amazon-neptune-jdbc-driver/src/main/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/main/java/software/aws/neptune/gremlin/GremlinConnection.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.gremlin; import lombok.Getter; import lombok.NonNull; import software.aws.neptune.NeptuneDatabaseMetadata; import software.aws.neptune.jdbc.Connection; import software.aws.neptune.jdbc.utilities.ConnectionProperties; import software.aws.neptune.jdbc.utilities.QueryExecutor; import java.sql.DatabaseMetaData; import java.sql.SQLException; /** * Gremlin implementation of Connection. */ public class GremlinConnection extends Connection implements java.sql.Connection { @Getter private final GremlinConnectionProperties gremlinConnectionProperties; /** * Gremlin constructor, initializes super class. * * @param connectionProperties ConnectionProperties Object. */ public GremlinConnection(@NonNull final ConnectionProperties connectionProperties) throws SQLException { super(connectionProperties); this.gremlinConnectionProperties = new GremlinConnectionProperties(getConnectionProperties()); } @Override public void doClose() { GremlinQueryExecutor.close(); } @Override public DatabaseMetaData getMetaData() { return new NeptuneDatabaseMetadata(this); } @Override public QueryExecutor getQueryExecutor() throws SQLException { return new GremlinQueryExecutor(getGremlinConnectionProperties()); } }
7,395
0
Create_ds/amazon-neptune-jdbc-driver/src/main/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/main/java/software/aws/neptune/gremlin/GremlinDataSource.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.gremlin; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.aws.neptune.NeptuneDriver; import software.aws.neptune.jdbc.DataSource; import software.aws.neptune.jdbc.utilities.AuthScheme; import software.aws.neptune.jdbc.utilities.SqlError; import javax.sql.PooledConnection; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLClientInfoException; import java.sql.SQLException; /** * Gremlin implementation of DataSource. */ public class GremlinDataSource extends DataSource implements javax.sql.DataSource, javax.sql.ConnectionPoolDataSource { public static final String GREMLIN_PREFIX = NeptuneDriver.CONN_STRING_PREFIX + "gremlin://"; private static final Logger LOGGER = LoggerFactory.getLogger(GremlinDataSource.class); private final GremlinConnectionProperties connectionProperties; /** * GremlinDataSource constructor, initializes super class. */ GremlinDataSource() throws SQLException { super(); this.connectionProperties = new GremlinConnectionProperties(); } @Override public Connection getConnection() throws SQLException { return DriverManager.getConnection(GREMLIN_PREFIX, connectionProperties); } @Override public Connection getConnection(final String username, final String password) throws SQLException { throw SqlError.createSQLFeatureNotSupportedException(LOGGER); } @Override public PooledConnection getPooledConnection() throws SQLException { return new GremlinPooledConnection(getConnection()); } @Override public PooledConnection getPooledConnection(final String user, final String password) throws SQLException { throw SqlError.createSQLFeatureNotSupportedException(LOGGER); } /** * Sets the timeout for opening a connection. * * @return the connection timeout in seconds. */ @Override public int getLoginTimeout() throws SQLException { return connectionProperties.getConnectionTimeoutMillis(); } /** * Sets the timeout for opening a connection. * * @param seconds The connection timeout in seconds. * @throws SQLException if timeout is negative. */ @Override public void setLoginTimeout(final int seconds) throws SQLException { connectionProperties.setConnectionTimeoutMillis(seconds); } /** * Gets the application name. * * @return The application name. */ public String getApplicationName() { return connectionProperties.getApplicationName(); } /** * Sets the application name. * * @param applicationName The application name. * @throws SQLException if value is invalid. */ public void setApplicationName(final String applicationName) throws SQLException { connectionProperties.setApplicationName(applicationName); } /** * Gets the connection endpoint. * * @return The connection endpoint. */ public String getContactPoint() { return connectionProperties.getContactPoint(); } /** * Sets the connection endpoint. * * @param endpoint The connection endpoint. * @throws SQLException if value is invalid. */ public void setContactPoint(final String endpoint) throws SQLException { connectionProperties.setContactPoint(endpoint); } /** * Gets the connection timeout in milliseconds. * * @return The connection timeout in milliseconds. */ public int getConnectionTimeoutMillis() { return connectionProperties.getConnectionTimeoutMillis(); } /** * Sets the connection timeout in milliseconds. * * @param timeoutMillis The connection timeout in milliseconds. * @throws SQLException if value is invalid. */ public void setConnectionTimeoutMillis(final int timeoutMillis) throws SQLException { connectionProperties.setConnectionTimeoutMillis(timeoutMillis); } /** * Gets the connection retry count. * * @return The connection retry count. */ public int getConnectionRetryCount() { return connectionProperties.getConnectionRetryCount(); } /** * Sets the connection retry count. * * @param retryCount The connection retry count. * @throws SQLException if value is invalid. */ public void setConnectionRetryCount(final int retryCount) throws SQLException { connectionProperties.setConnectionRetryCount(retryCount); } /** * Gets the authentication scheme. * * @return The authentication scheme. */ public AuthScheme getAuthScheme() { return connectionProperties.getAuthScheme(); } /** * Sets the authentication scheme. * * @param authScheme The authentication scheme. * @throws SQLException if value is invalid. */ public void setAuthScheme(final AuthScheme authScheme) throws SQLException { connectionProperties.setAuthScheme(authScheme); } /** * Gets the use encryption. * * @return The use encryption. */ public boolean getEnableSsl() { return connectionProperties.getEnableSsl(); } /** * Sets the use encryption. * * @param useEncryption The use encryption. */ public void setEnableSsl(final boolean useEncryption) throws SQLClientInfoException { connectionProperties.setEnableSsl(useEncryption); } }
7,396
0
Create_ds/amazon-neptune-jdbc-driver/src/main/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/main/java/software/aws/neptune/gremlin/GremlinTypeMapping.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.gremlin; import software.aws.neptune.jdbc.utilities.JdbcType; import java.sql.Time; import java.sql.Timestamp; import java.util.HashMap; import java.util.Map; /** * Gremlin type mapping class to simplify type conversion and mapping. */ public class GremlinTypeMapping { public static final Map<Class<?>, JdbcType> GREMLIN_TO_JDBC_TYPE_MAP = new HashMap<>(); static { GREMLIN_TO_JDBC_TYPE_MAP.put(String.class, JdbcType.VARCHAR); GREMLIN_TO_JDBC_TYPE_MAP.put(Boolean.class, JdbcType.BIT); GREMLIN_TO_JDBC_TYPE_MAP.put(byte[].class, JdbcType.VARCHAR); GREMLIN_TO_JDBC_TYPE_MAP.put(Byte.class, JdbcType.TINYINT); GREMLIN_TO_JDBC_TYPE_MAP.put(Short.class, JdbcType.SMALLINT); GREMLIN_TO_JDBC_TYPE_MAP.put(Integer.class, JdbcType.INTEGER); GREMLIN_TO_JDBC_TYPE_MAP.put(Long.class, JdbcType.BIGINT); GREMLIN_TO_JDBC_TYPE_MAP.put(Float.class, JdbcType.REAL); GREMLIN_TO_JDBC_TYPE_MAP.put(Double.class, JdbcType.DOUBLE); GREMLIN_TO_JDBC_TYPE_MAP.put(java.util.Date.class, JdbcType.DATE); GREMLIN_TO_JDBC_TYPE_MAP.put(java.sql.Date.class, JdbcType.DATE); GREMLIN_TO_JDBC_TYPE_MAP.put(Time.class, JdbcType.TIME); GREMLIN_TO_JDBC_TYPE_MAP.put(Timestamp.class, JdbcType.TIMESTAMP); } /** * Function to get JDBC type equivalent of Gremlin input type. * * @param gremlinClass Gremlin class type. * @return JDBC equivalent for Gremlin class type. */ public static JdbcType getJDBCType(final Class<?> gremlinClass) { return GREMLIN_TO_JDBC_TYPE_MAP.getOrDefault(gremlinClass, JdbcType.VARCHAR); } /** * Function to check if Gremlin has a direct converter for the given class type. * * @param gremlinClass Input class type. * @return True if a direct converter exists, false otherwise. */ public static boolean checkContains(final Class<?> gremlinClass) { return GREMLIN_TO_JDBC_TYPE_MAP.containsKey(gremlinClass); } }
7,397
0
Create_ds/amazon-neptune-jdbc-driver/src/main/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/main/java/software/aws/neptune/gremlin/GremlinPooledConnection.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.gremlin; import software.aws.neptune.jdbc.PooledConnection; import java.sql.SQLException; /** * Gremlin implementation of PooledConnection. */ public class GremlinPooledConnection extends PooledConnection implements javax.sql.PooledConnection { /** * GremlinPooledConnection constructor, initializes super class. * * @param connection Connection Object. */ public GremlinPooledConnection(final java.sql.Connection connection) { super(connection); } @Override public java.sql.Connection getConnection() throws SQLException { return new GremlinConnection(new GremlinConnectionProperties()); } }
7,398
0
Create_ds/amazon-neptune-jdbc-driver/src/main/java/software/aws/neptune
Create_ds/amazon-neptune-jdbc-driver/src/main/java/software/aws/neptune/gremlin/GremlinConnectionProperties.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.aws.neptune.gremlin; import com.google.common.collect.ImmutableList; import io.netty.handler.ssl.SslContext; import lombok.NonNull; import org.apache.commons.lang3.SystemUtils; import org.apache.tinkerpop.gremlin.driver.LoadBalancingStrategy; import org.apache.tinkerpop.gremlin.driver.MessageSerializer; import org.apache.tinkerpop.gremlin.driver.ser.Serializers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.aws.neptune.jdbc.Connection; import software.aws.neptune.jdbc.utilities.AuthScheme; import software.aws.neptune.jdbc.utilities.ConnectionProperties; import software.aws.neptune.jdbc.utilities.SqlError; import software.aws.neptune.jdbc.utilities.SqlState; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.sql.SQLClientInfoException; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; /** * Gremlin connection properties class. */ public class GremlinConnectionProperties extends ConnectionProperties { public static final String CONTACT_POINT_KEY = "contactPoint"; public static final String PATH_KEY = "path"; public static final String PORT_KEY = "port"; public static final String SERIALIZER_KEY = "serializer"; public static final String ENABLE_SSL_KEY = "enableSsl"; public static final String SSL_CONTEXT_KEY = "sslContext"; public static final String SSL_ENABLED_PROTOCOLS_KEY = "sslEnabledProtocols"; public static final String SSL_CIPHER_SUITES_KEY = "sslCipherSuites"; public static final String SSL_SKIP_VALIDATION_KEY = "sslSkipCertValidation"; public static final String KEY_STORE_KEY = "keyStore"; public static final String KEY_STORE_PASSWORD_KEY = "keyStorePassword"; public static final String KEY_STORE_TYPE_KEY = "keyStoreType"; public static final String TRUST_STORE_KEY = "trustStore"; public static final String TRUST_STORE_PASSWORD_KEY = "trustStorePassword"; public static final String TRUST_STORE_TYPE_KEY = "trustStoreType"; public static final String NIO_POOL_SIZE_KEY = "nioPoolSize"; public static final String WORKER_POOL_SIZE_KEY = "workerPoolSize"; public static final String MAX_CONNECTION_POOL_SIZE_KEY = "maxConnectionPoolSize"; public static final String MIN_CONNECTION_POOL_SIZE_KEY = "minConnectionPoolSize"; public static final String MAX_IN_PROCESS_PER_CONNECTION_KEY = "maxInProcessPerConnection"; public static final String MIN_IN_PROCESS_PER_CONNECTION_KEY = "minInProcessPerConnection"; public static final String MAX_SIMULT_USAGE_PER_CONNECTION_KEY = "maxSimultaneousUsagePerConnection"; public static final String MIN_SIMULT_USAGE_PER_CONNECTION_KEY = "minSimultaneousUsagePerConnection"; public static final String CHANNELIZER_KEY = "channelizer"; public static final String KEEPALIVE_INTERVAL_KEY = "keepAliveInterval"; public static final String RESULT_ITERATION_BATCH_SIZE_KEY = "resultIterationBatchSize"; public static final String MAX_WAIT_FOR_CONNECTION_KEY = "maxWaitForConnection"; public static final String MAX_WAIT_FOR_CLOSE_KEY = "maxWaitForClose"; public static final String MAX_CONTENT_LENGTH_KEY = "maxContentLength"; public static final String VALIDATION_REQUEST_KEY = "validationRequest"; public static final String RECONNECT_INTERVAL_KEY = "reconnectInterval"; public static final String LOAD_BALANCING_STRATEGY_KEY = "loadBalancingStrategy"; public static final String DEFAULT_PATH = "/gremlin"; public static final int DEFAULT_PORT = 8182; public static final boolean DEFAULT_ENABLE_SSL = true; public static final boolean DEFAULT_SSL_SKIP_VALIDATION = false; public static final Serializers DEFAULT_SERIALIZER = Serializers.GRAPHBINARY_V1D0; public static final Map<String, Object> DEFAULT_PROPERTIES_MAP = new HashMap<>(); private static final List<String> SUPPORTED_PROPERTIES_LIST = ImmutableList.<String>builder() .add(CONTACT_POINT_KEY) .add(PATH_KEY) .add(PORT_KEY) .add(SERIALIZER_KEY) .add(ENABLE_SSL_KEY) .add(SSL_CONTEXT_KEY) .add(SSL_ENABLED_PROTOCOLS_KEY) .add(SSL_CIPHER_SUITES_KEY) .add(SSL_SKIP_VALIDATION_KEY) .add(KEY_STORE_KEY) .add(KEY_STORE_PASSWORD_KEY) .add(KEY_STORE_TYPE_KEY) .add(TRUST_STORE_KEY) .add(TRUST_STORE_PASSWORD_KEY) .add(TRUST_STORE_TYPE_KEY) .add(NIO_POOL_SIZE_KEY) .add(WORKER_POOL_SIZE_KEY) .add(MAX_CONNECTION_POOL_SIZE_KEY) .add(MIN_CONNECTION_POOL_SIZE_KEY) .add(MAX_IN_PROCESS_PER_CONNECTION_KEY) .add(MIN_IN_PROCESS_PER_CONNECTION_KEY) .add(MAX_SIMULT_USAGE_PER_CONNECTION_KEY) .add(MIN_SIMULT_USAGE_PER_CONNECTION_KEY) .add(CHANNELIZER_KEY) .add(KEEPALIVE_INTERVAL_KEY) .add(RESULT_ITERATION_BATCH_SIZE_KEY) .add(MAX_WAIT_FOR_CONNECTION_KEY) .add(MAX_WAIT_FOR_CLOSE_KEY) .add(MAX_CONTENT_LENGTH_KEY) .add(VALIDATION_REQUEST_KEY) .add(RECONNECT_INTERVAL_KEY) .add(LOAD_BALANCING_STRATEGY_KEY) .build(); private static final Map<String, ConnectionProperties.PropertyConverter<?>> PROPERTY_CONVERTER_MAP = new HashMap<>(); private static final Logger LOGGER = LoggerFactory.getLogger(GremlinConnectionProperties.class); static { PROPERTY_CONVERTER_MAP.put(CONTACT_POINT_KEY, (key, value) -> value); PROPERTY_CONVERTER_MAP.put(PATH_KEY, (key, value) -> value); PROPERTY_CONVERTER_MAP.put(PORT_KEY, ConnectionProperties::toUnsigned); PROPERTY_CONVERTER_MAP.put(ENABLE_SSL_KEY, ConnectionProperties::toBoolean); PROPERTY_CONVERTER_MAP.put(NIO_POOL_SIZE_KEY, ConnectionProperties::toUnsigned); PROPERTY_CONVERTER_MAP.put(WORKER_POOL_SIZE_KEY, ConnectionProperties::toUnsigned); PROPERTY_CONVERTER_MAP.put(MAX_CONNECTION_POOL_SIZE_KEY, ConnectionProperties::toUnsigned); PROPERTY_CONVERTER_MAP.put(MIN_CONNECTION_POOL_SIZE_KEY, ConnectionProperties::toUnsigned); PROPERTY_CONVERTER_MAP.put(MAX_IN_PROCESS_PER_CONNECTION_KEY, ConnectionProperties::toUnsigned); PROPERTY_CONVERTER_MAP.put(MIN_IN_PROCESS_PER_CONNECTION_KEY, ConnectionProperties::toUnsigned); PROPERTY_CONVERTER_MAP.put(MAX_SIMULT_USAGE_PER_CONNECTION_KEY, ConnectionProperties::toUnsigned); PROPERTY_CONVERTER_MAP.put(MIN_SIMULT_USAGE_PER_CONNECTION_KEY, ConnectionProperties::toUnsigned); PROPERTY_CONVERTER_MAP.put(KEEPALIVE_INTERVAL_KEY, ConnectionProperties::toUnsigned); PROPERTY_CONVERTER_MAP.put(RESULT_ITERATION_BATCH_SIZE_KEY, ConnectionProperties::toUnsigned); PROPERTY_CONVERTER_MAP.put(MAX_WAIT_FOR_CONNECTION_KEY, ConnectionProperties::toUnsigned); PROPERTY_CONVERTER_MAP.put(MAX_WAIT_FOR_CLOSE_KEY, ConnectionProperties::toUnsigned); PROPERTY_CONVERTER_MAP.put(MAX_CONTENT_LENGTH_KEY, ConnectionProperties::toUnsigned); PROPERTY_CONVERTER_MAP.put(RECONNECT_INTERVAL_KEY, ConnectionProperties::toUnsigned); PROPERTY_CONVERTER_MAP.put(SSL_SKIP_VALIDATION_KEY, ConnectionProperties::toBoolean); } static { DEFAULT_PROPERTIES_MAP.put(CONTACT_POINT_KEY, ""); DEFAULT_PROPERTIES_MAP.put(PATH_KEY, DEFAULT_PATH); DEFAULT_PROPERTIES_MAP.put(PORT_KEY, DEFAULT_PORT); DEFAULT_PROPERTIES_MAP.put(ENABLE_SSL_KEY, DEFAULT_ENABLE_SSL); DEFAULT_PROPERTIES_MAP.put(SSL_SKIP_VALIDATION_KEY, DEFAULT_SSL_SKIP_VALIDATION); DEFAULT_PROPERTIES_MAP.put(SERIALIZER_KEY, DEFAULT_SERIALIZER); // Set to maximum value by default. Apparently max value is 1 GB. // https://stackoverflow.com/questions/58055662/aws-neptune-io-netty-handler-codec-corruptedframeexception DEFAULT_PROPERTIES_MAP.put(MAX_CONTENT_LENGTH_KEY, 1024 * 1024 * 1024); } /** * GremlinConnectionProperties constructor. */ public GremlinConnectionProperties() throws SQLException { super(new Properties(), DEFAULT_PROPERTIES_MAP, PROPERTY_CONVERTER_MAP); } /** * GremlinConnectionProperties constructor. * * @param properties Properties to examine and extract key details from. */ public GremlinConnectionProperties(final Properties properties) throws SQLException { super(properties, DEFAULT_PROPERTIES_MAP, PROPERTY_CONVERTER_MAP); } /** * Get the number of processors available to the Java virtual machine. * * @return The number of processors available to the Java virtual machine. */ private static int getNumberOfProcessors() { // get the runtime object associated with the current Java application return Runtime.getRuntime().availableProcessors(); } @Override public String getHostname() { return getContactPoint(); } @Override public void sshTunnelOverride(final int port) throws SQLException { setPort(port); } protected boolean isEncryptionEnabled() { // Neptune only supports https when using SPARQL. return getEnableSsl(); } /** * Gets the connection contact point. * * @return The connection contact point. */ public String getContactPoint() { return getProperty(CONTACT_POINT_KEY); } /** * Sets the connection contact point. * * @param contactPoint The connection contact point. * @throws SQLException if value is invalid. */ public void setContactPoint(@NonNull final String contactPoint) throws SQLException { setProperty(CONTACT_POINT_KEY, (String) PROPERTY_CONVERTER_MAP.get(CONTACT_POINT_KEY).convert(CONTACT_POINT_KEY, contactPoint)); } /** * Gets the path to the Gremlin service on the host. * * @return The path to the Gremlin service. */ public String getPath() { return getProperty(PATH_KEY); } /** * Sets the path to the Gremlin service on the host. * * @param path The path to the Gremlin service. * @throws SQLException if value is invalid. */ public void setPath(@NonNull final String path) throws SQLException { setProperty(PATH_KEY, (String) PROPERTY_CONVERTER_MAP.get(PATH_KEY).convert(PATH_KEY, path)); } /** * Gets the port that the Gremlin Servers will be listening on. * * @return The port. */ @Override public int getPort() { return (int) get(PORT_KEY); } /** * Sets the port that the Gremlin Servers will be listening on. * * @param port The port. */ public void setPort(final int port) throws SQLException { if (port < 0) { throw invalidConnectionPropertyError(PORT_KEY, port); } put(PORT_KEY, port); } /** * Check whether the Serializer is an object. * * @return True if Serializer is an object, otherwise false. */ public boolean isSerializerObject() { if (!containsKey(SERIALIZER_KEY)) { return false; } return (get(SERIALIZER_KEY) instanceof MessageSerializer); } /** * Check whether the Serializer is an enum. * * @return True if Serializer is an enum, otherwise false. */ public boolean isSerializerEnum() { if (!containsKey(SERIALIZER_KEY)) { return false; } return (get(SERIALIZER_KEY) instanceof Serializers); } /** * Check whether the Serializer is a string. * * @return True if Serializer is a string, otherwise false. */ public boolean isSerializerString() { if (!containsKey(SERIALIZER_KEY)) { return false; } return (get(SERIALIZER_KEY) instanceof String); } /** * Gets the MessageSerializer to use. * * @return The MessageSerializer. */ public MessageSerializer getSerializerObject() throws SQLException { if (!containsKey(SERIALIZER_KEY)) { return null; } final Object serializer = get(SERIALIZER_KEY); if (serializer instanceof MessageSerializer) { return (MessageSerializer) serializer; } else { throw SqlError.createSQLException(LOGGER, SqlState.DATA_TYPE_TRANSFORM_VIOLATION, SqlError.INVALID_TYPE_CONVERSION, serializer.getClass().getCanonicalName(), MessageSerializer.class.getCanonicalName()); } } /** * Gets the Serializers enum. * * @return The Serializers enum. */ public Serializers getSerializerEnum() throws SQLException { if (!containsKey(SERIALIZER_KEY)) { return null; } final Object serializer = get(SERIALIZER_KEY); if (serializer instanceof Serializers) { return (Serializers) serializer; } else { throw SqlError.createSQLException(LOGGER, SqlState.DATA_TYPE_TRANSFORM_VIOLATION, SqlError.INVALID_TYPE_CONVERSION, serializer.getClass().getCanonicalName(), Serializers.class.getCanonicalName()); } } /** * Gets the MessageSerializer enum name. * * @return The MessageSerializer enum name. */ public String getSerializerString() { if (!containsKey(SERIALIZER_KEY)) { return null; } final Object serializer = get(SERIALIZER_KEY); if (serializer instanceof String) { return (String) serializer; } else { return serializer.toString(); } } /** * Sets the MessageSerializer to use. * * @param serializer The MessageSerializer object. * @throws SQLException if value is invalid. */ public void setSerializer(@NonNull final MessageSerializer serializer) throws SQLException { put(SERIALIZER_KEY, serializer); } /** * Sets the MessageSerializer to use via the Serializers enum. * * @param serializer The Serializers enum. * @throws SQLException if value is invalid. */ public void setSerializer(@NonNull final Serializers serializer) throws SQLException { put(SERIALIZER_KEY, serializer); } /** * Sets the MessageSerializer to use given the exact name of a Serializers enum. * * @param serializerMimeType The exact name of a Serializers enum. * @throws SQLException if value is invalid. */ public void setSerializer(@NonNull final String serializerMimeType) throws SQLException { put(SERIALIZER_KEY, serializerMimeType); } /** * Gets the enable ssl flag. * * @return The enable ssl flag. */ public boolean getEnableSsl() { return (boolean) get(ENABLE_SSL_KEY); } /** * Sets the enable ssl flag. * * @param enableSsl The enable ssl flag. */ public void setEnableSsl(final boolean enableSsl) throws SQLClientInfoException { if (!enableSsl && getAuthScheme().equals(AuthScheme.IAMSigV4)) { throw SqlError.createSQLClientInfoException( LOGGER, Connection.getFailures("useEncrpytion", "true"), SqlError.INVALID_CONNECTION_PROPERTY, "useEncrpytion", "'false' when authScheme is set to 'IAMSigV4'"); } put(ENABLE_SSL_KEY, enableSsl); } /** * Gets the SslContext. * * @return The SslContext. */ public SslContext getSslContext() { if (!containsKey(SSL_CONTEXT_KEY)) { return null; } return (SslContext) get(SSL_CONTEXT_KEY); } /** * Sets the SslContext. * * @param sslContext The SslContext. * @throws SQLException if value is invalid. */ public void setSslContext(@NonNull final SslContext sslContext) throws SQLException { put(SSL_CONTEXT_KEY, sslContext); } /** * Gets the list of enabled SSL protocols. * * @return The list of enabled SSL protocols. */ @SuppressWarnings("unchecked") public List<String> getSslEnabledProtocols() { if (!containsKey(SSL_ENABLED_PROTOCOLS_KEY)) { return null; } return (List<String>) get(SSL_ENABLED_PROTOCOLS_KEY); } /** * Sets the list of SSL protocols to enable. * * @param sslEnabledProtocols The list of enabled SSL protocols. * @throws SQLException if value is invalid. */ public void setSslEnabledProtocols(@NonNull final List<String> sslEnabledProtocols) throws SQLException { put(SSL_ENABLED_PROTOCOLS_KEY, sslEnabledProtocols); } /** * Gets the list of enabled cipher suites. * * @return The list of enabled cipher suites. */ @SuppressWarnings("unchecked") public List<String> getSslCipherSuites() { if (!containsKey(SSL_CIPHER_SUITES_KEY)) { return null; } return (List<String>) get(SSL_CIPHER_SUITES_KEY); } /** * Sets the list of cipher suites to enable. * * @param sslCipherSuites The list of enabled cipher suites. * @throws SQLException if value is invalid. */ public void setSslCipherSuites(@NonNull final List<String> sslCipherSuites) throws SQLException { put(SSL_CIPHER_SUITES_KEY, sslCipherSuites); } /** * Gets whether to trust all certificates and not perform any validation. * * @return The skip SSL validation flag. */ public boolean getSslSkipCertValidation() { return (boolean) get(SSL_SKIP_VALIDATION_KEY); } /** * Sets whether to trust all certificates and not perform any validation. * * @param sslSkipCertValidation The skip SSL validation flag. */ public void setSslSkipCertValidation(final boolean sslSkipCertValidation) { put(SSL_SKIP_VALIDATION_KEY, sslSkipCertValidation); } /** * Gets the file location of the private key in JKS or PKCS#12 format. * * @return The file location of the private key store, or null if not found. */ public String getKeyStore() { if (!containsKey(KEY_STORE_KEY)) { return null; } return getProperty(KEY_STORE_KEY); } /** * Sets the file location of the private key in JKS or PKCS#12 format. * * @param keyStore The file location of the private key store. * @throws SQLException if value is invalid. */ public void setKeyStore(@NonNull final String keyStore) throws SQLException { put(KEY_STORE_KEY, keyStore); } /** * Gets the password of the keyStore, or null if it's not password-protected. * * @return The password of the keyStore, or null if it's not password-protected. */ public String getKeyStorePassword() { if (!containsKey(KEY_STORE_PASSWORD_KEY)) { return null; } return getProperty(KEY_STORE_PASSWORD_KEY); } /** * Sets the password of the keyStore, or null if it's not password-protected. * * @param keyStorePassword The password of the keyStore. * @throws SQLException if value is invalid. */ public void setKeyStorePassword(final String keyStorePassword) throws SQLException { if (keyStorePassword != null) { put(KEY_STORE_PASSWORD_KEY, keyStorePassword); } else { remove(KEY_STORE_PASSWORD_KEY); } } /** * Gets the format of the keyStore, either JKS or PKCS12. * * @return The format of the keyStore, or null if not found. */ public String getKeyStoreType() { if (!containsKey(KEY_STORE_TYPE_KEY)) { return null; } return getProperty(KEY_STORE_TYPE_KEY); } /** * Sets the format of the keyStore, either JKS or PKCS12. * * @param keyStoreType TThe format of the keyStore. * @throws SQLException if value is invalid. */ public void setKeyStoreType(@NonNull final String keyStoreType) throws SQLException { put(KEY_STORE_TYPE_KEY, keyStoreType); } /** * Gets the file location for a SSL Certificate Chain to use when SSL is enabled. * * @return The file location for a SSL Certificate Chain. */ public String getTrustStore() { if (!containsKey(TRUST_STORE_KEY)) { return null; } return getProperty(TRUST_STORE_KEY); } /** * Sets the file location for a SSL Certificate Chain to use when SSL is enabled. * * @param trustStore The file location for a SSL Certificate Chain. * @throws SQLException if value is invalid. */ public void setTrustStore(@NonNull final String trustStore) throws SQLException { put(TRUST_STORE_KEY, trustStore); } /** * Gets the password of the trustStore, or null if it's not password-protected. * * @return The password of the trustStore, or null if it's not password-protected. */ public String getTrustStorePassword() { if (!containsKey(TRUST_STORE_PASSWORD_KEY)) { return null; } return getProperty(TRUST_STORE_PASSWORD_KEY); } /** * Sets the password of the trustStore, or null if it's not password-protected. * * @param trustStorePassword The password of the trustStore. * @throws SQLException if value is invalid. */ public void setTrustStorePassword(final String trustStorePassword) throws SQLException { if (trustStorePassword != null) { put(TRUST_STORE_PASSWORD_KEY, trustStorePassword); } else { remove(TRUST_STORE_PASSWORD_KEY); } } /** * Gets the format of the trustStore, either JKS or PKCS12. * * @return The format of the trustStore, or null if not found. */ public String getTrustStoreType() { if (!containsKey(TRUST_STORE_TYPE_KEY)) { return null; } return getProperty(TRUST_STORE_TYPE_KEY); } /** * Sets the format of the trustStore, either JKS or PKCS12. * * @param trustStoreType TThe format of the trustStore. * @throws SQLException if value is invalid. */ public void setTrustStoreType(@NonNull final String trustStoreType) throws SQLException { put(TRUST_STORE_TYPE_KEY, trustStoreType); } /** * Gets the size of the pool for handling request/response operations. * * @return The size of the Nio pool. */ public int getNioPoolSize() { if (!containsKey(NIO_POOL_SIZE_KEY)) { return 0; } return (int) get(NIO_POOL_SIZE_KEY); } /** * Sets the size of the pool for handling request/response operations. * * @param nioPoolSize The size of the Nio pool. * @throws SQLException if value is invalid. */ public void setNioPoolSize(final int nioPoolSize) throws SQLException { if (nioPoolSize < 0) { throw invalidConnectionPropertyError(NIO_POOL_SIZE_KEY, nioPoolSize); } put(NIO_POOL_SIZE_KEY, nioPoolSize); } /** * Gets the size of the pool for handling background work. * * @return The size of the worker pool. */ public int getWorkerPoolSize() { if (!containsKey(WORKER_POOL_SIZE_KEY)) { return 0; } return (int) get(WORKER_POOL_SIZE_KEY); } /** * Sets the size of the pool for handling background work. * * @param workerPoolSize The size of the worker pool. * @throws SQLException if value is invalid. */ public void setWorkerPoolSize(final int workerPoolSize) throws SQLException { if (workerPoolSize < 0) { throw invalidConnectionPropertyError(WORKER_POOL_SIZE_KEY, workerPoolSize); } put(WORKER_POOL_SIZE_KEY, workerPoolSize); } /** * Gets the maximum connection pool size. * * @return The maximum connection pool size. */ public int getMaxConnectionPoolSize() { if (!containsKey(MAX_CONNECTION_POOL_SIZE_KEY)) { return 0; } return (int) get(MAX_CONNECTION_POOL_SIZE_KEY); } /** * Sets the maximum connection pool size. * * @param maxConnectionPoolSize The maximum connection pool size. * @throws SQLException if value is invalid. */ public void setMaxConnectionPoolSize(final int maxConnectionPoolSize) throws SQLException { if (maxConnectionPoolSize < 0) { throw invalidConnectionPropertyError(MAX_CONNECTION_POOL_SIZE_KEY, maxConnectionPoolSize); } put(MAX_CONNECTION_POOL_SIZE_KEY, maxConnectionPoolSize); } /** * Gets the minimum connection pool size. * * @return The minimum connection pool size. */ public int getMinConnectionPoolSize() { if (!containsKey(MIN_CONNECTION_POOL_SIZE_KEY)) { return 0; } return (int) get(MIN_CONNECTION_POOL_SIZE_KEY); } /** * Sets the minimum connection pool size. * * @param minConnectionPoolSize The minimum connection pool size. * @throws SQLException if value is invalid. */ public void setMinConnectionPoolSize(final int minConnectionPoolSize) throws SQLException { if (minConnectionPoolSize < 0) { throw invalidConnectionPropertyError(MIN_CONNECTION_POOL_SIZE_KEY, minConnectionPoolSize); } put(MIN_CONNECTION_POOL_SIZE_KEY, minConnectionPoolSize); } /** * Gets the maximum number of in-flight requests that can occur on a Connection. * * @return The maximum in-flight requests per Connection. */ public int getMaxInProcessPerConnection() { if (!containsKey(MAX_IN_PROCESS_PER_CONNECTION_KEY)) { return 0; } return (int) get(MAX_IN_PROCESS_PER_CONNECTION_KEY); } /** * Sets the maximum number of in-flight requests that can occur on a Connection. * * @param maxInProcessPerConnection The maximum in-flight requests per Connection. * @throws SQLException if value is invalid. */ public void setMaxInProcessPerConnection(final int maxInProcessPerConnection) throws SQLException { if (maxInProcessPerConnection < 0) { throw invalidConnectionPropertyError(MAX_IN_PROCESS_PER_CONNECTION_KEY, maxInProcessPerConnection); } put(MAX_IN_PROCESS_PER_CONNECTION_KEY, maxInProcessPerConnection); } /** * Gets the minimum number of in-flight requests that can occur on a Connection before it is considered for closing on return to the ConnectionPool. * * @return The minimum in-flight requests per Connection. */ public int getMinInProcessPerConnection() { if (!containsKey(MIN_IN_PROCESS_PER_CONNECTION_KEY)) { return 0; } return (int) get(MIN_IN_PROCESS_PER_CONNECTION_KEY); } /** * Sets the minimum number of in-flight requests that can occur on a Connection before it is considered for closing on return to the ConnectionPool. * * @param minInProcessPerConnection The minimum in-flight requests per Connection. * @throws SQLException if value is invalid. */ public void setMinInProcessPerConnection(final int minInProcessPerConnection) throws SQLException { if (minInProcessPerConnection < 0) { throw invalidConnectionPropertyError(MIN_IN_PROCESS_PER_CONNECTION_KEY, minInProcessPerConnection); } put(MIN_IN_PROCESS_PER_CONNECTION_KEY, minInProcessPerConnection); } /** * Gets the maximum number of times that a Connection can be borrowed from the pool simultaneously. * * @return The maximum number of simultaneous usage per Connection. */ public int getMaxSimultaneousUsagePerConnection() { if (!containsKey(MAX_SIMULT_USAGE_PER_CONNECTION_KEY)) { return 0; } return (int) get(MAX_SIMULT_USAGE_PER_CONNECTION_KEY); } /** * Sets the maximum number of times that a Connection can be borrowed from the pool simultaneously. * * @param maxSimultUsagePerConnection The maximum number of simultaneous usage per Connection. * @throws SQLException if value is invalid. */ public void setMaxSimultaneousUsagePerConnection(final int maxSimultUsagePerConnection) throws SQLException { if (maxSimultUsagePerConnection < 0) { throw invalidConnectionPropertyError(MAX_SIMULT_USAGE_PER_CONNECTION_KEY, maxSimultUsagePerConnection); } put(MAX_SIMULT_USAGE_PER_CONNECTION_KEY, maxSimultUsagePerConnection); } /** * Gets the minimum number of times that a Connection should be borrowed from the pool before it falls under consideration for closing. * * @return The minimum number of simultaneous usage per Connection. */ public int getMinSimultaneousUsagePerConnection() { if (!containsKey(MIN_SIMULT_USAGE_PER_CONNECTION_KEY)) { return 0; } return (int) get(MIN_SIMULT_USAGE_PER_CONNECTION_KEY); } /** * Sets the minimum number of times that a Connection should be borrowed from the pool before it falls under consideration for closing. * * @param minSimultUsagePerConnection The minimum number of simultaneous usage per Connection. * @throws SQLException if value is invalid. */ public void setMinSimultaneousUsagePerConnection(final int minSimultUsagePerConnection) throws SQLException { if (minSimultUsagePerConnection < 0) { throw invalidConnectionPropertyError(MIN_SIMULT_USAGE_PER_CONNECTION_KEY, minSimultUsagePerConnection); } put(MIN_SIMULT_USAGE_PER_CONNECTION_KEY, minSimultUsagePerConnection); } /** * Check whether the Channelizer is a class. * * @return True if Channelizer is a class, otherwise false. */ public boolean isChannelizerGeneric() { if (!containsKey(CHANNELIZER_KEY)) { return false; } return (get(CHANNELIZER_KEY) instanceof Class<?>); } /** * Check whether the Channelizer is a string. * * @return True if Channelizer is a string, otherwise false. */ public boolean isChannelizerString() { if (!containsKey(CHANNELIZER_KEY)) { return false; } return (get(CHANNELIZER_KEY) instanceof String); } /** * Gets the Channelizer class. * * @return The Channelizer class. */ public Class<?> getChannelizerGeneric() { if (!containsKey(CHANNELIZER_KEY)) { return null; } return (Class<?>) get(CHANNELIZER_KEY); } /** * Gets the Channelizer class name. * * @return The Channelizer class name. */ public String getChannelizerString() { if (!containsKey(CHANNELIZER_KEY)) { return null; } return (String) get(CHANNELIZER_KEY); } /** * Sets the Channelizer implementation to use on the client when creating a Connection. * * @param channelizerClass The Channelizer class. * @throws SQLException if value is invalid. */ public void setChannelizer(@NonNull final Class<?> channelizerClass) throws SQLException { put(CHANNELIZER_KEY, channelizerClass); } /** * Sets the Channelizer implementation to use on the client when creating a Connection. * * @param channelizerClass The Channelizer class name. * @throws SQLException if value is invalid. */ public void setChannelizer(@NonNull final String channelizerClass) throws SQLException { put(CHANNELIZER_KEY, channelizerClass); } /** * Gets the keep alive interval. * * @return The keep alive interval. */ public int getKeepAliveInterval() { if (!containsKey(KEEPALIVE_INTERVAL_KEY)) { return 0; } return (int) get(KEEPALIVE_INTERVAL_KEY); } /** * Sets the keep alive interval, as the length of time in milliseconds to wait on an idle connection * before sending a keep-alive request. This setting is only relevant to Channelizer implementations * that return true for Channelizer.supportsKeepAlive(). Set to zero to disable this feature. * * @param keepAliveInterval The keep alive interval. */ public void setKeepAliveInterval(final int keepAliveInterval) throws SQLException { if (keepAliveInterval < 0) { throw invalidConnectionPropertyError(KEEPALIVE_INTERVAL_KEY, keepAliveInterval); } put(KEEPALIVE_INTERVAL_KEY, keepAliveInterval); } /** * Gets how many results are returned per batch. * * @return The result iteration batch size. */ public int getResultIterationBatchSize() { if (!containsKey(RESULT_ITERATION_BATCH_SIZE_KEY)) { return 0; } return (int) get(RESULT_ITERATION_BATCH_SIZE_KEY); } /** * Sets how many results are returned per batch. * * @param resultIterationBatchSize The result iteration batch size. */ public void setResultIterationBatchSize(final int resultIterationBatchSize) throws SQLException { if (resultIterationBatchSize < 0) { throw invalidConnectionPropertyError(RESULT_ITERATION_BATCH_SIZE_KEY, resultIterationBatchSize); } put(RESULT_ITERATION_BATCH_SIZE_KEY, resultIterationBatchSize); } /** * Gets the maximum amount of time to wait for a connection to be borrowed from the connection pool. * * @return The maximum wait for Connection. */ public int getMaxWaitForConnection() { if (!containsKey(MAX_WAIT_FOR_CONNECTION_KEY)) { return 0; } return (int) get(MAX_WAIT_FOR_CONNECTION_KEY); } /** * Sets the maximum amount of time to wait for a connection to be borrowed from the connection pool. * * @param maxWaitForConnection The maximum wait for Connection. * @throws SQLException if value is invalid. */ public void setMaxWaitForConnection(final int maxWaitForConnection) throws SQLException { if (maxWaitForConnection < 0) { throw invalidConnectionPropertyError(MAX_WAIT_FOR_CONNECTION_KEY, maxWaitForConnection); } put(MAX_WAIT_FOR_CONNECTION_KEY, maxWaitForConnection); } /** * Gets the maximum amount of time in milliseconds to wait for the Connection to close before timing out. * * @return The maximum wait to close. */ public int getMaxWaitForClose() { if (!containsKey(MAX_WAIT_FOR_CLOSE_KEY)) { return 0; } return (int) get(MAX_WAIT_FOR_CLOSE_KEY); } /** * Sets the maximum amount of time in milliseconds to wait for the Connection to close before timing out. * * @param maxWaitForClose The maximum wait to close. * @throws SQLException if value is invalid. */ public void setMaxWaitForClose(final int maxWaitForClose) throws SQLException { if (maxWaitForClose < 0) { throw invalidConnectionPropertyError(MAX_WAIT_FOR_CLOSE_KEY, maxWaitForClose); } put(MAX_WAIT_FOR_CLOSE_KEY, maxWaitForClose); } /** * Gets the maximum size in bytes of any request sent to the server. * * @return The maximum size in bytes. */ public int getMaxContentLength() { if (!containsKey(MAX_CONTENT_LENGTH_KEY)) { return 0; } return (int) get(MAX_CONTENT_LENGTH_KEY); } /** * Sets the maximum size in bytes of any request sent to the server. * * @param maxContentLength The maximum size in bytes. * @throws SQLException if value is invalid. */ public void setMaxContentLength(final int maxContentLength) throws SQLException { if (maxContentLength < 0) { throw invalidConnectionPropertyError(MAX_CONTENT_LENGTH_KEY, maxContentLength); } put(MAX_CONTENT_LENGTH_KEY, maxContentLength); } /** * Gets a valid Gremlin script that can be used to test remote operations. * * @return The Gremlin script. */ public String getValidationRequest() { if (!containsKey(VALIDATION_REQUEST_KEY)) { return null; } return getProperty(VALIDATION_REQUEST_KEY); } /** * Sets a valid Gremlin script that can be used to test remote operations. * * @param script The Gremlin script. * @throws SQLException if value is invalid. */ public void setValidationRequest(@NonNull final String script) throws SQLException { put(VALIDATION_REQUEST_KEY, script); } /** * Gets the time in milliseconds to wait between retries when attempting to reconnect to a dead host. * * @return The reconnect interval. */ public int getReconnectInterval() { if (!containsKey(RECONNECT_INTERVAL_KEY)) { return 0; } return (int) get(RECONNECT_INTERVAL_KEY); } /** * Sets the time in milliseconds to wait between retries when attempting to reconnect to a dead host. * * @param reconnectInterval The reconnect interval. * @throws SQLException if value is invalid. */ public void setReconnectInterval(final int reconnectInterval) throws SQLException { if (reconnectInterval < 0) { throw invalidConnectionPropertyError(RECONNECT_INTERVAL_KEY, reconnectInterval); } put(RECONNECT_INTERVAL_KEY, reconnectInterval); } /** * Gets the load balancing strategy. * * @return The load balancing strategy. */ public LoadBalancingStrategy getLoadBalancingStrategy() { if (!containsKey(LOAD_BALANCING_STRATEGY_KEY)) { return null; } return (LoadBalancingStrategy) get(LOAD_BALANCING_STRATEGY_KEY); } /** * Sets the load balancing strategy to use on the client side. * * @param strategy The load balancing strategy. * @throws SQLException if value is invalid. */ public void setLoadBalancingStrategy(@NonNull final LoadBalancingStrategy strategy) throws SQLException { put(LOAD_BALANCING_STRATEGY_KEY, strategy); } /** * Validate the supported properties. */ @Override protected void validateProperties() throws SQLException { if (getAuthScheme() != null && getAuthScheme().equals(AuthScheme.IAMSigV4)) { // If IAMSigV4 is specified, we need the region provided to us. validateServiceRegionEnvVariable(); setServiceRegionEnvironmentVariable(getServiceRegion()); if (!getEnableSsl()) { throw invalidConnectionPropertyValueError(ENABLE_SSL_KEY, "SSL encryption must be enabled if IAMSigV4 is used"); } } } /** * Check if the property is supported by the driver. * * @param name The name of the property. * @return {@code true} if property is supported; {@code false} otherwise. */ @Override public boolean isSupportedProperty(final String name) { return SUPPORTED_PROPERTIES_LIST.contains(name); } /** * Updates the SERVICE_REGION env variable in JVM to the region set by Gremlin connection properties */ private void setServiceRegionEnvironmentVariable(final String region) throws SQLException { if (region.equals(System.getenv("SERVICE_REGION"))) { return; } if (System.getenv("SERVICE_REGION") != null) { LOGGER.info(String.format("Overriding the current SERVICE_REGION environment variable with '%s'.", region)); } try { if (SystemUtils.IS_OS_WINDOWS) { setWindowsEnvironmentVariable(region); } else { setMacEnvironmentVariable(region); } } catch (final Exception e) { throw new SQLException(String.format("Error: unable to set SERVICE_REGION environment variable to '%s' - %s.", region, e)); } } @SuppressWarnings({ "unchecked" }) private void setWindowsEnvironmentVariable(final String value) throws Exception { final Class<?> processEnv = Class.forName("java.lang.ProcessEnvironment"); final Method getenv = processEnv.getDeclaredMethod("getenv", String.class); getenv.setAccessible(true); final Field caseInsensitiveEnv = processEnv.getDeclaredField("theCaseInsensitiveEnvironment"); caseInsensitiveEnv.setAccessible(true); final Map<String, String> envMap = (Map<String, String>) caseInsensitiveEnv.get(null); envMap.put("SERVICE_REGION", value); } @SuppressWarnings({ "unchecked" }) private void setMacEnvironmentVariable(final String value) throws Exception { final Map<String, String> env = System.getenv(); final Field field = env.getClass().getDeclaredField("m"); field.setAccessible(true); ((Map<String, String>) field.get(env)).put("SERVICE_REGION", value); } }
7,399