TablesContext { public Optional<String> findTableName(final ColumnSegment column, final SchemaMetaData schemaMetaData) { if (1 == tables.size()) { return Optional.of(tables.iterator().next().getTableName().getIdentifier().getValue()); } if (column.getOwner().isPresent()) { return Optional.of(findTableNameFromSQL(column.getOwner().get().getIdentifier().getValue())); } return findTableNameFromMetaData(column.getIdentifier().getValue(), schemaMetaData); } TablesContext(final SimpleTableSegment tableSegment);  TablesContext(final Collection<SimpleTableSegment> tableSegments); Collection<String> getTableNames(); Optional<String> findTableName(final ColumnSegment column, final SchemaMetaData schemaMetaData); Optional<String> findTableName(final ColumnProjection column, final SchemaMetaData schemaMetaData); String findTableNameFromSQL(final String tableNameOrAlias);  }
@Test public void assertFindTableNameWhenSingleTable() { SimpleTableSegment tableSegment = createTableSegment("table_1", "tbl_1"); Optional<String> actual = new TablesContext(Collections.singletonList(tableSegment)).findTableName(createColumnSegment(), mock(SchemaMetaData.class)); assertTrue(actual.isPresent()); assertThat(actual.get(), is("table_1")); }
@Test public void assertFindTableNameWhenColumnSegmentOwnerPresent() { SimpleTableSegment tableSegment1 = createTableSegment("table_1", "tbl_1"); SimpleTableSegment tableSegment2 = createTableSegment("table_2", "tbl_2"); ColumnSegment columnSegment = createColumnSegment(); columnSegment.setOwner(new OwnerSegment(0, 10, new IdentifierValue("table_1"))); Optional<String> actual = new TablesContext(Arrays.asList(tableSegment1, tableSegment2)).findTableName(columnSegment, mock(SchemaMetaData.class)); assertTrue(actual.isPresent()); assertThat(actual.get(), is("table_1")); }
@Test public void assertFindTableNameWhenColumnSegmentOwnerAbsent() { SimpleTableSegment tableSegment1 = createTableSegment("table_1", "tbl_1"); SimpleTableSegment tableSegment2 = createTableSegment("table_2", "tbl_2"); Optional<String> actual = new TablesContext(Arrays.asList(tableSegment1, tableSegment2)).findTableName(createColumnSegment(), mock(SchemaMetaData.class)); assertFalse(actual.isPresent()); }
@Test public void assertFindTableNameWhenColumnSegmentOwnerAbsentAndSchemaMetaDataContainsColumn() { SimpleTableSegment tableSegment1 = createTableSegment("table_1", "tbl_1"); SimpleTableSegment tableSegment2 = createTableSegment("table_2", "tbl_2"); SchemaMetaData schemaMetaData = mock(SchemaMetaData.class); when(schemaMetaData.containsColumn(anyString(), anyString())).thenReturn(true); Optional<String> actual = new TablesContext(Arrays.asList(tableSegment1, tableSegment2)).findTableName(createColumnSegment(), schemaMetaData); assertTrue(actual.isPresent()); assertThat(actual.get(), is("table_1")); }