diff --git a/.mvn/wrapper/MavenWrapperDownloader.java b/.mvn/wrapper/MavenWrapperDownloader.java index b9836f57..cdb3c426 100644 --- a/.mvn/wrapper/MavenWrapperDownloader.java +++ b/.mvn/wrapper/MavenWrapperDownloader.java @@ -36,96 +36,100 @@ public class MavenWrapperDownloader { - private static final String WRAPPER_VERSION = "0.5.6"; - /** - * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. - */ - private static final String DEFAULT_DOWNLOAD_URL = - "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; + private static final String WRAPPER_VERSION = "0.5.6"; - /** - * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to - * use instead of the default one. - */ - private static final String MAVEN_WRAPPER_PROPERTIES_PATH = ".mvn/wrapper/maven-wrapper.properties"; + /** Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. */ + private static final String DEFAULT_DOWNLOAD_URL = + "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + + WRAPPER_VERSION + + "/maven-wrapper-" + + WRAPPER_VERSION + + ".jar"; - /** - * Path where the maven-wrapper.jar will be saved to. - */ - private static final String MAVEN_WRAPPER_JAR_PATH = ".mvn/wrapper/maven-wrapper.jar"; + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to use + * instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; - /** - * Name of the property which should be used to override the default download url for the wrapper. - */ - private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + /** Path where the maven-wrapper.jar will be saved to. */ + private static final String MAVEN_WRAPPER_JAR_PATH = ".mvn/wrapper/maven-wrapper.jar"; - public static void main(String args[]) { - System.out.println("- Downloader started"); - File baseDirectory = new File(args[0]); - System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; - // If the maven-wrapper.properties exists, read it and check if it contains a custom - // wrapperUrl parameter. - File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); - String url = DEFAULT_DOWNLOAD_URL; - if (mavenWrapperPropertyFile.exists()) { - FileInputStream mavenWrapperPropertyFileInputStream = null; - try { - mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); - Properties mavenWrapperProperties = new Properties(); - mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); - url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); - } catch (IOException e) { - System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); - } finally { - try { - if (mavenWrapperPropertyFileInputStream != null) { - mavenWrapperPropertyFileInputStream.close(); - } - } catch (IOException e) { - // Ignore ... - } - } - } - System.out.println("- Downloading from: " + url); + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); - File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); - if (!outputFile.getParentFile().exists()) { - if (!outputFile.getParentFile().mkdirs()) { - System.out.println("- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); - } - } - System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if (mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { try { - downloadFileFromURL(url, outputFile); - System.out.println("Done"); - System.exit(0); - } catch (Throwable e) { - System.out.println("- Error downloading"); - e.printStackTrace(); - System.exit(1); + if (mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... } + } } + System.out.println("- Downloading from: " + url); - private static void downloadFileFromURL(String urlString, File destination) throws Exception { - if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { - String username = System.getenv("MVNW_USERNAME"); - char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); - Authenticator.setDefault( - new Authenticator() { - @Override - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication(username, password); - } - } - ); - } - URL website = new URL(urlString); - ReadableByteChannel rbc; - rbc = Channels.newChannel(website.openStream()); - FileOutputStream fos = new FileOutputStream(destination); - fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); - fos.close(); - rbc.close(); + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if (!outputFile.getParentFile().exists()) { + if (!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output directory '" + + outputFile.getParentFile().getAbsolutePath() + + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault( + new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } } diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 0a2095a3..3439fff7 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -5,18 +5,20 @@ repos: - id: check-yaml - id: end-of-file-fixer - id: trailing-whitespace - - repo: https://github.com/pre-commit/mirrors-prettier - rev: v3.0.2 - hooks: - - id: prettier - additional_dependencies: - - prettier@2.3.2 - args: - - --write - - --list-different - - --ignore-unknown +# - repo: https://github.com/pre-commit/mirrors-prettier +# rev: v3.0.2 +# hooks: +# - id: prettier +# additional_dependencies: +# - prettier@2.3.2 +# args: +# - --write +# - --list-different +# - --ignore-unknown - repo: https://github.com/macisamuele/language-formatters-pre-commit-hooks rev: v2.14.0 hooks: - id: pretty-format-kotlin args: [--autofix] + - id: pretty-format-java + args: [--autofix] diff --git a/common/src/main/kotlin/com/arcadeanalytics/provider/DataSourceGraphDataProvider.kt b/common/src/main/kotlin/com/arcadeanalytics/provider/DataSourceGraphDataProvider.kt index 9f1fb923..1ade9c04 100644 --- a/common/src/main/kotlin/com/arcadeanalytics/provider/DataSourceGraphDataProvider.kt +++ b/common/src/main/kotlin/com/arcadeanalytics/provider/DataSourceGraphDataProvider.kt @@ -24,7 +24,6 @@ package com.arcadeanalytics.provider * @author Roberto Franchini */ interface DataSourceGraphDataProvider : DataSourceProvider { - /** * Test the connection to the given {@link DataSourceInfo} * @param dataSource to be tested diff --git a/common/src/main/kotlin/com/arcadeanalytics/provider/DataSourceGraphProvider.kt b/common/src/main/kotlin/com/arcadeanalytics/provider/DataSourceGraphProvider.kt index fc85abed..f1dbfac6 100644 --- a/common/src/main/kotlin/com/arcadeanalytics/provider/DataSourceGraphProvider.kt +++ b/common/src/main/kotlin/com/arcadeanalytics/provider/DataSourceGraphProvider.kt @@ -26,6 +26,8 @@ import com.arcadeanalytics.data.SpritePlayer * @author Roberto Franchini */ interface DataSourceGraphProvider : DataSourceProvider { - - fun provideTo(dataSource: DataSourceInfo, player: SpritePlayer) + fun provideTo( + dataSource: DataSourceInfo, + player: SpritePlayer, + ) } diff --git a/common/src/main/kotlin/com/arcadeanalytics/provider/DataSourceMetadataProvider.kt b/common/src/main/kotlin/com/arcadeanalytics/provider/DataSourceMetadataProvider.kt index e3908315..175309ad 100644 --- a/common/src/main/kotlin/com/arcadeanalytics/provider/DataSourceMetadataProvider.kt +++ b/common/src/main/kotlin/com/arcadeanalytics/provider/DataSourceMetadataProvider.kt @@ -42,6 +42,5 @@ data class DataSourceMetadata( ) interface DataSourceMetadataProvider : DataSourceProvider { - fun fetchMetadata(dataSource: DataSourceInfo): DataSourceMetadata } diff --git a/common/src/main/kotlin/com/arcadeanalytics/provider/DataSourceProviderFactory.kt b/common/src/main/kotlin/com/arcadeanalytics/provider/DataSourceProviderFactory.kt index ad4c8409..7267c223 100644 --- a/common/src/main/kotlin/com/arcadeanalytics/provider/DataSourceProviderFactory.kt +++ b/common/src/main/kotlin/com/arcadeanalytics/provider/DataSourceProviderFactory.kt @@ -30,7 +30,6 @@ class DataSourceProviderFactory( private val clazz: Class, pluginPath: String = "./plugins", ) { - private val log = LoggerFactory.getLogger(this::class.java) private val dataProviders: MutableMap = mutableMapOf() @@ -38,7 +37,8 @@ class DataSourceProviderFactory( init { log.info("services for:: {}", clazz.simpleName) - Files.walk(Paths.get(pluginPath)) + Files + .walk(Paths.get(pluginPath)) .asSequence() .filter { path -> Files.isRegularFile(path) } .map { path -> @@ -69,13 +69,12 @@ class DataSourceProviderFactory( fun provides(): Set = dataProviders.keys - private fun decorate(provider: T): T { - return when (provider) { + private fun decorate(provider: T): T = + when (provider) { is DataSourceMetadataProvider -> SshMetadataProviderDecorator(provider as DataSourceMetadataProvider) as T is DataSourceGraphDataProvider -> SshDataProviderDecorator(provider as DataSourceGraphDataProvider) as T is DataSourceGraphProvider -> SshGraphProviderDecorator(provider as DataSourceGraphProvider) as T is DataSourceTableDataProvider -> SshTableDataProviderDecorator(provider as DataSourceTableDataProvider) as T else -> provider } - } } diff --git a/common/src/main/kotlin/com/arcadeanalytics/provider/DataSourceTableDataProvider.kt b/common/src/main/kotlin/com/arcadeanalytics/provider/DataSourceTableDataProvider.kt index cbbb7896..575b694e 100644 --- a/common/src/main/kotlin/com/arcadeanalytics/provider/DataSourceTableDataProvider.kt +++ b/common/src/main/kotlin/com/arcadeanalytics/provider/DataSourceTableDataProvider.kt @@ -21,20 +21,21 @@ package com.arcadeanalytics.provider const val TABLE_CLASS = "Table" -data class QueryParam(val name: String, val type: String, val value: String) +data class QueryParam( + val name: String, + val type: String, + val value: String, +) typealias QueryParams = List -inline fun String.prefixIfAbsent(prefix: String): String { - return if (this.startsWith(prefix)) this else prefix + this -} +inline fun String.prefixIfAbsent(prefix: String): String = if (this.startsWith(prefix)) this else prefix + this /** * Interface to be implemented by specialized data providers * @author Roberto Franchini */ interface DataSourceTableDataProvider : DataSourceProvider { - fun fetchData( dataSource: DataSourceInfo, query: String, diff --git a/common/src/main/kotlin/com/arcadeanalytics/provider/GraphData.kt b/common/src/main/kotlin/com/arcadeanalytics/provider/GraphData.kt index 15b067db..99a40ba5 100644 --- a/common/src/main/kotlin/com/arcadeanalytics/provider/GraphData.kt +++ b/common/src/main/kotlin/com/arcadeanalytics/provider/GraphData.kt @@ -19,7 +19,10 @@ */ package com.arcadeanalytics.provider -data class Position(private val x: Double, private val y: Double) +data class Position( + private val x: Double, + private val y: Double, +) data class Data( val id: String, @@ -47,19 +50,18 @@ data class GraphData( val edges: Set, val truncated: Boolean = false, ) { - companion object { - /** * Null object */ @JvmStatic - val EMPTY = GraphData( - emptyMap(), - emptyMap(), - emptySet(), - emptySet(), - false, - ) + val EMPTY = + GraphData( + emptyMap(), + emptyMap(), + emptySet(), + emptySet(), + false, + ) } } diff --git a/common/src/main/kotlin/com/arcadeanalytics/provider/SshDataProviderDecorator.kt b/common/src/main/kotlin/com/arcadeanalytics/provider/SshDataProviderDecorator.kt index 1ea30ee5..0f64fbff 100644 --- a/common/src/main/kotlin/com/arcadeanalytics/provider/SshDataProviderDecorator.kt +++ b/common/src/main/kotlin/com/arcadeanalytics/provider/SshDataProviderDecorator.kt @@ -21,8 +21,10 @@ package com.arcadeanalytics.provider import org.slf4j.LoggerFactory -class SshDataProviderDecorator(private val provider: DataSourceGraphDataProvider) : SshTunnelTemplate(), DataSourceGraphDataProvider { - +class SshDataProviderDecorator( + private val provider: DataSourceGraphDataProvider, +) : SshTunnelTemplate(), + DataSourceGraphDataProvider { private val log = LoggerFactory.getLogger(SshDataProviderDecorator::class.java) override fun testConnection(dataSource: DataSourceInfo): Boolean { @@ -35,7 +37,11 @@ class SshDataProviderDecorator(private val provider: DataSourceGraphDataProvider return testConnection } - override fun fetchData(dataSource: DataSourceInfo, query: String, limit: Int): GraphData { + override fun fetchData( + dataSource: DataSourceInfo, + query: String, + limit: Int, + ): GraphData { val (session, wrapper) = buildTunnel(dataSource) val graphData = provider.fetchData(wrapper, query, limit) @@ -45,7 +51,13 @@ class SshDataProviderDecorator(private val provider: DataSourceGraphDataProvider return graphData } - override fun expand(dataSource: DataSourceInfo, ids: Array, direction: String, edgeLabel: String, maxTraversal: Int): GraphData { + override fun expand( + dataSource: DataSourceInfo, + ids: Array, + direction: String, + edgeLabel: String, + maxTraversal: Int, + ): GraphData { val (session, wrapper) = buildTunnel(dataSource) val graphData = provider.expand(wrapper, ids, direction, edgeLabel, maxTraversal) @@ -55,7 +67,12 @@ class SshDataProviderDecorator(private val provider: DataSourceGraphDataProvider return graphData } - override fun edges(dataSource: DataSourceInfo, fromIds: Array, edgesLabel: Array, toIds: Array): GraphData { + override fun edges( + dataSource: DataSourceInfo, + fromIds: Array, + edgesLabel: Array, + toIds: Array, + ): GraphData { val (session, wrapper) = buildTunnel(dataSource) val graphData = provider.edges(wrapper, fromIds, edgesLabel, toIds) @@ -65,7 +82,10 @@ class SshDataProviderDecorator(private val provider: DataSourceGraphDataProvider return graphData } - override fun load(dataSource: DataSourceInfo, ids: Array): GraphData { + override fun load( + dataSource: DataSourceInfo, + ids: Array, + ): GraphData { val (session, wrapper) = buildTunnel(dataSource) val graphData = provider.load(wrapper, ids) @@ -75,7 +95,11 @@ class SshDataProviderDecorator(private val provider: DataSourceGraphDataProvider return graphData } - override fun loadFromClass(dataSource: DataSourceInfo, className: String, limit: Int): GraphData { + override fun loadFromClass( + dataSource: DataSourceInfo, + className: String, + limit: Int, + ): GraphData { val (session, wrapper) = buildTunnel(dataSource) val graphData = provider.loadFromClass(wrapper, className, limit) @@ -85,7 +109,13 @@ class SshDataProviderDecorator(private val provider: DataSourceGraphDataProvider return graphData } - override fun loadFromClass(dataSource: DataSourceInfo, className: String, propName: String, propertyValue: String, limit: Int): GraphData { + override fun loadFromClass( + dataSource: DataSourceInfo, + className: String, + propName: String, + propertyValue: String, + limit: Int, + ): GraphData { val (session, wrapper) = buildTunnel(dataSource) val graphData = provider.loadFromClass(wrapper, className, propName, propertyValue, limit) diff --git a/common/src/main/kotlin/com/arcadeanalytics/provider/SshGraphProviderDecorator.kt b/common/src/main/kotlin/com/arcadeanalytics/provider/SshGraphProviderDecorator.kt index 4a7c47ad..ec436b59 100644 --- a/common/src/main/kotlin/com/arcadeanalytics/provider/SshGraphProviderDecorator.kt +++ b/common/src/main/kotlin/com/arcadeanalytics/provider/SshGraphProviderDecorator.kt @@ -22,11 +22,16 @@ package com.arcadeanalytics.provider import com.arcadeanalytics.data.SpritePlayer import org.slf4j.LoggerFactory -class SshGraphProviderDecorator(private val provider: DataSourceGraphProvider) : SshTunnelTemplate(), DataSourceGraphProvider { - +class SshGraphProviderDecorator( + private val provider: DataSourceGraphProvider, +) : SshTunnelTemplate(), + DataSourceGraphProvider { private val log = LoggerFactory.getLogger(SshGraphProviderDecorator::class.java) - override fun provideTo(dataSource: DataSourceInfo, player: SpritePlayer) { + override fun provideTo( + dataSource: DataSourceInfo, + player: SpritePlayer, + ) { val (session, wrapper) = buildTunnel(dataSource) provider.provideTo(wrapper, player) diff --git a/common/src/main/kotlin/com/arcadeanalytics/provider/SshMetadataProviderDecorator.kt b/common/src/main/kotlin/com/arcadeanalytics/provider/SshMetadataProviderDecorator.kt index 7c77d29d..624fad6f 100644 --- a/common/src/main/kotlin/com/arcadeanalytics/provider/SshMetadataProviderDecorator.kt +++ b/common/src/main/kotlin/com/arcadeanalytics/provider/SshMetadataProviderDecorator.kt @@ -19,8 +19,10 @@ */ package com.arcadeanalytics.provider -class SshMetadataProviderDecorator(val provider: DataSourceMetadataProvider) : SshTunnelTemplate(), DataSourceMetadataProvider { - +class SshMetadataProviderDecorator( + val provider: DataSourceMetadataProvider, +) : SshTunnelTemplate(), + DataSourceMetadataProvider { override fun fetchMetadata(dataSource: DataSourceInfo): DataSourceMetadata { val (session, wrapper) = buildTunnel(dataSource) diff --git a/common/src/main/kotlin/com/arcadeanalytics/provider/SshTableDataProviderDecorator.kt b/common/src/main/kotlin/com/arcadeanalytics/provider/SshTableDataProviderDecorator.kt index bb57824a..b9641bde 100644 --- a/common/src/main/kotlin/com/arcadeanalytics/provider/SshTableDataProviderDecorator.kt +++ b/common/src/main/kotlin/com/arcadeanalytics/provider/SshTableDataProviderDecorator.kt @@ -19,9 +19,16 @@ */ package com.arcadeanalytics.provider -class SshTableDataProviderDecorator(private val provider: DataSourceTableDataProvider) : SshTunnelTemplate(), DataSourceTableDataProvider { - - override fun fetchData(dataSource: DataSourceInfo, query: String, params: QueryParams, limit: Int): GraphData { +class SshTableDataProviderDecorator( + private val provider: DataSourceTableDataProvider, +) : SshTunnelTemplate(), + DataSourceTableDataProvider { + override fun fetchData( + dataSource: DataSourceInfo, + query: String, + params: QueryParams, + limit: Int, + ): GraphData { val (session, wrapper) = buildTunnel(dataSource) val graphData = provider.fetchData(wrapper, query, params, limit) @@ -31,7 +38,11 @@ class SshTableDataProviderDecorator(private val provider: DataSourceTableDataPro return graphData } - override fun fetchData(dataSource: DataSourceInfo, query: String, limit: Int): GraphData { + override fun fetchData( + dataSource: DataSourceInfo, + query: String, + limit: Int, + ): GraphData { val (session, wrapper) = buildTunnel(dataSource) val graphData = provider.fetchData(wrapper, query, limit) diff --git a/common/src/main/kotlin/com/arcadeanalytics/provider/SshTunnelTemplate.kt b/common/src/main/kotlin/com/arcadeanalytics/provider/SshTunnelTemplate.kt index 08c3fdb7..51eb0a7f 100644 --- a/common/src/main/kotlin/com/arcadeanalytics/provider/SshTunnelTemplate.kt +++ b/common/src/main/kotlin/com/arcadeanalytics/provider/SshTunnelTemplate.kt @@ -37,7 +37,6 @@ import java.util.function.Consumer * Template class to be extended if an ssh tunnel should be created */ abstract class SshTunnelTemplate : DataSourceProvider { - protected fun buildTunnel(dataSourceInfo: DataSourceInfo): Pair { JSch.setLogger(JschSlf4jLogger()) val jsch = JSch() @@ -92,8 +91,11 @@ abstract class SshTunnelTemplate : DataSourceProvider { throw IllegalStateException("Could not find a free TCP/IP port to open the ssh tunnel") } - private fun createLocalhostDataSource(dataSourceInfo: DataSourceInfo, localPort: Int): DataSourceInfo { - return DataSourceInfo( + private fun createLocalhostDataSource( + dataSourceInfo: DataSourceInfo, + localPort: Int, + ): DataSourceInfo = + DataSourceInfo( dataSourceInfo.id, dataSourceInfo.type, dataSourceInfo.name, @@ -111,11 +113,8 @@ abstract class SshTunnelTemplate : DataSourceProvider { localPort, "", ) - } - override fun supportedDataSourceTypes(): Set { - return Sets.newHashSet("SSH") - } + override fun supportedDataSourceTypes(): Set = Sets.newHashSet("SSH") class JschSlf4jLogger : com.jcraft.jsch.Logger { private val logMap = HashMap>() @@ -136,17 +135,17 @@ abstract class SshTunnelTemplate : DataSourceProvider { enabledMap[com.jcraft.jsch.Logger.WARN] = BooleanSupplier { log.isWarnEnabled } } - override fun log(level: Int, message: String) { + override fun log( + level: Int, + message: String, + ) { logMap[level]?.accept(message) } - override fun isEnabled(level: Int): Boolean { - return enabledMap[level]!!.getAsBoolean() - } + override fun isEnabled(level: Int): Boolean = enabledMap[level]!!.getAsBoolean() } companion object { - private val log = LoggerFactory.getLogger(SshTunnelTemplate::class.java) private val DEFAULT_SSH_USER = "player" diff --git a/common/src/main/kotlin/com/arcadeanalytics/provider/TypeMapper.kt b/common/src/main/kotlin/com/arcadeanalytics/provider/TypeMapper.kt index 0103a63e..8dacca13 100644 --- a/common/src/main/kotlin/com/arcadeanalytics/provider/TypeMapper.kt +++ b/common/src/main/kotlin/com/arcadeanalytics/provider/TypeMapper.kt @@ -25,34 +25,36 @@ import java.util.Locale.ENGLISH val log: Logger = LoggerFactory.getLogger("com.arcadeanalytics.provider.TypeMapper") -fun mapType(type: String): String = when ( - type.trim() - .toLowerCase(ENGLISH) - .removePrefix("http://www.w3.org/2001/xmlschema#") -) { - "string", "varchar", "text", "char", - "varchar2", "nvarchar2", "clob", "nclob", - "char varying", "character varying", "ntext", "nchar", - "national char", "national character", "nvarchar", "national char varying", - "national character varying", "longvarchar", "character large object", - "mediumtext", "longtext", "tinytext", - -> "String" +fun mapType(type: String): String = + when ( + type + .trim() + .lowercase(ENGLISH) + .removePrefix("http://www.w3.org/2001/xmlschema#") + ) { + "string", "varchar", "text", "char", + "varchar2", "nvarchar2", "clob", "nclob", + "char varying", "character varying", "ntext", "nchar", + "national char", "national character", "nvarchar", "national char varying", + "national character varying", "longvarchar", "character large object", + "mediumtext", "longtext", "tinytext", + -> "String" - "decimal", "dec", "numeric", "real", "integer", - "int", "int2", "int4", "tinyint", - "smallint unsigned", "tinyint unsigned", "mediumint unsigned", - "float", "double precision", - "long", "smallint", "money", "smallmoney", "double", - -> "Numeric" + "decimal", "dec", "numeric", "real", "integer", + "int", "int2", "int4", "tinyint", + "smallint unsigned", "tinyint unsigned", "mediumint unsigned", + "float", "double precision", + "long", "smallint", "money", "smallmoney", "double", + -> "Numeric" - "date", "datetime", "datetime2", "timestamp", "year", - "smalldatetime", "datetimeoffset", "time with time zone", - -> "Date" + "date", "datetime", "datetime2", "timestamp", "year", + "smalldatetime", "datetimeoffset", "time with time zone", + -> "Date" - "bool", "boolean", - -> "Boolean" - else -> { - if (log.isDebugEnabled) log.debug("type not mapped:: {} ", type) - type + "bool", "boolean", + -> "Boolean" + else -> { + if (log.isDebugEnabled) log.debug("type not mapped:: {} ", type) + type + } } -} diff --git a/common/src/test/kotlin/com/arcadeanalytics/provider/TypeMapperKtTest.kt b/common/src/test/kotlin/com/arcadeanalytics/provider/TypeMapperKtTest.kt index d0c26198..8d33a46e 100644 --- a/common/src/test/kotlin/com/arcadeanalytics/provider/TypeMapperKtTest.kt +++ b/common/src/test/kotlin/com/arcadeanalytics/provider/TypeMapperKtTest.kt @@ -20,18 +20,30 @@ package com.arcadeanalytics.provider import org.assertj.core.api.Assertions -import org.junit.Test +import org.junit.jupiter.api.Test class TypeMapperKtTest { - @Test fun shouldMapNumericTypes() { listOf( - "decimal", "dec", "numeric", "real", "integer", - "int", "int2", "int4", "tinyint", - "smallint unsigned", "tinyint unsigned", "mediumint unsigned", - "float", "double precision", - "smallint", "money", "double", "smallmoney", + "decimal", + "dec", + "numeric", + "real", + "integer", + "int", + "int2", + "int4", + "tinyint", + "smallint unsigned", + "tinyint unsigned", + "mediumint unsigned", + "float", + "double precision", + "smallint", + "money", + "double", + "smallmoney", ).forEach { Assertions.assertThat(mapType(it)).isEqualTo("Numeric") } @@ -40,16 +52,31 @@ class TypeMapperKtTest { @Test fun shouldMapTextTypes() { listOf( - "string", "varchar", "text", "char", - "varchar2", "nvarchar2", "clob", "nclob", - "char varying", "character varying", "ntext", "nchar", - "national char", "national character", "nvarchar", "national char varying", - "national character varying", "longvarchar", "character large object", - "mediumtext", "longtext", "tinytext", - ) - .forEach { - Assertions.assertThat(mapType(it)).isEqualTo("String") - } + "string", + "varchar", + "text", + "char", + "varchar2", + "nvarchar2", + "clob", + "nclob", + "char varying", + "character varying", + "ntext", + "nchar", + "national char", + "national character", + "nvarchar", + "national char varying", + "national character varying", + "longvarchar", + "character large object", + "mediumtext", + "longtext", + "tinytext", + ).forEach { + Assertions.assertThat(mapType(it)).isEqualTo("String") + } } @Test @@ -63,10 +90,9 @@ class TypeMapperKtTest { "smalldatetime", "datetimeoffset", "time with time zone", - ) - .forEach { - Assertions.assertThat(mapType(it)).isEqualTo("Date") - } + ).forEach { + Assertions.assertThat(mapType(it)).isEqualTo("Date") + } } @Test diff --git a/common/src/test/kotlin/com/arcadeanalytics/test/KGenericContainer.kt b/common/src/test/kotlin/com/arcadeanalytics/test/KGenericContainer.kt index 79aafed1..d3af7348 100644 --- a/common/src/test/kotlin/com/arcadeanalytics/test/KGenericContainer.kt +++ b/common/src/test/kotlin/com/arcadeanalytics/test/KGenericContainer.kt @@ -22,4 +22,6 @@ package com.arcadeanalytics.test import org.testcontainers.containers.GenericContainer import org.testcontainers.utility.DockerImageName -class KGenericContainer(imageName: DockerImageName) : GenericContainer(imageName) +class KGenericContainer( + imageName: DockerImageName, +) : GenericContainer(imageName) diff --git a/data/src/main/kotlin/com/arcadeanalytics/data/Sprite.kt b/data/src/main/kotlin/com/arcadeanalytics/data/Sprite.kt index 7e9172e7..67d8cbe2 100644 --- a/data/src/main/kotlin/com/arcadeanalytics/data/Sprite.kt +++ b/data/src/main/kotlin/com/arcadeanalytics/data/Sprite.kt @@ -31,49 +31,56 @@ import java.util.regex.Pattern * * @author Roberto Franchini */ -private const val copySuffix = "____COPY___" +private const val COPY_SUFFIX = "____COPY___" class Sprite { - val data: ListMultimap = ArrayListMultimap.create() - fun add(field: String, value: Any?): Sprite { + fun add( + field: String, + value: Any?, + ): Sprite { if (value is Collection<*>) { - value.asSequence() + value + .asSequence() .filter { it != null } .forEach { v -> data.put(field, v) } - } else if (value != null) data.put(field, value) + } else if (value != null) { + data.put(field, value) + } return this } - fun add(field: String, value: String): Sprite { + fun add( + field: String, + value: String, + ): Sprite { if (value.isNotBlank()) { data.put(field, value) } return this } - fun entries(): MutableCollection>? { - return data.entries() - } + fun entries(): MutableCollection>? = data.entries() - fun fields(): Set { - return HashSet(data.keySet()) - } + fun fields(): Set = HashSet(data.keySet()) - fun fields(pattern: Pattern): Set { - return data.keySet() + fun fields(pattern: Pattern): Set = + data + .keySet() .filter { k -> pattern.matcher(k).matches() } .toSet() - } - fun fields(pattern: Regex): Set { - return data.keySet() + fun fields(pattern: Regex): Set = + data + .keySet() .filter { k -> pattern.matches(k) } .toSet() - } - fun rename(field: String, renamed: String): Sprite { + fun rename( + field: String, + renamed: String, + ): Sprite { with(data) { copy(field, renamed) removeAll(field) @@ -81,7 +88,10 @@ class Sprite { return this } - fun copy(from: String, to: String): Sprite { + fun copy( + from: String, + to: String, + ): Sprite { with(data) { val fromValues = Lists.newArrayList(get(from)) addAll(to, fromValues) @@ -89,22 +99,34 @@ class Sprite { return this } - fun addAll(field: String, values: Iterable): Sprite { + fun addAll( + field: String, + values: Iterable, + ): Sprite { values.forEach { add(field, it) } return this } - fun addAll(field: String, values: List): Sprite { + fun addAll( + field: String, + values: List, + ): Sprite { values.forEach { add(field, it) } return this } - fun addAllIfNotExists(field: String, values: Iterable): Sprite { + fun addAllIfNotExists( + field: String, + values: Iterable, + ): Sprite { values.forEach { addIfNotExists(field, it) } return this } - fun addIfNotExists(field: String, fieldValue: Any): Sprite { + fun addIfNotExists( + field: String, + fieldValue: Any, + ): Sprite { if (hasNotValue(field, fieldValue)) { add(field, fieldValue) } @@ -112,25 +134,21 @@ class Sprite { return this } - fun hasNotValue(value: Any): Boolean { - return !data.containsValue(value) - } + fun hasNotValue(value: Any): Boolean = !data.containsValue(value) - fun hasNotValue(field: String, value: Any): Boolean { - return !data.containsEntry(field, value) - } + fun hasNotValue( + field: String, + value: Any, + ): Boolean = !data.containsEntry(field, value) - fun hasValue(value: Any): Boolean { - return data.containsValue(value) - } + fun hasValue(value: Any): Boolean = data.containsValue(value) - fun hasValue(field: String, value: Any): Boolean { - return data.containsEntry(field, value) - } + fun hasValue( + field: String, + value: Any, + ): Boolean = data.containsEntry(field, value) - fun hasField(field: String): Boolean { - return data.containsKey(field) - } + fun hasField(field: String): Boolean = data.containsKey(field) fun load(input: Map): Sprite { input.entries @@ -138,7 +156,10 @@ class Sprite { return this } - fun remove(field: String, fieldValue: Any): Sprite { + fun remove( + field: String, + fieldValue: Any, + ): Sprite { data.remove(field, fieldValue) return this } @@ -158,21 +179,30 @@ class Sprite { return this } - fun apply(pattern: Pattern, fieldModifier: (F) -> T): Sprite { + fun apply( + pattern: Pattern, + fieldModifier: (F) -> T, + ): Sprite { fields(pattern) .forEach { f -> apply(f, fieldModifier) } return this } - fun apply(pattern: Regex, fieldModifier: (F) -> T): Sprite { + fun apply( + pattern: Regex, + fieldModifier: (F) -> T, + ): Sprite { fields(pattern) .forEach { f -> apply(f, fieldModifier) } return this } - fun apply(field: String, fieldModifier: (F) -> T): Sprite { + fun apply( + field: String, + fieldModifier: (F) -> T, + ): Sprite { if (hasField(field)) { val newValues = newValuesOf(field, fieldModifier) remove(field) @@ -182,7 +212,11 @@ class Sprite { return this } - fun apply(from: String, transformer: (F) -> T, to: String): Sprite { + fun apply( + from: String, + transformer: (F) -> T, + to: String, + ): Sprite { if (hasField(from)) { val newValues = newValuesOf(from, transformer) addAll(to, newValues) @@ -191,16 +225,20 @@ class Sprite { return this } - private fun newValuesOf(field: String, fieldModifier: (F) -> T): List { + private fun newValuesOf( + field: String, + fieldModifier: (F) -> T, + ): List { val originalValues: List = rawValuesOf(field) return originalValues.map { it -> fieldModifier(it) }.toList() } - fun rawValuesOf(field: String): List { - return data.get(field).orEmpty() as List - } + fun rawValuesOf(field: String): List = data.get(field).orEmpty() as List - fun rename(field: Pattern, renamed: (v: String) -> String): Sprite { + fun rename( + field: Pattern, + renamed: (v: String) -> String, + ): Sprite { fields(field) .forEach { f -> val cleaned = renamed(f) @@ -218,65 +256,46 @@ class Sprite { limit: Int = -1, truncated: CharSequence = "...", ): Sprite { - val merged = rawValuesOf(field) - .joinToString(separator, prefix, postfix, limit, truncated) + val merged = + rawValuesOf(field) + .joinToString(separator, prefix, postfix, limit, truncated) remove(field) .add(field, merged) return this } - fun valueOf(field: String): String { - return rawValueOf(field).let(Any::toString) - } + fun valueOf(field: String): String = rawValueOf(field).let(Any::toString) - fun valuesOf(field: String): List { - return rawValuesOf(field).map { it -> it.toString() }.toList() - } + fun valuesOf(field: String): List = rawValuesOf(field).map { it -> it.toString() }.toList() - fun valuesOf(regex: Regex): List { - return fields(regex) + fun valuesOf(regex: Regex): List = + fields(regex) .map { field -> rawValuesOf(field) .map { it.toString() } - } - .flatMap { + }.flatMap { it.toList() - } - .toList() - } + }.toList() - fun valuesOf(regex: Pattern): List { - return fields(regex) + fun valuesOf(regex: Pattern): List = + fields(regex) .map { field -> rawValuesOf(field) .map { it.toString() } - } - .flatMap { + }.flatMap { it.toList() - } - .toList() - } + }.toList() - fun rawValueOf(field: String): T { - return rawValuesOf(field).first() - } + fun rawValueOf(field: String): T = rawValuesOf(field).first() - fun isMultiValue(field: String): Boolean { - return data.get(field).size > 1 - } + fun isMultiValue(field: String): Boolean = data.get(field).size > 1 - fun isSingleValue(field: String): Boolean { - return data.get(field).size == 1 - } + fun isSingleValue(field: String): Boolean = data.get(field).size == 1 - fun sizeOf(field: String): Int { - return data.get(field).size - } + fun sizeOf(field: String): Int = data.get(field).size - fun asMultimap(): MutableMap>? { - return data.asMap() - } + fun asMultimap(): MutableMap>? = data.asMap() fun asMap(): MutableMap? { val map = HashMap() @@ -296,8 +315,11 @@ class Sprite { return map } - fun splitValues(field: String, separator: String): Sprite { - val copySuffix = copySuffix + fun splitValues( + field: String, + separator: String, + ): Sprite { + val copySuffix = COPY_SUFFIX copy(field, "$field$copySuffix") .remove(field) .valuesOf("$field$copySuffix") @@ -311,9 +333,7 @@ class Sprite { return this } - fun isEmpty(): Boolean { - return data.isEmpty - } + fun isEmpty(): Boolean = data.isEmpty override fun hashCode(): Int { val prime = 31 @@ -334,7 +354,5 @@ class Sprite { return true } - override fun toString(): String { - return data.toString() - } + override fun toString(): String = data.toString() } diff --git a/data/src/main/kotlin/com/arcadeanalytics/data/SpritePlayer.kt b/data/src/main/kotlin/com/arcadeanalytics/data/SpritePlayer.kt index 3cd648a1..7161b7f3 100644 --- a/data/src/main/kotlin/com/arcadeanalytics/data/SpritePlayer.kt +++ b/data/src/main/kotlin/com/arcadeanalytics/data/SpritePlayer.kt @@ -20,7 +20,6 @@ package com.arcadeanalytics.data interface SpritePlayer { - fun begin() fun accept(sprite: Sprite): Boolean = true diff --git a/data/src/test/kotlin/com/arcadeanalytics/data/SpritePlayerShould.kt b/data/src/test/kotlin/com/arcadeanalytics/data/SpritePlayerShould.kt index 1dfebf1c..70c9f5da 100644 --- a/data/src/test/kotlin/com/arcadeanalytics/data/SpritePlayerShould.kt +++ b/data/src/test/kotlin/com/arcadeanalytics/data/SpritePlayerShould.kt @@ -23,20 +23,20 @@ import org.assertj.core.api.Assertions import org.junit.jupiter.api.Test class SpritePlayerShould { - @Test internal fun `mark the sprite with a new field `() { - val player: SpritePlayer = object : SpritePlayer { - override fun end() { - } + val player: SpritePlayer = + object : SpritePlayer { + override fun end() { + } - override fun begin() { - } + override fun begin() { + } - override fun play(sprite: Sprite) { - sprite.add("mark", "marked") + override fun play(sprite: Sprite) { + sprite.add("mark", "marked") + } } - } val sprite = Sprite() player.play(sprite) @@ -47,21 +47,20 @@ class SpritePlayerShould { @Test internal fun `accept empty sprite`() { - val player: SpritePlayer = object : SpritePlayer { - override fun begin() { - } + val player: SpritePlayer = + object : SpritePlayer { + override fun begin() { + } - override fun end() { - } + override fun end() { + } - override fun accept(sprite: Sprite): Boolean { - return sprite.isEmpty() - } + override fun accept(sprite: Sprite): Boolean = sprite.isEmpty() - override fun play(sprite: Sprite) { - sprite.add("mark", "marked") + override fun play(sprite: Sprite) { + sprite.add("mark", "marked") + } } - } val sprite = Sprite() diff --git a/data/src/test/kotlin/com/arcadeanalytics/data/SpriteShould.kt b/data/src/test/kotlin/com/arcadeanalytics/data/SpriteShould.kt index 5d972746..08956843 100644 --- a/data/src/test/kotlin/com/arcadeanalytics/data/SpriteShould.kt +++ b/data/src/test/kotlin/com/arcadeanalytics/data/SpriteShould.kt @@ -30,7 +30,6 @@ import java.time.format.DateTimeFormatter import java.util.regex.Pattern class SpriteShould { - private lateinit var sprite: Sprite @BeforeEach @@ -40,7 +39,8 @@ class SpriteShould { @Test internal fun `add values of different types`() { - sprite.add("field1", "value1") + sprite + .add("field1", "value1") .add("field2", 10) .add("field3", false) @@ -55,11 +55,13 @@ class SpriteShould { internal fun `flat collection value`() { val values = mutableListOf("value1", "value2", "value3") - sprite.add("field1", values) + sprite + .add("field1", values) .add("field2", 10) .add("field3", false) - assertThat(sprite.rawValuesOf("field1")).isNotEmpty + assertThat(sprite.rawValuesOf("field1")) + .isNotEmpty .hasSize(3) assertThat(sprite.entries()).contains( @@ -73,7 +75,8 @@ class SpriteShould { @Test internal fun `return single value as string`() { - sprite.add("field1", "value1") + sprite + .add("field1", "value1") .add("field2", 10) .add("field3", false) @@ -84,7 +87,8 @@ class SpriteShould { @Test internal fun `return multi value as string`() { - sprite.add("field1", 10) + sprite + .add("field1", 10) .add("field1", 20) .add("field1", 30) @@ -93,7 +97,8 @@ class SpriteShould { @Test internal fun `return multi value as int type`() { - sprite.add("field1", 10) + sprite + .add("field1", 10) .add("field1", 20) .add("field1", 30) @@ -102,7 +107,8 @@ class SpriteShould { @Test internal fun `return single value typed`() { - sprite.add("field1", "value1") + sprite + .add("field1", "value1") .add("field2", 10) .add("field3", false) @@ -113,19 +119,20 @@ class SpriteShould { @Test internal fun `copy single value field`() { - sprite.add("field", "value") + sprite + .add("field", "value") .copy("field", "copyOfField") assertThat(sprite.entries()).contains( entry("field", "value"), entry("copyOfField", "value"), - ) } @Test internal fun `copy multi values field`() { - sprite.add("field", "value1") + sprite + .add("field", "value1") .add("field", "value2") .add("field", "value3") .add("field", "value4") @@ -158,7 +165,8 @@ class SpriteShould { @Test internal fun `rename field`() { - sprite.add("field", "value1") + sprite + .add("field", "value1") .add("field", "value2") .add("field", "value3") .add("field", "value4") @@ -174,7 +182,8 @@ class SpriteShould { @Test internal fun `rename with lambda`() { - sprite.add("a_field", "value1") + sprite + .add("a_field", "value1") .rename(Pattern.compile("a_.*")) { v: String -> v.removePrefix("a_") } assertThat(sprite.data) @@ -184,7 +193,8 @@ class SpriteShould { @Test internal fun `join field values`() { - sprite.add("field", "value1") + sprite + .add("field", "value1") .add("field", "value2") .add("field", "value3") .add("field", "value4") @@ -205,7 +215,8 @@ class SpriteShould { @Test internal fun `split field value`() { - sprite.add("field", "value1 value2 value3 value4") + sprite + .add("field", "value1 value2 value3 value4") .splitValues("field", " ") assertThat(sprite.isMultiValue("field")).isTrue() @@ -222,7 +233,8 @@ class SpriteShould { @Test internal fun `retrieve field names`() { - sprite.add("field", "value") + sprite + .add("field", "value") .add("field2", "value2") .add("field3", "value3") @@ -232,7 +244,8 @@ class SpriteShould { @Test internal fun `retrieve field names with regexp`() { - sprite.add("field1", "value") + sprite + .add("field1", "value") .add("field2", "value2") .add("field3", "value3") .add("a_field", "value") @@ -249,7 +262,8 @@ class SpriteShould { @Test internal fun `retrieve field string values with regexp`() { - sprite.add("field1", "value") + sprite + .add("field1", "value") .add("field2", "value2") .add("field3", "value3") .add("a_field", "value") @@ -286,7 +300,8 @@ class SpriteShould { @Test internal fun `remove fields`() { - sprite.add("field", "value") + sprite + .add("field", "value") .add("field", "value2") .add("field2", "value2") @@ -297,7 +312,8 @@ class SpriteShould { @Test internal fun `remove fields with pattern`() { - sprite.add("field", "value") + sprite + .add("field", "value") .add("field", "value2") .add("field2", "value2") @@ -309,11 +325,12 @@ class SpriteShould { @Test internal fun `load from map`() { val now = LocalDate.now() - val input = mapOf( - "field1" to "value1", - "field2" to "value2", - "field3" to now, - ) + val input = + mapOf( + "field1" to "value1", + "field2" to "value2", + "field3" to now, + ) sprite.load(input) @@ -326,10 +343,11 @@ class SpriteShould { @Test internal fun `apply lambda to all field values`() { - sprite.add("field", "value") + sprite + .add("field", "value") .add("field", "value2") - sprite.apply("field", String::toUpperCase) + sprite.apply("field", String::uppercase) assertThat(sprite.data).isNotEmpty() @@ -338,10 +356,11 @@ class SpriteShould { @Test internal fun `apply lambda to all fields matching a pattern`() { - sprite.add("firstField", "value") + sprite + .add("firstField", "value") .add("secondField", "value2") - sprite.apply(Pattern.compile(".*Field"), String::toUpperCase) + sprite.apply(Pattern.compile(".*Field"), String::uppercase) assertThat(sprite.data).isNotEmpty() @@ -351,10 +370,11 @@ class SpriteShould { @Test internal fun `apply lambda to all field values and store on another field`() { - sprite.add("field", "value") + sprite + .add("field", "value") .add("field", "value2") - sprite.apply("field", String::toUpperCase, "to") + sprite.apply("field", String::uppercase, "to") assertThat(sprite.data).isNotEmpty() @@ -365,11 +385,13 @@ class SpriteShould { @Test internal fun `return map with single value`() { val now = LocalDate.now() - val map = sprite.add("field", "value") - .add("field", "value2") - .add("field", "value3") - .add("dateField", now) - .asMap() + val map = + sprite + .add("field", "value") + .add("field", "value2") + .add("field", "value3") + .add("dateField", now) + .asMap() assertThat(map?.get("field")).isEqualTo("value") assertThat(map?.get("dateField")).isEqualTo(now) @@ -378,11 +400,13 @@ class SpriteShould { @Test internal fun `return map with single value as string`() { val now = LocalDate.now() - val map = sprite.add("field", "value") - .add("field", "value2") - .add("field", "value3") - .add("dateField", now) - .asStringMap() + val map = + sprite + .add("field", "value") + .add("field", "value2") + .add("field", "value3") + .add("dateField", now) + .asStringMap() assertThat(map.get("field")).isEqualTo("value") @@ -391,11 +415,13 @@ class SpriteShould { @Test internal fun `transform sprite to mutable map of collections`() { - val map = sprite.add("field", "value") - .add("field", "value2") - .add("field", "value3") - .add("single", "singleValue") - .asMultimap() + val map = + sprite + .add("field", "value") + .add("field", "value2") + .add("field", "value3") + .add("single", "singleValue") + .asMultimap() assertThat(map?.get("field")) .hasSize(3) @@ -408,7 +434,8 @@ class SpriteShould { @Test internal fun `answer about field's size`() { - sprite.add("field", "value") + sprite + .add("field", "value") .add("field", "value2") .add("field", "value3") .add("dateField", LocalDate.now()) @@ -435,7 +462,8 @@ class SpriteShould { @Test internal fun `view date as string`() { - sprite.add("text", "the text") + sprite + .add("text", "the text") .add("text", "another text") .add("date", LocalDate.parse("20180901", DateTimeFormatter.ofPattern("yyyyMMdd"))) .add("age", 10) @@ -446,17 +474,18 @@ class SpriteShould { @Test internal fun `show an ETL example`() { - val data = Sprite() - .add("age", 90) - .add("name", "rob") - .add("text", "first phrase") - .add("text", "second phrase") - .add("text", "third phrase") - .add("text", "fourth phrase") - .rename("age", "weight") - .apply("weight") { v: Float -> v * 2.2 } - .apply("name", String::toUpperCase) - .joinValuesOf("text") + val data = + Sprite() + .add("age", 90) + .add("name", "rob") + .add("text", "first phrase") + .add("text", "second phrase") + .add("text", "third phrase") + .add("text", "fourth phrase") + .rename("age", "weight") + .apply("weight") { v: Int -> v * 2.2 } + .apply("name", String::uppercase) + .joinValuesOf("text") assertThat(data.hasField("age")) .isFalse() diff --git a/gremlin/src/main/kotlin/com/arcadeanalytics/provider/gremlin/GremlinDataProvider.kt b/gremlin/src/main/kotlin/com/arcadeanalytics/provider/gremlin/GremlinDataProvider.kt index 27b6311a..299f786a 100644 --- a/gremlin/src/main/kotlin/com/arcadeanalytics/provider/gremlin/GremlinDataProvider.kt +++ b/gremlin/src/main/kotlin/com/arcadeanalytics/provider/gremlin/GremlinDataProvider.kt @@ -40,10 +40,13 @@ import java.util.HashMap import java.util.HashSet class GremlinDataProvider : DataSourceGraphDataProvider { - private val log = LoggerFactory.getLogger(GremlinDataProvider::class.java) - override fun fetchData(dataSource: DataSourceInfo, query: String, limit: Int): GraphData { + override fun fetchData( + dataSource: DataSourceInfo, + query: String, + limit: Int, + ): GraphData { val cluster = getCluster(dataSource) val client = cluster.connect().init() @@ -57,7 +60,12 @@ class GremlinDataProvider : DataSourceGraphDataProvider { } } - private fun getGraphData(dataSource: DataSourceInfo, query: String, limit: Int, client: Client): GraphData { + private fun getGraphData( + dataSource: DataSourceInfo, + query: String, + limit: Int, + client: Client, + ): GraphData { val cytoNodes = HashSet() val cytoEdges = HashSet() val edgeClasses = HashMap>() @@ -65,25 +73,26 @@ class GremlinDataProvider : DataSourceGraphDataProvider { log.info("fetching data from '{}' with query '{}' ", dataSource.id, query) - val ids: Array = client.submit(query) - .asSequence() - .take(limit) - .map { r -> toCytoData(dataSource, r, client) } - .map { data -> - if (data.group == "nodes") { - cytoNodes.add(data) - populateClasses(nodeClasses, data) - emptyList() - } else { - cytoEdges.add(data) - - populateClasses(edgeClasses, data) - listOf(data.data.source, data.data.target) - } - } - .flatMap { it.asSequence() } - .toSet() - .toTypedArray() + val ids: Array = + client + .submit(query) + .asSequence() + .take(limit) + .map { r -> toCytoData(dataSource, r, client) } + .map { data -> + if (data.group == "nodes") { + cytoNodes.add(data) + populateClasses(nodeClasses, data) + emptyList() + } else { + cytoEdges.add(data) + + populateClasses(edgeClasses, data) + listOf(data.data.source, data.data.target) + } + }.flatMap { it.asSequence() } + .toSet() + .toTypedArray() if (ids.isNotEmpty()) { val load = load(dataSource, ids, client) @@ -102,7 +111,11 @@ class GremlinDataProvider : DataSourceGraphDataProvider { return graphData } - private fun toCytoData(dataSource: DataSourceInfo, result: Result, client: Client): CytoData { + private fun toCytoData( + dataSource: DataSourceInfo, + result: Result, + client: Client, + ): CytoData { val element = result.element // id clean @@ -120,50 +133,66 @@ class GremlinDataProvider : DataSourceGraphDataProvider { record.remove("id") } - val cyto = when (element) { - is Vertex -> { - outs.putAll( - client.submit("g.V('${element.id()}').outE()").asSequence() - .map { r1 -> r1.edge } - .map { e1 -> e1.label() } - .groupingBy { it } - .eachCount(), - ) - - ins.putAll( - client.submit("g.V('${element.id()}').inE()").asSequence() - .map { r1 -> r1.edge } - .map { e1 -> e1.label() } - .groupingBy { it } - .eachCount(), - ) - - var edgeCount = ins.values.asSequence().map { o -> o as Int }.sum() - edgeCount += outs.values.asSequence().map { o -> o as Int }.sum() - record["@edgeCount"] = edgeCount - - val data = Data(id = id, record = record) - CytoData(classes = element.label(), data = data, group = "nodes") - } - is Edge -> { - val sourceId = element.outVertex().id().toString() - val source = nativeIdToArcadeId(dataSource, sourceId) + val cyto = + when (element) { + is Vertex -> { + outs.putAll( + client + .submit("g.V('${element.id()}').outE()") + .asSequence() + .map { r1 -> r1.edge } + .map { e1 -> e1.label() } + .groupingBy { it } + .eachCount(), + ) + + ins.putAll( + client + .submit("g.V('${element.id()}').inE()") + .asSequence() + .map { r1 -> r1.edge } + .map { e1 -> e1.label() } + .groupingBy { it } + .eachCount(), + ) + + var edgeCount = + ins.values + .asSequence() + .map { o -> o as Int } + .sum() + edgeCount += + outs.values + .asSequence() + .map { o -> o as Int } + .sum() + record["@edgeCount"] = edgeCount + + val data = Data(id = id, record = record) + CytoData(classes = element.label(), data = data, group = "nodes") + } + is Edge -> { + val sourceId = element.outVertex().id().toString() + val source = nativeIdToArcadeId(dataSource, sourceId) - val targetId = element.inVertex().id().toString() - val target = nativeIdToArcadeId(dataSource, targetId) + val targetId = element.inVertex().id().toString() + val target = nativeIdToArcadeId(dataSource, targetId) - val data = Data(id = id, source = source, target = target, record = record) - CytoData(classes = element.label(), data = data, group = "edges") - } - else -> { - log.info("element not mappable:: $element") - CytoData(classes = element.label(), data = Data(id), group = "unk") + val data = Data(id = id, source = source, target = target, record = record) + CytoData(classes = element.label(), data = data, group = "edges") + } + else -> { + log.info("element not mappable:: $element") + CytoData(classes = element.label(), data = Data(id), group = "unk") + } } - } return cyto } - private fun populateClasses(classes: MutableMap>, element: CytoData): CytoData { + private fun populateClasses( + classes: MutableMap>, + element: CytoData, + ): CytoData { if (classes[element.classes] == null) { classes[element.classes] = Maps.newHashMap() } @@ -171,10 +200,14 @@ class GremlinDataProvider : DataSourceGraphDataProvider { return element } - private fun populateProperties(classes: Map>, element: CytoData) { + private fun populateProperties( + classes: Map>, + element: CytoData, + ) { val properties = classes[element.classes] - element.data.record.keys.asSequence() + element.data.record.keys + .asSequence() .filter { f -> !f.startsWith("@") } .filter { f -> !f.startsWith("in_") } .filter { f -> !f.startsWith("out_") } @@ -183,7 +216,9 @@ class GremlinDataProvider : DataSourceGraphDataProvider { private fun transformToMap(doc: Element): MutableMap { val record = Maps.newHashMap() - doc.keys().asSequence() + doc + .keys() + .asSequence() .forEach { k -> // take single value record[k] = doc.properties(k).next().value() @@ -192,31 +227,51 @@ class GremlinDataProvider : DataSourceGraphDataProvider { return record } - override fun load(dataSource: DataSourceInfo, ids: Array): GraphData { + override fun load( + dataSource: DataSourceInfo, + ids: Array, + ): GraphData { val query = loadQuery(dataSource, ids) return fetchData(dataSource, query, ids.size) } - private fun load(dataSource: DataSourceInfo, ids: Array, client: Client): GraphData { + private fun load( + dataSource: DataSourceInfo, + ids: Array, + client: Client, + ): GraphData { val query = loadQuery(dataSource, ids) return getGraphData(dataSource, query, ids.size, client) } - override fun loadFromClass(dataSource: DataSourceInfo, className: String, limit: Int): GraphData { + override fun loadFromClass( + dataSource: DataSourceInfo, + className: String, + limit: Int, + ): GraphData { val query = "g.V().hasLabel(${splitMultilabel(className)}).limit($limit)" return fetchData(dataSource, query, limit) } - override fun loadFromClass(dataSource: DataSourceInfo, className: String, propName: String, propertyValue: String, limit: Int): GraphData { + override fun loadFromClass( + dataSource: DataSourceInfo, + className: String, + propName: String, + propertyValue: String, + limit: Int, + ): GraphData { val query = "g.V().hasLabel(${splitMultilabel(className)}).has('$propName', eq('$propertyValue')).limit($limit)" return fetchData(dataSource, query, limit) } - private fun loadQuery(dataSource: DataSourceInfo, ids: Array): String { + private fun loadQuery( + dataSource: DataSourceInfo, + ids: Array, + ): String { check(ids.isNotEmpty()) log.debug("load ids {} ", *ids) @@ -228,26 +283,30 @@ class GremlinDataProvider : DataSourceGraphDataProvider { private fun cleanIds( dataSource: DataSourceInfo, ids: Array, - ): String = ids.asSequence() - .map { id -> arcadeIdToNativeId(dataSource, id) } - .map { id -> """ '$id' """ } - .joinToString(",") + ): String = + ids + .asSequence() + .map { id -> arcadeIdToNativeId(dataSource, id) } + .map { id -> """ '$id' """ } + .joinToString(",") private fun nativeIdToArcadeId( dataSource: DataSourceInfo, id: String, - ): String = when (dataSource.type) { - "GREMLIN_ORIENTDB" -> "${dataSource.id}_${id.removePrefix("#").replace(":", "_")}" - else -> "${dataSource.id}_$id" - } + ): String = + when (dataSource.type) { + "GREMLIN_ORIENTDB" -> "${dataSource.id}_${id.removePrefix("#").replace(":", "_")}" + else -> "${dataSource.id}_$id" + } private fun arcadeIdToNativeId( dataSource: DataSourceInfo, id: String, - ): String = when (dataSource.type) { - "GREMLIN_ORIENTDB" -> id.removePrefix("${dataSource.id}_").prefixIfAbsent("#").replace("_", ":") - else -> id.removePrefix("${dataSource.id}_") - } + ): String = + when (dataSource.type) { + "GREMLIN_ORIENTDB" -> id.removePrefix("${dataSource.id}_").prefixIfAbsent("#").replace("_", ":") + else -> id.removePrefix("${dataSource.id}_") + } override fun expand( dataSource: DataSourceInfo, @@ -262,11 +321,12 @@ class GremlinDataProvider : DataSourceGraphDataProvider { if (StringUtils.isNotEmpty(edgeLabel)) edgeLabel = wrap(edgeLabel, '"') - query += when (direction.toLowerCase()) { - "out" -> """.outE($edgeLabel)""" - "in" -> """.inE($edgeLabel)""" - else -> """.bothE($edgeLabel)""" - } + query += + when (direction.toLowerCase()) { + "out" -> """.outE($edgeLabel)""" + "in" -> """.inE($edgeLabel)""" + else -> """.bothE($edgeLabel)""" + } return fetchData(dataSource, query, maxTraversal) } @@ -314,7 +374,5 @@ class GremlinDataProvider : DataSourceGraphDataProvider { } } - override fun supportedDataSourceTypes(): Set { - return Sets.newHashSet("GREMLIN_ORIENTDB", "GREMLIN_NEPTUNE", "GREMLIN_JANUSGRAPH") - } + override fun supportedDataSourceTypes(): Set = Sets.newHashSet("GREMLIN_ORIENTDB", "GREMLIN_NEPTUNE", "GREMLIN_JANUSGRAPH") } diff --git a/gremlin/src/main/kotlin/com/arcadeanalytics/provider/gremlin/GremlinGraphProvider.kt b/gremlin/src/main/kotlin/com/arcadeanalytics/provider/gremlin/GremlinGraphProvider.kt index 53f3ac2c..967d841c 100644 --- a/gremlin/src/main/kotlin/com/arcadeanalytics/provider/gremlin/GremlinGraphProvider.kt +++ b/gremlin/src/main/kotlin/com/arcadeanalytics/provider/gremlin/GremlinGraphProvider.kt @@ -37,12 +37,14 @@ import kotlin.math.min */ class GremlinGraphProvider : DataSourceGraphProvider { - private val log = LoggerFactory.getLogger(GremlinGraphProvider::class.java) private val allFields: Pattern - override fun provideTo(dataSource: DataSourceInfo, player: SpritePlayer) { + override fun provideTo( + dataSource: DataSourceInfo, + player: SpritePlayer, + ) { val cluster = getCluster(dataSource) val client = cluster.connect().init() try { @@ -56,7 +58,11 @@ class GremlinGraphProvider : DataSourceGraphProvider { } } - private fun provideNodes(dataSource: DataSourceInfo, processor: SpritePlayer, client: Client) { + private fun provideNodes( + dataSource: DataSourceInfo, + processor: SpritePlayer, + client: Client, + ) { val nodes = client.submit("g.V().count()").one().long var fetched: Long = 0 var skip: Long = 0 @@ -67,12 +73,14 @@ class GremlinGraphProvider : DataSourceGraphProvider { for (r in resultSet) { val element = r.vertex val sprite = Sprite() - element.keys() + element + .keys() .asSequence() .flatMap { key: String? -> element.properties(key).asSequence() } .forEach { v: VertexProperty -> sprite.add(v.label(), v.value()) } - sprite.add(ARCADE_ID, dataSource.id.toString() + "_" + cleanOrientId(element.id().toString())) + sprite + .add(ARCADE_ID, dataSource.id.toString() + "_" + cleanOrientId(element.id().toString())) .add(ARCADE_TYPE, ARCADE_NODE_TYPE) .add("@class", element.label()) @@ -84,7 +92,11 @@ class GremlinGraphProvider : DataSourceGraphProvider { } } - private fun provideEdges(dataSource: DataSourceInfo, processor: SpritePlayer, client: Client) { + private fun provideEdges( + dataSource: DataSourceInfo, + processor: SpritePlayer, + client: Client, + ) { val edges = client.submit("g.E().count()").one().long var fetched: Long = 0 var skip: Long = 0 @@ -96,10 +108,13 @@ class GremlinGraphProvider : DataSourceGraphProvider { val element = r.element if (element.keys().isNotEmpty()) { val sprite = Sprite() - element.keys().asSequence() + element + .keys() + .asSequence() .forEach { k: String? -> sprite.add(k!!, element.value(k).toString()) } - sprite.add(ARCADE_ID, dataSource.id.toString() + "_" + cleanOrientId(element.id().toString())) + sprite + .add(ARCADE_ID, dataSource.id.toString() + "_" + cleanOrientId(element.id().toString())) .add(ARCADE_TYPE, ARCADE_EDGE_TYPE) .add("@class", element.label()) @@ -112,14 +127,12 @@ class GremlinGraphProvider : DataSourceGraphProvider { } } - private fun cleanOrientId(id: String): String { - return StringUtils.removeStart(id, "#") + private fun cleanOrientId(id: String): String = + StringUtils + .removeStart(id, "#") .replace(":", "_") - } - override fun supportedDataSourceTypes(): Set { - return Sets.newHashSet("GREMLIN_ORIENTDB", "GREMLIN_NEPTUNE", "GREMLIN_JANUSGRAPH") - } + override fun supportedDataSourceTypes(): Set = Sets.newHashSet("GREMLIN_ORIENTDB", "GREMLIN_NEPTUNE", "GREMLIN_JANUSGRAPH") init { allFields = Pattern.compile(".*") diff --git a/gremlin/src/main/kotlin/com/arcadeanalytics/provider/gremlin/GremlinMetadataProvider.kt b/gremlin/src/main/kotlin/com/arcadeanalytics/provider/gremlin/GremlinMetadataProvider.kt index f6d6c301..ada171e7 100644 --- a/gremlin/src/main/kotlin/com/arcadeanalytics/provider/gremlin/GremlinMetadataProvider.kt +++ b/gremlin/src/main/kotlin/com/arcadeanalytics/provider/gremlin/GremlinMetadataProvider.kt @@ -32,7 +32,6 @@ import org.apache.tinkerpop.gremlin.driver.Client import org.slf4j.LoggerFactory class GremlinMetadataProvider : DataSourceMetadataProvider { - private val log = LoggerFactory.getLogger(GremlinMetadataProvider::class.java) override fun supportedDataSourceTypes() = setOf("GREMLIN_ORIENTDB", "GREMLIN_NEPTUNE", "GREMLIN_JANUSGRAPH") @@ -54,8 +53,9 @@ class GremlinMetadataProvider : DataSourceMetadataProvider { } } - fun mapNodeClasses(client: Client): NodesClasses { - return client.submit("g.V().label().groupCount()") + fun mapNodeClasses(client: Client): NodesClasses = + client + .submit("g.V().label().groupCount()") .asSequence() .onEach { tc -> println("tc = $tc") } .map { r -> r.`object` as Map } @@ -64,42 +64,56 @@ class GremlinMetadataProvider : DataSourceMetadataProvider { .map { it.name to it }.toMap() - } - private fun mapNodeProperties(label: String, client: Client): TypeProperties { - return client.submit("""g.V().hasLabel(${splitMultilabel(label)}).limit(1).next()""") + private fun mapNodeProperties( + label: String, + client: Client, + ): TypeProperties = + client + .submit("""g.V().hasLabel(${splitMultilabel(label)}).limit(1).next()""") .asSequence() .flatMap { r -> r.element.properties().asSequence() } .map { property -> TypeProperty(property.key(), mapType(property.value().javaClass.simpleName)) } .map { it.name to it } .toMap() - } - private fun mapEdgesClasses(client: Client): EdgesClasses { - return client.submit("g.E().label().dedup()").asSequence() + private fun mapEdgesClasses(client: Client): EdgesClasses = + client + .submit("g.E().label().dedup()") + .asSequence() .map { r -> r.`object`.toString() } .map { TypeClass(it, countEdgeLabel(it, client), mapEdgeProperties(it, client)) } .map { it.name to it }.toMap() - } - private fun mapEdgeProperties(label: String, client: Client): TypeProperties { - return client.submit("""g.E().hasLabel(${splitMultilabel(label)} ).limit(1).next()""") + private fun mapEdgeProperties( + label: String, + client: Client, + ): TypeProperties = + client + .submit("""g.E().hasLabel(${splitMultilabel(label)} ).limit(1).next()""") .asSequence() .flatMap { r -> r.element.properties().asSequence() } .map { property -> TypeProperty(property.key(), mapType(property.value().javaClass.simpleName)) } .map { it.name to it } .toMap() - } - private fun countNodeLabel(label: String, client: Client): Long { - return client.submit("""g.V().hasLabel(${splitMultilabel(label)}).count()""") - .one().long - } + private fun countNodeLabel( + label: String, + client: Client, + ): Long = + client + .submit("""g.V().hasLabel(${splitMultilabel(label)}).count()""") + .one() + .long - private fun countEdgeLabel(label: String, client: Client): Long { - return client.submit("""g.E().hasLabel(${splitMultilabel(label)}).count()""") - .one().long - } + private fun countEdgeLabel( + label: String, + client: Client, + ): Long = + client + .submit("""g.E().hasLabel(${splitMultilabel(label)}).count()""") + .one() + .long } diff --git a/gremlin/src/main/kotlin/com/arcadeanalytics/provider/gremlin/GremlinUtil.kt b/gremlin/src/main/kotlin/com/arcadeanalytics/provider/gremlin/GremlinUtil.kt index d252a10a..a5328298 100644 --- a/gremlin/src/main/kotlin/com/arcadeanalytics/provider/gremlin/GremlinUtil.kt +++ b/gremlin/src/main/kotlin/com/arcadeanalytics/provider/gremlin/GremlinUtil.kt @@ -29,7 +29,8 @@ import org.apache.tinkerpop.gremlin.structure.io.gryo.GryoMapper import org.janusgraph.graphdb.tinkerpop.JanusGraphIoRegistry fun getCluster(dataSource: DataSourceInfo): Cluster = - Cluster.build(dataSource.server) + Cluster + .build(dataSource.server) .port(dataSource.port) .serializer(createSerializer(dataSource)) .enableSsl(dataSource.enableSsl) @@ -40,20 +41,23 @@ fun getCluster(dataSource: DataSourceInfo): Cluster = .create() fun splitMultilabel(label: String): String = - label.split("::") + label + .split("::") .joinToString("','", "'", "'") -fun createSerializer(dataSource: DataSourceInfo): MessageSerializer { - return when (dataSource.type) { +fun createSerializer(dataSource: DataSourceInfo): MessageSerializer = + when (dataSource.type) { "GREMLIN_ORIENTDB" -> GryoMessageSerializerV3d0( - GryoMapper.build() + GryoMapper + .build() .addRegistry(OrientIoRegistry.getInstance()), ) "GREMLIN_NEPTUNE" -> GryoMessageSerializerV3d0() "GREMLIN_JANUSGRAPH" -> GryoMessageSerializerV3d0( - GryoMapper.build() + GryoMapper + .build() .addRegistry(JanusGraphIoRegistry.getInstance()), ) "GREMLIN_COSMOSDB" -> { @@ -63,4 +67,3 @@ fun createSerializer(dataSource: DataSourceInfo): MessageSerializer { } else -> throw RuntimeException("requested type not implemented yet:: ${dataSource.type}") } -} diff --git a/gremlin/src/main/kotlin/com/arcadeanalytics/provider/gremlin/cosmosdb/CosmosDBGremlinDataProvider.kt b/gremlin/src/main/kotlin/com/arcadeanalytics/provider/gremlin/cosmosdb/CosmosDBGremlinDataProvider.kt index 1fc789b5..7b7bd51b 100644 --- a/gremlin/src/main/kotlin/com/arcadeanalytics/provider/gremlin/cosmosdb/CosmosDBGremlinDataProvider.kt +++ b/gremlin/src/main/kotlin/com/arcadeanalytics/provider/gremlin/cosmosdb/CosmosDBGremlinDataProvider.kt @@ -38,14 +38,15 @@ import java.util.HashMap import java.util.HashSet class CosmosDBGremlinDataProvider : DataSourceGraphDataProvider { - private val log = LoggerFactory.getLogger(CosmosDBGremlinDataProvider::class.java) - override fun supportedDataSourceTypes(): Set { - return Sets.newHashSet("GREMLIN_COSMOSDB") - } + override fun supportedDataSourceTypes(): Set = Sets.newHashSet("GREMLIN_COSMOSDB") - override fun fetchData(dataSource: DataSourceInfo, query: String, limit: Int): GraphData { + override fun fetchData( + dataSource: DataSourceInfo, + query: String, + limit: Int, + ): GraphData { val cluster = getCluster(dataSource) log.info("fetching data from '{}' with query '{}' ", dataSource.id, query) @@ -65,7 +66,8 @@ class CosmosDBGremlinDataProvider : DataSourceGraphDataProvider { private fun getCluster(dataSource: DataSourceInfo): Cluster { val serializer = createSerializer(dataSource) - return Cluster.build(dataSource.server) + return Cluster + .build(dataSource.server) .port(dataSource.port) .serializer(serializer) .enableSsl(dataSource.type == "GREMLIN_COSMOSDB") @@ -74,7 +76,12 @@ class CosmosDBGremlinDataProvider : DataSourceGraphDataProvider { .create() } - private fun getGraphData(dataSource: DataSourceInfo, query: String, limit: Int, client: Client): GraphData { + private fun getGraphData( + dataSource: DataSourceInfo, + query: String, + limit: Int, + client: Client, + ): GraphData { val nodes = HashSet() val edges = HashSet() val edgeClasses = HashMap>() @@ -82,7 +89,8 @@ class CosmosDBGremlinDataProvider : DataSourceGraphDataProvider { // final Contract contract = dataSource.getWorkspace().getUser().getCompany().getContract(); - client.submit(query) + client + .submit(query) .stream() .limit(limit.toLong()) .map { r -> toData(dataSource, r, client) } @@ -112,7 +120,11 @@ class CosmosDBGremlinDataProvider : DataSourceGraphDataProvider { return graphData } - private fun toData(dataSource: DataSourceInfo, result: Result, client: Client): CytoData { + private fun toData( + dataSource: DataSourceInfo, + result: Result, + client: Client, + ): CytoData { log.info("result:: {}", result) val record = transformToMap(result) @@ -132,58 +144,73 @@ class CosmosDBGremlinDataProvider : DataSourceGraphDataProvider { record.remove("id") } - val cyto = when (record["type"]) { - "vertex" -> { - outs.putAll( - client.submit("g.V('${record["id"]}').outE()").asSequence() - .map { r1 -> r1.getObject() as Map } - .map { e1 -> e1["label"].toString() } - .groupingBy { it } - .eachCount(), - ) - - ins.putAll( - client.submit("g.V('${record["id"]}').inE()").asSequence() - .map { r1 -> r1.getObject() as Map } - .map { e1 -> e1["label"].toString() } - .groupingBy { it } - .eachCount(), - ) - - var edgeCount = ins.values.stream().mapToLong { o -> o as Long }.sum() - edgeCount += outs.values.stream().mapToLong { o -> o as Long }.sum() - record["@edgeCount"] = edgeCount - - val data = Data(id = id, record = record) - CytoData(classes = record["label"].toString(), data = data, group = "nodes") - } + val cyto = + when (record["type"]) { + "vertex" -> { + outs.putAll( + client + .submit("g.V('${record["id"]}').outE()") + .asSequence() + .map { r1 -> r1.getObject() as Map } + .map { e1 -> e1["label"].toString() } + .groupingBy { it } + .eachCount(), + ) + + ins.putAll( + client + .submit("g.V('${record["id"]}').inE()") + .asSequence() + .map { r1 -> r1.getObject() as Map } + .map { e1 -> e1["label"].toString() } + .groupingBy { it } + .eachCount(), + ) + + var edgeCount = + ins.values + .stream() + .mapToLong { o -> o as Long } + .sum() + edgeCount += + outs.values + .stream() + .mapToLong { o -> o as Long } + .sum() + record["@edgeCount"] = edgeCount + + val data = Data(id = id, record = record) + CytoData(classes = record["label"].toString(), data = data, group = "nodes") + } - "edge" -> { - val sourceId = record["inV"].toString() - val source = dataSource.id.toString() + "_" + cleanOrientId(sourceId) - val targetId = record["outV"].toString() - val target = dataSource.id.toString() + "_" + cleanOrientId(targetId) + "edge" -> { + val sourceId = record["inV"].toString() + val source = dataSource.id.toString() + "_" + cleanOrientId(sourceId) + val targetId = record["outV"].toString() + val target = dataSource.id.toString() + "_" + cleanOrientId(targetId) - record.remove("outV") - record.remove("inV") + record.remove("outV") + record.remove("inV") - val data = Data(id = id, source = source, target = target, record = record) - CytoData(classes = record["label"].toString(), data = data, group = "edges") - } - else -> { - log.info("element not mappable:: $record") - CytoData(classes = record["label"].toString(), data = Data(id), group = "unk") + val data = Data(id = id, source = source, target = target, record = record) + CytoData(classes = record["label"].toString(), data = data, group = "edges") + } + else -> { + log.info("element not mappable:: $record") + CytoData(classes = record["label"].toString(), data = Data(id), group = "unk") + } } - } return cyto } - private fun cleanOrientId(id: String): String { - return removeStart(id, "#") + private fun cleanOrientId(id: String): String = + removeStart(id, "#") .replace(":", "_") - } - protected fun populateClasses(classes: MutableMap>, element: CytoData): CytoData { + protected fun populateClasses( + classes: MutableMap>, + element: CytoData, + ): CytoData { if (classes[element.classes] == null) { classes[element.classes] = Maps.newHashMap() } @@ -208,7 +235,10 @@ class CosmosDBGremlinDataProvider : DataSourceGraphDataProvider { return res } - override fun load(dataSource: DataSourceInfo, ids: Array): GraphData { + override fun load( + dataSource: DataSourceInfo, + ids: Array, + ): GraphData { val query = loadQuery(dataSource, ids) val cluster = getCluster(dataSource) @@ -226,40 +256,60 @@ class CosmosDBGremlinDataProvider : DataSourceGraphDataProvider { } } - private fun load(dataSource: DataSourceInfo, ids: Array, client: Client): GraphData { + private fun load( + dataSource: DataSourceInfo, + ids: Array, + client: Client, + ): GraphData { val query = loadQuery(dataSource, ids) return getGraphData(dataSource, query, ids.size, client) } - override fun loadFromClass(dataSource: DataSourceInfo, className: String, limit: Int): GraphData { + override fun loadFromClass( + dataSource: DataSourceInfo, + className: String, + limit: Int, + ): GraphData { val query = "g.V().hasLabel('$className').limit($limit)" return this.fetchData(dataSource, query, limit) } - override fun loadFromClass(dataSource: DataSourceInfo, className: String, propName: String, propertyValue: String, limit: Int): GraphData { + override fun loadFromClass( + dataSource: DataSourceInfo, + className: String, + propName: String, + propertyValue: String, + limit: Int, + ): GraphData { val query = "g.V().hasLabel('$className').has('$propName', eq('$propertyValue')).limit($limit)" return this.fetchData(dataSource, query, limit) } - private fun loadQuery(dataSource: DataSourceInfo, ids: Array): String { + private fun loadQuery( + dataSource: DataSourceInfo, + ids: Array, + ): String { var query = "g.V(" log.debug("load ids {} ", *ids) - query += ids.asSequence() - .map { id -> removeStart(id, dataSource.id.toString() + "_") } - .map { id -> arcadeIdToNativeId(dataSource, id) } - .map { id -> """"$id"""" } - .joinToString(",") + query += + ids + .asSequence() + .map { id -> removeStart(id, dataSource.id.toString() + "_") } + .map { id -> arcadeIdToNativeId(dataSource, id) } + .map { id -> """"$id"""" } + .joinToString(",") query += ") " return query } - private fun arcadeIdToNativeId(dataSource: DataSourceInfo, id: String): String { - return if (dataSource.type == "GREMLIN_ORIENTDB") StringUtils.prependIfMissing(id, "#").replace("_", ":") else id - } + private fun arcadeIdToNativeId( + dataSource: DataSourceInfo, + id: String, + ): String = if (dataSource.type == "GREMLIN_ORIENTDB") StringUtils.prependIfMissing(id, "#").replace("_", ":") else id override fun expand( dataSource: DataSourceInfo, @@ -271,41 +321,53 @@ class CosmosDBGremlinDataProvider : DataSourceGraphDataProvider { var edgeLabel = edgeLabel var query = "g.V(" - query += roots.asSequence() - .map { id -> removeStart(id, dataSource.id.toString() + "_") } - .map { id -> arcadeIdToNativeId(dataSource, id) } - .map { id -> wrap(id, '"') } - .joinToString(",") + query += + roots + .asSequence() + .map { id -> removeStart(id, dataSource.id.toString() + "_") } + .map { id -> arcadeIdToNativeId(dataSource, id) } + .map { id -> wrap(id, '"') } + .joinToString(",") query += ")" if (StringUtils.isNotEmpty(edgeLabel)) edgeLabel = wrap(edgeLabel, '"') - query += when (direction.toLowerCase()) { - "out" -> """.outE($edgeLabel) """ - "in" -> """.inE($edgeLabel) """ - else -> """.bothE($edgeLabel) """ - } + query += + when (direction.toLowerCase()) { + "out" -> """.outE($edgeLabel) """ + "in" -> """.inE($edgeLabel) """ + else -> """.bothE($edgeLabel) """ + } return fetchData(dataSource, query, maxTraversal) } - override fun edges(dataSource: DataSourceInfo, fromIds: Array, edgesLabel: Array, toIds: Array): GraphData { + override fun edges( + dataSource: DataSourceInfo, + fromIds: Array, + edgesLabel: Array, + toIds: Array, + ): GraphData { TODO("Not yet implemented") } override fun testConnection(dataSource: DataSourceInfo): Boolean { try { log.info("testing connection to :: '{}' ", dataSource.server) - val cluster = Cluster.build(dataSource.server) - .port(dataSource.port) - .enableSsl(true) - .serializer(createSerializer(dataSource)) - .credentials(dataSource.username, dataSource.password) - .maxWaitForConnection(10000) - .create() - - cluster.availableHosts() - .stream().forEach { h -> log.info("gremlin host:: {} ", h) } + val cluster = + Cluster + .build(dataSource.server) + .port(dataSource.port) + .enableSsl(true) + .serializer(createSerializer(dataSource)) + .credentials(dataSource.username, dataSource.password) + .maxWaitForConnection(10000) + .create() + + cluster + .availableHosts() + .stream() + .forEach { h -> log.info("gremlin host:: {} ", h) } val client = cluster.connect().init() diff --git a/gremlin/src/main/kotlin/com/arcadeanalytics/provider/gremlin/cosmosdb/CosmosDBGremlinGraphProvider.kt b/gremlin/src/main/kotlin/com/arcadeanalytics/provider/gremlin/cosmosdb/CosmosDBGremlinGraphProvider.kt index 29d663a1..959bb740 100644 --- a/gremlin/src/main/kotlin/com/arcadeanalytics/provider/gremlin/cosmosdb/CosmosDBGremlinGraphProvider.kt +++ b/gremlin/src/main/kotlin/com/arcadeanalytics/provider/gremlin/cosmosdb/CosmosDBGremlinGraphProvider.kt @@ -35,7 +35,6 @@ import org.slf4j.LoggerFactory import java.util.regex.Pattern class CosmosDBGremlinGraphProvider : DataSourceGraphProvider { - private val log = LoggerFactory.getLogger(CosmosDBGremlinGraphProvider::class.java) private val allFields: Pattern @@ -43,17 +42,20 @@ class CosmosDBGremlinGraphProvider : DataSourceGraphProvider { allFields = Pattern.compile(".*") } - override fun supportedDataSourceTypes(): Set { - return Sets.newHashSet("GREMLIN_COSMOSDB") - } - - override fun provideTo(dataSource: DataSourceInfo, player: SpritePlayer) { - val cluster = Cluster.build(dataSource.server) - .port(dataSource.port) - .serializer(createSerializer(dataSource)) - .enableSsl(dataSource.type == "GREMLIN_COSMOSDB") - .credentials(dataSource.username, dataSource.password) - .create() + override fun supportedDataSourceTypes(): Set = Sets.newHashSet("GREMLIN_COSMOSDB") + + override fun provideTo( + dataSource: DataSourceInfo, + player: SpritePlayer, + ) { + val cluster = + Cluster + .build(dataSource.server) + .port(dataSource.port) + .serializer(createSerializer(dataSource)) + .enableSsl(dataSource.type == "GREMLIN_COSMOSDB") + .credentials(dataSource.username, dataSource.password) + .create() val client = cluster.connect().init() @@ -67,7 +69,11 @@ class CosmosDBGremlinGraphProvider : DataSourceGraphProvider { player.end() } - private fun provideNodes(dataSource: DataSourceInfo, processor: SpritePlayer, client: Client) { + private fun provideNodes( + dataSource: DataSourceInfo, + processor: SpritePlayer, + client: Client, + ) { val nodes = client.submit("g.V().count()").one().long var fetched: Long = 0 var skip: Long = 0 @@ -93,7 +99,8 @@ class CosmosDBGremlinGraphProvider : DataSourceGraphProvider { res.keys .forEach { k -> sprite.add(k, res[k].toString()) } - sprite.add(ARCADE_ID, dataSource.id.toString() + "_" + res["id"]) + sprite + .add(ARCADE_ID, dataSource.id.toString() + "_" + res["id"]) .add(ARCADE_TYPE, ARCADE_NODE_TYPE) .add("@class", res["label"]) .apply(allFields) { v -> v.toString() } @@ -107,7 +114,11 @@ class CosmosDBGremlinGraphProvider : DataSourceGraphProvider { } } - private fun provideEdges(dataSource: DataSourceInfo, processor: SpritePlayer, client: Client) { + private fun provideEdges( + dataSource: DataSourceInfo, + processor: SpritePlayer, + client: Client, + ) { val edges = client.submit("g.E().count()").one().long var fetched: Long = 0 var skip: Long = 0 @@ -133,7 +144,8 @@ class CosmosDBGremlinGraphProvider : DataSourceGraphProvider { res.keys .forEach { k -> sprite.add(k, res[k].toString()) } - sprite.add(ARCADE_ID, dataSource.id.toString() + "_" + res["id"]) + sprite + .add(ARCADE_ID, dataSource.id.toString() + "_" + res["id"]) .add(ARCADE_TYPE, ARCADE_EDGE_TYPE) .add("@class", res["label"]) .apply(allFields) { v -> v.toString() } diff --git a/gremlin/src/main/kotlin/com/arcadeanalytics/provider/gremlin/cosmosdb/CosmosDBGremlinMetadataProvider.kt b/gremlin/src/main/kotlin/com/arcadeanalytics/provider/gremlin/cosmosdb/CosmosDBGremlinMetadataProvider.kt index aa8fbb02..70b34668 100644 --- a/gremlin/src/main/kotlin/com/arcadeanalytics/provider/gremlin/cosmosdb/CosmosDBGremlinMetadataProvider.kt +++ b/gremlin/src/main/kotlin/com/arcadeanalytics/provider/gremlin/cosmosdb/CosmosDBGremlinMetadataProvider.kt @@ -32,8 +32,7 @@ import org.apache.tinkerpop.gremlin.driver.Client import org.apache.tinkerpop.gremlin.driver.Cluster import org.slf4j.LoggerFactory -class CosmosDBGremlinMetadataProvider() : DataSourceMetadataProvider { - +class CosmosDBGremlinMetadataProvider : DataSourceMetadataProvider { private val log = LoggerFactory.getLogger(CosmosDBGremlinMetadataProvider::class.java) override fun supportedDataSourceTypes(): Set = setOf("GREMLIN_COSMOSDB") @@ -43,13 +42,15 @@ class CosmosDBGremlinMetadataProvider() : DataSourceMetadataProvider { val serializer = createSerializer(datasource) - val cluster = Cluster.build(datasource.server) - .port(datasource.port!!) - .serializer(serializer) - .enableSsl(datasource.type == "GREMLIN_COSMOSDB") - .credentials(datasource.username, datasource.password) - .maxWaitForConnection(10000) - .create() + val cluster = + Cluster + .build(datasource.server) + .port(datasource.port!!) + .serializer(serializer) + .enableSsl(datasource.type == "GREMLIN_COSMOSDB") + .credentials(datasource.username, datasource.password) + .maxWaitForConnection(10000) + .create() val client = cluster.connect().init() try { @@ -63,17 +64,22 @@ class CosmosDBGremlinMetadataProvider() : DataSourceMetadataProvider { } } - fun mapNodeClasses(client: Client): NodesClasses { - return client.submit("g.V().label().dedup()").asSequence() + fun mapNodeClasses(client: Client): NodesClasses = + client + .submit("g.V().label().dedup()") + .asSequence() .map { r -> r.`object`.toString() } .map { TypeClass(it, countNodeLabel(it, client), mapNodeProperties(it, client)) } .map { it.name to it }.toMap() - } - private fun mapNodeProperties(label: String, client: Client): TypeProperties { - return client.submit("g.V().hasLabel('$label').limit(1)") + private fun mapNodeProperties( + label: String, + client: Client, + ): TypeProperties = + client + .submit("g.V().hasLabel('$label').limit(1)") .asSequence() .map { it -> it.`object` as Map } .map { it -> it["properties"] as Map>> } @@ -83,34 +89,45 @@ class CosmosDBGremlinMetadataProvider() : DataSourceMetadataProvider { .map { property -> TypeProperty(property, "STRING") } .map { it.name to it } .toMap() - } - fun mapEdgesClasses(client: Client): EdgesClasses { - return client.submit("g.E().label().dedup()").asSequence() + fun mapEdgesClasses(client: Client): EdgesClasses = + client + .submit("g.E().label().dedup()") + .asSequence() .map { r -> r.`object`.toString() } .map { TypeClass(it, countEdgeLabel(it, client), mapEdgeProperties(it, client)) } .map { it.name to it }.toMap() - } - private fun mapEdgeProperties(label: String, client: Client): TypeProperties { - return client.submit("g.E().hasLabel('$label').limit(1)") + private fun mapEdgeProperties( + label: String, + client: Client, + ): TypeProperties = + client + .submit("g.E().hasLabel('$label').limit(1)") .asSequence() .map { it -> it.`object` as Map } .flatMap { it -> it.keys.asSequence() } .map { property -> TypeProperty(property, "STRING") } .map { it.name to it } .toMap() - } - private fun countNodeLabel(label: String, client: Client): Long { - return client.submit("g.V().hasLabel('$label').count()") - .one().long - } + private fun countNodeLabel( + label: String, + client: Client, + ): Long = + client + .submit("g.V().hasLabel('$label').count()") + .one() + .long - private fun countEdgeLabel(label: String, client: Client): Long { - return client.submit("g.E().hasLabel('$label').count()") - .one().long - } + private fun countEdgeLabel( + label: String, + client: Client, + ): Long = + client + .submit("g.E().hasLabel('$label').count()") + .one() + .long } diff --git a/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/GremlinDataProviderIntTest.kt b/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/GremlinDataProviderIntTest.kt index 31d78b2e..45ebf98f 100644 --- a/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/GremlinDataProviderIntTest.kt +++ b/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/GremlinDataProviderIntTest.kt @@ -26,7 +26,6 @@ import org.junit.jupiter.api.TestInstance @TestInstance(TestInstance.Lifecycle.PER_CLASS) class GremlinDataProviderIntTest { - private val provider: GremlinDataProvider = GremlinDataProvider() @Test @@ -42,7 +41,8 @@ class GremlinDataProviderIntTest { assertThat(cytoData.data.target).isNullOrEmpty() val record = cytoData.data.record - assertThat(record).isNotNull + assertThat(record) + .isNotNull .containsKeys("@in", "@out", "Name", "@edgeCount") } @@ -73,9 +73,11 @@ class GremlinDataProviderIntTest { val data = provider.fetchData(dataSource, query, 10) - val ids = data.nodes.asSequence() - .map { it.data.id } - .toList() + val ids = + data.nodes + .asSequence() + .map { it.data.id } + .toList() val load = provider.load(dataSource, ids.toTypedArray()) @@ -88,15 +90,19 @@ class GremlinDataProviderIntTest { val data = provider.fetchData(dataSource, query, 10) - val ids = data.nodes.asSequence() - .map { it.data.id } - .toList() + val ids = + data.nodes + .asSequence() + .map { it.data.id } + .toList() - val label: String = data.nodes.asSequence() - .map { it.data.record["@in"] as Map } - .map { ins -> ins.keys } - .flatMap { k -> k.asSequence() } - .first() + val label: String = + data.nodes + .asSequence() + .map { it.data.record["@in"] as Map } + .map { ins -> ins.keys } + .flatMap { k -> k.asSequence() } + .first() val load = provider.expand(dataSource, ids.toTypedArray(), "in", label, 300) @@ -114,9 +120,11 @@ class GremlinDataProviderIntTest { val data = provider.fetchData(dataSource, query, 10) - val ids = data.nodes.asSequence() - .map { it.data.id } - .toList() + val ids = + data.nodes + .asSequence() + .map { it.data.id } + .toList() val load = provider.expand(dataSource, ids.toTypedArray(), "both", "", 300) @@ -140,7 +148,8 @@ class GremlinDataProviderIntTest { assertThat(cytoData.data.target).isNotNull() val record = cytoData.data.record - assertThat(record).isNotNull + assertThat(record) + .isNotNull .containsKeys("@in", "@out") assertThat(data.nodes).isNotEmpty @@ -157,10 +166,12 @@ class GremlinDataProviderIntTest { val firstNode = firstDataSet.nodes.first().data val secondNode = secondDataSet.nodes.first().data - val edgeClasses = (firstNode.record["@in"] as Map).keys - .union((firstNode.record["@out"] as Map).keys) - .union((secondNode.record["@in"] as Map).keys) - .union((secondNode.record["@out"] as Map).keys) + val edgeClasses = + (firstNode.record["@in"] as Map) + .keys + .union((firstNode.record["@out"] as Map).keys) + .union((secondNode.record["@in"] as Map).keys) + .union((secondNode.record["@out"] as Map).keys) val data = provider.edges(dataSource, arrayOf(firstNode.id), edgeClasses.toTypedArray(), arrayOf(secondNode.id)) diff --git a/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/GremlinGraphProviderTest.kt b/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/GremlinGraphProviderTest.kt index 25e71038..0e51ff48 100644 --- a/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/GremlinGraphProviderTest.kt +++ b/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/GremlinGraphProviderTest.kt @@ -31,7 +31,6 @@ import java.util.ArrayList @TestInstance(TestInstance.Lifecycle.PER_CLASS) class GremlinGraphProviderTest { - private val provider: GremlinGraphProvider = GremlinGraphProvider() @Test @@ -39,26 +38,25 @@ class GremlinGraphProviderTest { val nodes = ArrayList() val edges = ArrayList() - val indexer = object : SpritePlayer { - override fun begin() { - TODO("not implemented") // To change body of created functions use File | Settings | File Templates. - } + val indexer = + object : SpritePlayer { + override fun begin() { + TODO("not implemented") // To change body of created functions use File | Settings | File Templates. + } - override fun processed(): Long { - return 0 - } + override fun processed(): Long = 0 - override fun play(sprite: Sprite) { - when (sprite.valueOf(ARCADE_TYPE)) { - ARCADE_NODE_TYPE -> nodes.add(sprite) - ARCADE_EDGE_TYPE -> edges.add(sprite) + override fun play(sprite: Sprite) { + when (sprite.valueOf(ARCADE_TYPE)) { + ARCADE_NODE_TYPE -> nodes.add(sprite) + ARCADE_EDGE_TYPE -> edges.add(sprite) + } + assertThat(sprite.valueOf("@class")).isNotBlank } - assertThat(sprite.valueOf("@class")).isNotBlank - } - override fun end() { + override fun end() { + } } - } provider.provideTo(OrientDBGremlinContainer.dataSource, indexer) assertThat(nodes).hasSize(7275) diff --git a/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/GremlinMetadataProviderTest.kt b/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/GremlinMetadataProviderTest.kt index 31b4d436..1ff97bd1 100644 --- a/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/GremlinMetadataProviderTest.kt +++ b/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/GremlinMetadataProviderTest.kt @@ -25,7 +25,6 @@ import org.junit.jupiter.api.TestInstance @TestInstance(TestInstance.Lifecycle.PER_CLASS) class GremlinMetadataProviderTest { - private val provider: GremlinMetadataProvider = GremlinMetadataProvider() @Test diff --git a/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/OrientDBGremlinContainer.kt b/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/OrientDBGremlinContainer.kt index 9f39e2b6..b882a5c0 100644 --- a/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/OrientDBGremlinContainer.kt +++ b/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/OrientDBGremlinContainer.kt @@ -25,28 +25,29 @@ import org.testcontainers.containers.wait.strategy.Wait import org.testcontainers.utility.DockerImageName object OrientDBGremlinContainer { + private val container: KGenericContainer = + KGenericContainer(DockerImageName.parse("arcadeanalytics/orientdb3")) + .apply { - private val container: KGenericContainer = KGenericContainer(DockerImageName.parse("arcadeanalytics/orientdb3")) - .apply { - - withExposedPorts(8182, 2424) - withEnv("ORIENTDB_ROOT_PASSWORD", "arcade") - waitingFor(Wait.defaultWaitStrategy()) - start() - } + withExposedPorts(8182, 2424) + withEnv("ORIENTDB_ROOT_PASSWORD", "arcade") + waitingFor(Wait.defaultWaitStrategy()) + start() + } val dataSource: DataSourceInfo init { - dataSource = DataSourceInfo( - id = 1L, - type = "GREMLIN_ORIENTDB", - name = "testDataSource", - server = container.containerIpAddress, - port = container.firstMappedPort, - username = "root", - password = "arcade", - database = "demodb", - ) + dataSource = + DataSourceInfo( + id = 1L, + type = "GREMLIN_ORIENTDB", + name = "testDataSource", + server = container.containerIpAddress, + port = container.firstMappedPort, + username = "root", + password = "arcade", + database = "demodb", + ) } } diff --git a/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/cosmosdb/CosmosDBGremlinDataProviderIntTest.kt b/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/cosmosdb/CosmosDBGremlinDataProviderIntTest.kt index e21dc869..f67e6326 100644 --- a/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/cosmosdb/CosmosDBGremlinDataProviderIntTest.kt +++ b/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/cosmosdb/CosmosDBGremlinDataProviderIntTest.kt @@ -26,23 +26,23 @@ import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Test class CosmosDBGremlinDataProviderIntTest { - private lateinit var dataSource: DataSourceInfo private lateinit var provider: CosmosDBGremlinDataProvider @BeforeEach fun setup() { - dataSource = DataSourceInfo( - id = 1L, - type = "GREMLIN_COSMOSDB", - name = "testDataSource", - server = "YOUR SERVER", - port = 443, - username = "USERNAME", - password = "PASSWORD", - database = "N/A", - ) + dataSource = + DataSourceInfo( + id = 1L, + type = "GREMLIN_COSMOSDB", + name = "testDataSource", + server = "YOUR SERVER", + port = 443, + username = "USERNAME", + password = "PASSWORD", + database = "N/A", + ) provider = CosmosDBGremlinDataProvider() } @@ -61,7 +61,8 @@ class CosmosDBGremlinDataProviderIntTest { assertThat(cytoData.data.target).isNull() val record = cytoData.data.record - assertThat(record).isNotNull + assertThat(record) + .isNotNull .containsKeys("@in", "@out", "Name", "@edgeCount") println("cytoData = $cytoData") @@ -76,9 +77,11 @@ class CosmosDBGremlinDataProviderIntTest { val data = provider.fetchData(dataSource, query, 5) - val ids = data.nodes.asSequence() - .map { data -> data.data.id } - .toList() + val ids = + data.nodes + .asSequence() + .map { data -> data.data.id } + .toList() val load = provider.load(dataSource, ids.toTypedArray()) @@ -94,15 +97,19 @@ class CosmosDBGremlinDataProviderIntTest { val data = provider.fetchData(dataSource, query, 10) - val ids = data.nodes.asSequence() - .map { data -> data.data.id } - .toList() + val ids = + data.nodes + .asSequence() + .map { data -> data.data.id } + .toList() - val label: String = data.nodes.asSequence() - .map { data -> data.data.record["@in"] as Map } - .map { ins -> ins.keys } - .flatMap { k -> k.asSequence() } - .first() + val label: String = + data.nodes + .asSequence() + .map { data -> data.data.record["@in"] as Map } + .map { ins -> ins.keys } + .flatMap { k -> k.asSequence() } + .first() val load = provider.expand(dataSource, ids.toTypedArray(), "in", label, 300) @@ -117,9 +124,11 @@ class CosmosDBGremlinDataProviderIntTest { val data = provider.fetchData(dataSource, query, 10) - val ids = data.nodes.asSequence() - .map { data -> data.data.id } - .toList() + val ids = + data.nodes + .asSequence() + .map { data -> data.data.id } + .toList() val load = provider.expand(dataSource, ids.toTypedArray(), "both", "", 300) @@ -140,7 +149,8 @@ class CosmosDBGremlinDataProviderIntTest { assertThat(cytoData.data.target).isNotNull() val record = cytoData.data.record - assertThat(record).isNotNull + assertThat(record) + .isNotNull .containsKeys("@in", "@out") assertThat(data.nodes).isNotEmpty diff --git a/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/cosmosdb/CosmosDBGremlinGraphProviderTest.kt b/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/cosmosdb/CosmosDBGremlinGraphProviderTest.kt index b3c04d6d..57bb4e6c 100644 --- a/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/cosmosdb/CosmosDBGremlinGraphProviderTest.kt +++ b/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/cosmosdb/CosmosDBGremlinGraphProviderTest.kt @@ -14,23 +14,23 @@ import org.junit.jupiter.api.Test import java.util.ArrayList class CosmosDBGremlinGraphProviderTest { - private lateinit var provider: DataSourceGraphProvider private lateinit var dataSource: DataSourceInfo @BeforeEach fun setup() { - dataSource = DataSourceInfo( - id = 1L, - type = "GREMLIN_COSMOSDB", - name = "testDataSource", - server = "4c7bff3b-0ee0-4-231-b9ee.gremlin.cosmosdb.azure.com", - port = 443, - username = "\"/dbs/arcade/colls/arcade-graph\"", - password = "arcade", - database = this::class.java.simpleName, - ) + dataSource = + DataSourceInfo( + id = 1L, + type = "GREMLIN_COSMOSDB", + name = "testDataSource", + server = "4c7bff3b-0ee0-4-231-b9ee.gremlin.cosmosdb.azure.com", + port = 443, + username = "\"/dbs/arcade/colls/arcade-graph\"", + password = "arcade", + database = this::class.java.simpleName, + ) provider = CosmosDBGremlinGraphProvider() } @@ -41,22 +41,22 @@ class CosmosDBGremlinGraphProviderTest { val nodes = ArrayList() val edges = ArrayList() - val indexer = object : SpritePlayer { - override fun begin() { - TODO("not implemented") // To change body of created functions use File | Settings | File Templates. - } + val indexer = + object : SpritePlayer { + override fun begin() { + TODO("not implemented") // To change body of created functions use File | Settings | File Templates. + } - override fun processed(): Long { - return 0 - } + override fun processed(): Long = 0 - override fun play(document: Sprite) { - when (document.valueOf(ARCADE_TYPE)) { - ARCADE_NODE_TYPE -> nodes.add(document) - ARCADE_EDGE_TYPE -> edges.add(document) - } - Assertions.assertThat(document.valueOf("@class")) - .isNotBlank() + override fun play(document: Sprite) { + when (document.valueOf(ARCADE_TYPE)) { + ARCADE_NODE_TYPE -> nodes.add(document) + ARCADE_EDGE_TYPE -> edges.add(document) + } + Assertions + .assertThat(document.valueOf("@class")) + .isNotBlank() /*- * #%L @@ -77,11 +77,11 @@ class CosmosDBGremlinGraphProviderTest { * limitations under the License. * #L% */ - } + } - override fun end() { + override fun end() { + } } - } provider.provideTo(dataSource, indexer) Assertions.assertThat(nodes).hasSize(7) diff --git a/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/cosmosdb/CosmosDBGremlinMetadataProviderTest.kt b/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/cosmosdb/CosmosDBGremlinMetadataProviderTest.kt index ea01ebb6..52f85068 100644 --- a/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/cosmosdb/CosmosDBGremlinMetadataProviderTest.kt +++ b/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/cosmosdb/CosmosDBGremlinMetadataProviderTest.kt @@ -28,23 +28,23 @@ import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Test class CosmosDBGremlinMetadataProviderTest { - private lateinit var dataSource: DataSourceInfo private lateinit var provider: DataSourceMetadataProvider @BeforeEach fun setup() { - dataSource = DataSourceInfo( - id = 1L, - type = "GREMLIN_COSMOSDB", - name = "testDataSource", - server = "4c7bff3b-0ee0-4-231-b9ee.gremlin.cosmosdb.azure.com", - port = 443, - username = "\"/dbs/arcade/colls/arcade-graph\"", - password = "arcade", - database = JanusgraphGremlinDataProviderIntTest::class.java.simpleName, - ) + dataSource = + DataSourceInfo( + id = 1L, + type = "GREMLIN_COSMOSDB", + name = "testDataSource", + server = "4c7bff3b-0ee0-4-231-b9ee.gremlin.cosmosdb.azure.com", + port = 443, + username = "\"/dbs/arcade/colls/arcade-graph\"", + password = "arcade", + database = JanusgraphGremlinDataProviderIntTest::class.java.simpleName, + ) provider = CosmosDBGremlinMetadataProvider() } @@ -56,13 +56,15 @@ class CosmosDBGremlinMetadataProviderTest { println("metadata = $metadata") - Assertions.assertThat(metadata.nodesClasses) + Assertions + .assertThat(metadata.nodesClasses) .hasSize(2) .containsKeys("Office") Assertions.assertThat(metadata.nodesClasses["Office"]!!.cardinality).isEqualTo(6) - Assertions.assertThat(metadata.edgesClasses) + Assertions + .assertThat(metadata.edgesClasses) .hasSize(2) .containsKeys("works_for") diff --git a/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/janusgraph/JanusgraphContainer.kt b/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/janusgraph/JanusgraphContainer.kt index 98fa738b..3e925721 100644 --- a/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/janusgraph/JanusgraphContainer.kt +++ b/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/janusgraph/JanusgraphContainer.kt @@ -28,7 +28,6 @@ import org.testcontainers.containers.wait.strategy.Wait import org.testcontainers.utility.DockerImageName object JanusgraphContainer { - private val container: KGenericContainer = KGenericContainer(DockerImageName.parse("janusgraph/janusgraph:${JanusGraph.version()}")) .apply { @@ -37,16 +36,17 @@ object JanusgraphContainer { start() } - val dataSource: DataSourceInfo = DataSourceInfo( - id = 1L, - type = "GREMLIN_JANUSGRAPH", - name = "testDataSource", - server = container.containerIpAddress, - port = container.firstMappedPort, - username = "", - password = "", - database = "", - ) + val dataSource: DataSourceInfo = + DataSourceInfo( + id = 1L, + type = "GREMLIN_JANUSGRAPH", + name = "testDataSource", + server = container.containerIpAddress, + port = container.firstMappedPort, + username = "", + password = "", + database = "", + ) init { diff --git a/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/janusgraph/JanusgraphGremlinDataProviderIntTest.kt b/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/janusgraph/JanusgraphGremlinDataProviderIntTest.kt index aa65b3ff..8656764d 100644 --- a/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/janusgraph/JanusgraphGremlinDataProviderIntTest.kt +++ b/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/janusgraph/JanusgraphGremlinDataProviderIntTest.kt @@ -27,7 +27,6 @@ import org.junit.jupiter.api.TestInstance @TestInstance(TestInstance.Lifecycle.PER_CLASS) internal class JanusgraphGremlinDataProviderIntTest { - private val provider: GremlinDataProvider = GremlinDataProvider() @Test @@ -43,7 +42,8 @@ internal class JanusgraphGremlinDataProviderIntTest { assertThat(cytoData.data.target).isNullOrEmpty() val record = cytoData.data.record - assertThat(record).isNotNull + assertThat(record) + .isNotNull .containsKeys("@in", "@out", "name", "@edgeCount") } @@ -55,9 +55,11 @@ internal class JanusgraphGremlinDataProviderIntTest { val data = provider.fetchData(dataSource, query, 10) - val ids = data.nodes.asSequence() - .map { it.data.id } - .toList() + val ids = + data.nodes + .asSequence() + .map { it.data.id } + .toList() val load = provider.load(dataSource, ids.toTypedArray()) @@ -70,15 +72,19 @@ internal class JanusgraphGremlinDataProviderIntTest { val data = provider.fetchData(dataSource, query, 10) - val ids = data.nodes.asSequence() - .map { it.data.id } - .toList() + val ids = + data.nodes + .asSequence() + .map { it.data.id } + .toList() - val label: String = data.nodes.asSequence() - .map { it.data.record["@in"] as Map } - .map { ins -> ins.keys } - .flatMap { k -> k.asSequence() } - .first() + val label: String = + data.nodes + .asSequence() + .map { it.data.record["@in"] as Map } + .map { ins -> ins.keys } + .flatMap { k -> k.asSequence() } + .first() val load = provider.expand(dataSource, ids.toTypedArray(), "in", label, 50) @@ -92,9 +98,11 @@ internal class JanusgraphGremlinDataProviderIntTest { val data = provider.fetchData(dataSource, query, 10) - val ids = data.nodes.asSequence() - .map { it.data.id } - .toList() + val ids = + data.nodes + .asSequence() + .map { it.data.id } + .toList() val load = provider.expand(dataSource, ids.toTypedArray(), "both", "", 50) @@ -114,7 +122,8 @@ internal class JanusgraphGremlinDataProviderIntTest { assertThat(cytoData.data.target).isNotNull() val record = cytoData.data.record - assertThat(record).isNotNull + assertThat(record) + .isNotNull .containsKeys("@in", "@out") assertThat(data.nodes).isNotEmpty @@ -132,17 +141,27 @@ internal class JanusgraphGremlinDataProviderIntTest { val firstNode = firstDataSet.nodes.first().data val secondNode = firstDataSet.nodes.elementAt(2).data - val fromIds = firstDataSet.nodes.asSequence().map { it.data.id }.toList() - val toIds = secondDataSet.nodes.asSequence().map { it.data.id }.toList() - - val edgeClasses = firstDataSet.nodes.union(secondDataSet.nodes) - .asSequence() - .map { d -> - (d.data.record["@in"] as Map).keys - .union((d.data.record["@out"] as Map).keys) - } - .flatMap { it.asSequence() } - .toSet() + val fromIds = + firstDataSet.nodes + .asSequence() + .map { it.data.id } + .toList() + val toIds = + secondDataSet.nodes + .asSequence() + .map { it.data.id } + .toList() + + val edgeClasses = + firstDataSet.nodes + .union(secondDataSet.nodes) + .asSequence() + .map { d -> + (d.data.record["@in"] as Map) + .keys + .union((d.data.record["@out"] as Map).keys) + }.flatMap { it.asSequence() } + .toSet() // val edgeClasses = (firstNode.record["@in"] as Map).keys // .union((firstNode.record["@out"] as Map).keys) diff --git a/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/janusgraph/JanusgraphGremlinGraphProviderTest.kt b/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/janusgraph/JanusgraphGremlinGraphProviderTest.kt index fcb945da..183ef6f6 100644 --- a/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/janusgraph/JanusgraphGremlinGraphProviderTest.kt +++ b/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/janusgraph/JanusgraphGremlinGraphProviderTest.kt @@ -32,7 +32,6 @@ import java.util.ArrayList @TestInstance(TestInstance.Lifecycle.PER_CLASS) internal class JanusgraphGremlinGraphProviderTest { - private val provider: GremlinGraphProvider = GremlinGraphProvider() @Test @@ -40,29 +39,28 @@ internal class JanusgraphGremlinGraphProviderTest { val nodes = ArrayList() val edges = ArrayList() - val indexer = object : SpritePlayer { - override fun begin() { - // noop - } + val indexer = + object : SpritePlayer { + override fun begin() { + // noop + } - override fun processed(): Long { - return 0 - } + override fun processed(): Long = 0 - override fun play(sprite: Sprite) { - when (sprite.valueOf(ARCADE_TYPE)) { - ARCADE_NODE_TYPE -> nodes.add(sprite) - ARCADE_EDGE_TYPE -> edges.add(sprite) + override fun play(sprite: Sprite) { + when (sprite.valueOf(ARCADE_TYPE)) { + ARCADE_NODE_TYPE -> nodes.add(sprite) + ARCADE_EDGE_TYPE -> edges.add(sprite) + } + assertThat(sprite.valueOf("@class")).isNotBlank + assertThat(sprite.hasField("_a_id")).isTrue + assertThat(sprite.hasField("_a_type")).isTrue + assertThat(sprite.hasField("_a_type")).isTrue } - assertThat(sprite.valueOf("@class")).isNotBlank - assertThat(sprite.hasField("_a_id")).isTrue - assertThat(sprite.hasField("_a_type")).isTrue - assertThat(sprite.hasField("_a_type")).isTrue - } - override fun end() { + override fun end() { + } } - } provider.provideTo(JanusgraphContainer.dataSource, indexer) assertThat(nodes).hasSize(808) diff --git a/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/janusgraph/JanusgraphGremlinMetadataProviderTest.kt b/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/janusgraph/JanusgraphGremlinMetadataProviderTest.kt index 615dd565..9b3079dd 100644 --- a/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/janusgraph/JanusgraphGremlinMetadataProviderTest.kt +++ b/gremlin/src/test/kotlin/com/arcadeanalytics/provider/gremlin/janusgraph/JanusgraphGremlinMetadataProviderTest.kt @@ -26,7 +26,6 @@ import org.junit.jupiter.api.TestInstance @TestInstance(TestInstance.Lifecycle.PER_CLASS) internal class JanusgraphGremlinMetadataProviderTest { - private val provider: GremlinMetadataProvider = GremlinMetadataProvider() @Test diff --git a/integration/src/test/kotlin/com/arcadeanalytics/provider/DataSourceGraphDataProviderFactoryTest.kt b/integration/src/test/kotlin/com/arcadeanalytics/provider/DataSourceGraphDataProviderFactoryTest.kt index 7d6cb6ad..7deab573 100644 --- a/integration/src/test/kotlin/com/arcadeanalytics/provider/DataSourceGraphDataProviderFactoryTest.kt +++ b/integration/src/test/kotlin/com/arcadeanalytics/provider/DataSourceGraphDataProviderFactoryTest.kt @@ -27,26 +27,25 @@ import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.MethodSource internal class DataSourceGraphDataProviderFactoryTest { - companion object { @JvmStatic - fun types2implementation() = listOf( - Arguments.of("ORIENTDB", "OrientDBDataSourceGraphDataProvider"), - Arguments.of("ORIENTDB3", "OrientDB3DataSourceGraphDataProvider"), - Arguments.of("GREMLIN_ORIENTDB", "GremlinDataProvider"), - Arguments.of("GREMLIN_NEPTUNE", "GremlinDataProvider"), - Arguments.of("GREMLIN_JANUSGRAPH", "GremlinDataProvider"), - Arguments.of("GREMLIN_COSMOSDB", "CosmosDBGremlinDataProvider"), - Arguments.of("NEO4J", "Neo4jDataProvider"), - Arguments.of("NEO4J_MEMGRAPH", "Neo4jDataProvider"), - Arguments.of("RDBMS_POSTGRESQL", "RDBMSDataProvider"), - Arguments.of("RDBMS_MYSQL", "RDBMSDataProvider"), - Arguments.of("RDBMS_MSSQLSERVER", "RDBMSDataProvider"), - Arguments.of("RDBMS_ORACLE", "RDBMSDataProvider"), - Arguments.of("RDBMS_HSQL", "RDBMSDataProvider"), - Arguments.of("RDBMS_DATA_WORLD", "RDBMSDataProvider"), - - ) + fun types2implementation() = + listOf( + Arguments.of("ORIENTDB", "OrientDBDataSourceGraphDataProvider"), + Arguments.of("ORIENTDB3", "OrientDB3DataSourceGraphDataProvider"), + Arguments.of("GREMLIN_ORIENTDB", "GremlinDataProvider"), + Arguments.of("GREMLIN_NEPTUNE", "GremlinDataProvider"), + Arguments.of("GREMLIN_JANUSGRAPH", "GremlinDataProvider"), + Arguments.of("GREMLIN_COSMOSDB", "CosmosDBGremlinDataProvider"), + Arguments.of("NEO4J", "Neo4jDataProvider"), + Arguments.of("NEO4J_MEMGRAPH", "Neo4jDataProvider"), + Arguments.of("RDBMS_POSTGRESQL", "RDBMSDataProvider"), + Arguments.of("RDBMS_MYSQL", "RDBMSDataProvider"), + Arguments.of("RDBMS_MSSQLSERVER", "RDBMSDataProvider"), + Arguments.of("RDBMS_ORACLE", "RDBMSDataProvider"), + Arguments.of("RDBMS_HSQL", "RDBMSDataProvider"), + Arguments.of("RDBMS_DATA_WORLD", "RDBMSDataProvider"), + ) } private lateinit var factory: DataSourceProviderFactory @@ -84,16 +83,17 @@ internal class DataSourceGraphDataProviderFactoryTest { type: String, impl: String, ) { - val dataSource = DataSourceInfo( - id = 1L, - type = type, - name = "testDataSource", - server = "1.2.3.4", - port = 1234, - username = "admin", - password = "admin", - database = "testDb", - ) + val dataSource = + DataSourceInfo( + id = 1L, + type = type, + name = "testDataSource", + server = "1.2.3.4", + port = 1234, + username = "admin", + password = "admin", + database = "testDb", + ) val provider = factory.create(dataSource) assertThat(provider).isNotNull @@ -107,20 +107,21 @@ internal class DataSourceGraphDataProviderFactoryTest { type: String, impl: String, ) { - val dataSource = DataSourceInfo( - id = 1L, - type = type, - name = "testDataSource", - server = "1.2.3.4", - port = 1234, - username = "admin", - password = "admin", - database = "testDb", - remote = true, - gateway = "192.168.1.12", - sshPort = 22, - sshUser = "sshUser", - ) + val dataSource = + DataSourceInfo( + id = 1L, + type = type, + name = "testDataSource", + server = "1.2.3.4", + port = 1234, + username = "admin", + password = "admin", + database = "testDb", + remote = true, + gateway = "192.168.1.12", + sshPort = 22, + sshUser = "sshUser", + ) val provider = factory.create(dataSource) assertThat(provider).isNotNull diff --git a/integration/src/test/kotlin/com/arcadeanalytics/provider/DataSourceGraphProviderFactoryTest.kt b/integration/src/test/kotlin/com/arcadeanalytics/provider/DataSourceGraphProviderFactoryTest.kt index 74aac1de..e6e6b4ba 100644 --- a/integration/src/test/kotlin/com/arcadeanalytics/provider/DataSourceGraphProviderFactoryTest.kt +++ b/integration/src/test/kotlin/com/arcadeanalytics/provider/DataSourceGraphProviderFactoryTest.kt @@ -28,25 +28,24 @@ import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.MethodSource internal class DataSourceGraphProviderFactoryTest { - companion object { @JvmStatic - fun types2implementation() = listOf( - Arguments.of("ORIENTDB", "OrientDBDataSourceGraphProvider"), - Arguments.of("ORIENTDB3", "OrientDB3DataSourceGraphProvider"), - Arguments.of("GREMLIN_ORIENTDB", "GremlinGraphProvider"), - Arguments.of("GREMLIN_NEPTUNE", "GremlinGraphProvider"), - Arguments.of("GREMLIN_JANUSGRAPH", "GremlinGraphProvider"), - Arguments.of("GREMLIN_COSMOSDB", "CosmosDBGremlinGraphProvider"), - Arguments.of("NEO4J", "Neo4jGraphProvider"), - Arguments.of("NEO4J_MEMGRAPH", "Neo4jGraphProvider"), - Arguments.of("RDBMS_MYSQL", "RDBMSGraphProvider"), - Arguments.of("RDBMS_MSSQLSERVER", "RDBMSGraphProvider"), - Arguments.of("RDBMS_ORACLE", "RDBMSGraphProvider"), - Arguments.of("RDBMS_HSQL", "RDBMSGraphProvider"), - Arguments.of("RDBMS_DATA_WORLD", "RDBMSGraphProvider"), - - ) + fun types2implementation() = + listOf( + Arguments.of("ORIENTDB", "OrientDBDataSourceGraphProvider"), + Arguments.of("ORIENTDB3", "OrientDB3DataSourceGraphProvider"), + Arguments.of("GREMLIN_ORIENTDB", "GremlinGraphProvider"), + Arguments.of("GREMLIN_NEPTUNE", "GremlinGraphProvider"), + Arguments.of("GREMLIN_JANUSGRAPH", "GremlinGraphProvider"), + Arguments.of("GREMLIN_COSMOSDB", "CosmosDBGremlinGraphProvider"), + Arguments.of("NEO4J", "Neo4jGraphProvider"), + Arguments.of("NEO4J_MEMGRAPH", "Neo4jGraphProvider"), + Arguments.of("RDBMS_MYSQL", "RDBMSGraphProvider"), + Arguments.of("RDBMS_MSSQLSERVER", "RDBMSGraphProvider"), + Arguments.of("RDBMS_ORACLE", "RDBMSGraphProvider"), + Arguments.of("RDBMS_HSQL", "RDBMSGraphProvider"), + Arguments.of("RDBMS_DATA_WORLD", "RDBMSGraphProvider"), + ) } private lateinit var factory: DataSourceProviderFactory @@ -84,16 +83,17 @@ internal class DataSourceGraphProviderFactoryTest { type: String, impl: String, ) { - val dataSource = DataSourceInfo( - id = 1L, - type = type, - name = "testDataSource", - server = "1.2.3.4", - port = 1234, - username = "admin", - password = "admin", - database = "testDb", - ) + val dataSource = + DataSourceInfo( + id = 1L, + type = type, + name = "testDataSource", + server = "1.2.3.4", + port = 1234, + username = "admin", + password = "admin", + database = "testDb", + ) val provider = factory.create(dataSource) Assertions.assertThat(provider).isNotNull diff --git a/integration/src/test/kotlin/com/arcadeanalytics/provider/DataSourceInfoMetadataProviderFactoryTest.kt b/integration/src/test/kotlin/com/arcadeanalytics/provider/DataSourceInfoMetadataProviderFactoryTest.kt index 9cbd30a0..42197f5c 100644 --- a/integration/src/test/kotlin/com/arcadeanalytics/provider/DataSourceInfoMetadataProviderFactoryTest.kt +++ b/integration/src/test/kotlin/com/arcadeanalytics/provider/DataSourceInfoMetadataProviderFactoryTest.kt @@ -28,24 +28,24 @@ import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.MethodSource internal class DataSourceInfoMetadataProviderFactoryTest { - companion object { @JvmStatic - fun types2implementation() = listOf( - Arguments.of("ORIENTDB", "OrientDBDataSourceMetadataProvider"), - Arguments.of("ORIENTDB3", "OrientDB3DataSourceMetadataProvider"), - Arguments.of("GREMLIN_ORIENTDB", "GremlinMetadataProvider"), - Arguments.of("GREMLIN_NEPTUNE", "GremlinMetadataProvider"), - Arguments.of("GREMLIN_JANUSGRAPH", "GremlinMetadataProvider"), - Arguments.of("GREMLIN_COSMOSDB", "CosmosDBGremlinMetadataProvider"), - Arguments.of("NEO4J", "Neo4jMetadataProvider"), - Arguments.of("NEO4J_MEMGRAPH", "Neo4jMetadataProvider"), - Arguments.of("RDBMS_MYSQL", "RDBMSMetadataProvider"), - Arguments.of("RDBMS_MSSQLSERVER", "RDBMSMetadataProvider"), - Arguments.of("RDBMS_ORACLE", "RDBMSMetadataProvider"), - Arguments.of("RDBMS_HSQL", "RDBMSMetadataProvider"), - Arguments.of("RDBMS_DATA_WORLD", "RDBMSMetadataProvider"), - ) + fun types2implementation() = + listOf( + Arguments.of("ORIENTDB", "OrientDBDataSourceMetadataProvider"), + Arguments.of("ORIENTDB3", "OrientDB3DataSourceMetadataProvider"), + Arguments.of("GREMLIN_ORIENTDB", "GremlinMetadataProvider"), + Arguments.of("GREMLIN_NEPTUNE", "GremlinMetadataProvider"), + Arguments.of("GREMLIN_JANUSGRAPH", "GremlinMetadataProvider"), + Arguments.of("GREMLIN_COSMOSDB", "CosmosDBGremlinMetadataProvider"), + Arguments.of("NEO4J", "Neo4jMetadataProvider"), + Arguments.of("NEO4J_MEMGRAPH", "Neo4jMetadataProvider"), + Arguments.of("RDBMS_MYSQL", "RDBMSMetadataProvider"), + Arguments.of("RDBMS_MSSQLSERVER", "RDBMSMetadataProvider"), + Arguments.of("RDBMS_ORACLE", "RDBMSMetadataProvider"), + Arguments.of("RDBMS_HSQL", "RDBMSMetadataProvider"), + Arguments.of("RDBMS_DATA_WORLD", "RDBMSMetadataProvider"), + ) } private lateinit var factory: DataSourceProviderFactory @@ -83,16 +83,17 @@ internal class DataSourceInfoMetadataProviderFactoryTest { type: String, impl: String, ) { - val dataSource = DataSourceInfo( - id = 1L, - type = type, - name = "testDataSource", - server = "1.2.3.4", - port = 1234, - username = "admin", - password = "admin", - database = "testDb", - ) + val dataSource = + DataSourceInfo( + id = 1L, + type = type, + name = "testDataSource", + server = "1.2.3.4", + port = 1234, + username = "admin", + password = "admin", + database = "testDb", + ) val provider = factory.create(dataSource) Assertions.assertThat(provider).isNotNull diff --git a/integration/src/test/kotlin/com/arcadeanalytics/provider/DataSourceTableDataProviderFactoryTest.kt b/integration/src/test/kotlin/com/arcadeanalytics/provider/DataSourceTableDataProviderFactoryTest.kt index efa4ab90..4828296f 100644 --- a/integration/src/test/kotlin/com/arcadeanalytics/provider/DataSourceTableDataProviderFactoryTest.kt +++ b/integration/src/test/kotlin/com/arcadeanalytics/provider/DataSourceTableDataProviderFactoryTest.kt @@ -28,18 +28,18 @@ import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.MethodSource internal class DataSourceTableDataProviderFactoryTest { - companion object { @JvmStatic - fun types2implementation() = listOf( - Arguments.of("ORIENTDB3", "OrientDB3DataSourceTableDataProvider"), - Arguments.of("RDBMS_POSTGRESQL", "RDBMSTableDataProvider"), - Arguments.of("RDBMS_MYSQL", "RDBMSTableDataProvider"), - Arguments.of("RDBMS_MSSQLSERVER", "RDBMSTableDataProvider"), - Arguments.of("RDBMS_HSQL", "RDBMSTableDataProvider"), - Arguments.of("RDBMS_ORACLE", "RDBMSTableDataProvider"), - Arguments.of("RDBMS_DATA_WORLD", "RDBMSTableDataProvider"), - ) + fun types2implementation() = + listOf( + Arguments.of("ORIENTDB3", "OrientDB3DataSourceTableDataProvider"), + Arguments.of("RDBMS_POSTGRESQL", "RDBMSTableDataProvider"), + Arguments.of("RDBMS_MYSQL", "RDBMSTableDataProvider"), + Arguments.of("RDBMS_MSSQLSERVER", "RDBMSTableDataProvider"), + Arguments.of("RDBMS_HSQL", "RDBMSTableDataProvider"), + Arguments.of("RDBMS_ORACLE", "RDBMSTableDataProvider"), + Arguments.of("RDBMS_DATA_WORLD", "RDBMSTableDataProvider"), + ) } private lateinit var factory: DataSourceProviderFactory @@ -70,16 +70,17 @@ internal class DataSourceTableDataProviderFactoryTest { type: String, impl: String, ) { - val dataSource = DataSourceInfo( - id = 1L, - type = type, - name = "testDataSource", - server = "1.2.3.4", - port = 1234, - username = "admin", - password = "admin", - database = "testDb", - ) + val dataSource = + DataSourceInfo( + id = 1L, + type = type, + name = "testDataSource", + server = "1.2.3.4", + port = 1234, + username = "admin", + password = "admin", + database = "testDb", + ) val provider = factory.create(dataSource) Assertions.assertThat(provider).isNotNull diff --git a/neo4j3/src/main/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jDataProvider.kt b/neo4j3/src/main/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jDataProvider.kt index 79be86fb..3273c7e7 100644 --- a/neo4j3/src/main/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jDataProvider.kt +++ b/neo4j3/src/main/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jDataProvider.kt @@ -35,7 +35,6 @@ import org.slf4j.LoggerFactory */ class Neo4jDataProvider : DataSourceGraphDataProvider { - private val log = LoggerFactory.getLogger(Neo4jDataProvider::class.java) override fun fetchData( @@ -70,11 +69,12 @@ class Neo4jDataProvider : DataSourceGraphDataProvider { ): GraphData { val label: String = if (edgeLabel.isEmpty()) "[rel]" else "[rel:$edgeLabel]" - val rel = when (direction) { - "out" -> "-$label->" - "in" -> "<-$label-" - else -> "<-$label->" - } + val rel = + when (direction) { + "out" -> "-$label->" + "in" -> "<-$label-" + else -> "<-$label->" + } val cleanedIds = cleanIds(ids, dataSource) @@ -83,7 +83,12 @@ class Neo4jDataProvider : DataSourceGraphDataProvider { return fetchData(dataSource, query, maxTraversal) } - override fun edges(dataSource: DataSourceInfo, fromIds: Array, edgesLabel: Array, toIds: Array): GraphData { + override fun edges( + dataSource: DataSourceInfo, + fromIds: Array, + edgesLabel: Array, + toIds: Array, + ): GraphData { val cleanedFromIds = cleanIds(fromIds, dataSource) val cleanedToIds = cleanIds(toIds, dataSource) @@ -96,7 +101,10 @@ class Neo4jDataProvider : DataSourceGraphDataProvider { return fetchData(dataSource, query, 10000) } - override fun load(dataSource: DataSourceInfo, ids: Array): GraphData { + override fun load( + dataSource: DataSourceInfo, + ids: Array, + ): GraphData { val cleanedIds = cleanIds(ids, dataSource) val query = @@ -109,19 +117,32 @@ class Neo4jDataProvider : DataSourceGraphDataProvider { return graphData } - private fun cleanIds(ids: Array, dataSource: DataSourceInfo): String { - return ids.asSequence() + private fun cleanIds( + ids: Array, + dataSource: DataSourceInfo, + ): String = + ids + .asSequence() .map { id -> toNeo4jId(dataSource, id) } .distinct() .joinToString(",") - } - override fun loadFromClass(dataSource: DataSourceInfo, className: String, limit: Int): GraphData { + override fun loadFromClass( + dataSource: DataSourceInfo, + className: String, + limit: Int, + ): GraphData { val query = "MATCH (element:$className) RETURN element LIMIT $limit" return this.fetchData(dataSource, query, limit) } - override fun loadFromClass(dataSource: DataSourceInfo, className: String, propName: String, propertyValue: String, limit: Int): GraphData { + override fun loadFromClass( + dataSource: DataSourceInfo, + className: String, + propName: String, + propertyValue: String, + limit: Int, + ): GraphData { val query = "MATCH (element:$className) WHERE element.$propName = '$propertyValue' RETURN element LIMIT $limit" return this.fetchData(dataSource, query, limit) } @@ -158,13 +179,23 @@ class Neo4jDataProvider : DataSourceGraphDataProvider { val graphData = mapper.map(result) - log.debug("run query and map -results:: nodes {} - edges {} - truncated {} ", graphData.nodes.size, graphData.edges.size, graphData.truncated) + log.debug( + "run query and map -results:: nodes {} - edges {} - truncated {} ", + graphData.nodes.size, + graphData.edges.size, + graphData.truncated, + ) return graphData } - private fun countInAndOutOnNode(session: Session, dataSource: DataSourceInfo, nodes: Set): Set { - nodes.asSequence() + private fun countInAndOutOnNode( + session: Session, + dataSource: DataSourceInfo, + nodes: Set, + ): Set { + nodes + .asSequence() .forEach { data -> val id = toNeo4jId(dataSource, data.data.id) val record = data.data.record @@ -207,7 +238,5 @@ class Neo4jDataProvider : DataSourceGraphDataProvider { return nodes } - override fun supportedDataSourceTypes(): Set { - return setOf(NEO4J.name, NEO4J_MEMGRAPH.name) - } + override fun supportedDataSourceTypes(): Set = setOf(NEO4J.name, NEO4J_MEMGRAPH.name) } diff --git a/neo4j3/src/main/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jGraphProvider.kt b/neo4j3/src/main/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jGraphProvider.kt index 8c8cc84f..a02220e6 100644 --- a/neo4j3/src/main/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jGraphProvider.kt +++ b/neo4j3/src/main/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jGraphProvider.kt @@ -39,15 +39,14 @@ import java.util.regex.Pattern */ class Neo4jGraphProvider : DataSourceGraphProvider { - private val log = LoggerFactory.getLogger(Neo4jGraphProvider::class.java) - private val queries = mapOf( - "NEO4J::LABELS" to "CALL db.labels() YIELD label", - "NEO4J::EDGES" to "CALL db.relationshipTypes() YIELD relationshipType", - - "NEO4J_MEMGRAPH::LABELS" to "MATCH (n) UNWIND labels(n) AS label RETURN DISTINCT label", - "NEO4J_MEMGRAPH::EDGES" to "MATCH ()-[r]->() RETURN DISTINCT type(r) AS relationshipType", - ) + private val queries = + mapOf( + "NEO4J::LABELS" to "CALL db.labels() YIELD label", + "NEO4J::EDGES" to "CALL db.relationshipTypes() YIELD relationshipType", + "NEO4J_MEMGRAPH::LABELS" to "MATCH (n) UNWIND labels(n) AS label RETURN DISTINCT label", + "NEO4J_MEMGRAPH::EDGES" to "MATCH ()-[r]->() RETURN DISTINCT type(r) AS relationshipType", + ) private val allFields: Pattern = Pattern.compile(".*") @@ -73,7 +72,8 @@ class Neo4jGraphProvider : DataSourceGraphProvider { ) { val labels = session.run(queries["${dataSource.type}::LABELS"]) - labels.list() + labels + .list() .asSequence() .map { res -> res.get("label").asString() } .forEach { label -> indexLabel(dataSource, processor, session, label) } @@ -93,25 +93,33 @@ class Neo4jGraphProvider : DataSourceGraphProvider { while (fetched < edges) { val params = ImmutableMap.of("skip", skip, "limit", limit) - log.info("fetching edges from '{}' with query '{}' and params {} - {}", session, "MATCH ()-[r]->() RETURN r SKIP \$skip LIMIT \$limit", skip, limit) + log.info( + "fetching edges from '{}' with query '{}' and params {} - {}", + session, + "MATCH ()-[r]->() RETURN r SKIP \$skip LIMIT \$limit", + skip, + limit, + ) val rels = session.run("MATCH ()-[r]->() RETURN r SKIP \$skip LIMIT \$limit", params) while (rels.hasNext()) { val record = rels.next() - record.fields().asSequence() + record + .fields() + .asSequence() .map { p -> p.value() } .filter { v -> v.type().name() == "RELATIONSHIP" } .map { v -> v.asRelationship() } .filter { r -> r.size() > 0 } .map { n -> - Sprite().load(n.asMap()) + Sprite() + .load(n.asMap()) .add("@class", n.type()) .add(ARCADE_ID, toArcadeId(dataSource, Neo4jType.EDGE, n.id())) .add(ARCADE_TYPE, "edge") .apply(allFields) { v -> v.toString() } - } - .forEach { s -> processor.play(s) } + }.forEach { s -> processor.play(s) } fetched++ } skip = limit @@ -142,18 +150,20 @@ class Neo4jGraphProvider : DataSourceGraphProvider { while (result.hasNext()) { val record = result.next() - record.fields().asSequence() + record + .fields() + .asSequence() .map { p -> p.value() } .filter { v -> v.type().name() == "NODE" } .map { v -> v.asNode() } .map { n -> - Sprite().load(n.asMap()) + Sprite() + .load(n.asMap()) .addAll("@class", n.labels()) .add(ARCADE_ID, toArcadeId(dataSource, Neo4jType.NODE, n.id())) .add(ARCADE_TYPE, "node") .apply(allFields, Any::toString) - } - .forEach { s -> processor.play(s) } + }.forEach { s -> processor.play(s) } fetched++ } @@ -166,21 +176,30 @@ class Neo4jGraphProvider : DataSourceGraphProvider { processor.end() } - private fun countNodes(session: Session, label: String): Int { - val count = session.run("MATCH (n:$label) RETURN count(*) AS count") - .single().get("count").asInt() + private fun countNodes( + session: Session, + label: String, + ): Int { + val count = + session + .run("MATCH (n:$label) RETURN count(*) AS count") + .single() + .get("count") + .asInt() log.info("nodes for label '{}' : {}", label, count) return count } private fun countEdges(session: Session): Int { - val count = session.run("MATCH ()-[r]->() RETURN count(*) AS count") - .single().get("count").asInt() + val count = + session + .run("MATCH ()-[r]->() RETURN count(*) AS count") + .single() + .get("count") + .asInt() log.info("edges count: {}", count) return count } - override fun supportedDataSourceTypes(): Set { - return setOf(NEO4J.name, NEO4J_MEMGRAPH.name) - } + override fun supportedDataSourceTypes(): Set = setOf(NEO4J.name, NEO4J_MEMGRAPH.name) } diff --git a/neo4j3/src/main/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jIdUtils.kt b/neo4j3/src/main/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jIdUtils.kt index 5e3d4103..281b80d2 100644 --- a/neo4j3/src/main/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jIdUtils.kt +++ b/neo4j3/src/main/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jIdUtils.kt @@ -28,30 +28,37 @@ import org.neo4j.driver.v1.Driver import org.neo4j.driver.v1.GraphDatabase import java.util.concurrent.TimeUnit -private const val connectionTemplate = "bolt://{server}:{port}" +private const val CONNECTION_TEMPLATE = "bolt://{server}:{port}" -fun toArcadeId(dataSource: DataSourceInfo, type: Neo4jType, neo4jId: Long): String { - return dataSource.id.toString() + type.suffix() + neo4jId -} +fun toArcadeId( + dataSource: DataSourceInfo, + type: Neo4jType, + neo4jId: Long, +): String = dataSource.id.toString() + type.suffix() + neo4jId -fun toNeo4jId(dataSource: DataSourceInfo, arcadeId: String): String { +fun toNeo4jId( + dataSource: DataSourceInfo, + arcadeId: String, +): String { val cleaned = StringUtils.removeStart(arcadeId, dataSource.id.toString() + Neo4jType.NODE.suffix()) return StringUtils.removeStart(cleaned, dataSource.id.toString() + Neo4jType.EDGE.suffix()) } -fun createConnectionUrl(datasource: DataSourceInfo): String { - return connectionTemplate.replace("{server}", datasource.server) +fun createConnectionUrl(datasource: DataSourceInfo): String = + CONNECTION_TEMPLATE + .replace("{server}", datasource.server) .replace("{port}", datasource.port.toString()) -} fun getDriver(datasource: DataSourceInfo): Driver { val connectionUrl = createConnectionUrl(datasource) - val config = Config.build() - .withConnectionTimeout(30, TimeUnit.SECONDS) - .withMaxConnectionPoolSize(1) - .toConfig() + val config = + Config + .build() + .withConnectionTimeout(30, TimeUnit.SECONDS) + .withMaxConnectionPoolSize(1) + .toConfig() return GraphDatabase.driver( connectionUrl, @@ -62,19 +69,16 @@ fun getDriver(datasource: DataSourceInfo): Driver { enum class Neo4jType { NODE { - override fun suffix(): String { - return "_n_" - } + override fun suffix(): String = "_n_" }, EDGE { - override fun suffix(): String { - return "_e_" - } + override fun suffix(): String = "_e_" }, ; abstract fun suffix(): String } enum class Neo4jDialect { - NEO4J, NEO4J_MEMGRAPH + NEO4J, + NEO4J_MEMGRAPH, } diff --git a/neo4j3/src/main/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jMetadataProvider.kt b/neo4j3/src/main/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jMetadataProvider.kt index 427e0744..99b1b901 100644 --- a/neo4j3/src/main/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jMetadataProvider.kt +++ b/neo4j3/src/main/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jMetadataProvider.kt @@ -42,13 +42,13 @@ import java.util.concurrent.TimeUnit class Neo4jMetadataProvider : DataSourceMetadataProvider { private val log = LoggerFactory.getLogger(Neo4jMetadataProvider::class.java) - private val queries = mapOf( - "NEO4J::LABELS" to "CALL db.labels() YIELD label", - "NEO4J::EDGES" to "CALL db.relationshipTypes() YIELD relationshipType", - - "NEO4J_MEMGRAPH::LABELS" to "MATCH (n) UNWIND labels(n) AS label RETURN DISTINCT label", - "NEO4J_MEMGRAPH::EDGES" to "MATCH ()-[r]->() RETURN DISTINCT type(r) AS relationshipType", - ) + private val queries = + mapOf( + "NEO4J::LABELS" to "CALL db.labels() YIELD label", + "NEO4J::EDGES" to "CALL db.relationshipTypes() YIELD relationshipType", + "NEO4J_MEMGRAPH::LABELS" to "MATCH (n) UNWIND labels(n) AS label RETURN DISTINCT label", + "NEO4J_MEMGRAPH::EDGES" to "MATCH ()-[r]->() RETURN DISTINCT type(r) AS relationshipType", + ) override fun supportedDataSourceTypes(): Set = setOf("NEO4J", "NEO4J_MEMGRAPH") @@ -57,14 +57,18 @@ class Neo4jMetadataProvider : DataSourceMetadataProvider { log.info("fetching metadata for dataSource {} ", dataSource.id) - val config = Config.build() - .withConnectionTimeout(5, TimeUnit.SECONDS) - .withConnectionLivenessCheckTimeout(1L, TimeUnit.SECONDS) - .toConfig() + val config = + Config + .build() + .withConnectionTimeout(5, TimeUnit.SECONDS) + .withConnectionLivenessCheckTimeout(1L, TimeUnit.SECONDS) + .toConfig() - GraphDatabase.driver(connectionUrl, AuthTokens.basic(dataSource.username, dataSource.password), config) + GraphDatabase + .driver(connectionUrl, AuthTokens.basic(dataSource.username, dataSource.password), config) .use { - it.session(AccessMode.READ) + it + .session(AccessMode.READ) .use { session -> val nodesClasses = nodeClasses(session, dataSource.type) @@ -76,7 +80,10 @@ class Neo4jMetadataProvider : DataSourceMetadataProvider { } } - private fun nodeClasses(session: Session, type: String): NodesClasses { + private fun nodeClasses( + session: Session, + type: String, + ): NodesClasses { log.info("get metadata for nodes") return session .run(queries["$type::LABELS"]) @@ -88,21 +95,30 @@ class Neo4jMetadataProvider : DataSourceMetadataProvider { }.toMap() } - private fun countLabel(label: String, session: Session): Long { + private fun countLabel( + label: String, + session: Session, + ): Long { val count = session.run("MATCH (n:$label) RETURN count(*) AS count") return count.single().get("count").asLong() } - private fun mapNodeProperties(nodeClass: String, session: Session): TypeProperties { - return session.run("MATCH (n:$nodeClass) RETURN distinct(keys(n))") + private fun mapNodeProperties( + nodeClass: String, + session: Session, + ): TypeProperties = + session + .run("MATCH (n:$nodeClass) RETURN distinct(keys(n))") .asSequence() .flatMap { record -> record.get("(keys(n))").asList().asSequence() } .map { property -> TypeProperty(property.toString(), "STRING") } .map { it.name to it } .toMap() - } - private fun edgeClasses(session: Session, type: String): EdgesClasses { + private fun edgeClasses( + session: Session, + type: String, + ): EdgesClasses { log.info("get metadata for edges") return session .run(queries["$type::EDGES"]) @@ -114,13 +130,20 @@ class Neo4jMetadataProvider : DataSourceMetadataProvider { }.toMap() } - private fun countRelType(relType: String, session: Session): Long { + private fun countRelType( + relType: String, + session: Session, + ): Long { val count = session.run("MATCH ()-[r:$relType]->() RETURN count(*) AS count") return count.single().get("count").asLong() } - private fun mapRelationshipProperties(edgeClass: String, session: Session): TypeProperties { - return session.run("MATCH ()-[r:$edgeClass]->() RETURN distinct(keys(r))") + private fun mapRelationshipProperties( + edgeClass: String, + session: Session, + ): TypeProperties = + session + .run("MATCH ()-[r:$edgeClass]->() RETURN distinct(keys(r))") .asSequence() .map { record -> record.get("(keys(n))") } .filter { value -> !value.isNull } @@ -128,5 +151,4 @@ class Neo4jMetadataProvider : DataSourceMetadataProvider { .map { property -> TypeProperty(property.toString(), "STRING") } .map { it.name to it } .toMap() - } } diff --git a/neo4j3/src/main/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jStatementResultMapper.kt b/neo4j3/src/main/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jStatementResultMapper.kt index df4a21e8..48c27a78 100644 --- a/neo4j3/src/main/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jStatementResultMapper.kt +++ b/neo4j3/src/main/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jStatementResultMapper.kt @@ -30,8 +30,10 @@ import org.neo4j.driver.v1.types.Node import org.neo4j.driver.v1.types.Relationship import org.slf4j.LoggerFactory -class Neo4jStatementResultMapper(private val dataSource: DataSourceInfo, private val maxTraversal: Int) { - +class Neo4jStatementResultMapper( + private val dataSource: DataSourceInfo, + private val maxTraversal: Int, +) { private fun countInOut(cyto: CytoData): CytoData { val inAndOutCountByEdgeType: MutableMap> = mutableMapOf() inAndOutCountByEdgeType.putIfAbsent("@in", mutableMapOf()) @@ -45,9 +47,10 @@ class Neo4jStatementResultMapper(private val dataSource: DataSourceInfo, private private fun toCytoData(node: Node): CytoData { val id = toArcadeId(dataSource, Neo4jType.NODE, node.id()) - val record = Sprite() - .load(node.asMap()) - .rename("id", "_id_") + val record = + Sprite() + .load(node.asMap()) + .rename("id", "_id_") val data = Data(id = id, record = record.asMap() as MutableMap) @@ -60,9 +63,10 @@ class Neo4jStatementResultMapper(private val dataSource: DataSourceInfo, private val id = toArcadeId(dataSource, Neo4jType.EDGE, rel.id()) val source = toArcadeId(dataSource, Neo4jType.NODE, rel.startNodeId()) val target = toArcadeId(dataSource, Neo4jType.NODE, rel.endNodeId()) - val record = Sprite() - .load(rel.asMap()) - .rename("id", "_id_") + val record = + Sprite() + .load(rel.asMap()) + .rename("id", "_id_") val data = Data(id = id, record = record.asMap() as MutableMap, source = source, target = target) @@ -82,7 +86,8 @@ class Neo4jStatementResultMapper(private val dataSource: DataSourceInfo, private while (result.hasNext() && fetchMore) { val record = result.next() - record.values() + record + .values() .asSequence() .forEach { f -> when (f.type().name()) { @@ -109,37 +114,43 @@ class Neo4jStatementResultMapper(private val dataSource: DataSourceInfo, private } log.info("fethced:: {} - nodes:: {} - rels:: {} ", fetched, nodes.size, rels.size) - val relsWithEachEnds = rels.asSequence() - .filter { rel -> + val relsWithEachEnds = + rels + .asSequence() + .filter { rel -> - val endNodeId = rel.endNodeId() + val endNodeId = rel.endNodeId() - val startNodeId = rel.startNodeId() + val startNodeId = rel.startNodeId() - var foundStart = false - var foundEnd = false + var foundStart = false + var foundEnd = false - for (node in nodes) { - if (node.id() == endNodeId) { - foundEnd = true - } else if (node.id() == startNodeId) { - foundStart = true + for (node in nodes) { + if (node.id() == endNodeId) { + foundEnd = true + } else if (node.id() == startNodeId) { + foundStart = true + } } - } - foundStart && foundEnd - }.toSet() + foundStart && foundEnd + }.toSet() - val cytoNodes = nodes.asSequence() - .map { c -> mapProperties(nodesClasses, c) } - .map { n -> toCytoData(n) } - .map { c -> countInOut(c) } - .toSet() + val cytoNodes = + nodes + .asSequence() + .map { c -> mapProperties(nodesClasses, c) } + .map { n -> toCytoData(n) } + .map { c -> countInOut(c) } + .toSet() - val edges = rels.asSequence() - .map { c -> mapProperties(edgeClasses, c) } - .map { r -> toCytoData(r) } - .toSet() + val edges = + rels + .asSequence() + .map { c -> mapProperties(edgeClasses, c) } + .map { r -> toCytoData(r) } + .toSet() val graphData = GraphData(nodesClasses, edgeClasses, cytoNodes, edges, !fetchMore) @@ -148,32 +159,39 @@ class Neo4jStatementResultMapper(private val dataSource: DataSourceInfo, private return graphData } - private fun mapProperties(nodesClasses: MutableMap>, node: Node): Node { + private fun mapProperties( + nodesClasses: MutableMap>, + node: Node, + ): Node { val className = node.labels().joinToString("_") nodesClasses.putIfAbsent(className, HashMap()) val properties = nodesClasses[className] - node.keys() + node + .keys() .forEach { k -> properties?.putIfAbsent(k, mapType(node.get(k).type().name())) } return node } - private fun mapProperties(nodesClasses: MutableMap>, rel: Relationship): Relationship { + private fun mapProperties( + nodesClasses: MutableMap>, + rel: Relationship, + ): Relationship { nodesClasses.putIfAbsent(rel.type(), HashMap()) val properties = nodesClasses[rel.type()] - rel.keys() + rel + .keys() .forEach { k -> properties?.putIfAbsent(k, rel.get(k).type().name()) } return rel } companion object { - private val log = LoggerFactory.getLogger(Neo4jDataProvider::class.java) } } diff --git a/neo4j3/src/test/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jConnectionTest.kt b/neo4j3/src/test/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jConnectionTest.kt index 7a0e2b38..f1ca72d1 100644 --- a/neo4j3/src/test/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jConnectionTest.kt +++ b/neo4j3/src/test/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jConnectionTest.kt @@ -32,16 +32,16 @@ import org.testcontainers.containers.wait.strategy.Wait import org.testcontainers.utility.DockerImageName class Neo4jConnectionTest { + private val log = LoggerFactory.getLogger(Neo4jDataProviderIntTest::class.java) - private val LOGGER = LoggerFactory.getLogger(Neo4jDataProviderIntTest::class.java) - - private val container: KGenericContainer = KGenericContainer(DockerImageName.parse("neo4j:3.5")) - .apply { - withExposedPorts(7687, 7474) - withEnv("NEO4J_AUTH", "neo4j/arcade") - waitingFor(Wait.forListeningPort()) - start() - } + private val container: KGenericContainer = + KGenericContainer(DockerImageName.parse("neo4j:3.5")) + .apply { + withExposedPorts(7687, 7474) + withEnv("NEO4J_AUTH", "neo4j/arcade") + waitingFor(Wait.forListeningPort()) + start() + } private val provider: Neo4jDataProvider @@ -49,18 +49,19 @@ class Neo4jConnectionTest { init { - container.followOutput(Slf4jLogConsumer(LOGGER)) + container.followOutput(Slf4jLogConsumer(log)) - dataSource = DataSourceInfo( - id = 1L, - type = "NEO4J", - name = "testDataSource", - server = container.containerIpAddress, - port = container.firstMappedPort, - username = "neo4j", - password = "arcade", - database = Neo4jDataProviderIntTest::class.java.simpleName, - ) + dataSource = + DataSourceInfo( + id = 1L, + type = "NEO4J", + name = "testDataSource", + server = container.containerIpAddress, + port = container.firstMappedPort, + username = "neo4j", + password = "arcade", + database = Neo4jDataProviderIntTest::class.java.simpleName, + ) getDriver(dataSource).use { driver -> driver.session().use { diff --git a/neo4j3/src/test/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jContainer.kt b/neo4j3/src/test/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jContainer.kt index 287c373e..95d10c11 100644 --- a/neo4j3/src/test/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jContainer.kt +++ b/neo4j3/src/test/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jContainer.kt @@ -27,28 +27,29 @@ import org.testcontainers.containers.wait.strategy.Wait import org.testcontainers.utility.DockerImageName object Neo4jContainer { - - private val container: KGenericContainer = KGenericContainer(DockerImageName.parse("neo4j:3.5")) - .apply { - withExposedPorts(7687, 7474) - withEnv("NEO4J_AUTH", "neo4j/arcade") - waitingFor(Wait.forListeningPort()) - start() - } + private val container: KGenericContainer = + KGenericContainer(DockerImageName.parse("neo4j:3.5")) + .apply { + withExposedPorts(7687, 7474) + withEnv("NEO4J_AUTH", "neo4j/arcade") + waitingFor(Wait.forListeningPort()) + start() + } val dataSource: DataSourceInfo init { - dataSource = DataSourceInfo( - id = 1L, - type = "NEO4J", - name = "testDataSource", - server = container.containerIpAddress, - port = container.firstMappedPort, - username = "neo4j", - password = "arcade", - database = "empty", - ) + dataSource = + DataSourceInfo( + id = 1L, + type = "NEO4J", + name = "testDataSource", + server = container.containerIpAddress, + port = container.firstMappedPort, + username = "neo4j", + password = "arcade", + database = "empty", + ) getDriver(dataSource).use { driver -> driver.session().use { diff --git a/neo4j3/src/test/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jDataProviderIntTest.kt b/neo4j3/src/test/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jDataProviderIntTest.kt index da74a5ae..d739df4b 100644 --- a/neo4j3/src/test/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jDataProviderIntTest.kt +++ b/neo4j3/src/test/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jDataProviderIntTest.kt @@ -32,7 +32,6 @@ import org.neo4j.driver.v1.AccessMode @TestInstance(TestInstance.Lifecycle.PER_CLASS) class Neo4jDataProviderIntTest { - private val provider: Neo4jDataProvider = Neo4jDataProvider() @Test @@ -58,7 +57,7 @@ class Neo4jDataProviderIntTest { @Test @Throws(Exception::class) - fun testFetchData() { + fun fetchData() { // given // when @@ -72,12 +71,14 @@ class Neo4jDataProviderIntTest { assertThat(data.edgesClasses).containsKeys("FriendOf") val cytoData = data.nodes.first() - assertThat(cytoData.data.record).isNotNull + assertThat(cytoData.data.record) + .isNotNull .containsKeys("name", "@edgeCount", "@in", "@out") println("cytoData = $cytoData") val record = cytoData.data.record - assertThat(record).isNotNull + assertThat(record) + .isNotNull .containsKeys("name", "@edgeCount", "@in", "@out") assertThat(record["@edgeCount"]).isEqualTo(2) @@ -87,7 +88,7 @@ class Neo4jDataProviderIntTest { @Test @Throws(Exception::class) - fun testFetchNodes() { + fun fetchNodes() { // given // when @@ -131,12 +132,17 @@ class Neo4jDataProviderIntTest { val cytoData = data.nodes.first() assertThat(cytoData.data.record).isNotNull - assertThat(cytoData.data.record["@edgeCount"].toString().toInt()).isGreaterThan(0) + assertThat( + cytoData.data.record["@edgeCount"] + .toString() + .toInt(), + ).isGreaterThan(0) assertThat(cytoData.data.source).isEmpty() val record = cytoData.data.record - assertThat(record).isNotNull + assertThat(record) + .isNotNull .containsKeys("name", "@edgeCount", "@in", "@out") assertThat(record["@edgeCount"]).isEqualTo(2) @@ -152,12 +158,17 @@ class Neo4jDataProviderIntTest { val cytoData = data.nodes.first() assertThat(cytoData.data.record).isNotNull - assertThat(cytoData.data.record["@edgeCount"].toString().toInt()).isGreaterThan(0) + assertThat( + cytoData.data.record["@edgeCount"] + .toString() + .toInt(), + ).isGreaterThan(0) assertThat(cytoData.data.source).isEmpty() val record = cytoData.data.record - assertThat(record).isNotNull + assertThat(record) + .isNotNull .containsKeys("name", "@edgeCount", "@in", "@out") assertThat(record["@edgeCount"]).isEqualTo(2) @@ -176,10 +187,12 @@ class Neo4jDataProviderIntTest { val firstNode = firstDataSet.nodes.first().data val secondNode = secondDataSet.nodes.first().data - val edgeClasses = (firstNode.record["@in"] as Map).keys - .union((firstNode.record["@out"] as Map).keys) - .union((secondNode.record["@in"] as Map).keys) - .union((secondNode.record["@out"] as Map).keys) + val edgeClasses = + (firstNode.record["@in"] as Map) + .keys + .union((firstNode.record["@out"] as Map).keys) + .union((secondNode.record["@in"] as Map).keys) + .union((secondNode.record["@out"] as Map).keys) val data = provider.edges(dataSource, arrayOf(firstNode.id), edgeClasses.toTypedArray(), arrayOf(secondNode.id)) @@ -201,12 +214,17 @@ class Neo4jDataProviderIntTest { val cytoData = data.nodes.first() println("cytoData = $cytoData") assertThat(cytoData.data.record).isNotNull - assertThat(cytoData.data.record["@edgeCount"].toString().toInt()).isGreaterThan(0) + assertThat( + cytoData.data.record["@edgeCount"] + .toString() + .toInt(), + ).isGreaterThan(0) assertThat(cytoData.data.source).isEmpty() val record = cytoData.data.record - assertThat(record).isNotNull + assertThat(record) + .isNotNull .containsKeys("name", "@edgeCount", "@in", "@out") assertThat(record["@edgeCount"]).isEqualTo(2) @@ -229,7 +247,11 @@ class Neo4jDataProviderIntTest { assertThat(data.nodesClasses).containsKeys("Person") assertThat(data.edgesClasses).containsKeys("FriendOf") - val cytoData = data.nodes.stream().findFirst().get() + val cytoData = + data.nodes + .stream() + .findFirst() + .get() assertThat(cytoData.data.record).isNotNull assertThat(cytoData.data.record["@edgeCount"]).isEqualTo(2) diff --git a/neo4j3/src/test/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jGraphProviderTest.kt b/neo4j3/src/test/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jGraphProviderTest.kt index 77de349f..4dfd5224 100644 --- a/neo4j3/src/test/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jGraphProviderTest.kt +++ b/neo4j3/src/test/kotlin/com/arcadeanalytics/provider/neo4j3/Neo4jGraphProviderTest.kt @@ -29,34 +29,33 @@ import java.util.ArrayList @TestInstance(TestInstance.Lifecycle.PER_CLASS) class Neo4jGraphProviderTest { - private val provider: Neo4jGraphProvider = Neo4jGraphProvider() @Test fun shouldFetchAllElements() { val docs = ArrayList() - val indexer = object : SpritePlayer { - override fun end() { - } + val indexer = + object : SpritePlayer { + override fun end() { + } - override fun begin() { - } + override fun begin() { + } - override fun processed(): Long { - return 0 - } + override fun processed(): Long = 0 - override fun play(document: Sprite) { - docs.add(document) + override fun play(document: Sprite) { + docs.add(document) + } } - } provider.provideTo(Neo4jContainer.dataSource, indexer) assertThat(docs).hasSize(12) assertThat( - docs.asSequence() + docs + .asSequence() .map { s -> s.valueOf("@class") } .any { c -> c == "Person" || c == "Car" || c == "fraternal" || c == "killer" }, ).isTrue() diff --git a/orientdb2/src/main/kotlin/com/arcadeanalytics/provider/orient2/OrientDBDataSourceGraphDataProvider.kt b/orientdb2/src/main/kotlin/com/arcadeanalytics/provider/orient2/OrientDBDataSourceGraphDataProvider.kt index cd3358e1..f0f0770f 100644 --- a/orientdb2/src/main/kotlin/com/arcadeanalytics/provider/orient2/OrientDBDataSourceGraphDataProvider.kt +++ b/orientdb2/src/main/kotlin/com/arcadeanalytics/provider/orient2/OrientDBDataSourceGraphDataProvider.kt @@ -51,7 +51,6 @@ import java.util.HashMap * @author Roberto Franchini */ class OrientDBDataSourceGraphDataProvider : DataSourceGraphDataProvider { - private val log = LoggerFactory.getLogger(OrientDBDataSourceGraphDataProvider::class.java) override fun supportedDataSourceTypes(): Set = setOf("ORIENTDB") @@ -69,7 +68,11 @@ class OrientDBDataSourceGraphDataProvider : DataSourceGraphDataProvider { return true } - override fun fetchData(dataSource: DataSourceInfo, query: String, limit: Int): GraphData { + override fun fetchData( + dataSource: DataSourceInfo, + query: String, + limit: Int, + ): GraphData { open(dataSource) .use { db -> log.info("fetching data from '{}' with query '{}' ", dataSource.id, truncate(query, 256)) @@ -94,14 +97,14 @@ class OrientDBDataSourceGraphDataProvider : DataSourceGraphDataProvider { val outs = HashMap() record["@out"] = outs - val keys = record.entries - .asSequence() - .filter { e -> e.key.startsWith("in_") } - .map { e -> - ins[removeFirst(e.key, "in_")] = e.value - e.key - } - .toMutableSet() + val keys = + record.entries + .asSequence() + .filter { e -> e.key.startsWith("in_") } + .map { e -> + ins[removeFirst(e.key, "in_")] = e.value + e.key + }.toMutableSet() keys.addAll( record.entries @@ -113,7 +116,8 @@ class OrientDBDataSourceGraphDataProvider : DataSourceGraphDataProvider { }.toSet(), ) - keys.asSequence() + keys + .asSequence() .forEach { k -> record.remove(k) } cleanRecord(record) @@ -184,7 +188,10 @@ class OrientDBDataSourceGraphDataProvider : DataSourceGraphDataProvider { return map } - private fun mapField(doc: ODocument, fieldName: String): Any { + private fun mapField( + doc: ODocument, + fieldName: String, + ): Any { val type = doc.fieldType(fieldName) if (type.isEmbedded) { @@ -206,7 +213,8 @@ class OrientDBDataSourceGraphDataProvider : DataSourceGraphDataProvider { val edges = mutableSetOf() val resultSet = collector.collected() - resultSet.asSequence() + resultSet + .asSequence() .forEach { doc -> if (doc.isVertexType()) { val vertex = graph.getVertex(doc) @@ -224,30 +232,37 @@ class OrientDBDataSourceGraphDataProvider : DataSourceGraphDataProvider { log.info("Computing edge map on {} edges...", edges.size) val edgeClasses = mutableMapOf>() - val cytoEdges = edges.asSequence() - .map { e -> e.record } - .map { d -> populateClasses(edgeClasses, d) } - .map { d -> mapRid(dataSource, d) } - .map { d -> mapInAndOut(dataSource, d) } - .map { d -> countInAndOut(d) } - .map { d -> toData(d) } - .toSet() + val cytoEdges = + edges + .asSequence() + .map { e -> e.record } + .map { d -> populateClasses(edgeClasses, d) } + .map { d -> mapRid(dataSource, d) } + .map { d -> mapInAndOut(dataSource, d) } + .map { d -> countInAndOut(d) } + .map { d -> toData(d) } + .toSet() log.info("Computing vertex map on {} vertices...", nodes.size) val nodeClasses = mutableMapOf>() - val cytoNodes = nodes.asSequence() - .map { e -> e.record } - .map { d -> populateClasses(nodeClasses, d) } - .map { d -> mapRid(dataSource, d) } - .map { d -> countInAndOut(d) } - .map { d -> toData(d) } - .toSet() + val cytoNodes = + nodes + .asSequence() + .map { e -> e.record } + .map { d -> populateClasses(nodeClasses, d) } + .map { d -> mapRid(dataSource, d) } + .map { d -> countInAndOut(d) } + .map { d -> toData(d) } + .toSet() return GraphData(nodeClasses, edgeClasses, cytoNodes, cytoEdges, collector.isTruncated) } - private fun addConnectedVertex(connectedVertices: MutableSet, vertex: OrientVertex) { + private fun addConnectedVertex( + connectedVertices: MutableSet, + vertex: OrientVertex, + ) { val record = vertex.record if (connectedVertices.add(record)) { record.isTrackingChanges = false @@ -256,7 +271,8 @@ class OrientDBDataSourceGraphDataProvider : DataSourceGraphDataProvider { } private fun countInAndOut(doc: ODocument): ODocument { - doc.fieldNames() + doc + .fieldNames() .asSequence() .filter { f -> f.startsWith("out_") || f.startsWith("in_") } .forEach { f -> @@ -280,7 +296,10 @@ class OrientDBDataSourceGraphDataProvider : DataSourceGraphDataProvider { return d } - private fun mapInAndOut(dataSource: DataSourceInfo, d: ODocument): ODocument { + private fun mapInAndOut( + dataSource: DataSourceInfo, + d: ODocument, + ): ODocument { if (!d.containsField("out")) { return d } @@ -295,7 +314,10 @@ class OrientDBDataSourceGraphDataProvider : DataSourceGraphDataProvider { return d } - private fun mapRid(dataSource: DataSourceInfo, doc: ODocument): ODocument { + private fun mapRid( + dataSource: DataSourceInfo, + doc: ODocument, + ): ODocument { val rid = doc.identity doc.field("@id", "${dataSource.id}_${rid.clusterId}_${rid.clusterPosition}") @@ -303,17 +325,24 @@ class OrientDBDataSourceGraphDataProvider : DataSourceGraphDataProvider { return doc } - private fun populateClasses(classes: MutableMap>, element: ODocument): ODocument { + private fun populateClasses( + classes: MutableMap>, + element: ODocument, + ): ODocument { classes.putIfAbsent(element.className, Maps.newHashMap()) populateProperties(classes, element) return element } - private fun populateProperties(classes: Map>, element: ODocument) { + private fun populateProperties( + classes: Map>, + element: ODocument, + ) { val properties = classes[element.className] as MutableMap - element.fieldNames() + element + .fieldNames() .asSequence() .filter { f -> !f.startsWith("@") } .filter { f -> !f.startsWith("in_") } @@ -325,8 +354,7 @@ class OrientDBDataSourceGraphDataProvider : DataSourceGraphDataProvider { fieldType != OType.LINKSET && fieldType != OType.LINKLIST && fieldType != OType.LINKBAG - } - .forEach { f -> + }.forEach { f -> val type = element.fieldType(f) if (type != null) { properties.putIfAbsent(f, mapType(type.name)) @@ -353,11 +381,12 @@ class OrientDBDataSourceGraphDataProvider : DataSourceGraphDataProvider { query += " FROM [" - query += ids - .asSequence() - .map { r -> r.removePrefix("${dataSource.id}_") } - .map { r -> "#" + r.replace('_', ':') } - .joinToString { it } + query += + ids + .asSequence() + .map { r -> r.removePrefix("${dataSource.id}_") } + .map { r -> "#" + r.replace('_', ':') } + .joinToString { it } query += "] MAXDEPTH 2) LIMIT $maxTraversal" @@ -384,35 +413,51 @@ class OrientDBDataSourceGraphDataProvider : DataSourceGraphDataProvider { return fetchData(dataSource, query, 10000) } - override fun load(dataSource: DataSourceInfo, ids: Array): GraphData { + override fun load( + dataSource: DataSourceInfo, + ids: Array, + ): GraphData { var query = "SELECT FROM [" - query += ids - .asSequence() - .map { r -> r.removePrefix("${dataSource.id}_") } - .map { r -> "#" + r.replace('_', ':') } - .joinToString { it } + query += + ids + .asSequence() + .map { r -> r.removePrefix("${dataSource.id}_") } + .map { r -> "#" + r.replace('_', ':') } + .joinToString { it } query += "] " return fetchData(dataSource, query, ids.size) } - override fun loadFromClass(dataSource: DataSourceInfo, className: String, limit: Int): GraphData { + override fun loadFromClass( + dataSource: DataSourceInfo, + className: String, + limit: Int, + ): GraphData { val query = "select * from $className limit $limit" return fetchData(dataSource, query, limit) } - override fun loadFromClass(dataSource: DataSourceInfo, className: String, propName: String, propertyValue: String, limit: Int): GraphData { + override fun loadFromClass( + dataSource: DataSourceInfo, + className: String, + propName: String, + propertyValue: String, + limit: Int, + ): GraphData { val query = "select * from $className where $propName = '$propertyValue' limit $limit" return fetchData(dataSource, query, limit) } - private fun cleanIds(dataSource: DataSourceInfo, ids: Array): String { - return ids + private fun cleanIds( + dataSource: DataSourceInfo, + ids: Array, + ): String = + ids .asSequence() .map { r -> r.removePrefix("${dataSource.id}_") } .map { r -> "#" + r.replace('_', ':') } .joinToString { it } - } } diff --git a/orientdb2/src/main/kotlin/com/arcadeanalytics/provider/orient2/OrientDBDataSourceGraphProvider.kt b/orientdb2/src/main/kotlin/com/arcadeanalytics/provider/orient2/OrientDBDataSourceGraphProvider.kt index 2ca9441f..9c105a56 100644 --- a/orientdb2/src/main/kotlin/com/arcadeanalytics/provider/orient2/OrientDBDataSourceGraphProvider.kt +++ b/orientdb2/src/main/kotlin/com/arcadeanalytics/provider/orient2/OrientDBDataSourceGraphProvider.kt @@ -31,30 +31,31 @@ import org.slf4j.LoggerFactory import java.util.regex.Pattern class OrientDBDataSourceGraphProvider : DataSourceGraphProvider { - private val log = LoggerFactory.getLogger(OrientDBDataSourceGraphProvider::class.java) private val queries: List - private val ALL_V = "SELECT FROM V LIMIT 1000" + private val allV = "SELECT FROM V LIMIT 1000" - private val ALL_E = "SELECT FROM E LIMIT 1000" + private val allE = "SELECT FROM E LIMIT 1000" private val allFields: Pattern = Pattern.compile(".*") init { - this.queries = listOf(ALL_V, ALL_E) + this.queries = listOf(allV, allE) } - override fun supportedDataSourceTypes(): Set { - return setOf("ORIENTDB") - } + override fun supportedDataSourceTypes(): Set = setOf("ORIENTDB") - override fun provideTo(dataSource: DataSourceInfo, player: SpritePlayer) { + override fun provideTo( + dataSource: DataSourceInfo, + player: SpritePlayer, + ) { open(dataSource).use { db -> - queries.asSequence() + queries + .asSequence() .onEach { query -> log.info("fetching documents from datasource {} with query ' {} ' ", dataSource.id, query) } .forEach { sql -> @@ -63,7 +64,8 @@ class OrientDBDataSourceGraphProvider : DataSourceGraphProvider { var resultset = db.query>(query) while (!resultset.isEmpty()) { - resultset.asSequence() + resultset + .asSequence() .map { res -> res as ODocument } .filter { doc -> doc.fields() > 0 } .map { doc -> toSprite(doc) } @@ -79,22 +81,22 @@ class OrientDBDataSourceGraphProvider : DataSourceGraphProvider { private fun toSprite(document: ODocument): Sprite { val rid = document.identity - val sprite = Sprite() - .load(document.toMap()) - .addAll( - "@class", - document.schemaClass - .allSuperClasses - .asSequence() - .map { c -> c.name } - .toList(), - ) - .apply(allFields) { v -> v.toString() } - .remove("@class", "V") - .remove("@class", "E") - .remove("@rid") - .add(ARCADE_ID, "${rid.clusterId}_${rid.clusterPosition}") - .add(ARCADE_TYPE, document.type()) + val sprite = + Sprite() + .load(document.toMap()) + .addAll( + "@class", + document.schemaClass + .allSuperClasses + .asSequence() + .map { c -> c.name } + .toList(), + ).apply(allFields) { v -> v.toString() } + .remove("@class", "V") + .remove("@class", "E") + .remove("@rid") + .add(ARCADE_ID, "${rid.clusterId}_${rid.clusterPosition}") + .add(ARCADE_TYPE, document.type()) return sprite } } diff --git a/orientdb2/src/main/kotlin/com/arcadeanalytics/provider/orient2/OrientDBDataSourceMetadataProvider.kt b/orientdb2/src/main/kotlin/com/arcadeanalytics/provider/orient2/OrientDBDataSourceMetadataProvider.kt index c2cfa299..6a75a3aa 100644 --- a/orientdb2/src/main/kotlin/com/arcadeanalytics/provider/orient2/OrientDBDataSourceMetadataProvider.kt +++ b/orientdb2/src/main/kotlin/com/arcadeanalytics/provider/orient2/OrientDBDataSourceMetadataProvider.kt @@ -30,8 +30,7 @@ import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx import com.orientechnologies.orient.core.metadata.schema.OImmutableSchema import org.slf4j.LoggerFactory -class OrientDBDataSourceMetadataProvider() : DataSourceMetadataProvider { - +class OrientDBDataSourceMetadataProvider : DataSourceMetadataProvider { private val log = LoggerFactory.getLogger(OrientDBDataSourceMetadataProvider::class.java) override fun fetchMetadata(dataSource: DataSourceInfo): DataSourceMetadata { @@ -48,37 +47,45 @@ class OrientDBDataSourceMetadataProvider() : DataSourceMetadataProvider { } } - private fun edgeClasses(schema: OImmutableSchema, db: ODatabaseDocumentTx): EdgesClasses { - return schema.classes + private fun edgeClasses( + schema: OImmutableSchema, + db: ODatabaseDocumentTx, + ): EdgesClasses = + schema.classes .asSequence() .filter { it.isEdgeType } .filter { it.name != "E" } .map { - val props = it.properties() - .map { prop -> prop.name to TypeProperty(prop.name, prop.type.name) } - .toMap() + val props = + it + .properties() + .map { prop -> prop.name to TypeProperty(prop.name, prop.type.name) } + .toMap() TypeClass(it.name, db.countClass(it.name, true), props) }.map { it.name to it }.toMap() - } - private fun nodeClasses(schema: OImmutableSchema, db: ODatabaseDocumentTx): NodesClasses { - return schema.classes + private fun nodeClasses( + schema: OImmutableSchema, + db: ODatabaseDocumentTx, + ): NodesClasses = + schema.classes .asSequence() .filter { it.isVertexType } .filter { it.name != "V" } .map { - val props = it.properties() - .map { prop -> prop.name to TypeProperty(prop.name, prop.type.name) } - .toMap() + val props = + it + .properties() + .map { prop -> prop.name to TypeProperty(prop.name, prop.type.name) } + .toMap() TypeClass(it.name, db.countClass(it.name, true), props) }.map { it.name to it }.toMap() - } override fun supportedDataSourceTypes(): Set = setOf("ORIENTDB") } diff --git a/orientdb2/src/main/kotlin/com/arcadeanalytics/provider/orient2/OrientDBDocumentCollector.kt b/orientdb2/src/main/kotlin/com/arcadeanalytics/provider/orient2/OrientDBDocumentCollector.kt index f6634c94..c570a394 100644 --- a/orientdb2/src/main/kotlin/com/arcadeanalytics/provider/orient2/OrientDBDocumentCollector.kt +++ b/orientdb2/src/main/kotlin/com/arcadeanalytics/provider/orient2/OrientDBDocumentCollector.kt @@ -23,7 +23,6 @@ import com.orientechnologies.orient.core.record.impl.ODocument import java.util.ArrayList class OrientDBDocumentCollector { - private val documents = ArrayList() internal var isTruncated = false @@ -31,13 +30,9 @@ class OrientDBDocumentCollector { documents.add(document) } - fun size(): Int { - return documents.size - } + fun size(): Int = documents.size - fun collected(): List { - return documents - } + fun collected(): List = documents fun truncated(truncated: Boolean) { this.isTruncated = truncated diff --git a/orientdb2/src/main/kotlin/com/arcadeanalytics/provider/orient2/OrientDBResultListener.kt b/orientdb2/src/main/kotlin/com/arcadeanalytics/provider/orient2/OrientDBResultListener.kt index defc4348..764ce7c3 100644 --- a/orientdb2/src/main/kotlin/com/arcadeanalytics/provider/orient2/OrientDBResultListener.kt +++ b/orientdb2/src/main/kotlin/com/arcadeanalytics/provider/orient2/OrientDBResultListener.kt @@ -25,9 +25,7 @@ import com.orientechnologies.orient.core.record.impl.ODocument internal class OrientDBResultListener( private val documentCollector: OrientDBDocumentCollector, private val limit: Int, -) : - OCommandResultListener { - +) : OCommandResultListener { // state private var nodes: Int = 0 private var edges: Int = 0 @@ -52,7 +50,5 @@ internal class OrientDBResultListener( override fun end() { } - override fun getResult(): Any? { - return null - } + override fun getResult(): Any? = null } diff --git a/orientdb2/src/main/kotlin/com/arcadeanalytics/provider/orient2/OrientDBUtils.kt b/orientdb2/src/main/kotlin/com/arcadeanalytics/provider/orient2/OrientDBUtils.kt index 744f2993..f4d7920b 100644 --- a/orientdb2/src/main/kotlin/com/arcadeanalytics/provider/orient2/OrientDBUtils.kt +++ b/orientdb2/src/main/kotlin/com/arcadeanalytics/provider/orient2/OrientDBUtils.kt @@ -25,11 +25,11 @@ import com.orientechnologies.orient.core.record.impl.ODocument private val connectionTemplate = "remote:{server}:{port}/{database}" -fun createConnectionUrl(dataSource: DataSourceInfo): String { - return connectionTemplate.replace("{server}", dataSource.server) +fun createConnectionUrl(dataSource: DataSourceInfo): String = + connectionTemplate + .replace("{server}", dataSource.server) .replace("{port}", dataSource.port.toString()) .replace("{database}", dataSource.database) -} fun open(dataSource: DataSourceInfo): ODatabaseDocumentTx { val connectionUrl = createConnectionUrl(dataSource) @@ -37,16 +37,13 @@ fun open(dataSource: DataSourceInfo): ODatabaseDocumentTx { return db.open(dataSource.username, dataSource.password) } -fun ODocument.isEdgeType(): Boolean { - return this.schemaClass.isEdgeType -} +fun ODocument.isEdgeType(): Boolean = this.schemaClass.isEdgeType -fun ODocument.isVertexType(): Boolean { - return this.schemaClass.isVertexType -} +fun ODocument.isVertexType(): Boolean = this.schemaClass.isVertexType -fun ODocument.type(): String = when { - isEdgeType() -> "edge" - isVertexType() -> "node" - else -> "document" -} +fun ODocument.type(): String = + when { + isEdgeType() -> "edge" + isVertexType() -> "node" + else -> "document" + } diff --git a/orientdb2/src/test/kotlin/com/arcadeanalytics/provider/orient2/OrientDBConnectionTest.kt b/orientdb2/src/test/kotlin/com/arcadeanalytics/provider/orient2/OrientDBConnectionTest.kt index 5e472c36..18d1a0b8 100644 --- a/orientdb2/src/test/kotlin/com/arcadeanalytics/provider/orient2/OrientDBConnectionTest.kt +++ b/orientdb2/src/test/kotlin/com/arcadeanalytics/provider/orient2/OrientDBConnectionTest.kt @@ -27,14 +27,14 @@ import org.junit.jupiter.api.Test import org.testcontainers.containers.wait.strategy.Wait class OrientDBConnectionTest { - - private val container: KGenericContainer = KGenericContainer(ORIENTDB_DOCKER_IMAGE) - .apply { - withExposedPorts(2424) - withEnv("ORIENTDB_ROOT_PASSWORD", ORIENTDB_ROOT_PASSWORD) - waitingFor(Wait.forListeningPort()) - start() - } + private val container: KGenericContainer = + KGenericContainer(ORIENTDB_DOCKER_IMAGE) + .apply { + withExposedPorts(2424) + withEnv("ORIENTDB_ROOT_PASSWORD", ORIENTDB_ROOT_PASSWORD) + waitingFor(Wait.forListeningPort()) + start() + } private val provider: OrientDBDataSourceGraphDataProvider @@ -42,16 +42,17 @@ class OrientDBConnectionTest { init { - dataSource = DataSourceInfo( - id = 1L, - type = "ORIENTDB", - name = "testDataSource", - server = container.containerIpAddress, - port = container.firstMappedPort, - username = "admin", - password = "admin", - database = OrientDBDataSourceGraphDataProviderIntTest::class.java.simpleName, - ) + dataSource = + DataSourceInfo( + id = 1L, + type = "ORIENTDB", + name = "testDataSource", + server = container.containerIpAddress, + port = container.firstMappedPort, + username = "admin", + password = "admin", + database = OrientDBDataSourceGraphDataProviderIntTest::class.java.simpleName, + ) val serverUrl = getServerUrl(container) @@ -68,7 +69,8 @@ class OrientDBConnectionTest { container.stop() - Assertions.assertThatExceptionOfType(RuntimeException::class.java) + Assertions + .assertThatExceptionOfType(RuntimeException::class.java) .isThrownBy { provider.testConnection(dataSource) } } } diff --git a/orientdb2/src/test/kotlin/com/arcadeanalytics/provider/orient2/OrientDBDataSourceGraphDataProviderIntTest.kt b/orientdb2/src/test/kotlin/com/arcadeanalytics/provider/orient2/OrientDBDataSourceGraphDataProviderIntTest.kt index 0adf5fcb..a609db25 100644 --- a/orientdb2/src/test/kotlin/com/arcadeanalytics/provider/orient2/OrientDBDataSourceGraphDataProviderIntTest.kt +++ b/orientdb2/src/test/kotlin/com/arcadeanalytics/provider/orient2/OrientDBDataSourceGraphDataProviderIntTest.kt @@ -29,7 +29,6 @@ import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class OrientDBDataSourceGraphDataProviderIntTest { - private val provider: OrientDBDataSourceGraphDataProvider = OrientDBDataSourceGraphDataProvider() @Test @@ -49,7 +48,8 @@ class OrientDBDataSourceGraphDataProviderIntTest { assertThat(cytoData.data.id).startsWith("${dataSource.id}") val record = cytoData.data.record - assertThat(record).isNotNull + assertThat(record) + .isNotNull .containsKeys("name", "@out", "@in", "@edgeCount") } @@ -59,7 +59,10 @@ class OrientDBDataSourceGraphDataProviderIntTest { // given val person = provider.loadFromClass(dataSource, "Person", "name", "frank", 1) - val id = person.nodes.first().data.id + val id = + person.nodes + .first() + .data.id // when val data = provider.expand(dataSource, arrayOf(id), "in", "FriendOf", 300) @@ -84,7 +87,10 @@ class OrientDBDataSourceGraphDataProviderIntTest { val person = provider.loadFromClass(dataSource, "Person", "name", "frank", 1) - val id = person.nodes.first().data.id + val id = + person.nodes + .first() + .data.id // when val data = provider.expand(dataSource, arrayOf(id), "both", "", 300) @@ -116,7 +122,11 @@ class OrientDBDataSourceGraphDataProviderIntTest { // then assertThat(data.nodes).hasSize(2) - val cytoData = data.nodes.stream().findFirst().get() + val cytoData = + data.nodes + .stream() + .findFirst() + .get() assertThat(cytoData.data.record).isNotNull assertThat(cytoData.data.source).isEmpty() } @@ -146,10 +156,12 @@ class OrientDBDataSourceGraphDataProviderIntTest { val firstNode = firstDataSet.nodes.first().data val secondNode = secondDataSet.nodes.first().data - val edgeClasses = (firstNode.record["@in"] as Map).keys - .union((firstNode.record["@out"] as Map).keys) - .union((secondNode.record["@in"] as Map).keys) - .union((secondNode.record["@out"] as Map).keys) + val edgeClasses = + (firstNode.record["@in"] as Map) + .keys + .union((firstNode.record["@out"] as Map).keys) + .union((secondNode.record["@in"] as Map).keys) + .union((secondNode.record["@out"] as Map).keys) val data = provider.edges(dataSource, arrayOf(firstNode.id), edgeClasses.toTypedArray(), arrayOf(secondNode.id)) @@ -163,9 +175,11 @@ class OrientDBDataSourceGraphDataProviderIntTest { } private fun getPersonsIdentity(limit: Int): Array { - ODatabaseDocumentTx(dbUrl).open("admin", "admin") + ODatabaseDocumentTx(dbUrl) + .open("admin", "admin") .use { - return it.query>(OSQLSynchQuery("""SELECT from Person limit $limit""")) + return it + .query>(OSQLSynchQuery("""SELECT from Person limit $limit""")) .asSequence() .map { doc -> doc.identity } .map { id -> id.clusterId.toString() + "_" + id.clusterPosition } diff --git a/orientdb2/src/test/kotlin/com/arcadeanalytics/provider/orient2/OrientDBDataSourceGraphProviderIntTest.kt b/orientdb2/src/test/kotlin/com/arcadeanalytics/provider/orient2/OrientDBDataSourceGraphProviderIntTest.kt index 3e320c9d..59d23121 100644 --- a/orientdb2/src/test/kotlin/com/arcadeanalytics/provider/orient2/OrientDBDataSourceGraphProviderIntTest.kt +++ b/orientdb2/src/test/kotlin/com/arcadeanalytics/provider/orient2/OrientDBDataSourceGraphProviderIntTest.kt @@ -35,25 +35,25 @@ import java.util.ArrayList @TestInstance(TestInstance.Lifecycle.PER_CLASS) class OrientDBDataSourceGraphProviderIntTest { - private val provider: OrientDBDataSourceGraphProvider = OrientDBDataSourceGraphProvider() @Test fun shouldFetchAllVerticesAndEdges() { val docs = ArrayList() - val indexer = object : SpritePlayer { - override fun begin() { - } + val indexer = + object : SpritePlayer { + override fun begin() { + } - override fun end() { - } + override fun end() { + } - override fun play(document: Sprite) { - docs.add(document) - assertThat(document.valuesOf("@class")).doesNotContain("V", "E") + override fun play(document: Sprite) { + docs.add(document) + assertThat(document.valuesOf("@class")).doesNotContain("V", "E") + } } - } provider.provideTo(OrientDBContainer.dataSource, indexer) diff --git a/orientdb2/src/test/kotlin/com/arcadeanalytics/provider/orient2/OrientDBDataSourceMetadataProviderTest.kt b/orientdb2/src/test/kotlin/com/arcadeanalytics/provider/orient2/OrientDBDataSourceMetadataProviderTest.kt index 0fd8997b..ab3f352f 100644 --- a/orientdb2/src/test/kotlin/com/arcadeanalytics/provider/orient2/OrientDBDataSourceMetadataProviderTest.kt +++ b/orientdb2/src/test/kotlin/com/arcadeanalytics/provider/orient2/OrientDBDataSourceMetadataProviderTest.kt @@ -25,7 +25,6 @@ import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class OrientDBDataSourceMetadataProviderTest { - private val provider: OrientDBDataSourceMetadataProvider = OrientDBDataSourceMetadataProvider() @Test diff --git a/orientdb2/src/test/kotlin/com/arcadeanalytics/provider/orient2/OrientDBTestHelper.kt b/orientdb2/src/test/kotlin/com/arcadeanalytics/provider/orient2/OrientDBTestHelper.kt index e6ff9dd0..7adb20f1 100644 --- a/orientdb2/src/test/kotlin/com/arcadeanalytics/provider/orient2/OrientDBTestHelper.kt +++ b/orientdb2/src/test/kotlin/com/arcadeanalytics/provider/orient2/OrientDBTestHelper.kt @@ -35,14 +35,14 @@ val ORIENTDB_DOCKER_IMAGE = DockerImageName.parse("orientdb:2.2.37-spatial") const val ORIENTDB_ROOT_PASSWORD = "arcade" object OrientDBContainer { - - private val container: KGenericContainer = KGenericContainer(ORIENTDB_DOCKER_IMAGE) - .apply { - withExposedPorts(2424) - withEnv("ORIENTDB_ROOT_PASSWORD", ORIENTDB_ROOT_PASSWORD) - waitingFor(Wait.forListeningPort()) - start() - } + private val container: KGenericContainer = + KGenericContainer(ORIENTDB_DOCKER_IMAGE) + .apply { + withExposedPorts(2424) + withEnv("ORIENTDB_ROOT_PASSWORD", ORIENTDB_ROOT_PASSWORD) + waitingFor(Wait.forListeningPort()) + start() + } val dataSource: DataSourceInfo @@ -50,16 +50,17 @@ object OrientDBContainer { init { - dataSource = DataSourceInfo( - id = 1L, - type = "ORIENTDB", - name = "testDataSource", - server = container.containerIpAddress, - port = container.firstMappedPort, - username = "admin", - password = "admin", - database = "testDatabase", - ) + dataSource = + DataSourceInfo( + id = 1L, + type = "ORIENTDB", + name = "testDataSource", + server = container.containerIpAddress, + port = container.firstMappedPort, + username = "admin", + password = "admin", + database = "testDatabase", + ) val serverUrl = getServerUrl(container) @@ -75,9 +76,7 @@ object OrientDBContainer { * @param container * @return */ -fun getServerUrl(container: GenericContainer<*>): String { - return "remote:${container.getContainerIpAddress()}:${container.getMappedPort(2424)}" -} +fun getServerUrl(container: GenericContainer<*>): String = "remote:${container.getContainerIpAddress()}:${container.getMappedPort(2424)}" /** * Given an OrientDB's database url, creates the Person schema and fills it with samples data @@ -88,35 +87,36 @@ fun createPersonSchema(dbUrl: String) { ODatabaseDocumentTx(dbUrl) .open("admin", "admin") .use { - it.command( - OCommandScript( - "sql", - """ - - CREATE CLASS Person EXTENDS V; - - CREATE PROPERTY Person.name STRING; - CREATE PROPERTY Person.age INTEGER; - CREATE INDEX Person.name ON Person(name) UNIQUE; - - CREATE CLASS FriendOf EXTENDS E; - CREATE PROPERTY FriendOf.kind STRING; - - CREATE CLASS HaterOf EXTENDS E; - CREATE PROPERTY HaterOf.kind STRING; - - INSERT INTO Person SET name='rob', age='45'; - INSERT INTO Person SET name='frank', age='45'; - INSERT INTO Person SET name='john', age='35'; - INSERT INTO Person SET name='jane', age='34'; - - CREATE EDGE FriendOf FROM (SELECT FROM Person WHERE name = 'rob') TO (SELECT FROM Person WHERE name = 'frank') set kind='fraternal'; - CREATE EDGE FriendOf FROM (SELECT FROM Person WHERE name = 'john') TO (SELECT FROM Person WHERE name = 'jane') set kind='fraternal'; - CREATE EDGE HaterOf FROM (SELECT FROM Person WHERE name = 'jane') TO (SELECT FROM Person WHERE name = 'rob') set kind='killer'; - CREATE EDGE HaterOf FROM (SELECT FROM Person WHERE name = 'frank') TO (SELECT FROM Person WHERE name = 'john') set kind='killer'; - """.trimIndent(), - ), - ).execute() + it + .command( + OCommandScript( + "sql", + """ + + CREATE CLASS Person EXTENDS V; + + CREATE PROPERTY Person.name STRING; + CREATE PROPERTY Person.age INTEGER; + CREATE INDEX Person.name ON Person(name) UNIQUE; + + CREATE CLASS FriendOf EXTENDS E; + CREATE PROPERTY FriendOf.kind STRING; + + CREATE CLASS HaterOf EXTENDS E; + CREATE PROPERTY HaterOf.kind STRING; + + INSERT INTO Person SET name='rob', age='45'; + INSERT INTO Person SET name='frank', age='45'; + INSERT INTO Person SET name='john', age='35'; + INSERT INTO Person SET name='jane', age='34'; + + CREATE EDGE FriendOf FROM (SELECT FROM Person WHERE name = 'rob') TO (SELECT FROM Person WHERE name = 'frank') set kind='fraternal'; + CREATE EDGE FriendOf FROM (SELECT FROM Person WHERE name = 'john') TO (SELECT FROM Person WHERE name = 'jane') set kind='fraternal'; + CREATE EDGE HaterOf FROM (SELECT FROM Person WHERE name = 'jane') TO (SELECT FROM Person WHERE name = 'rob') set kind='killer'; + CREATE EDGE HaterOf FROM (SELECT FROM Person WHERE name = 'frank') TO (SELECT FROM Person WHERE name = 'john') set kind='killer'; + """.trimIndent(), + ), + ).execute() } } @@ -126,7 +126,10 @@ fun createPersonSchema(dbUrl: String) { * @param serverUrl * @return */ -fun createTestDatabase(serverUrl: String, dbname: String): String { +fun createTestDatabase( + serverUrl: String, + dbname: String, +): String { try { OServerAdmin(serverUrl) .apply { diff --git a/orientdb3/src/main/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceGraphDataProvider.kt b/orientdb3/src/main/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceGraphDataProvider.kt index 99d127f6..683ec4c7 100644 --- a/orientdb3/src/main/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceGraphDataProvider.kt +++ b/orientdb3/src/main/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceGraphDataProvider.kt @@ -48,7 +48,6 @@ import org.slf4j.LoggerFactory * Specialized provider for OrientDB 3.0.x */ class OrientDB3DataSourceGraphDataProvider : DataSourceGraphDataProvider { - private val log = LoggerFactory.getLogger(OrientDB3DataSourceGraphDataProvider::class.java) override fun supportedDataSourceTypes(): Set = setOf("ORIENTDB3") @@ -69,7 +68,11 @@ class OrientDB3DataSourceGraphDataProvider : DataSourceGraphDataProvider { } } - override fun fetchData(dataSource: DataSourceInfo, query: String, limit: Int): GraphData { + override fun fetchData( + dataSource: DataSourceInfo, + query: String, + limit: Int, + ): GraphData { log.info("fetching data from '{}' with query '{}' ", dataSource.id, query) open(dataSource) @@ -77,7 +80,8 @@ class OrientDB3DataSourceGraphDataProvider : DataSourceGraphDataProvider { val lang = if (query.startsWith("gremlin:")) "gremlin" else "sql" - db.execute(lang, query.removePrefix("gremlin:")) + db + .execute(lang, query.removePrefix("gremlin:")) .use { resultSet -> val data = mapResultSet(dataSource, resultSet) log.info("Fetched {} nodes and {} edges ", data.nodes.size, data.edges.size) @@ -87,24 +91,25 @@ class OrientDB3DataSourceGraphDataProvider : DataSourceGraphDataProvider { } private fun toCytoData(element: OElement): CytoData { - var record: MutableMap = when { - element.isVertex -> transformToMap(element as OVertexDocument) - else -> transformToMap(element as OEdgeDocument) - } + var record: MutableMap = + when { + element.isVertex -> transformToMap(element as OVertexDocument) + else -> transformToMap(element as OEdgeDocument) + } val ins = HashMap() record["@in"] = ins val outs = HashMap() record["@out"] = outs - val keys = record.entries - .asSequence() - .filter { e -> e.key.startsWith("in_") } - .map { e -> - ins[removeFirst(e.key, "in_")] = e.value - e.key - } - .toMutableSet() + val keys = + record.entries + .asSequence() + .filter { e -> e.key.startsWith("in_") } + .map { e -> + ins[removeFirst(e.key, "in_")] = e.value + e.key + }.toMutableSet() keys.addAll( record.entries @@ -116,7 +121,8 @@ class OrientDB3DataSourceGraphDataProvider : DataSourceGraphDataProvider { }.toSet(), ) - keys.asSequence() + keys + .asSequence() .forEach { k -> record.remove(k) } cleanRecord(record) @@ -187,7 +193,10 @@ class OrientDB3DataSourceGraphDataProvider : DataSourceGraphDataProvider { return map } - private fun mapField(doc: ODocument, fieldName: String): Any { + private fun mapField( + doc: ODocument, + fieldName: String, + ): Any { val type = doc.fieldType(fieldName) if (type.isEmbedded) { @@ -197,11 +206,15 @@ class OrientDB3DataSourceGraphDataProvider : DataSourceGraphDataProvider { return doc.field(fieldName) } - fun mapResultSet(dataSource: DataSourceInfo, resultSet: OResultSet): GraphData { + fun mapResultSet( + dataSource: DataSourceInfo, + resultSet: OResultSet, + ): GraphData { // DIVIDE VERTICES FROM EDGES val nodes = mutableSetOf() val edges = mutableSetOf() - resultSet.asSequence() + resultSet + .asSequence() .onEach { res -> log.info(res.toJSON()) } .map { res -> res.element.get() } .forEach { element -> @@ -220,24 +233,28 @@ class OrientDB3DataSourceGraphDataProvider : DataSourceGraphDataProvider { log.info("Computing edge map on {} edges...", edges.size) val edgeClasses = HashMap>() - val cytoEdges = edges.asSequence() - .filter { e -> nodes.contains(e.from) && nodes.contains(e.to) } - .map { e -> populateClasses(edgeClasses, e) } - .map { e -> mapRid(dataSource, e) } - .map { e -> mapInAndOut(dataSource, e) } - .map { e -> countInAndOut(e) } - .map { e -> toCytoData(e) } - .toSet() + val cytoEdges = + edges + .asSequence() + .filter { e -> nodes.contains(e.from) && nodes.contains(e.to) } + .map { e -> populateClasses(edgeClasses, e) } + .map { e -> mapRid(dataSource, e) } + .map { e -> mapInAndOut(dataSource, e) } + .map { e -> countInAndOut(e) } + .map { e -> toCytoData(e) } + .toSet() log.info("Computing vertex map on {} vertices...", nodes.size) val nodeClasses = HashMap>() - val cytoNodes = nodes.asSequence() - .map { v -> populateClasses(nodeClasses, v) } - .map { v -> mapRid(dataSource, v) } - .map { v -> countInAndOut(v) } - .map { v -> toCytoData(v) } - .toSet() + val cytoNodes = + nodes + .asSequence() + .map { v -> populateClasses(nodeClasses, v) } + .map { v -> mapRid(dataSource, v) } + .map { v -> countInAndOut(v) } + .map { v -> toCytoData(v) } + .toSet() return GraphData(nodeClasses, edgeClasses, cytoNodes, cytoEdges, false) } @@ -245,7 +262,8 @@ class OrientDB3DataSourceGraphDataProvider : DataSourceGraphDataProvider { private fun countInAndOut(element: OElement): OElement { if (element.isVertex) { element as OVertexDocument - element.fieldNames() + element + .fieldNames() .asSequence() .filter { f -> f.startsWith("out_") || f.startsWith("in_") } .forEach { f -> @@ -255,7 +273,8 @@ class OrientDB3DataSourceGraphDataProvider : DataSourceGraphDataProvider { } } else { element as OEdgeDocument - element.fieldNames() + element + .fieldNames() .asSequence() .filter { f -> f.startsWith("out_") || f.startsWith("in_") } .forEach { f -> @@ -268,7 +287,10 @@ class OrientDB3DataSourceGraphDataProvider : DataSourceGraphDataProvider { return element } - private fun mapInAndOut(dataSource: DataSourceInfo, element: OElement): OElement { + private fun mapInAndOut( + dataSource: DataSourceInfo, + element: OElement, + ): OElement { element as OEdgeDocument if (!element.containsField("out")) { @@ -286,7 +308,10 @@ class OrientDB3DataSourceGraphDataProvider : DataSourceGraphDataProvider { return element } - private fun mapRid(dataSource: DataSourceInfo, doc: OElement): OElement { + private fun mapRid( + dataSource: DataSourceInfo, + doc: OElement, + ): OElement { val rid = doc.identity doc.setProperty("@id", "${dataSource.id}_${rid.clusterId}_${rid.clusterPosition}") @@ -294,7 +319,10 @@ class OrientDB3DataSourceGraphDataProvider : DataSourceGraphDataProvider { return doc } - private fun populateClasses(classes: MutableMap>, element: OElement): OElement { + private fun populateClasses( + classes: MutableMap>, + element: OElement, + ): OElement { classes.putIfAbsent(element.schemaType.get().toString(), Maps.newHashMap()) populateProperties(classes, element as ODocument) @@ -302,7 +330,10 @@ class OrientDB3DataSourceGraphDataProvider : DataSourceGraphDataProvider { return element } - private fun populateProperties(classes: Map>, vertex: ODocument) { + private fun populateProperties( + classes: Map>, + vertex: ODocument, + ) { val properties = classes[vertex.schemaType.get().toString()] vertex.propertyNames @@ -317,8 +348,7 @@ class OrientDB3DataSourceGraphDataProvider : DataSourceGraphDataProvider { propertyType != OType.LINKSET && propertyType != OType.LINKLIST && propertyType != OType.LINKBAG - } - .forEach { f -> + }.forEach { f -> val type = vertex.fieldType(f) if (type != null) { (properties as MutableMap).putIfAbsent(f, mapType(type.name)) @@ -372,7 +402,10 @@ class OrientDB3DataSourceGraphDataProvider : DataSourceGraphDataProvider { return fetchData(dataSource, query, 10000) } - override fun load(dataSource: DataSourceInfo, ids: Array): GraphData { + override fun load( + dataSource: DataSourceInfo, + ids: Array, + ): GraphData { var query = "SELECT FROM [" query += cleanIds(dataSource, ids) @@ -382,20 +415,32 @@ class OrientDB3DataSourceGraphDataProvider : DataSourceGraphDataProvider { return fetchData(dataSource, query, ids.size) } - private fun cleanIds(dataSource: DataSourceInfo, ids: Array): String { - return ids + private fun cleanIds( + dataSource: DataSourceInfo, + ids: Array, + ): String = + ids .asSequence() .map { r -> r.removePrefix("${dataSource.id}_") } .map { r -> "#" + r.replace('_', ':') } .joinToString { it } - } - override fun loadFromClass(dataSource: DataSourceInfo, className: String, limit: Int): GraphData { + override fun loadFromClass( + dataSource: DataSourceInfo, + className: String, + limit: Int, + ): GraphData { val query = "select * from `$className` limit $limit" return fetchData(dataSource, query, limit) } - override fun loadFromClass(dataSource: DataSourceInfo, className: String, propName: String, propertyValue: String, limit: Int): GraphData { + override fun loadFromClass( + dataSource: DataSourceInfo, + className: String, + propName: String, + propertyValue: String, + limit: Int, + ): GraphData { val query = "select * from `$className` where `$propName` = '$propertyValue' limit $limit" return fetchData(dataSource, query, limit) } diff --git a/orientdb3/src/main/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceGraphProvider.kt b/orientdb3/src/main/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceGraphProvider.kt index aa06e9ca..47f03368 100644 --- a/orientdb3/src/main/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceGraphProvider.kt +++ b/orientdb3/src/main/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceGraphProvider.kt @@ -33,20 +33,20 @@ import org.slf4j.LoggerFactory import java.util.regex.Pattern class OrientDB3DataSourceGraphProvider : DataSourceGraphProvider { - private val log = LoggerFactory.getLogger(OrientDB3DataSourceGraphProvider::class.java) - private val V_COUNT = "select count(*) as count from V" + private val vertexCount = "select count(*) as count from V" - private val E_COUNT = "select count(*) as count from E" + private val edgeCount = "select count(*) as count from E" private val allFields: Pattern = Pattern.compile(".*") - override fun supportedDataSourceTypes(): Set { - return setOf("ORIENTDB3") - } + override fun supportedDataSourceTypes(): Set = setOf("ORIENTDB3") - override fun provideTo(dataSource: DataSourceInfo, player: SpritePlayer) { + override fun provideTo( + dataSource: DataSourceInfo, + player: SpritePlayer, + ) { try { provide(dataSource, player, "V") provide(dataSource, player, "E") @@ -55,12 +55,17 @@ class OrientDB3DataSourceGraphProvider : DataSourceGraphProvider { } } - private fun provide(dataSource: DataSourceInfo, player: SpritePlayer, what: String) { - val count: Long = open(dataSource).use { db -> - db.query("select count(*) as count from $what").use { result -> - result.asSequence().first().getProperty("count") + private fun provide( + dataSource: DataSourceInfo, + player: SpritePlayer, + what: String, + ) { + val count: Long = + open(dataSource).use { db -> + db.query("select count(*) as count from $what").use { result -> + result.asSequence().first().getProperty("count") + } } - } var fetched: Long = 0 var skip: ORID = ORecordId("#-1:-1") @@ -71,7 +76,8 @@ class OrientDB3DataSourceGraphProvider : DataSourceGraphProvider { while (fetched < count) { open(dataSource).use { db -> db.query("SELECT * FROM $what WHERE @rid > $skip LIMIT 1000").use { resultSet -> - resultSet.asSequence() + resultSet + .asSequence() .map { res -> res.element.get() } .filter { elem -> elem.propertyNames.size > 0 } .onEach { elem: OElement -> lastORID = elem.identity } @@ -101,8 +107,7 @@ class OrientDB3DataSourceGraphProvider : DataSourceGraphProvider { .asSequence() .map { c -> c.name } .toList(), - ) - .apply(allFields) { v -> v.toString() } + ).apply(allFields) { v -> v.toString() } .remove("@class", "V") .remove("@class", "E") .remove("@rid") diff --git a/orientdb3/src/main/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceMetadataProvider.kt b/orientdb3/src/main/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceMetadataProvider.kt index 97fc96d9..1d89b2c3 100644 --- a/orientdb3/src/main/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceMetadataProvider.kt +++ b/orientdb3/src/main/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceMetadataProvider.kt @@ -32,8 +32,7 @@ import com.orientechnologies.orient.core.metadata.schema.OClass import com.orientechnologies.orient.core.metadata.schema.OSchema import org.slf4j.LoggerFactory -class OrientDB3DataSourceMetadataProvider() : DataSourceMetadataProvider { - +class OrientDB3DataSourceMetadataProvider : DataSourceMetadataProvider { private val log = LoggerFactory.getLogger(OrientDB3DataSourceMetadataProvider::class.java) override fun fetchMetadata(dataSource: DataSourceInfo): DataSourceMetadata { @@ -50,28 +49,38 @@ class OrientDB3DataSourceMetadataProvider() : DataSourceMetadataProvider { } } - private fun edgeClasses(schema: OSchema, db: ODatabaseSession): EdgesClasses { - return schema.classes + private fun edgeClasses( + schema: OSchema, + db: ODatabaseSession, + ): EdgesClasses = + schema.classes .asSequence() .filter { isEdgeType(it) } .map { mapToType(it, db) } .map { it.name to it } .toMap() - } - private fun nodeClasses(schema: OSchema, db: ODatabaseSession): NodesClasses { - return schema.classes + private fun nodeClasses( + schema: OSchema, + db: ODatabaseSession, + ): NodesClasses = + schema.classes .asSequence() .filter { isVertexType(it) } .map { mapToType(it, db) } - .map { it.name to it }.toMap() - } - - private fun mapToType(oClass: OClass, db: ODatabaseSession): TypeClass { - val props: TypeProperties = oClass.properties() - .map { prop -> prop.name to TypeProperty(prop.name, prop.type.name) } + .map { it.name to it } .toMap() + private fun mapToType( + oClass: OClass, + db: ODatabaseSession, + ): TypeClass { + val props: TypeProperties = + oClass + .properties() + .map { prop -> prop.name to TypeProperty(prop.name, prop.type.name) } + .toMap() + return TypeClass(oClass.name, db.countClass(oClass.name, true), props) } diff --git a/orientdb3/src/main/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceTableDataProvider.kt b/orientdb3/src/main/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceTableDataProvider.kt index 69d9b2d4..8094d803 100644 --- a/orientdb3/src/main/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceTableDataProvider.kt +++ b/orientdb3/src/main/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceTableDataProvider.kt @@ -39,20 +39,29 @@ import org.slf4j.LoggerFactory * Specialized provider for OrientDB 3.0.x */ class OrientDB3DataSourceTableDataProvider : DataSourceTableDataProvider { - private val log = LoggerFactory.getLogger(OrientDB3DataSourceTableDataProvider::class.java) override fun supportedDataSourceTypes(): Set = setOf(ORIENTDB3) - override fun fetchData(dataSource: DataSourceInfo, query: String, params: QueryParams, limit: Int): GraphData { + override fun fetchData( + dataSource: DataSourceInfo, + query: String, + params: QueryParams, + limit: Int, + ): GraphData { var filledQuery = query - params.asSequence() + params + .asSequence() .forEach { p -> filledQuery = filledQuery.replace("${p.name.prefixIfAbsent(":")}", p.value) } return fetchData(dataSource, filledQuery, limit) } - override fun fetchData(dataSource: DataSourceInfo, query: String, limit: Int): GraphData { + override fun fetchData( + dataSource: DataSourceInfo, + query: String, + limit: Int, + ): GraphData { log.info("fetching data from '{}' with query '{}' ", dataSource.id, truncate(query, 256)) open(dataSource) @@ -60,7 +69,8 @@ class OrientDB3DataSourceTableDataProvider : DataSourceTableDataProvider { val lang = if (query.startsWith("gremlin:")) "gremlin" else "sql" - db.execute(lang, query.removePrefix("gremlin:")) + db + .execute(lang, query.removePrefix("gremlin:")) .use { resultSet -> val data = mapResultSet(resultSet) @@ -76,10 +86,12 @@ class OrientDB3DataSourceTableDataProvider : DataSourceTableDataProvider { val nodesProperties = mutableMapOf() var count: Long = 0 - val cytoNodes = resultSet.asSequence() - .map { v -> populateProperties(nodesProperties, v) } - .map { v -> toCytoData(v, count++) } - .toSet() + val cytoNodes = + resultSet + .asSequence() + .map { v -> populateProperties(nodesProperties, v) } + .map { v -> toCytoData(v, count++) } + .toSet() log.debug("properties:: {} ", nodesProperties) val tableClass = mutableMapOf() @@ -96,28 +108,35 @@ class OrientDB3DataSourceTableDataProvider : DataSourceTableDataProvider { return GraphData(nodeClasses, edgeClasses, cytoNodes, cytoEdges) } - private fun populateProperties(properties: MutableMap, element: OResult): OResult { - val props = element.propertyNames - .asSequence() - .filter { name -> !properties.containsKey(name) } - .filter { p -> !p.startsWith("@") } - .filter { p -> !p.startsWith("in_") } - .filter { p -> !p.startsWith("out_") } - .map { name -> + private fun populateProperties( + properties: MutableMap, + element: OResult, + ): OResult { + val props = + element.propertyNames + .asSequence() + .filter { name -> !properties.containsKey(name) } + .filter { p -> !p.startsWith("@") } + .filter { p -> !p.startsWith("in_") } + .filter { p -> !p.startsWith("out_") } + .map { name -> - val property = element.getProperty(name) + val property = element.getProperty(name) - val type = property.javaClass.simpleName + val type = property.javaClass.simpleName - name to TypeProperty(name, type) - }.toMap() + name to TypeProperty(name, type) + }.toMap() properties.putAll(props) return element } - private fun toCytoData(element: OResult, index: Long): CytoData { + private fun toCytoData( + element: OResult, + index: Long, + ): CytoData { val record: MutableMap = transformToMap(element) cleanRecord(record) @@ -139,7 +158,8 @@ class OrientDB3DataSourceTableDataProvider : DataSourceTableDataProvider { private fun transformToMap(doc: OResult): MutableMap { val record = HashMap() - doc.propertyNames.asSequence() + doc.propertyNames + .asSequence() .filter { p -> !p.startsWith("@") } .filter { p -> !p.startsWith("in_") } .filter { p -> !p.startsWith("out_") } @@ -150,8 +170,7 @@ class OrientDB3DataSourceTableDataProvider : DataSourceTableDataProvider { propertyType != OType.LINKLIST || propertyType != OType.LINKSET || propertyType != OType.LINKMAP - } - .filter { property -> doc.getProperty(property) != null } + }.filter { property -> doc.getProperty(property) != null } .forEach { property -> var value = doc.getProperty(property) @@ -159,9 +178,10 @@ class OrientDB3DataSourceTableDataProvider : DataSourceTableDataProvider { record[property] = value } - record[ODocumentHelper.ATTRIBUTE_RID] = doc.identity - .filter { id -> id.isValid } - .map { id -> id.toString() } + record[ODocumentHelper.ATTRIBUTE_RID] = + doc.identity + .filter { id -> id.isValid } + .map { id -> id.toString() } record[ODocumentHelper.ATTRIBUTE_CLASS] = TABLE_CLASS diff --git a/orientdb3/src/main/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3Utils.kt b/orientdb3/src/main/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3Utils.kt index a88ab3f1..547054d7 100644 --- a/orientdb3/src/main/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3Utils.kt +++ b/orientdb3/src/main/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3Utils.kt @@ -37,10 +37,10 @@ const val ORIENTDB3 = "ORIENTDB3" private val orientdbConnectionUrl = "remote:{server}:{port}" -fun createOrientdbConnectionUrl(dataSource: DataSourceInfo): String { - return orientdbConnectionUrl.replace("{server}", dataSource.server) +fun createOrientdbConnectionUrl(dataSource: DataSourceInfo): String = + orientdbConnectionUrl + .replace("{server}", dataSource.server) .replace("{port}", dataSource.port.toString()) -} fun open(dataSource: DataSourceInfo): ODatabaseSession { val orientdbConnectionUrl = createOrientdbConnectionUrl(dataSource) @@ -72,16 +72,13 @@ fun ODatabaseDocument.getEdge(document: ODocument): Optional? { return result.asSequence().first().edge } -fun ODocument.isEdgeType(): Boolean { - return this.schemaClass.isEdgeType -} +fun ODocument.isEdgeType(): Boolean = this.schemaClass.isEdgeType -fun ODocument.isVertexType(): Boolean { - return this.schemaClass.isVertexType -} +fun ODocument.isVertexType(): Boolean = this.schemaClass.isVertexType -fun ODocument.type(): String = when { - isEdgeType() -> "edge" - isVertexType() -> "node" - else -> "document" -} +fun ODocument.type(): String = + when { + isEdgeType() -> "edge" + isVertexType() -> "node" + else -> "document" + } diff --git a/orientdb3/src/test/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3ConnectionTest.kt b/orientdb3/src/test/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3ConnectionTest.kt index 69e60318..e3750239 100644 --- a/orientdb3/src/test/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3ConnectionTest.kt +++ b/orientdb3/src/test/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3ConnectionTest.kt @@ -25,12 +25,12 @@ import org.junit.jupiter.api.Test import org.testcontainers.containers.OrientDBContainer class OrientDB3ConnectionTest { - - private val container = OrientDBContainer(ORIENTDB_DOCKER_IMAGE) - .withServerPassword(ORIENTDB_ROOT_PASSWORD) - .apply { - start() - } + private val container = + OrientDBContainer(ORIENTDB_DOCKER_IMAGE) + .withServerPassword(ORIENTDB_ROOT_PASSWORD) + .apply { + start() + } private val provider: OrientDB3DataSourceGraphDataProvider @@ -38,16 +38,17 @@ class OrientDB3ConnectionTest { init { - dataSource = DataSourceInfo( - id = 1L, - type = "ORIENTDB", - name = "testDataSource", - server = container.containerIpAddress, - port = container.firstMappedPort, - username = "admin", - password = "admin", - database = OrientDB3DataSourceGraphDataProviderIntTest::class.java.simpleName, - ) + dataSource = + DataSourceInfo( + id = 1L, + type = "ORIENTDB", + name = "testDataSource", + server = container.containerIpAddress, + port = container.firstMappedPort, + username = "admin", + password = "admin", + database = OrientDB3DataSourceGraphDataProviderIntTest::class.java.simpleName, + ) val dbUrl = createTestDatabase(container.serverUrl, dataSource.database) @@ -62,7 +63,8 @@ class OrientDB3ConnectionTest { container.stop() - Assertions.assertThatExceptionOfType(RuntimeException::class.java) + Assertions + .assertThatExceptionOfType(RuntimeException::class.java) .isThrownBy { provider.testConnection(dataSource) } } } diff --git a/orientdb3/src/test/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceGraphDataProviderIntTest.kt b/orientdb3/src/test/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceGraphDataProviderIntTest.kt index 13568db5..dd3d8ab7 100644 --- a/orientdb3/src/test/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceGraphDataProviderIntTest.kt +++ b/orientdb3/src/test/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceGraphDataProviderIntTest.kt @@ -27,7 +27,6 @@ import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class OrientDB3DataSourceGraphDataProviderIntTest { - private val provider: OrientDB3DataSourceGraphDataProvider = OrientDB3DataSourceGraphDataProvider() @Test @@ -53,7 +52,8 @@ class OrientDB3DataSourceGraphDataProviderIntTest { assertThat(cytoData.data.source).isEmpty() val record = cytoData.data.record - assertThat(record).isNotNull + assertThat(record) + .isNotNull .containsKeys("name", "@out", "@in", "@edgeCount") } @@ -80,7 +80,8 @@ class OrientDB3DataSourceGraphDataProviderIntTest { assertThat(cytoData.data.source).isEmpty() val record = cytoData.data.record - assertThat(record).isNotNull + assertThat(record) + .isNotNull .containsKeys("name", "@out", "@in", "@edgeCount") } @@ -102,7 +103,11 @@ class OrientDB3DataSourceGraphDataProviderIntTest { assertThat(data.nodesClasses).containsKeys("Person") assertThat(data.edgesClasses).containsKeys("FriendOf") - val cytoData = data.nodes.stream().findFirst().get() + val cytoData = + data.nodes + .stream() + .findFirst() + .get() assertThat(cytoData.data.record).isNotNull assertThat(cytoData.data.source).isEmpty() } @@ -127,7 +132,11 @@ class OrientDB3DataSourceGraphDataProviderIntTest { assertThat(data.edgesClasses).containsKeys("FriendOf") assertThat(data.edgesClasses).containsKeys("HaterOf") - val cytoData = data.nodes.stream().findFirst().get() + val cytoData = + data.nodes + .stream() + .findFirst() + .get() assertThat(cytoData.data.record).isNotNull assertThat(cytoData.data.source).isEmpty() } @@ -145,7 +154,11 @@ class OrientDB3DataSourceGraphDataProviderIntTest { // then assertThat(data.nodes).hasSize(2) - val cytoData = data.nodes.stream().findFirst().get() + val cytoData = + data.nodes + .stream() + .findFirst() + .get() assertThat(cytoData.data.record).isNotNull assertThat(cytoData.data.source).isEmpty() } @@ -175,10 +188,12 @@ class OrientDB3DataSourceGraphDataProviderIntTest { val firstNode = firstDataSet.nodes.first().data val secondNode = secondDataSet.nodes.first().data - val edgeClasses = (firstNode.record["@in"] as Map).keys - .union((firstNode.record["@out"] as Map).keys) - .union((secondNode.record["@in"] as Map).keys) - .union((secondNode.record["@out"] as Map).keys) + val edgeClasses = + (firstNode.record["@in"] as Map) + .keys + .union((firstNode.record["@out"] as Map).keys) + .union((secondNode.record["@in"] as Map).keys) + .union((secondNode.record["@out"] as Map).keys) val data = provider.edges(dataSource, arrayOf(firstNode.id), edgeClasses.toTypedArray(), arrayOf(secondNode.id)) @@ -193,9 +208,11 @@ class OrientDB3DataSourceGraphDataProviderIntTest { private fun getPersonsIdentity(count: Int): Array { val orientDB = OrientDB(getServerUrl(OrientDB3Container.getContainer()), OrientDBConfig.defaultConfig()) - orientDB.open(dataSource.database, "admin", "admin") + orientDB + .open(dataSource.database, "admin", "admin") .use { - return it.execute("sql", "SELECT from Person") + return it + .execute("sql", "SELECT from Person") .asSequence() .take(count) .map { doc -> doc.identity } diff --git a/orientdb3/src/test/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceGraphProviderIntTest.kt b/orientdb3/src/test/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceGraphProviderIntTest.kt index fe29121d..b38e7901 100644 --- a/orientdb3/src/test/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceGraphProviderIntTest.kt +++ b/orientdb3/src/test/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceGraphProviderIntTest.kt @@ -33,25 +33,25 @@ import java.util.ArrayList @TestInstance(TestInstance.Lifecycle.PER_CLASS) class OrientDB3DataSourceGraphProviderIntTest { - private val provider: OrientDB3DataSourceGraphProvider = OrientDB3DataSourceGraphProvider() @Test fun shouldFetchAllVerticesAndEdges() { val docs = ArrayList() - val indexer = object : SpritePlayer { - override fun begin() { - } + val indexer = + object : SpritePlayer { + override fun begin() { + } - override fun end() { - } + override fun end() { + } - override fun play(document: Sprite) { - docs.add(document) - assertThat(document.valuesOf("@class")).doesNotContain("V", "E") + override fun play(document: Sprite) { + docs.add(document) + assertThat(document.valuesOf("@class")).doesNotContain("V", "E") + } } - } provider.provideTo(OrientDB3Container.dataSource, indexer) diff --git a/orientdb3/src/test/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceMetadataProviderTest.kt b/orientdb3/src/test/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceMetadataProviderTest.kt index 76492dcb..cf8a5a35 100644 --- a/orientdb3/src/test/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceMetadataProviderTest.kt +++ b/orientdb3/src/test/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceMetadataProviderTest.kt @@ -24,7 +24,6 @@ import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class OrientDB3DataSourceMetadataProviderTest { - private val provider: OrientDB3DataSourceMetadataProvider = OrientDB3DataSourceMetadataProvider() @Test diff --git a/orientdb3/src/test/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceTableDataProviderTest.kt b/orientdb3/src/test/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceTableDataProviderTest.kt index 923b1fbb..5e0d4a60 100644 --- a/orientdb3/src/test/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceTableDataProviderTest.kt +++ b/orientdb3/src/test/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3DataSourceTableDataProviderTest.kt @@ -28,7 +28,6 @@ import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Test internal class OrientDB3DataSourceTableDataProviderTest { - private val provider: OrientDB3DataSourceTableDataProvider = OrientDB3DataSourceTableDataProvider() @Test @@ -119,12 +118,21 @@ internal class OrientDB3DataSourceTableDataProviderTest { fun shouldFetchDataWithAggregateParametrizedQuery() { // when - var query = "select avg(age) as age, count(name) as count from Person where age < :age group by age order by count desc limit :limit " - - val params: QueryParams = listOf( - QueryParam("age", "query", "(SELECT age FROM Person WHERE name ='rob')"), - QueryParam("limit", "single", "1"), - ) + val query = + """ + select avg(age) as age, count(name) as count + from Person + where age < :age + group by age + order by count desc + limit :limit + """.trimIndent() + + val params: QueryParams = + listOf( + QueryParam("age", "query", "(SELECT age FROM Person WHERE name ='rob')"), + QueryParam("limit", "single", "1"), + ) val data = provider.fetchData(OrientDB3Container.dataSource, query, params, 20) diff --git a/orientdb3/src/test/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3TestHelper.kt b/orientdb3/src/test/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3TestHelper.kt index 5a832d8e..5d599296 100644 --- a/orientdb3/src/test/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3TestHelper.kt +++ b/orientdb3/src/test/kotlin/com/arcadeanalytics/provider/orient3/OrientDB3TestHelper.kt @@ -29,29 +29,32 @@ import org.testcontainers.containers.OrientDBContainer import org.testcontainers.utility.DockerImageName import java.io.IOException -val ORIENTDB_DOCKER_IMAGE = DockerImageName.parse("arcadeanalytics/orientdb3:latest") - .asCompatibleSubstituteFor("orientdb") +val ORIENTDB_DOCKER_IMAGE = + DockerImageName + .parse("arcadeanalytics/orientdb3:latest") + .asCompatibleSubstituteFor("orientdb") const val ORIENTDB_ROOT_PASSWORD = "arcade" object OrientDB3Container { - - private val container = OrientDBContainer(ORIENTDB_DOCKER_IMAGE) - .withServerPassword(ORIENTDB_ROOT_PASSWORD) - .apply { - start() - } - - val dataSource: DataSourceInfo = DataSourceInfo( - id = 1L, - type = "ORIENTDB", - name = "testDataSource", - server = container.containerIpAddress, - port = container.firstMappedPort, - username = "admin", - password = "admin", - database = "testDatabase", - ) + private val container = + OrientDBContainer(ORIENTDB_DOCKER_IMAGE) + .withServerPassword(ORIENTDB_ROOT_PASSWORD) + .apply { + start() + } + + val dataSource: DataSourceInfo = + DataSourceInfo( + id = 1L, + type = "ORIENTDB", + name = "testDataSource", + server = container.containerIpAddress, + port = container.firstMappedPort, + username = "admin", + password = "admin", + database = "testDatabase", + ) val dbUrl: String = createTestDatabase(container.serverUrl, dataSource.database) @@ -60,9 +63,7 @@ object OrientDB3Container { createPersonSchema(dbUrl, dataSource) } - fun getContainer(): OrientDBContainer { - return container - } + fun getContainer(): OrientDBContainer = container } /** @@ -71,45 +72,47 @@ object OrientDB3Container { * @param container * @return */ -fun getServerUrl(container: GenericContainer<*>): String { - return "remote:${container.getContainerIpAddress()}:${container.getMappedPort(2424)}" -} +fun getServerUrl(container: GenericContainer<*>): String = "remote:${container.getContainerIpAddress()}:${container.getMappedPort(2424)}" /** * Given an OrientDB's database url, creates the Person schema and fills it with samples data * * @param dbUrl */ -fun createPersonSchema(dbUrl: String, dataSource: DataSourceInfo) { +fun createPersonSchema( + dbUrl: String, + dataSource: DataSourceInfo, +) { val command: String = """ - CREATE CLASS Person EXTENDS V; + CREATE CLASS Person EXTENDS V; - CREATE PROPERTY Person.name STRING; - CREATE PROPERTY Person.age INTEGER; - CREATE INDEX Person.name ON Person(name) UNIQUE; + CREATE PROPERTY Person.name STRING; + CREATE PROPERTY Person.age INTEGER; + CREATE INDEX Person.name ON Person(name) UNIQUE; - CREATE CLASS FriendOf EXTENDS E; - CREATE PROPERTY FriendOf.kind STRING; + CREATE CLASS FriendOf EXTENDS E; + CREATE PROPERTY FriendOf.kind STRING; - CREATE CLASS HaterOf EXTENDS E; - CREATE PROPERTY HaterOf.kind STRING; + CREATE CLASS HaterOf EXTENDS E; + CREATE PROPERTY HaterOf.kind STRING; - INSERT INTO Person SET name='rob', age='45'; - INSERT INTO Person SET name='frank', age='45'; - INSERT INTO Person SET name='john', age='35'; - INSERT INTO Person SET name='jane', age='34'; + INSERT INTO Person SET name='rob', age='45'; + INSERT INTO Person SET name='frank', age='45'; + INSERT INTO Person SET name='john', age='35'; + INSERT INTO Person SET name='jane', age='34'; - CREATE EDGE FriendOf FROM (SELECT FROM Person WHERE name = 'rob') TO (SELECT FROM Person WHERE name = 'frank') set kind='fraternal'; - CREATE EDGE FriendOf FROM (SELECT FROM Person WHERE name = 'john') TO (SELECT FROM Person WHERE name = 'jane') set kind='fraternal'; - CREATE EDGE HaterOf FROM (SELECT FROM Person WHERE name = 'jane') TO (SELECT FROM Person WHERE name = 'rob') set kind='killer'; - CREATE EDGE HaterOf FROM (SELECT FROM Person WHERE name = 'frank') TO (SELECT FROM Person WHERE name = 'john') set kind='killer'; + CREATE EDGE FriendOf FROM (SELECT FROM Person WHERE name = 'rob') TO (SELECT FROM Person WHERE name = 'frank') set kind='fraternal'; + CREATE EDGE FriendOf FROM (SELECT FROM Person WHERE name = 'john') TO (SELECT FROM Person WHERE name = 'jane') set kind='fraternal'; + CREATE EDGE HaterOf FROM (SELECT FROM Person WHERE name = 'jane') TO (SELECT FROM Person WHERE name = 'rob') set kind='killer'; + CREATE EDGE HaterOf FROM (SELECT FROM Person WHERE name = 'frank') TO (SELECT FROM Person WHERE name = 'john') set kind='killer'; """.trimIndent() val orientDB = OrientDB(dbUrl, OrientDBConfig.defaultConfig()) - orientDB.open(dataSource.database, dataSource.username, dataSource.password) + orientDB + .open(dataSource.database, dataSource.username, dataSource.password) .use { it.execute("sql", command) } @@ -121,7 +124,10 @@ fun createPersonSchema(dbUrl: String, dataSource: DataSourceInfo) { * @param serverUrl * @return */ -fun createTestDatabase(serverUrl: String, dbname: String): String { +fun createTestDatabase( + serverUrl: String, + dbname: String, +): String { try { val orientDB = OrientDB(serverUrl, "root", ORIENTDB_ROOT_PASSWORD, OrientDBConfig.defaultConfig()) orientDB.create(dbname, ODatabaseType.PLOCAL) diff --git a/pom.xml b/pom.xml index 009f8841..c4b74927 100644 --- a/pom.xml +++ b/pom.xml @@ -39,7 +39,7 @@ 3.2.7 3.2.4 3.1.0 - 3.0.0-M5 + 3.1.2 3.2.0 3.8.1 0.8.6 @@ -59,8 +59,7 @@ 3.19.0 3.4.0 1.20.2 - - + 2.18.1 @@ -88,13 +87,13 @@ data common - gremlin - neo4j3 - orientdb2 - orientdb3 + + + + rdbms integration - test-coverage-aggregator + @@ -206,16 +205,16 @@ - - org.jacoco - jacoco-maven-plugin - ${jacoco-maven-plugin.version} - - - - prepare-agent - - + + + + + + + + + + @@ -224,8 +223,8 @@ - - + + org.sonatype.plugins @@ -442,6 +441,19 @@ + + + + + com.fasterxml.jackson + jackson-bom + ${jackson.version} + import + pom + + + + @@ -497,6 +509,12 @@ kotlin-test-junit ${kotlin.version} test + + + junit + junit + + org.assertj diff --git a/rdbms/pom.xml b/rdbms/pom.xml index 82c04233..f8c60d74 100644 --- a/rdbms/pom.xml +++ b/rdbms/pom.xml @@ -24,7 +24,6 @@ 42.3.8 2.7.1 0.4.4 - 2.16.1 4.0 @@ -124,7 +123,6 @@ com.fasterxml.jackson.core jackson-databind - ${jackson-databind.version} compile diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/context/MessageHandler.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/context/MessageHandler.java index fc17f675..37ead9e3 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/context/MessageHandler.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/context/MessageHandler.java @@ -23,91 +23,92 @@ import java.io.PrintStream; /** - * Implementation of PluginMessageHandler for Arcade Analytics plugin. - * It receives messages application from the application and just delegates its printing on a stream through the OutputStreamManager. + * Implementation of PluginMessageHandler for Arcade Analytics plugin. It receives messages + * application from the application and just delegates its printing on a stream through the + * OutputStreamManager. * * @author Gabriele Ponzi */ public class MessageHandler implements PluginMessageHandler { - private int level; // affects OutputStreamManager level - private OutputStreamManager outputManager; - - public MessageHandler(PrintStream outputStream, int level) { - this.level = level; - this.outputManager = new OutputStreamManager(outputStream, level); - } - - public MessageHandler(int level) { - this.level = level; - this.outputManager = new OutputStreamManager(level); - } - - public MessageHandler(OutputStreamManager outputStreamManager) { - this.outputManager = outputStreamManager; - this.level = this.outputManager.getLevel(); - } - - public OutputStreamManager getOutputManager() { - return this.outputManager; - } - - public void setOutputManager(OutputStreamManager outputManager) { - this.outputManager = outputManager; - } - - @Override - public int getOutputManagerLevel() { - return this.level; - } - - @Override - public void setOutputManagerLevel(int level) { - this.level = level; - this.updateOutputStreamManagerLevel(); - } - - private synchronized void updateOutputStreamManagerLevel() { - this.outputManager.setLevel(this.level); - } - - @Override - public synchronized void debug(Object requester, String message) { - this.outputManager.debug(message); - } - - @Override - public synchronized void debug(Object requester, String format, Object... args) { - this.outputManager.debug(format, args); - } - - @Override - public synchronized void info(Object requester, String message) { - this.outputManager.info(message); - } - - @Override - public synchronized void info(Object requester, String format, Object... args) { - this.outputManager.info(format, args); - } - - @Override - public synchronized void warn(Object requester, String message) { - this.outputManager.warn(message); - } - - @Override - public synchronized void warn(Object requester, String format, Object... args) { - this.outputManager.warn(format, args); - } - - @Override - public synchronized void error(Object requester, String message) { - this.outputManager.error(message); - } - - @Override - public synchronized void error(Object requester, String format, Object... args) { - this.outputManager.error(format, args); - } + private int level; // affects OutputStreamManager level + private OutputStreamManager outputManager; + + public MessageHandler(PrintStream outputStream, int level) { + this.level = level; + this.outputManager = new OutputStreamManager(outputStream, level); + } + + public MessageHandler(int level) { + this.level = level; + this.outputManager = new OutputStreamManager(level); + } + + public MessageHandler(OutputStreamManager outputStreamManager) { + this.outputManager = outputStreamManager; + this.level = this.outputManager.getLevel(); + } + + public OutputStreamManager getOutputManager() { + return this.outputManager; + } + + public void setOutputManager(OutputStreamManager outputManager) { + this.outputManager = outputManager; + } + + @Override + public int getOutputManagerLevel() { + return this.level; + } + + @Override + public void setOutputManagerLevel(int level) { + this.level = level; + this.updateOutputStreamManagerLevel(); + } + + private synchronized void updateOutputStreamManagerLevel() { + this.outputManager.setLevel(this.level); + } + + @Override + public synchronized void debug(Object requester, String message) { + this.outputManager.debug(message); + } + + @Override + public synchronized void debug(Object requester, String format, Object... args) { + this.outputManager.debug(format, args); + } + + @Override + public synchronized void info(Object requester, String message) { + this.outputManager.info(message); + } + + @Override + public synchronized void info(Object requester, String format, Object... args) { + this.outputManager.info(format, args); + } + + @Override + public synchronized void warn(Object requester, String message) { + this.outputManager.warn(message); + } + + @Override + public synchronized void warn(Object requester, String format, Object... args) { + this.outputManager.warn(format, args); + } + + @Override + public synchronized void error(Object requester, String message) { + this.outputManager.error(message); + } + + @Override + public synchronized void error(Object requester, String format, Object... args) { + this.outputManager.error(format, args); + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/context/OutputStreamManager.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/context/OutputStreamManager.java index bd54f14e..52344099 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/context/OutputStreamManager.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/context/OutputStreamManager.java @@ -24,95 +24,90 @@ import java.io.PrintStream; /** - * It contains and manages an OutputStream at different and desired levels. - * The default OutputStream is 'System.out', but it's possible to instantiate the class with - * a specific one by passing it to the class Constructor. - * Levels: - * - 0 : no output - * - 3 : only error level is printed - * - 2 : from info to error is printed - * - 1 : from debug to error is printed + * It contains and manages an OutputStream at different and desired levels. The default OutputStream + * is 'System.out', but it's possible to instantiate the class with a specific one by passing it to + * the class Constructor. Levels: - 0 : no output - 3 : only error level is printed - 2 : from info + * to error is printed - 1 : from debug to error is printed * * @author Gabriele Ponzi */ - public class OutputStreamManager { - public static final int BLANK_LEVEL = 0; - public static final int DEBUG_LEVEL = 1; - public static final int INFO_LEVEL = 2; - public static final int WARNING_LEVEL = 3; - public static final int ERROR_LEVEL = 4; - public PrintStream outputStream; - private int level; - - public OutputStreamManager(int level) { - this.outputStream = System.out; - this.level = level; - } - - public OutputStreamManager(PrintStream outputStream, int level) { - this.outputStream = outputStream; - this.level = level; - } - - public OutputStream getOutputStream() { - return outputStream; - } - - public synchronized int getLevel() { - return level; - } - - public synchronized void setLevel(int level) { - this.level = level; - } - - public synchronized void debug(String message) { - if (!(this.level == BLANK_LEVEL) && message != null) { - if (this.level <= DEBUG_LEVEL) this.outputStream.print(message); - } + public static final int BLANK_LEVEL = 0; + public static final int DEBUG_LEVEL = 1; + public static final int INFO_LEVEL = 2; + public static final int WARNING_LEVEL = 3; + public static final int ERROR_LEVEL = 4; + public PrintStream outputStream; + private int level; + + public OutputStreamManager(int level) { + this.outputStream = System.out; + this.level = level; + } + + public OutputStreamManager(PrintStream outputStream, int level) { + this.outputStream = outputStream; + this.level = level; + } + + public OutputStream getOutputStream() { + return outputStream; + } + + public synchronized int getLevel() { + return level; + } + + public synchronized void setLevel(int level) { + this.level = level; + } + + public synchronized void debug(String message) { + if (!(this.level == BLANK_LEVEL) && message != null) { + if (this.level <= DEBUG_LEVEL) this.outputStream.print(message); } + } - public synchronized void debug(String format, Object... args) { - if (!(this.level == BLANK_LEVEL) && format != null) { - if (this.level <= DEBUG_LEVEL) this.outputStream.printf(format, args); - } + public synchronized void debug(String format, Object... args) { + if (!(this.level == BLANK_LEVEL) && format != null) { + if (this.level <= DEBUG_LEVEL) this.outputStream.printf(format, args); } + } - public synchronized void info(String message) { - if (!(this.level == BLANK_LEVEL) && message != null) { - if (this.level <= INFO_LEVEL) this.outputStream.print(message); - } + public synchronized void info(String message) { + if (!(this.level == BLANK_LEVEL) && message != null) { + if (this.level <= INFO_LEVEL) this.outputStream.print(message); } + } - public synchronized void info(String format, Object... args) { - if (!(this.level == BLANK_LEVEL) && format != null) { - if (this.level <= INFO_LEVEL) this.outputStream.printf(format, args); - } + public synchronized void info(String format, Object... args) { + if (!(this.level == BLANK_LEVEL) && format != null) { + if (this.level <= INFO_LEVEL) this.outputStream.printf(format, args); } + } - public synchronized void warn(String message) { - if (!(this.level == BLANK_LEVEL) && message != null) { - if (this.level <= WARNING_LEVEL) this.outputStream.print(message); - } + public synchronized void warn(String message) { + if (!(this.level == BLANK_LEVEL) && message != null) { + if (this.level <= WARNING_LEVEL) this.outputStream.print(message); } + } - public synchronized void warn(String format, Object... args) { - if (!(this.level == BLANK_LEVEL) && format != null) { - if (this.level <= WARNING_LEVEL) this.outputStream.printf(format, args); - } + public synchronized void warn(String format, Object... args) { + if (!(this.level == BLANK_LEVEL) && format != null) { + if (this.level <= WARNING_LEVEL) this.outputStream.printf(format, args); } + } - public synchronized void error(String message) { - if (!(this.level == BLANK_LEVEL) && message != null) { - if (this.level <= ERROR_LEVEL) this.outputStream.print("\nERROR: " + message); - } + public synchronized void error(String message) { + if (!(this.level == BLANK_LEVEL) && message != null) { + if (this.level <= ERROR_LEVEL) this.outputStream.print("\nERROR: " + message); } + } - public synchronized void error(String format, Object... args) { - if (!(this.level == BLANK_LEVEL) && format != null) { - if (this.level <= ERROR_LEVEL) this.outputStream.printf("\nERROR: " + format, args); - } + public synchronized void error(String format, Object... args) { + if (!(this.level == BLANK_LEVEL) && format != null) { + if (this.level <= ERROR_LEVEL) this.outputStream.printf("\nERROR: " + format, args); } + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/context/PluginMessageHandler.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/context/PluginMessageHandler.java index ed71e4a9..9df5c9da 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/context/PluginMessageHandler.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/context/PluginMessageHandler.java @@ -25,25 +25,24 @@ * * @author Gabriele Ponzi */ - public interface PluginMessageHandler { - int getOutputManagerLevel(); + int getOutputManagerLevel(); - void setOutputManagerLevel(int outputManagerLevel); + void setOutputManagerLevel(int outputManagerLevel); - void debug(Object requester, String message); + void debug(Object requester, String message); - void debug(Object requester, String format, Object... args); + void debug(Object requester, String format, Object... args); - void info(Object requester, String message); + void info(Object requester, String message); - void info(Object requester, String format, Object... args); + void info(Object requester, String format, Object... args); - void warn(Object requester, String message); + void warn(Object requester, String message); - void warn(Object requester, String format, Object... args); + void warn(Object requester, String format, Object... args); - void error(Object requester, String message); + void error(Object requester, String message); - void error(Object requester, String format, Object... args); + void error(Object requester, String format, Object... args); } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/context/Statistics.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/context/Statistics.java index ec528d50..78ee23b7 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/context/Statistics.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/context/Statistics.java @@ -25,165 +25,170 @@ import java.util.Set; /** - * Collects and updates statistics about the Drakkar execution state. - * It identifies and monitors 4 step in the global execution: - * 1. Source DB Schema building - * 2. Graph Model building - * 3. OrientDB Schema writing - * 4. OrientDB importing + * Collects and updates statistics about the Drakkar execution state. It identifies and monitors 4 + * step in the global execution: 1. Source DB Schema building 2. Graph Model building 3. OrientDB + * Schema writing 4. OrientDB importing * * @author Gabriele Ponzi */ - public class Statistics { - // indicates the running step, -1 if no step are running - public volatile int runningStepNumber; - - // Source DB Schema building statistics - public volatile int totalNumberOfEntities; - public volatile int builtEntities; - public volatile int entitiesAnalyzedForRelationship; // used only for te progress monitor because we can't know the total number of relationships before all the entities are scanned. - public volatile int builtRelationships; - public volatile int totalNumberOfRelationships; - public volatile Date startWork1Time; - - // Graph Model building statistics - public volatile int totalNumberOfModelVertices; - public volatile int builtModelVertexTypes; - public volatile int totalNumberOfModelEdges; - public volatile int builtModelEdgeTypes; - public volatile Date startWork2Time; - - // OrientDB Schema writing statistics - public volatile int totalNumberOfVertexTypes; - public volatile int wroteVertexType; - public volatile int totalNumberOfEdgeTypes; - public volatile int wroteEdgeType; - public volatile int totalNumberOfIndices; - public volatile int wroteIndexes; - public volatile Date startWork3Time; - - // OrientDB importing - public volatile int totalNumberOfRecords; - public volatile int analyzedRecords; - public volatile int orientAddedVertices; - public volatile int orientUpdatedVertices; - public volatile int orientAddedEdges; - public volatile Date startWork4Time; - - // Logical Relationships - public volatile int totalNumberOfLogicalRelationships; - public volatile int doneLogicalRelationships; - public volatile int leftVerticesCurrentLogicalRelationship; - public volatile int doneLeftVerticesCurrentLogicalRelationship; - public volatile Date startWork5Time; - - // Warnings and Error Messages - public volatile Set warningMessages; - public volatile Set errorMessages; - - public Statistics() { - init(); - warningMessages = new HashSet<>(); - errorMessages = new HashSet<>(); - } - - private void init() { - runningStepNumber = -1; - - totalNumberOfEntities = 0; - builtEntities = 0; - entitiesAnalyzedForRelationship = 0; - builtRelationships = 0; - totalNumberOfRelationships = 0; - - totalNumberOfModelVertices = 0; - builtModelVertexTypes = 0; - totalNumberOfModelEdges = 0; - builtModelEdgeTypes = 0; - - totalNumberOfVertexTypes = 0; - wroteVertexType = 0; - totalNumberOfEdgeTypes = 0; - wroteEdgeType = 0; - totalNumberOfIndices = 0; - wroteIndexes = 0; - - totalNumberOfRecords = 0; - analyzedRecords = 0; - orientAddedVertices = 0; - orientAddedEdges = 0; - - totalNumberOfLogicalRelationships = 0; - doneLogicalRelationships = 0; - leftVerticesCurrentLogicalRelationship = 0; - doneLeftVerticesCurrentLogicalRelationship = 0; - } - - public void reset() { - this.init(); + // indicates the running step, -1 if no step are running + public volatile int runningStepNumber; + + // Source DB Schema building statistics + public volatile int totalNumberOfEntities; + public volatile int builtEntities; + public volatile int + entitiesAnalyzedForRelationship; // used only for te progress monitor because we can't know + // the total number of relationships before all the entities + // are scanned. + public volatile int builtRelationships; + public volatile int totalNumberOfRelationships; + public volatile Date startWork1Time; + + // Graph Model building statistics + public volatile int totalNumberOfModelVertices; + public volatile int builtModelVertexTypes; + public volatile int totalNumberOfModelEdges; + public volatile int builtModelEdgeTypes; + public volatile Date startWork2Time; + + // OrientDB Schema writing statistics + public volatile int totalNumberOfVertexTypes; + public volatile int wroteVertexType; + public volatile int totalNumberOfEdgeTypes; + public volatile int wroteEdgeType; + public volatile int totalNumberOfIndices; + public volatile int wroteIndexes; + public volatile Date startWork3Time; + + // OrientDB importing + public volatile int totalNumberOfRecords; + public volatile int analyzedRecords; + public volatile int orientAddedVertices; + public volatile int orientUpdatedVertices; + public volatile int orientAddedEdges; + public volatile Date startWork4Time; + + // Logical Relationships + public volatile int totalNumberOfLogicalRelationships; + public volatile int doneLogicalRelationships; + public volatile int leftVerticesCurrentLogicalRelationship; + public volatile int doneLeftVerticesCurrentLogicalRelationship; + public volatile Date startWork5Time; + + // Warnings and Error Messages + public volatile Set warningMessages; + public volatile Set errorMessages; + + public Statistics() { + init(); + warningMessages = new HashSet<>(); + errorMessages = new HashSet<>(); + } + + private void init() { + runningStepNumber = -1; + + totalNumberOfEntities = 0; + builtEntities = 0; + entitiesAnalyzedForRelationship = 0; + builtRelationships = 0; + totalNumberOfRelationships = 0; + + totalNumberOfModelVertices = 0; + builtModelVertexTypes = 0; + totalNumberOfModelEdges = 0; + builtModelEdgeTypes = 0; + + totalNumberOfVertexTypes = 0; + wroteVertexType = 0; + totalNumberOfEdgeTypes = 0; + wroteEdgeType = 0; + totalNumberOfIndices = 0; + wroteIndexes = 0; + + totalNumberOfRecords = 0; + analyzedRecords = 0; + orientAddedVertices = 0; + orientAddedEdges = 0; + + totalNumberOfLogicalRelationships = 0; + doneLogicalRelationships = 0; + leftVerticesCurrentLogicalRelationship = 0; + doneLeftVerticesCurrentLogicalRelationship = 0; + } + + public void reset() { + this.init(); + } + + public void notifyListeners() {} + + /* + * toString methods + */ + + public String sourceDbSchemaBuildingProgress() { + String s = "Source DB Schema\n"; + s += "Entities: " + this.builtEntities; + s += "\nRelationships: " + this.builtRelationships; + return s; + } + + public String graphModelBuildingProgress() { + String s = "Graph Model Building\n"; + s += "Built Model Vertices: " + this.builtModelVertexTypes; + s += "\nBuilt Model Edges: " + this.builtModelEdgeTypes; + return s; + } + + public String orientSchemaWritingProgress() { + String s = "OrientDB Schema\n"; + s += "Vertex Type: " + this.wroteVertexType; + s += "\nEdge Type: " + this.wroteEdgeType; + s += "\nIndexes: " + this.wroteIndexes; + return s; + } + + public String importingProgress() { + String s = "OrientDB Importing\n"; + s += "Analyzed Records: " + this.analyzedRecords + "/" + this.totalNumberOfRecords; + s += "\nAdded Vertices on OrientDB: " + this.orientAddedVertices; + s += "\nUpdated Vertices on OrientDB: " + this.orientUpdatedVertices; + s += "\nAdded Edges on OrientDB: " + this.orientAddedEdges; + + return s; + } + + public String toString() { + String s = "\n\nSUMMARY\n\n"; + s += + this.sourceDbSchemaBuildingProgress() + + "\n\n" + + this.orientSchemaWritingProgress() + + "\n\n" + + this.importingProgress() + + "\n\n"; + + // printing error messages + if (this.errorMessages.size() > 0) { + s += "Error Messages:\n"; + for (String message : this.errorMessages) { + s += message + "\n"; + } } - public void notifyListeners() {} - - /* - * toString methods - */ - - public String sourceDbSchemaBuildingProgress() { - String s = "Source DB Schema\n"; - s += "Entities: " + this.builtEntities; - s += "\nRelationships: " + this.builtRelationships; - return s; - } - - public String graphModelBuildingProgress() { - String s = "Graph Model Building\n"; - s += "Built Model Vertices: " + this.builtModelVertexTypes; - s += "\nBuilt Model Edges: " + this.builtModelEdgeTypes; - return s; - } - - public String orientSchemaWritingProgress() { - String s = "OrientDB Schema\n"; - s += "Vertex Type: " + this.wroteVertexType; - s += "\nEdge Type: " + this.wroteEdgeType; - s += "\nIndexes: " + this.wroteIndexes; - return s; - } - - public String importingProgress() { - String s = "OrientDB Importing\n"; - s += "Analyzed Records: " + this.analyzedRecords + "/" + this.totalNumberOfRecords; - s += "\nAdded Vertices on OrientDB: " + this.orientAddedVertices; - s += "\nUpdated Vertices on OrientDB: " + this.orientUpdatedVertices; - s += "\nAdded Edges on OrientDB: " + this.orientAddedEdges; - - return s; - } + s += "\n\n"; - public String toString() { - String s = "\n\nSUMMARY\n\n"; - s += this.sourceDbSchemaBuildingProgress() + "\n\n" + this.orientSchemaWritingProgress() + "\n\n" + this.importingProgress() + "\n\n"; - - // printing error messages - if (this.errorMessages.size() > 0) { - s += "Error Messages:\n"; - for (String message : this.errorMessages) { - s += message + "\n"; - } - } - - s += "\n\n"; - - // printing warning messages - if (this.warningMessages.size() > 0) { - s += "Warning Messages:\n"; - for (String message : this.warningMessages) { - s += message + "\n"; - } - } - return s; + // printing warning messages + if (this.warningMessages.size() > 0) { + s += "Warning Messages:\n"; + for (String message : this.warningMessages) { + s += message + "\n"; + } } + return s; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dataprovider/DataFetcher.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dataprovider/DataFetcher.java index 3556113d..264a7635 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dataprovider/DataFetcher.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dataprovider/DataFetcher.java @@ -48,250 +48,263 @@ public class DataFetcher { - private final Logger log = LoggerFactory.getLogger(RDBMSDataProvider.class); - private ER2GraphMapper mapper; - - public DataFetcher() {} - - public ER2GraphMapper getMapper() { - return this.mapper; - } - - public void setMapper(ER2GraphMapper mapper) { - this.mapper = mapper; + private final Logger log = LoggerFactory.getLogger(RDBMSDataProvider.class); + private ER2GraphMapper mapper; + + public DataFetcher() {} + + public ER2GraphMapper getMapper() { + return this.mapper; + } + + public void setMapper(ER2GraphMapper mapper) { + this.mapper = mapper; + } + + public GraphData mapResultSet( + QueryResult queryResult, + Entity entity, + List outCountResult, + List inCountResult) + throws SQLException { + // collections to build CytoGraph + final Set cytoNodes = new LinkedHashSet<>(); + final Set cytoEdges = new LinkedHashSet<>(); + final Map> nodeClasses = new LinkedHashMap<>(); + final Map> edgeClasses = new LinkedHashMap<>(); + + ResultSet scanningRecords = queryResult.getResult(); + + String vertexClassName = this.mapper.getVertexTypeByEntity(entity).getName(); + + // fetching properties from the graph model + VertexType vertexType = mapper.getVertexTypeByEntity(entity); + Set vertexTypeProperties = vertexType.getAllProperties(); + Map property2type = new LinkedHashMap<>(); + for (ModelProperty currProperty : vertexTypeProperties) { + property2type.put(currProperty.getName(), currProperty.getOrientdbType()); } - - public GraphData mapResultSet( - QueryResult queryResult, - Entity entity, - List outCountResult, - List inCountResult - ) throws SQLException { - // collections to build CytoGraph - final Set cytoNodes = new LinkedHashSet<>(); - final Set cytoEdges = new LinkedHashSet<>(); - final Map> nodeClasses = new LinkedHashMap<>(); - final Map> edgeClasses = new LinkedHashMap<>(); - - ResultSet scanningRecords = queryResult.getResult(); - - String vertexClassName = this.mapper.getVertexTypeByEntity(entity).getName(); - - // fetching properties from the graph model - VertexType vertexType = mapper.getVertexTypeByEntity(entity); - Set vertexTypeProperties = vertexType.getAllProperties(); - Map property2type = new LinkedHashMap<>(); - for (ModelProperty currProperty : vertexTypeProperties) { - property2type.put(currProperty.getName(), currProperty.getOrientdbType()); + nodeClasses.put(vertexClassName, property2type); + + Map outRelationshipName2cardinality; + Map inRelationshipName2cardinality; + + int totalEdgeCount; + + // each record is imported as vertex in the orient graph + while (scanningRecords.next()) { + log.debug("current record:: {} ", scanningRecords); + outRelationshipName2cardinality = new LinkedHashMap<>(); + inRelationshipName2cardinality = new LinkedHashMap<>(); + totalEdgeCount = 0; + + // move the cursor ahead fot the out relationships + for (RelationshipQueryResult currentOutRelationshipsCount : outCountResult) { + ResultSet currentOutRelationshipsCursor = currentOutRelationshipsCount.getResult(); + ResultSet currentCountRecord; + if (currentOutRelationshipsCursor.next()) { + currentCountRecord = currentOutRelationshipsCursor; + int cardinality = currentCountRecord.getInt("connectionsCount"); + totalEdgeCount += cardinality; + String relationshipName = currentOutRelationshipsCount.getRelationshipName(); + if (outRelationshipName2cardinality.get(relationshipName) != null) { + cardinality += outRelationshipName2cardinality.get(relationshipName); + } + outRelationshipName2cardinality.put(relationshipName, cardinality); } - nodeClasses.put(vertexClassName, property2type); - - Map outRelationshipName2cardinality; - Map inRelationshipName2cardinality; - - int totalEdgeCount; - - // each record is imported as vertex in the orient graph - while (scanningRecords.next()) { - log.debug("current record:: {} ", scanningRecords); - outRelationshipName2cardinality = new LinkedHashMap<>(); - inRelationshipName2cardinality = new LinkedHashMap<>(); - totalEdgeCount = 0; - - // move the cursor ahead fot the out relationships - for (RelationshipQueryResult currentOutRelationshipsCount : outCountResult) { - ResultSet currentOutRelationshipsCursor = currentOutRelationshipsCount.getResult(); - ResultSet currentCountRecord; - if (currentOutRelationshipsCursor.next()) { - currentCountRecord = currentOutRelationshipsCursor; - int cardinality = currentCountRecord.getInt("connectionsCount"); - totalEdgeCount += cardinality; - String relationshipName = currentOutRelationshipsCount.getRelationshipName(); - if (outRelationshipName2cardinality.get(relationshipName) != null) { - cardinality += outRelationshipName2cardinality.get(relationshipName); - } - outRelationshipName2cardinality.put(relationshipName, cardinality); - } - } - - // move the cursor ahead fot the in relationships - for (RelationshipQueryResult currentInRelationshipsCount : inCountResult) { - ResultSet currentInRelationshipsCursor = currentInRelationshipsCount.getResult(); - ResultSet currentCountRecord; - if (currentInRelationshipsCursor.next()) { - currentCountRecord = currentInRelationshipsCursor; - int cardinality = currentCountRecord.getInt("connectionsCount"); - totalEdgeCount += cardinality; - String relationshipName = currentInRelationshipsCount.getRelationshipName(); - if (inRelationshipName2cardinality.get(relationshipName) != null) { - cardinality += inRelationshipName2cardinality.get(relationshipName); - } - inRelationshipName2cardinality.put(currentInRelationshipsCount.getRelationshipName(), cardinality); - } - } - - // create a correspondent CytoNode - CytoData currentConvertedData = toData( - scanningRecords, - entity, - vertexClassName, - totalEdgeCount, - outRelationshipName2cardinality, - inRelationshipName2cardinality - ); - cytoNodes.add(currentConvertedData); + } + + // move the cursor ahead fot the in relationships + for (RelationshipQueryResult currentInRelationshipsCount : inCountResult) { + ResultSet currentInRelationshipsCursor = currentInRelationshipsCount.getResult(); + ResultSet currentCountRecord; + if (currentInRelationshipsCursor.next()) { + currentCountRecord = currentInRelationshipsCursor; + int cardinality = currentCountRecord.getInt("connectionsCount"); + totalEdgeCount += cardinality; + String relationshipName = currentInRelationshipsCount.getRelationshipName(); + if (inRelationshipName2cardinality.get(relationshipName) != null) { + cardinality += inRelationshipName2cardinality.get(relationshipName); + } + inRelationshipName2cardinality.put( + currentInRelationshipsCount.getRelationshipName(), cardinality); } + } + + // create a correspondent CytoNode + CytoData currentConvertedData = + toData( + scanningRecords, + entity, + vertexClassName, + totalEdgeCount, + outRelationshipName2cardinality, + inRelationshipName2cardinality); + cytoNodes.add(currentConvertedData); + } - final GraphData data = new GraphData(nodeClasses, edgeClasses, cytoNodes, cytoEdges, false); - return data; + final GraphData data = new GraphData(nodeClasses, edgeClasses, cytoNodes, cytoEdges, false); + return data; + } + + private CytoData toData( + ResultSet sourceRecord, + Entity entity, + String vertexClassName, + int edgeCount, + Map outRelationshipName2cardinality, + Map inRelationshipName2cardinality) + throws SQLException { + String id = getCytoIdFromPrimaryKey(sourceRecord, entity); + + HashMap targetRecord = new LinkedHashMap(); + for (Attribute attribute : entity.getAllAttributes()) { + String propertyName = mapper.getPropertyNameByEntityAndAttribute(entity, attribute.getName()); + if (attribute.getDataType().equals("_text")) { + // then we are handling an array field: we must deserialize it otherwise we'll get an + // exception during the map serialization performed by jackson + String[] arrayValues = (String[]) sourceRecord.getArray(attribute.getName()).getArray(); + String stringifiedArray = Arrays.toString(arrayValues); + targetRecord.put(propertyName, stringifiedArray); + } else { + targetRecord.put(propertyName, sourceRecord.getObject(attribute.getName())); + } } + targetRecord.put("@out", outRelationshipName2cardinality); + targetRecord.put("@in", inRelationshipName2cardinality); + targetRecord.put("@edgeCount", edgeCount); - private CytoData toData( - ResultSet sourceRecord, - Entity entity, - String vertexClassName, - int edgeCount, - Map outRelationshipName2cardinality, - Map inRelationshipName2cardinality - ) throws SQLException { - String id = getCytoIdFromPrimaryKey(sourceRecord, entity); - - HashMap targetRecord = new LinkedHashMap(); - for (Attribute attribute : entity.getAllAttributes()) { - String propertyName = mapper.getPropertyNameByEntityAndAttribute(entity, attribute.getName()); - if (attribute.getDataType().equals("_text")) { - // then we are handling an array field: we must deserialize it otherwise we'll get an exception during the map serialization performed by jackson - String[] arrayValues = (String[]) sourceRecord.getArray(attribute.getName()).getArray(); - String stringifiedArray = Arrays.toString(arrayValues); - targetRecord.put(propertyName, stringifiedArray); - } else { - targetRecord.put(propertyName, sourceRecord.getObject(attribute.getName())); - } - } - targetRecord.put("@out", outRelationshipName2cardinality); - targetRecord.put("@in", inRelationshipName2cardinality); - targetRecord.put("@edgeCount", edgeCount); + Data data = new Data(id, "", "", "", targetRecord); + + CytoData cyto = + new CytoData(vertexClassName, "nodes", data, new Position(0.0, 0.0), "", "", "", ""); + return cyto; + } - Data data = new Data(id, "", "", "", targetRecord); + @NotNull + private String getCytoIdFromPrimaryKey(ResultSet sourceRecord, Entity entity) + throws SQLException { + PrimaryKey primaryKey = entity.getPrimaryKey(); + String id = entity.getSchemaPosition() + "_"; - CytoData cyto = new CytoData(vertexClassName, "nodes", data, new Position(0.0, 0.0), "", "", "", ""); - return cyto; + for (Attribute attribute : primaryKey.getInvolvedAttributes()) { + id += sourceRecord.getString(attribute.getName()) + "_"; } + id = id.substring(0, id.lastIndexOf("_")); + return id; + } + + public GraphData buildEdgesFromJoinResultAndRelationship( + QueryResult queryResult, Relationship relationship, String direction) throws SQLException { + ResultSet scanningRecords = queryResult.getResult(); + scanningRecords.beforeFirst(); + + // collections to build CytoGraph + final Set cytoNodes = new LinkedHashSet(); + final Set cytoEdges = new LinkedHashSet(); + final Map> nodeClasses = + new LinkedHashMap>(); + final Map> edgeClasses = + new LinkedHashMap>(); + + // adding the edge class + String edgeClassName = mapper.getRelationship2edgeType().get(relationship).getName(); + Map edgeClassInfo = new LinkedHashMap(); + edgeClasses.put(edgeClassName, edgeClassInfo); + + while (scanningRecords.next()) { + String edgeId; + String sourceId = null; + String targetId = null; + Entity foreignEntity = relationship.getForeignEntity(); + Entity parentEntity = relationship.getParentEntity(); + + if (direction.equals("in")) { + sourceId = this.getCytoIdFromPrimaryKey(scanningRecords, foreignEntity); + targetId = parentEntity.getSchemaPosition() + ""; + for (Attribute currColumn : parentEntity.getPrimaryKey().getInvolvedAttributes()) { + targetId += "_" + scanningRecords.getString(currColumn.getName()); + } + } else if (direction.equals("out")) { + sourceId = foreignEntity.getSchemaPosition() + ""; + for (Attribute currColumn : foreignEntity.getPrimaryKey().getInvolvedAttributes()) { + sourceId += "_" + scanningRecords.getString(currColumn.getName()); + } + targetId = this.getCytoIdFromPrimaryKey(scanningRecords, parentEntity); + } + edgeId = sourceId.replaceAll("_", "") + "_" + targetId.replaceAll("_", ""); - @NotNull - private String getCytoIdFromPrimaryKey(ResultSet sourceRecord, Entity entity) throws SQLException { - PrimaryKey primaryKey = entity.getPrimaryKey(); - String id = entity.getSchemaPosition() + "_"; + HashMap targetEdgeRecord = new LinkedHashMap(); - for (Attribute attribute : primaryKey.getInvolvedAttributes()) { - id += sourceRecord.getString(attribute.getName()) + "_"; - } - id = id.substring(0, id.lastIndexOf("_")); - return id; - } + Data data = new Data(edgeId, "", sourceId, targetId, targetEdgeRecord); - public GraphData buildEdgesFromJoinResultAndRelationship(QueryResult queryResult, Relationship relationship, String direction) throws SQLException { - ResultSet scanningRecords = queryResult.getResult(); - scanningRecords.beforeFirst(); - - // collections to build CytoGraph - final Set cytoNodes = new LinkedHashSet(); - final Set cytoEdges = new LinkedHashSet(); - final Map> nodeClasses = new LinkedHashMap>(); - final Map> edgeClasses = new LinkedHashMap>(); - - // adding the edge class - String edgeClassName = mapper.getRelationship2edgeType().get(relationship).getName(); - Map edgeClassInfo = new LinkedHashMap(); - edgeClasses.put(edgeClassName, edgeClassInfo); - - while (scanningRecords.next()) { - String edgeId; - String sourceId = null; - String targetId = null; - Entity foreignEntity = relationship.getForeignEntity(); - Entity parentEntity = relationship.getParentEntity(); - - if (direction.equals("in")) { - sourceId = this.getCytoIdFromPrimaryKey(scanningRecords, foreignEntity); - targetId = parentEntity.getSchemaPosition() + ""; - for (Attribute currColumn : parentEntity.getPrimaryKey().getInvolvedAttributes()) { - targetId += "_" + scanningRecords.getString(currColumn.getName()); - } - } else if (direction.equals("out")) { - sourceId = foreignEntity.getSchemaPosition() + ""; - for (Attribute currColumn : foreignEntity.getPrimaryKey().getInvolvedAttributes()) { - sourceId += "_" + scanningRecords.getString(currColumn.getName()); - } - targetId = this.getCytoIdFromPrimaryKey(scanningRecords, parentEntity); - } - edgeId = sourceId.replaceAll("_", "") + "_" + targetId.replaceAll("_", ""); - - HashMap targetEdgeRecord = new LinkedHashMap(); - - Data data = new Data(edgeId, "", sourceId, targetId, targetEdgeRecord); - - CytoData cyto = new CytoData(edgeClassName, "edges", data, new Position(0.0, 0.0), "", "", "", ""); - - cytoEdges.add(cyto); - } + CytoData cyto = + new CytoData(edgeClassName, "edges", data, new Position(0.0, 0.0), "", "", "", ""); - final GraphData graphData = new GraphData(nodeClasses, edgeClasses, cytoNodes, cytoEdges, false); - return graphData; + cytoEdges.add(cyto); } - public GraphData buildEdgesFromJoinTableRecords( - QueryResult queryResult, - String edgeClassName, - Entity firstExternalEntity, - Entity joinTable, - Entity secondExternalEntity, - String direction - ) throws SQLException { - ResultSet scanningRecords = queryResult.getResult(); - scanningRecords.beforeFirst(); - - // collections to build CytoGraph - final Set cytoNodes = new LinkedHashSet(); - final Set cytoEdges = new LinkedHashSet(); - final Map> nodeClasses = new LinkedHashMap>(); - final Map> edgeClasses = new LinkedHashMap>(); - - // adding the edge class - Map edgeClassInfo = new LinkedHashMap(); - edgeClasses.put(edgeClassName, edgeClassInfo); - - while (scanningRecords.next()) { - // setting sourceId, targetId and edgeId - String sourceId = null; - String targetId = null; - if (direction.equals("in")) { - sourceId = this.getCytoIdFromPrimaryKey(scanningRecords, secondExternalEntity); - targetId = this.getCytoIdFromPrimaryKey(scanningRecords, firstExternalEntity); - } else if (direction.equals("out")) { - sourceId = this.getCytoIdFromPrimaryKey(scanningRecords, firstExternalEntity); - targetId = this.getCytoIdFromPrimaryKey(scanningRecords, secondExternalEntity); - } - String edgeId = this.getCytoIdFromPrimaryKey(scanningRecords, joinTable); - - // adding edge fields - HashMap targetEdgeRecord = new LinkedHashMap(); - for (Attribute a : joinTable.getAllAttributes()) { - if (!joinTable.getPrimaryKey().getInvolvedAttributes().contains(a)) { - String fieldName = a.getName(); - Object fieldValue = scanningRecords.getObject(fieldName); - targetEdgeRecord.put(fieldName, fieldValue); - } - } - - Data data = new Data(edgeId, "", sourceId, targetId, targetEdgeRecord); - - CytoData cyto = new CytoData(edgeClassName, "edges", data, new Position(0.0, 0.0), "", "", "", ""); - - cytoEdges.add(cyto); + final GraphData graphData = + new GraphData(nodeClasses, edgeClasses, cytoNodes, cytoEdges, false); + return graphData; + } + + public GraphData buildEdgesFromJoinTableRecords( + QueryResult queryResult, + String edgeClassName, + Entity firstExternalEntity, + Entity joinTable, + Entity secondExternalEntity, + String direction) + throws SQLException { + ResultSet scanningRecords = queryResult.getResult(); + scanningRecords.beforeFirst(); + + // collections to build CytoGraph + final Set cytoNodes = new LinkedHashSet(); + final Set cytoEdges = new LinkedHashSet(); + final Map> nodeClasses = + new LinkedHashMap>(); + final Map> edgeClasses = + new LinkedHashMap>(); + + // adding the edge class + Map edgeClassInfo = new LinkedHashMap(); + edgeClasses.put(edgeClassName, edgeClassInfo); + + while (scanningRecords.next()) { + // setting sourceId, targetId and edgeId + String sourceId = null; + String targetId = null; + if (direction.equals("in")) { + sourceId = this.getCytoIdFromPrimaryKey(scanningRecords, secondExternalEntity); + targetId = this.getCytoIdFromPrimaryKey(scanningRecords, firstExternalEntity); + } else if (direction.equals("out")) { + sourceId = this.getCytoIdFromPrimaryKey(scanningRecords, firstExternalEntity); + targetId = this.getCytoIdFromPrimaryKey(scanningRecords, secondExternalEntity); + } + String edgeId = this.getCytoIdFromPrimaryKey(scanningRecords, joinTable); + + // adding edge fields + HashMap targetEdgeRecord = new LinkedHashMap(); + for (Attribute a : joinTable.getAllAttributes()) { + if (!joinTable.getPrimaryKey().getInvolvedAttributes().contains(a)) { + String fieldName = a.getName(); + Object fieldValue = scanningRecords.getObject(fieldName); + targetEdgeRecord.put(fieldName, fieldValue); } + } + + Data data = new Data(edgeId, "", sourceId, targetId, targetEdgeRecord); - final GraphData graphData = new GraphData(nodeClasses, edgeClasses, cytoNodes, cytoEdges, false); - return graphData; + CytoData cyto = + new CytoData(edgeClassName, "edges", data, new Position(0.0, 0.0), "", "", "", ""); + + cytoEdges.add(cyto); } + + final GraphData graphData = + new GraphData(nodeClasses, edgeClasses, cytoNodes, cytoEdges, false); + return graphData; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dataprovider/RDBMSDataProvider.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dataprovider/RDBMSDataProvider.java index fd3a9d48..5f44d32b 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dataprovider/RDBMSDataProvider.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dataprovider/RDBMSDataProvider.java @@ -75,719 +75,795 @@ public class RDBMSDataProvider implements DataSourceGraphDataProvider { - private final Logger log = LoggerFactory.getLogger(RDBMSDataProvider.class); - - private final DataFetcher dataFetcher; - private final Statistics statistics; - - private DBQueryEngine dbQueryEngine; - private String datasourceId; - - public RDBMSDataProvider() { - dataFetcher = new DataFetcher(); - - statistics = new Statistics(); + private final Logger log = LoggerFactory.getLogger(RDBMSDataProvider.class); + + private final DataFetcher dataFetcher; + private final Statistics statistics; + + private DBQueryEngine dbQueryEngine; + private String datasourceId; + + public RDBMSDataProvider() { + dataFetcher = new DataFetcher(); + + statistics = new Statistics(); + } + + public void prepareMapperAndDataFetcher(final DataSourceInfo datasource) { + datasourceId = Optional.ofNullable(datasource.getId()).orElse(-1L).toString(); + + dbQueryEngine = new DBQueryEngine(datasource, 300); + + final Boolean aggregate = Optional.ofNullable(datasource.isAggregationEnabled()).orElse(false); + String chosenStrategy = aggregate ? "interactive-aggr" : "interactive"; + + ER2GraphMapper mapper; + + DataTypeHandlerFactory dataTypeHandlerFactory = new DataTypeHandlerFactory(); + DBMSDataTypeHandler handler = dataTypeHandlerFactory.buildDataTypeHandler(datasource.getType()); + + NameResolverFactory nameResolverFactory = new NameResolverFactory(); + NameResolver nameResolver = nameResolverFactory.buildNameResolver("original"); + + StrategyFactory strategyFactory = new StrategyFactory(); + try { + mapper = + ((AbstractDBMSModelBuildingStrategy) strategyFactory.buildStrategy(chosenStrategy)) + .createSchemaMapper( + datasource, + null, + "basicDBMapper", + null, + nameResolver, + handler, + null, + null, + chosenStrategy, + dbQueryEngine, + statistics); + } catch (RDBMSProviderIOException e) { + throw new RuntimeException(e); } - public void prepareMapperAndDataFetcher(final DataSourceInfo datasource) { - datasourceId = Optional.ofNullable(datasource.getId()).orElse(-1L).toString(); - - dbQueryEngine = new DBQueryEngine(datasource, 300); - - final Boolean aggregate = Optional.ofNullable(datasource.isAggregationEnabled()).orElse(false); - String chosenStrategy = aggregate ? "interactive-aggr" : "interactive"; - - ER2GraphMapper mapper; - - DataTypeHandlerFactory dataTypeHandlerFactory = new DataTypeHandlerFactory(); - DBMSDataTypeHandler handler = dataTypeHandlerFactory.buildDataTypeHandler(datasource.getType()); - - NameResolverFactory nameResolverFactory = new NameResolverFactory(); - NameResolver nameResolver = nameResolverFactory.buildNameResolver("original"); - - StrategyFactory strategyFactory = new StrategyFactory(); - try { - mapper = - ((AbstractDBMSModelBuildingStrategy) strategyFactory.buildStrategy(chosenStrategy)).createSchemaMapper( - datasource, - null, - "basicDBMapper", - null, - nameResolver, - handler, - null, - null, - chosenStrategy, - dbQueryEngine, - statistics - ); - } catch (RDBMSProviderIOException e) { - throw new RuntimeException(e); - } + // adding the mapper to the cache + dataFetcher.setMapper(mapper); + } - // adding the mapper to the cache - dataFetcher.setMapper(mapper); - } - - @Override - public GraphData fetchData(DataSourceInfo datasource, String query, int limit) { - query = fixQuery(datasource, query); - - log.info("query datasource {} with '{}'", datasource.getId(), query); - // preparing the mapper in the data fetcher - - prepareMapperAndDataFetcher(datasource); - - /* - * Fetching data - */ - - QueryResult queryResult = null; - GraphData data; - List outCountResults = new LinkedList<>(); - List inCountResults = new LinkedList<>(); - - try { - String originalQuery = query; - String queryWords[] = originalQuery.split(" "); - String tableName; - int indexOfTableNameWord = 0; - for (int i = 0; i < queryWords.length; i++) { - if (queryWords[i].equalsIgnoreCase("from")) { - indexOfTableNameWord = i + 1; - break; - } - } - tableName = queryWords[indexOfTableNameWord]; - Entity entity = dataFetcher.getMapper().getEntityByNameIgnoreCase(tableName); - - final Boolean isAggregationEnabled = Optional.ofNullable(datasource.isAggregationEnabled()).orElse(false); - if (isAggregationEnabled && entity.isAggregableJoinTable()) { - VertexType aggregatedVertexType = this.dataFetcher.getMapper().getVertexTypeByEntity(entity); - AggregatorEdge edgeType = this.dataFetcher.getMapper().getAggregatorEdgeByJoinVertexTypeName(aggregatedVertexType.getName()); - throw new RDBMSProviderAggregationException( - "Wrong query content: " + "the requested table was aggregated into the " + edgeType.getEdgeType().getName() + " edge class." - ); - } + @Override + public GraphData fetchData(DataSourceInfo datasource, String query, int limit) { + query = fixQuery(datasource, query); - queryResult = dbQueryEngine.scanTableAndOrder(query, limit, entity, datasource); + log.info("query datasource {} with '{}'", datasource.getId(), query); + // preparing the mapper in the data fetcher - if (isAggregationEnabled) { - Map> direction2countQueryResults = getRelationshipsCountAggregationCase(datasource, entity); + prepareMapperAndDataFetcher(datasource); - // getting out relationships counts - outCountResults = direction2countQueryResults.get("out"); - - // getting in relationships counts - inCountResults = direction2countQueryResults.get("in"); - } else { - // getting out relationships counts - outCountResults = getOutRelationshipsCount(datasource, entity); - - // getting in relationships counts - inCountResults = getInRelationshipsCount(datasource, entity); - } + /* + * Fetching data + */ - data = dataFetcher.mapResultSet(queryResult, entity, outCountResults, inCountResults); - } catch (Exception e) { - throw new RDBMSProviderRuntimeException(e); - } finally { - // closing resultset, connection and statement - if (queryResult != null) { - queryResult.close(); - } - for (RelationshipQueryResult outRelationshipsQueryResult : outCountResults) { - if (outRelationshipsQueryResult != null) { - outRelationshipsQueryResult.close(); - } - } - for (RelationshipQueryResult inRelationshipsQueryResult : inCountResults) { - if (inRelationshipsQueryResult != null) { - inRelationshipsQueryResult.close(); - } - } + QueryResult queryResult = null; + GraphData data; + List outCountResults = new LinkedList<>(); + List inCountResults = new LinkedList<>(); + + try { + String originalQuery = query; + String queryWords[] = originalQuery.split(" "); + String tableName; + int indexOfTableNameWord = 0; + for (int i = 0; i < queryWords.length; i++) { + if (queryWords[i].equalsIgnoreCase("from")) { + indexOfTableNameWord = i + 1; + break; + } + } + tableName = queryWords[indexOfTableNameWord]; + Entity entity = dataFetcher.getMapper().getEntityByNameIgnoreCase(tableName); + + final Boolean isAggregationEnabled = + Optional.ofNullable(datasource.isAggregationEnabled()).orElse(false); + if (isAggregationEnabled && entity.isAggregableJoinTable()) { + VertexType aggregatedVertexType = + this.dataFetcher.getMapper().getVertexTypeByEntity(entity); + AggregatorEdge edgeType = + this.dataFetcher + .getMapper() + .getAggregatorEdgeByJoinVertexTypeName(aggregatedVertexType.getName()); + throw new RDBMSProviderAggregationException( + "Wrong query content: " + + "the requested table was aggregated into the " + + edgeType.getEdgeType().getName() + + " edge class."); + } + + queryResult = dbQueryEngine.scanTableAndOrder(query, limit, entity, datasource); + + if (isAggregationEnabled) { + Map> direction2countQueryResults = + getRelationshipsCountAggregationCase(datasource, entity); + + // getting out relationships counts + outCountResults = direction2countQueryResults.get("out"); + + // getting in relationships counts + inCountResults = direction2countQueryResults.get("in"); + } else { + // getting out relationships counts + outCountResults = getOutRelationshipsCount(datasource, entity); + + // getting in relationships counts + inCountResults = getInRelationshipsCount(datasource, entity); + } + + data = dataFetcher.mapResultSet(queryResult, entity, outCountResults, inCountResults); + } catch (Exception e) { + throw new RDBMSProviderRuntimeException(e); + } finally { + // closing resultset, connection and statement + if (queryResult != null) { + queryResult.close(); + } + for (RelationshipQueryResult outRelationshipsQueryResult : outCountResults) { + if (outRelationshipsQueryResult != null) { + outRelationshipsQueryResult.close(); } - dbQueryEngine.close(); - return data; + } + for (RelationshipQueryResult inRelationshipsQueryResult : inCountResults) { + if (inRelationshipsQueryResult != null) { + inRelationshipsQueryResult.close(); + } + } } - - /** - * Fix the query adding missing columns, if needed. - *

- * At the moment adds "row_index" column when the datasource is a DataWorld dataset - * - * @param datasource data source - * @param query the original query - * @return the fixed query - */ - private String fixQuery(DataSourceInfo datasource, String query) { - try { - final Select select = (Select) CCJSqlParserUtil.parse(query); - PlainSelect plain = (PlainSelect) select.getSelectBody(); - if (datasource.getType().equals("RDBMS_DATA_WORLD")) { - boolean notFound = plain - .getSelectItems() - .stream() - .filter(item -> item instanceof SelectExpressionItem) - .map(item -> ((SelectExpressionItem) item).getExpression()) - .filter(expression -> expression instanceof Column) - .map(column -> ((Column) column).getColumnName()) - .filter(name -> name.equals("raw_index")) - .collect(Collectors.toList()) - .isEmpty(); - if (notFound) { - log.debug("fixing query to DW, add 'row_index' column"); - plain.addSelectItems(new SelectExpressionItem(new Column("row_index"))); - } - } - query = plain.toString(); - } catch (JSQLParserException e) { - //NOOP + dbQueryEngine.close(); + return data; + } + + /** + * Fix the query adding missing columns, if needed. + * + *

At the moment adds "row_index" column when the datasource is a DataWorld dataset + * + * @param datasource data source + * @param query the original query + * @return the fixed query + */ + private String fixQuery(DataSourceInfo datasource, String query) { + try { + final Select select = (Select) CCJSqlParserUtil.parse(query); + PlainSelect plain = (PlainSelect) select.getSelectBody(); + if (datasource.getType().equals("RDBMS_DATA_WORLD")) { + boolean notFound = + plain.getSelectItems().stream() + .filter(item -> item instanceof SelectExpressionItem) + .map(item -> ((SelectExpressionItem) item).getExpression()) + .filter(expression -> expression instanceof Column) + .map(column -> ((Column) column).getColumnName()) + .filter(name -> name.equals("raw_index")) + .collect(Collectors.toList()) + .isEmpty(); + if (notFound) { + log.debug("fixing query to DW, add 'row_index' column"); + plain.addSelectItems(new SelectExpressionItem(new Column("row_index"))); } - return query; + } + query = plain.toString(); + } catch (JSQLParserException e) { + // NOOP + } + return query; + } + + @Override + public GraphData expand( + DataSourceInfo datasource, + String[] roots, + final String direction, + String edgeClassName, + int maxTraversal) { + if (StringUtils.isEmpty(edgeClassName)) { + throw new RDBMSProviderOperationNotAllowedException( + "Cannot perform a traverse all operation over a Relational Datasource."); } - @Override - public GraphData expand(DataSourceInfo datasource, String[] roots, final String direction, String edgeClassName, int maxTraversal) { - if (StringUtils.isEmpty(edgeClassName)) { - throw new RDBMSProviderOperationNotAllowedException("Cannot perform a traverse all operation over a Relational Datasource."); + // preparing the mapper in the data fetcher + prepareMapperAndDataFetcher(datasource); + + /* + * Fetching data + */ + QueryResult queryResult = null; + List outCountResults = new LinkedList<>(); + List inCountResults = new LinkedList<>(); + List graphDataCollection = new LinkedList<>(); + + try { + EdgeType edgeClass = dataFetcher.getMapper().getGraphModel().getEdgeTypeByName(edgeClassName); + + if (!edgeClass.isAggregatorEdge()) { + // edge class does not correspond to an aggregator edge + List mappedRelationships = + dataFetcher.getMapper().getEdgeType2relationships().get(edgeClass); + Set rootEntitiesInQuery = new HashSet<>(); + for (String rootId : roots) { + int entityId = Integer.parseInt(rootId.split("_")[0]); + rootEntitiesInQuery.add( + dataFetcher.getMapper().getDataBaseSchema().getEntityByPosition(entityId)); } - // preparing the mapper in the data fetcher - prepareMapperAndDataFetcher(datasource); - - /* - * Fetching data - */ - QueryResult queryResult = null; - List outCountResults = new LinkedList<>(); - List inCountResults = new LinkedList<>(); - List graphDataCollection = new LinkedList<>(); - - try { - EdgeType edgeClass = dataFetcher.getMapper().getGraphModel().getEdgeTypeByName(edgeClassName); - - if (!edgeClass.isAggregatorEdge()) { - // edge class does not correspond to an aggregator edge - List mappedRelationships = dataFetcher.getMapper().getEdgeType2relationships().get(edgeClass); - Set rootEntitiesInQuery = new HashSet<>(); - for (String rootId : roots) { - int entityId = Integer.parseInt(rootId.split("_")[0]); - rootEntitiesInQuery.add(dataFetcher.getMapper().getDataBaseSchema().getEntityByPosition(entityId)); - } - - // filtering in just the relationships with the chosen direction - mappedRelationships = - mappedRelationships - .stream() - .filter( - r -> { - Entity rootEntity = null; - if (direction.equals("in")) { - rootEntity = r.getParentEntity(); - } else if (direction.equals("out")) { - rootEntity = r.getForeignEntity(); - } - return rootEntitiesInQuery.contains(rootEntity); - } - ) - .collect(Collectors.toList()); - - List filteringColumns = null; - - for (Relationship currRelationship : mappedRelationships) { - Entity enteringEntity = null; - Entity rootEntity = null; - if (direction.equals("in")) { - enteringEntity = currRelationship.getForeignEntity(); - rootEntity = currRelationship.getParentEntity(); - filteringColumns = currRelationship.getFromColumns(); - } else if (direction.equals("out")) { - enteringEntity = currRelationship.getParentEntity(); - rootEntity = currRelationship.getForeignEntity(); - filteringColumns = currRelationship.getToColumns(); - } - - // build and perform the query, then collect the result - - //filtering nodes contained in the correspondent tables involved in the current relationship - final int rootEntityId = rootEntity.getSchemaPosition(); - final int enteringEntityId = enteringEntity.getSchemaPosition(); - List rootNodeIds = Arrays - .asList(roots) - .stream() - .filter( - id -> { - int tableId = Integer.parseInt(id.split("_")[0]); - return tableId == rootEntityId || tableId == enteringEntityId; - } - ) - .map(id -> id.substring(id.indexOf("_") + 1)) // cleaning ids to get the original ones back - .collect(Collectors.toList()); - - queryResult = - dbQueryEngine.expandRelationship( - enteringEntity, - rootEntity, - currRelationship.getFromColumns(), - currRelationship.getToColumns(), - rootNodeIds, - direction, - datasource - ); - - List newNodeIds = new ArrayList<>(rootNodeIds); - - String[] idParts = rootNodeIds.get(0).split("_"); - if (idParts.length > 1) { - // extract just the required id from the composite rootNodesId - Integer idTargetIndexToExtract = null; - - if (direction.equals("out")) { - // look for the pk column in the fromColumn - idTargetIndexToExtract = currRelationship.getFromColumns().get(0).getOrdinalPosition() - 1; - } else if (direction.equals("in")) { - // look for the pk column in the toColumn - idTargetIndexToExtract = currRelationship.getToColumns().get(0).getOrdinalPosition() - 1; - } - if (idTargetIndexToExtract != null) { - final int index = idTargetIndexToExtract.intValue(); - newNodeIds = - newNodeIds - .stream() - .map( - id -> { - String[] splits = id.split("_"); - return splits[index]; - } - ) - .collect(Collectors.toList()); - } - } - - // getting out relationships counts - outCountResults = getOutRelationshipsCount(datasource, enteringEntity, filteringColumns, newNodeIds); - - // getting in relationships counts - inCountResults = getInRelationshipsCount(datasource, enteringEntity, filteringColumns, newNodeIds); - - GraphData enteringNodesGraphData = dataFetcher.mapResultSet(queryResult, enteringEntity, outCountResults, inCountResults); - graphDataCollection.add(enteringNodesGraphData); - - // building the edges - GraphData enteringEdgesGraphData = dataFetcher.buildEdgesFromJoinResultAndRelationship(queryResult, currRelationship, direction); - graphDataCollection.add(enteringEdgesGraphData); - } - } else { - // aggregation case - - // looking for the edge class among the aggregator edges - edgeClass = dataFetcher.getMapper().getAggregatorEdgeByEdgeTypeName(edgeClassName).getEdgeType(); - - VertexType joinVertexType = dataFetcher.getMapper().getJoinVertexTypeByAggregatorEdge(edgeClass.getName()); - Entity joinTable = dataFetcher.getMapper().getEntityByVertexType(joinVertexType); - List joinTableRelationships = new LinkedList<>(joinTable.getOutCanonicalRelationships()); - if (joinTableRelationships.size() != 2) { - throw new RDBMSProviderAggregationException( - "Wrong relationships mapping: " + - "the aggregated " + - joinTable.getName() + - " join table does not have 2 out relationships to represent the N-N relationship." - ); - } - Relationship firstJoinTableRelationship = null; - Relationship secondJoinTableRelationship = null; - Entity firstExternalEntity = null; // the external entity involved in the first join with the join table - Entity secondExternalEntity = null; // the external entity involved in the second join with the join table - if (direction.equals("out")) { - firstJoinTableRelationship = joinTableRelationships.get(0); - secondJoinTableRelationship = joinTableRelationships.get(1); - firstExternalEntity = firstJoinTableRelationship.getParentEntity(); - secondExternalEntity = secondJoinTableRelationship.getParentEntity(); - } else if (direction.equals("in")) { - firstJoinTableRelationship = joinTableRelationships.get(1); - secondJoinTableRelationship = joinTableRelationships.get(0); - firstExternalEntity = firstJoinTableRelationship.getParentEntity(); - secondExternalEntity = secondJoinTableRelationship.getParentEntity(); - } - - // cleaning ids to get the original ones back - List rootNodeIds = Arrays.asList(roots).stream().map(id -> id.substring(id.indexOf("_") + 1)).collect(Collectors.toList()); - - // first external entity join: getting join table's records - QueryResult joinTableRecordsResult = dbQueryEngine.expandRelationship( - joinTable, - firstExternalEntity, - firstJoinTableRelationship.getFromColumns(), - firstJoinTableRelationship.getToColumns(), - rootNodeIds, - direction, - datasource - ); - - // building the edges from the join table records - GraphData enteringEdgesGraphData = dataFetcher.buildEdgesFromJoinTableRecords( - joinTableRecordsResult, - edgeClassName, - firstExternalEntity, - joinTable, - secondExternalEntity, - direction - ); - graphDataCollection.add(enteringEdgesGraphData); - - // new root ids: we need the ids from the join table records - - rootNodeIds = - enteringEdgesGraphData - .getEdges() - .stream() - .map( - cytoData -> { - String id = cytoData.getData().getId(); - id = id.substring(id.indexOf("_") + 1); - return id; - } - ) - .collect(Collectors.toList()); - - // second external entity join: getting entering entity's records - queryResult = - dbQueryEngine.expandRelationship( - secondExternalEntity, - joinTable, - secondJoinTableRelationship.getFromColumns(), - secondJoinTableRelationship.getToColumns(), - rootNodeIds, - direction, - datasource - ); - - Map> direction2countQueryResults = getRelationshipsCountAggregationCase(datasource, secondExternalEntity); - - // getting out relationships counts - outCountResults = direction2countQueryResults.get("out"); - - // getting in relationships counts - inCountResults = direction2countQueryResults.get("in"); - - GraphData enteringNodesGraphData = dataFetcher.mapResultSet(queryResult, secondExternalEntity, outCountResults, inCountResults); - graphDataCollection.add(enteringNodesGraphData); - } - } catch (Exception e) { - throw new RDBMSProviderRuntimeException(e); - } finally { - // closing resultset, connection and statement - if (queryResult != null) { - queryResult.close(); - } - for (RelationshipQueryResult outRelationshipsQueryResult : outCountResults) { - if (outRelationshipsQueryResult != null) { - outRelationshipsQueryResult.close(); - } + // filtering in just the relationships with the chosen direction + mappedRelationships = + mappedRelationships.stream() + .filter( + r -> { + Entity rootEntity = null; + if (direction.equals("in")) { + rootEntity = r.getParentEntity(); + } else if (direction.equals("out")) { + rootEntity = r.getForeignEntity(); + } + return rootEntitiesInQuery.contains(rootEntity); + }) + .collect(Collectors.toList()); + + List filteringColumns = null; + + for (Relationship currRelationship : mappedRelationships) { + Entity enteringEntity = null; + Entity rootEntity = null; + if (direction.equals("in")) { + enteringEntity = currRelationship.getForeignEntity(); + rootEntity = currRelationship.getParentEntity(); + filteringColumns = currRelationship.getFromColumns(); + } else if (direction.equals("out")) { + enteringEntity = currRelationship.getParentEntity(); + rootEntity = currRelationship.getForeignEntity(); + filteringColumns = currRelationship.getToColumns(); + } + + // build and perform the query, then collect the result + + // filtering nodes contained in the correspondent tables involved in the current + // relationship + final int rootEntityId = rootEntity.getSchemaPosition(); + final int enteringEntityId = enteringEntity.getSchemaPosition(); + List rootNodeIds = + Arrays.asList(roots).stream() + .filter( + id -> { + int tableId = Integer.parseInt(id.split("_")[0]); + return tableId == rootEntityId || tableId == enteringEntityId; + }) + .map( + id -> + id.substring( + id.indexOf("_") + 1)) // cleaning ids to get the original ones back + .collect(Collectors.toList()); + + queryResult = + dbQueryEngine.expandRelationship( + enteringEntity, + rootEntity, + currRelationship.getFromColumns(), + currRelationship.getToColumns(), + rootNodeIds, + direction, + datasource); + + List newNodeIds = new ArrayList<>(rootNodeIds); + + String[] idParts = rootNodeIds.get(0).split("_"); + if (idParts.length > 1) { + // extract just the required id from the composite rootNodesId + Integer idTargetIndexToExtract = null; + + if (direction.equals("out")) { + // look for the pk column in the fromColumn + idTargetIndexToExtract = + currRelationship.getFromColumns().get(0).getOrdinalPosition() - 1; + } else if (direction.equals("in")) { + // look for the pk column in the toColumn + idTargetIndexToExtract = + currRelationship.getToColumns().get(0).getOrdinalPosition() - 1; } - for (RelationshipQueryResult inRelationshipsQueryResult : inCountResults) { - if (inRelationshipsQueryResult != null) { - inRelationshipsQueryResult.close(); - } + if (idTargetIndexToExtract != null) { + final int index = idTargetIndexToExtract.intValue(); + newNodeIds = + newNodeIds.stream() + .map( + id -> { + String[] splits = id.split("_"); + return splits[index]; + }) + .collect(Collectors.toList()); } + } + + // getting out relationships counts + outCountResults = + getOutRelationshipsCount(datasource, enteringEntity, filteringColumns, newNodeIds); + + // getting in relationships counts + inCountResults = + getInRelationshipsCount(datasource, enteringEntity, filteringColumns, newNodeIds); + + GraphData enteringNodesGraphData = + dataFetcher.mapResultSet( + queryResult, enteringEntity, outCountResults, inCountResults); + graphDataCollection.add(enteringNodesGraphData); + + // building the edges + GraphData enteringEdgesGraphData = + dataFetcher.buildEdgesFromJoinResultAndRelationship( + queryResult, currRelationship, direction); + graphDataCollection.add(enteringEdgesGraphData); } - - dbQueryEngine.close(); - final GraphData graphData = collectGraphDatasInSingle(graphDataCollection); - return graphData; - } - - @Override - public GraphData load(DataSourceInfo datasource, String[] ids) { - // preparing the mapper in the data fetcher - prepareMapperAndDataFetcher(datasource); - - // order ids by table - Map> tableName2ids = new LinkedHashMap>(); - - for (String currentId : ids) { - int tableId = Integer.parseInt(currentId.split("_")[0]); - Entity currentTable = dataFetcher.getMapper().getEntityBySchemaPosition(tableId); - if (!tableName2ids.containsKey(currentTable)) { - List currentIds = new LinkedList(); - tableName2ids.put(currentTable, currentIds); - } - currentId = currentId.substring(currentId.indexOf("_") + 1); - tableName2ids.get(currentTable).add(currentId); + } else { + // aggregation case + + // looking for the edge class among the aggregator edges + edgeClass = + dataFetcher.getMapper().getAggregatorEdgeByEdgeTypeName(edgeClassName).getEdgeType(); + + VertexType joinVertexType = + dataFetcher.getMapper().getJoinVertexTypeByAggregatorEdge(edgeClass.getName()); + Entity joinTable = dataFetcher.getMapper().getEntityByVertexType(joinVertexType); + List joinTableRelationships = + new LinkedList<>(joinTable.getOutCanonicalRelationships()); + if (joinTableRelationships.size() != 2) { + throw new RDBMSProviderAggregationException( + "Wrong relationships mapping: " + + "the aggregated " + + joinTable.getName() + + " join table does not have 2 out relationships to represent the N-N" + + " relationship."); + } + Relationship firstJoinTableRelationship = null; + Relationship secondJoinTableRelationship = null; + Entity firstExternalEntity = + null; // the external entity involved in the first join with the join table + Entity secondExternalEntity = + null; // the external entity involved in the second join with the join table + if (direction.equals("out")) { + firstJoinTableRelationship = joinTableRelationships.get(0); + secondJoinTableRelationship = joinTableRelationships.get(1); + firstExternalEntity = firstJoinTableRelationship.getParentEntity(); + secondExternalEntity = secondJoinTableRelationship.getParentEntity(); + } else if (direction.equals("in")) { + firstJoinTableRelationship = joinTableRelationships.get(1); + secondJoinTableRelationship = joinTableRelationships.get(0); + firstExternalEntity = firstJoinTableRelationship.getParentEntity(); + secondExternalEntity = secondJoinTableRelationship.getParentEntity(); } - List queryDtos = dbQueryEngine.buildLoadQueries(tableName2ids); - - List graphDataCollection = new LinkedList(); - for (String currentQueryDto : queryDtos) { - GraphData currGraphData = fetchData(datasource, currentQueryDto, ids.length); - graphDataCollection.add(currGraphData); + // cleaning ids to get the original ones back + List rootNodeIds = + Arrays.asList(roots).stream() + .map(id -> id.substring(id.indexOf("_") + 1)) + .collect(Collectors.toList()); + + // first external entity join: getting join table's records + QueryResult joinTableRecordsResult = + dbQueryEngine.expandRelationship( + joinTable, + firstExternalEntity, + firstJoinTableRelationship.getFromColumns(), + firstJoinTableRelationship.getToColumns(), + rootNodeIds, + direction, + datasource); + + // building the edges from the join table records + GraphData enteringEdgesGraphData = + dataFetcher.buildEdgesFromJoinTableRecords( + joinTableRecordsResult, + edgeClassName, + firstExternalEntity, + joinTable, + secondExternalEntity, + direction); + graphDataCollection.add(enteringEdgesGraphData); + + // new root ids: we need the ids from the join table records + + rootNodeIds = + enteringEdgesGraphData.getEdges().stream() + .map( + cytoData -> { + String id = cytoData.getData().getId(); + id = id.substring(id.indexOf("_") + 1); + return id; + }) + .collect(Collectors.toList()); + + // second external entity join: getting entering entity's records + queryResult = + dbQueryEngine.expandRelationship( + secondExternalEntity, + joinTable, + secondJoinTableRelationship.getFromColumns(), + secondJoinTableRelationship.getToColumns(), + rootNodeIds, + direction, + datasource); + + Map> direction2countQueryResults = + getRelationshipsCountAggregationCase(datasource, secondExternalEntity); + + // getting out relationships counts + outCountResults = direction2countQueryResults.get("out"); + + // getting in relationships counts + inCountResults = direction2countQueryResults.get("in"); + + GraphData enteringNodesGraphData = + dataFetcher.mapResultSet( + queryResult, secondExternalEntity, outCountResults, inCountResults); + graphDataCollection.add(enteringNodesGraphData); + } + } catch (Exception e) { + throw new RDBMSProviderRuntimeException(e); + } finally { + // closing resultset, connection and statement + if (queryResult != null) { + queryResult.close(); + } + for (RelationshipQueryResult outRelationshipsQueryResult : outCountResults) { + if (outRelationshipsQueryResult != null) { + outRelationshipsQueryResult.close(); } - dbQueryEngine.close(); - final GraphData graphData = collectGraphDatasInSingle(graphDataCollection); - return graphData; + } + for (RelationshipQueryResult inRelationshipsQueryResult : inCountResults) { + if (inRelationshipsQueryResult != null) { + inRelationshipsQueryResult.close(); + } + } } - @Override - public GraphData loadFromClass(DataSourceInfo datasource, String className, int limit) { - String query = "select " + className + ".* from " + className + " limit " + limit; - return fetchData(datasource, query, limit); + dbQueryEngine.close(); + final GraphData graphData = collectGraphDatasInSingle(graphDataCollection); + return graphData; + } + + @Override + public GraphData load(DataSourceInfo datasource, String[] ids) { + // preparing the mapper in the data fetcher + prepareMapperAndDataFetcher(datasource); + + // order ids by table + Map> tableName2ids = new LinkedHashMap>(); + + for (String currentId : ids) { + int tableId = Integer.parseInt(currentId.split("_")[0]); + Entity currentTable = dataFetcher.getMapper().getEntityBySchemaPosition(tableId); + if (!tableName2ids.containsKey(currentTable)) { + List currentIds = new LinkedList(); + tableName2ids.put(currentTable, currentIds); + } + currentId = currentId.substring(currentId.indexOf("_") + 1); + tableName2ids.get(currentTable).add(currentId); } - @Override - public GraphData loadFromClass(DataSourceInfo datasource, String className, String propName, String propertyValue, int limit) { - String query = "select " + className + ".* from " + className + " where " + propName + " = '" + propertyValue + "' limit " + limit; + List queryDtos = dbQueryEngine.buildLoadQueries(tableName2ids); - return fetchData(datasource, query, limit); + List graphDataCollection = new LinkedList(); + for (String currentQueryDto : queryDtos) { + GraphData currGraphData = fetchData(datasource, currentQueryDto, ids.length); + graphDataCollection.add(currGraphData); } - - @Override - public boolean testConnection(DataSourceInfo datasource) { - try (Connection connection = DBSourceConnection.getConnection(datasource)) { - log.info("connection works fine:: '{}' ", datasource.getId()); - } catch (Exception e) { - throw new RDBMSProviderRuntimeException(e); - } - return true; + dbQueryEngine.close(); + final GraphData graphData = collectGraphDatasInSingle(graphDataCollection); + return graphData; + } + + @Override + public GraphData loadFromClass(DataSourceInfo datasource, String className, int limit) { + String query = "select " + className + ".* from " + className + " limit " + limit; + return fetchData(datasource, query, limit); + } + + @Override + public GraphData loadFromClass( + DataSourceInfo datasource, + String className, + String propName, + String propertyValue, + int limit) { + String query = + "select " + + className + + ".* from " + + className + + " where " + + propName + + " = '" + + propertyValue + + "' limit " + + limit; + + return fetchData(datasource, query, limit); + } + + @Override + public boolean testConnection(DataSourceInfo datasource) { + try (Connection connection = DBSourceConnection.getConnection(datasource)) { + log.info("connection works fine:: '{}' ", datasource.getId()); + } catch (Exception e) { + throw new RDBMSProviderRuntimeException(e); } - - /** - * Auxiliary functions - */ - - private GraphData collectGraphDatasInSingle(List graphDataCollection) { - // merge all graph data in a single graph data object - Map> nodeClasses = new LinkedHashMap<>(); - Map> edgeClasses = new LinkedHashMap<>(); - Set nodes = new LinkedHashSet(); - Set edges = new LinkedHashSet(); - - for (GraphData currentGraphData : graphDataCollection) { - nodes.addAll(currentGraphData.getNodes()); - edges.addAll(currentGraphData.getEdges()); - nodeClasses.putAll(currentGraphData.getNodesClasses()); - edgeClasses.putAll(currentGraphData.getEdgesClasses()); - } - - return new GraphData(nodeClasses, edgeClasses, nodes, edges, false); + return true; + } + + /** Auxiliary functions */ + private GraphData collectGraphDatasInSingle(List graphDataCollection) { + // merge all graph data in a single graph data object + Map> nodeClasses = new LinkedHashMap<>(); + Map> edgeClasses = new LinkedHashMap<>(); + Set nodes = new LinkedHashSet(); + Set edges = new LinkedHashSet(); + + for (GraphData currentGraphData : graphDataCollection) { + nodes.addAll(currentGraphData.getNodes()); + edges.addAll(currentGraphData.getEdges()); + nodeClasses.putAll(currentGraphData.getNodesClasses()); + edgeClasses.putAll(currentGraphData.getEdgesClasses()); } - /** - * Counting algorithms: base case (without aggregation) - */ - - /** - * Returns a query result containing the joinable records counts for each out relationship and for each record. - * Input Entity cannot be an aggregated join table. - * - * @param datasource the datasource - * @param entity the netity - * @return a list of results - */ - - public List getOutRelationshipsCount(DataSourceInfo datasource, Entity entity) { - return getOutRelationshipsCount(datasource, entity, null, null); + return new GraphData(nodeClasses, edgeClasses, nodes, edges, false); + } + + /** Counting algorithms: base case (without aggregation) */ + + /** + * Returns a query result containing the joinable records counts for each out relationship and for + * each record. Input Entity cannot be an aggregated join table. + * + * @param datasource the datasource + * @param entity the netity + * @return a list of results + */ + public List getOutRelationshipsCount( + DataSourceInfo datasource, Entity entity) { + return getOutRelationshipsCount(datasource, entity, null, null); + } + + public List getOutRelationshipsCount( + DataSourceInfo datasource, + Entity entity, + List filteringColumns, + List filteringRootNodeIds) { + List countResults = new LinkedList<>(); + + for (Relationship currentRelationship : entity.getAllOutCanonicalRelationships()) { + String relationshipName = + dataFetcher + .getMapper() + .getRelationship2edgeType() + .get(currentRelationship) + .getName(); // we choose the correspondent edgeClass name as relationship name + + final RelationshipQueryResult queryResult; + try { + queryResult = + dbQueryEngine.performConnectionCountQueryGroupedByElement( + currentRelationship, + "foreignTable", + filteringColumns, + filteringRootNodeIds, + datasource, + relationshipName); + countResults.add(queryResult); + } catch (SQLException e) { + log.error("unable to get OUT relationship count for :: " + currentRelationship, e); + } } - - public List getOutRelationshipsCount( - DataSourceInfo datasource, - Entity entity, - List filteringColumns, - List filteringRootNodeIds - ) { - List countResults = new LinkedList<>(); - - for (Relationship currentRelationship : entity.getAllOutCanonicalRelationships()) { - String relationshipName = dataFetcher.getMapper().getRelationship2edgeType().get(currentRelationship).getName(); // we choose the correspondent edgeClass name as relationship name - - final RelationshipQueryResult queryResult; - try { - queryResult = - dbQueryEngine.performConnectionCountQueryGroupedByElement( - currentRelationship, - "foreignTable", - filteringColumns, - filteringRootNodeIds, - datasource, - relationshipName - ); - countResults.add(queryResult); - } catch (SQLException e) { - log.error("unable to get OUT relationship count for :: " + currentRelationship, e); - } - } - return countResults; + return countResults; + } + + /** + * Returns a query result containing the joinable records counts for each in relationship and for + * each record. Input Entity cannot be an aggregated join table. + * + * @param datasource the datasource + * @param entity the entity + * @return list of results + */ + public List getInRelationshipsCount( + DataSourceInfo datasource, Entity entity) { + return getInRelationshipsCount(datasource, entity, null, null); + } + + public List getInRelationshipsCount( + DataSourceInfo datasource, + Entity entity, + List filteringColumns, + List filteringRootNodeIds) { + List countResults = new LinkedList<>(); + + for (Relationship currentRelationship : entity.getAllInCanonicalRelationships()) { + String relationshipName = + dataFetcher + .getMapper() + .getRelationship2edgeType() + .get(currentRelationship) + .getName(); // we choose the correspondent edgeClass name as relationship name + + final RelationshipQueryResult queryResult; + try { + queryResult = + dbQueryEngine.performConnectionCountQueryGroupedByElement( + currentRelationship, + "parentTable", + filteringColumns, + filteringRootNodeIds, + datasource, + relationshipName); + countResults.add(queryResult); + } catch (SQLException e) { + log.error("unable to get IN relationship count for :: " + currentRelationship, e); + } } - - /** - * Returns a query result containing the joinable records counts for each in relationship and for each record. - * Input Entity cannot be an aggregated join table. - * - * @param datasource the datasource - * @param entity the entity - * @return list of results + return countResults; + } + + // Counting algorithm: aggregation case + + private Map> getRelationshipsCountAggregationCase( + DataSourceInfo datasource, Entity entity) { + return getRelationshipsCountAggregationCase(datasource, entity, null, null); + } + + private Map> getRelationshipsCountAggregationCase( + DataSourceInfo datasource, + Entity entity, + List filteringColumns, + List filteringRootNodeIds) { + List outCountResults = new LinkedList<>(); + List inCountResults = new LinkedList<>(); + + /* + * Out Relationships */ - public List getInRelationshipsCount(DataSourceInfo datasource, Entity entity) { - return getInRelationshipsCount(datasource, entity, null, null); - } - - public List getInRelationshipsCount( - DataSourceInfo datasource, - Entity entity, - List filteringColumns, - List filteringRootNodeIds - ) { - List countResults = new LinkedList<>(); - - for (Relationship currentRelationship : entity.getAllInCanonicalRelationships()) { - String relationshipName = dataFetcher.getMapper().getRelationship2edgeType().get(currentRelationship).getName(); // we choose the correspondent edgeClass name as relationship name - - final RelationshipQueryResult queryResult; - try { - queryResult = - dbQueryEngine.performConnectionCountQueryGroupedByElement( - currentRelationship, - "parentTable", - filteringColumns, - filteringRootNodeIds, - datasource, - relationshipName - ); - countResults.add(queryResult); - } catch (SQLException e) { - log.error("unable to get IN relationship count for :: " + currentRelationship, e); - } + for (Relationship currentRelationship : entity.getAllOutCanonicalRelationships()) { + String relationshipName = null; + String direction = null; + Entity currParentEntity = currentRelationship.getParentEntity(); + if (currParentEntity.isAggregableJoinTable()) { + // maybe this case is never actual, reported as is symmetrical with the in-relationship-case + // perform counting in the same way but change the edgeName: use the aggregator edge name + VertexType outVertexType = + this.dataFetcher + .getMapper() + .getVertexTypeByEntity(currentRelationship.getForeignEntity()); + VertexType aggregatedVertexType = + this.dataFetcher.getMapper().getVertexTypeByEntity(currParentEntity); + AggregatorEdge aggregatorEdge = + this.dataFetcher + .getMapper() + .getAggregatorEdgeByJoinVertexTypeName(aggregatedVertexType.getName()); + relationshipName = aggregatorEdge.getEdgeType().getName(); + + // direction + if (outVertexType.getName().equals(aggregatorEdge.getOutVertexClassName())) { + direction = "out"; + } else { + direction = "in"; } - return countResults; - } - - // Counting algorithm: aggregation case - - private Map> getRelationshipsCountAggregationCase(DataSourceInfo datasource, Entity entity) { - return getRelationshipsCountAggregationCase(datasource, entity, null, null); + } else { + direction = "out"; // edge direction follows the relationship direction, then is 'out' + relationshipName = + dataFetcher + .getMapper() + .getRelationship2edgeType() + .get(currentRelationship) + .getName(); // we choose the correspondent edgeClass name as relationship name + } + + final RelationshipQueryResult queryResult; + try { + queryResult = + dbQueryEngine.performConnectionCountQueryGroupedByElement( + currentRelationship, + "foreignTable", + filteringColumns, + filteringRootNodeIds, + datasource, + relationshipName); + if (direction.equals("out")) { + outCountResults.add(queryResult); + } else { + inCountResults.add(queryResult); + } + } catch (SQLException e) { + log.error("unable to get OUT relationship count for :: " + currentRelationship, e); + } } - private Map> getRelationshipsCountAggregationCase( - DataSourceInfo datasource, - Entity entity, - List filteringColumns, - List filteringRootNodeIds - ) { - List outCountResults = new LinkedList<>(); - List inCountResults = new LinkedList<>(); - - /* - * Out Relationships - */ - - for (Relationship currentRelationship : entity.getAllOutCanonicalRelationships()) { - String relationshipName = null; - String direction = null; - Entity currParentEntity = currentRelationship.getParentEntity(); - if (currParentEntity.isAggregableJoinTable()) { - // maybe this case is never actual, reported as is symmetrical with the in-relationship-case - // perform counting in the same way but change the edgeName: use the aggregator edge name - VertexType outVertexType = this.dataFetcher.getMapper().getVertexTypeByEntity(currentRelationship.getForeignEntity()); - VertexType aggregatedVertexType = this.dataFetcher.getMapper().getVertexTypeByEntity(currParentEntity); - AggregatorEdge aggregatorEdge = this.dataFetcher.getMapper().getAggregatorEdgeByJoinVertexTypeName(aggregatedVertexType.getName()); - relationshipName = aggregatorEdge.getEdgeType().getName(); - - // direction - if (outVertexType.getName().equals(aggregatorEdge.getOutVertexClassName())) { - direction = "out"; - } else { - direction = "in"; - } - } else { - direction = "out"; // edge direction follows the relationship direction, then is 'out' - relationshipName = dataFetcher.getMapper().getRelationship2edgeType().get(currentRelationship).getName(); // we choose the correspondent edgeClass name as relationship name - } + /* + * In relationships + */ - final RelationshipQueryResult queryResult; - try { - queryResult = - dbQueryEngine.performConnectionCountQueryGroupedByElement( - currentRelationship, - "foreignTable", - filteringColumns, - filteringRootNodeIds, - datasource, - relationshipName - ); - if (direction.equals("out")) { - outCountResults.add(queryResult); - } else { - inCountResults.add(queryResult); - } - } catch (SQLException e) { - log.error("unable to get OUT relationship count for :: " + currentRelationship, e); - } + for (Relationship currentRelationship : entity.getAllInCanonicalRelationships()) { + String relationshipName = null; + String direction = null; + Entity currForeignEntity = currentRelationship.getForeignEntity(); + if (currForeignEntity.isAggregableJoinTable()) { + // perform counting in the same way but change the edgeName: use the aggregator edge name + VertexType inVertexType = + this.dataFetcher + .getMapper() + .getVertexTypeByEntity(currentRelationship.getParentEntity()); + VertexType aggregatedVertexType = + this.dataFetcher.getMapper().getVertexTypeByEntity(currForeignEntity); + AggregatorEdge aggregatorEdge = + this.dataFetcher + .getMapper() + .getAggregatorEdgeByJoinVertexTypeName(aggregatedVertexType.getName()); + relationshipName = aggregatorEdge.getEdgeType().getName(); + + // direction + if (inVertexType.getName().equals(aggregatorEdge.getInVertexClassName())) { + direction = "in"; + } else { + direction = "out"; } - - /* - * In relationships - */ - - for (Relationship currentRelationship : entity.getAllInCanonicalRelationships()) { - String relationshipName = null; - String direction = null; - Entity currForeignEntity = currentRelationship.getForeignEntity(); - if (currForeignEntity.isAggregableJoinTable()) { - // perform counting in the same way but change the edgeName: use the aggregator edge name - VertexType inVertexType = this.dataFetcher.getMapper().getVertexTypeByEntity(currentRelationship.getParentEntity()); - VertexType aggregatedVertexType = this.dataFetcher.getMapper().getVertexTypeByEntity(currForeignEntity); - AggregatorEdge aggregatorEdge = this.dataFetcher.getMapper().getAggregatorEdgeByJoinVertexTypeName(aggregatedVertexType.getName()); - relationshipName = aggregatorEdge.getEdgeType().getName(); - - // direction - if (inVertexType.getName().equals(aggregatorEdge.getInVertexClassName())) { - direction = "in"; - } else { - direction = "out"; - } - } else { - direction = "in"; // edge direction follows the relationship direction, then is 'out' - relationshipName = dataFetcher.getMapper().getRelationship2edgeType().get(currentRelationship).getName(); // we choose the correspondent edgeClass name as relationship name - } - - final RelationshipQueryResult queryResult; - try { - queryResult = - dbQueryEngine.performConnectionCountQueryGroupedByElement( - currentRelationship, - "parentTable", - filteringColumns, - filteringRootNodeIds, - datasource, - relationshipName - ); - if (direction.equals("out")) { - outCountResults.add(queryResult); - } else { - inCountResults.add(queryResult); - } - } catch (SQLException e) { - log.error("unable to get IN relationship count for :: " + currentRelationship, e); - } + } else { + direction = "in"; // edge direction follows the relationship direction, then is 'out' + relationshipName = + dataFetcher + .getMapper() + .getRelationship2edgeType() + .get(currentRelationship) + .getName(); // we choose the correspondent edgeClass name as relationship name + } + + final RelationshipQueryResult queryResult; + try { + queryResult = + dbQueryEngine.performConnectionCountQueryGroupedByElement( + currentRelationship, + "parentTable", + filteringColumns, + filteringRootNodeIds, + datasource, + relationshipName); + if (direction.equals("out")) { + outCountResults.add(queryResult); + } else { + inCountResults.add(queryResult); } - - Map> direction2countQueryResults = new HashMap>(); - direction2countQueryResults.put("out", outCountResults); - direction2countQueryResults.put("in", inCountResults); - return direction2countQueryResults; - } - - @NotNull - @Override - public Set supportedDataSourceTypes() { - return Sets.newHashSet("RDBMS_POSTGRESQL", "RDBMS_MYSQL", "RDBMS_MSSQLSERVER", "RDBMS_HSQL", "RDBMS_ORACLE", "RDBMS_DATA_WORLD"); + } catch (SQLException e) { + log.error("unable to get IN relationship count for :: " + currentRelationship, e); + } } - @NotNull - @Override - public GraphData edges(@NotNull DataSourceInfo dataSource, @NotNull String[] fromIds, @NotNull String[] edgesLabel, @NotNull String[] toIds) { - return null; - } + Map> direction2countQueryResults = + new HashMap>(); + direction2countQueryResults.put("out", outCountResults); + direction2countQueryResults.put("in", inCountResults); + return direction2countQueryResults; + } + + @NotNull + @Override + public Set supportedDataSourceTypes() { + return Sets.newHashSet( + "RDBMS_POSTGRESQL", + "RDBMS_MYSQL", + "RDBMS_MSSQLSERVER", + "RDBMS_HSQL", + "RDBMS_ORACLE", + "RDBMS_DATA_WORLD"); + } + + @NotNull + @Override + public GraphData edges( + @NotNull DataSourceInfo dataSource, + @NotNull String[] fromIds, + @NotNull String[] edgesLabel, + @NotNull String[] toIds) { + return null; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dataprovider/RDBMSGraphProvider.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dataprovider/RDBMSGraphProvider.java index 9625f797..84ef6936 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dataprovider/RDBMSGraphProvider.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dataprovider/RDBMSGraphProvider.java @@ -58,228 +58,257 @@ public class RDBMSGraphProvider implements DataSourceGraphProvider { - private final Logger log = LoggerFactory.getLogger(RDBMSGraphProvider.class); + private final Logger log = LoggerFactory.getLogger(RDBMSGraphProvider.class); - @Override - public void provideTo(DataSourceInfo datasource, final SpritePlayer player) { - Statistics statistics = new Statistics(); + @Override + public void provideTo(DataSourceInfo datasource, final SpritePlayer player) { + Statistics statistics = new Statistics(); - String connectionUrl = DBSourceConnection.createConnectionUrl(datasource); - try { - final ER2GraphMapper mapper = prepareMapperAndDataFetcher(datasource, statistics); + String connectionUrl = DBSourceConnection.createConnectionUrl(datasource); + try { + final ER2GraphMapper mapper = prepareMapperAndDataFetcher(datasource, statistics); - DBQueryEngine dbQueryEngine = new DBQueryEngine(datasource, 300); + DBQueryEngine dbQueryEngine = new DBQueryEngine(datasource, 300); - final Map entity2count = countEntities(datasource, mapper); + final Map entity2count = countEntities(datasource, mapper); - for (Map.Entry entry : entity2count.entrySet()) { - Entity currentEntity = entry.getKey(); - final String tableName = entry.getKey().getName(); - String query = "select * from " + tableName; - if (datasource.getType().equals("RDBMS_DATA_WORLD")) { - query = "select " + tableName + ".*, row_index from " + tableName; - } - // String tableName = query.substring(query.lastIndexOf("from ") + 5); - int count = entry.getValue(); - log.info("fetching data from source'{}', table '{}' with query '{}' - total records '{}' ", connectionUrl, tableName, query, count); - - QueryResult queryResult = dbQueryEngine.executeQuery(query, datasource); - ResultSet result = queryResult.getResult(); - - while (result.next()) { - ResultSet currentRecord = result; - - ResultSetMetaData rsmd = currentRecord.getMetaData(); - int columnCount = rsmd.getColumnCount(); - - String id = getCytoIdFromPrimaryKey(currentRecord, currentEntity); - String vertexClassName = mapper.getVertexTypeByEntity(currentEntity).getName(); - Sprite document = new Sprite() - .add("@class", vertexClassName) - .add(com.arcadeanalytics.provider.IndexConstants.ARCADE_ID, id) - .add(com.arcadeanalytics.provider.IndexConstants.ARCADE_TYPE, com.arcadeanalytics.provider.IndexConstants.ARCADE_NODE_TYPE); - for (int i = 1; i <= columnCount; i++) { - document.add(rsmd.getColumnName(i), currentRecord.getObject(i)); - } - player.play(document); - } - player.end(); - - // releasing the resources - queryResult.close(); - } - player.end(); - - if (datasource.isAggregationEnabled()) { - final Map jointTable2count = countJoinTables(datasource, mapper); - // we have to index just the aggregator edges - for (Map.Entry entry : jointTable2count.entrySet()) { - Entity currentEntity = entry.getKey(); - if (currentEntity.isAggregableJoinTable()) { - String query = "select * from " + entry.getKey().getName(); - String tableName = query.substring(query.lastIndexOf("from ") + 5); - int count = entry.getValue(); - log.info("fetching data from source'{}', table '{}' with query '{}' - total records '{}' ", connectionUrl, tableName, query, count); - - QueryResult queryResult = dbQueryEngine.executeQuery(query, datasource); - ResultSet result = queryResult.getResult(); - - while (result.next()) { - ResultSet currentRecord = result; - - ResultSetMetaData rsmd = currentRecord.getMetaData(); - int columnCount = rsmd.getColumnCount(); - - String id = getCytoIdFromPrimaryKey(currentRecord, currentEntity); - VertexType vertextype = mapper.getVertexTypeByEntity(currentEntity); - String edgeClassName = mapper.getAggregatorEdgeByJoinVertexTypeName(vertextype.getName()).getEdgeType().getName(); - Sprite document = new Sprite() - .add("@class", edgeClassName) - .add(com.arcadeanalytics.provider.IndexConstants.ARCADE_ID, id) - .add(com.arcadeanalytics.provider.IndexConstants.ARCADE_TYPE, com.arcadeanalytics.provider.IndexConstants.ARCADE_EDGE_TYPE); - List pkColumnsNames = currentEntity - .getPrimaryKey() - .getInvolvedAttributes() - .stream() - .map(attribute -> attribute.getName()) - .collect(Collectors.toList()); - for (int i = 1; i <= columnCount; i++) { - if (!pkColumnsNames.contains(rsmd.getColumnName(i))) { - document.add(rsmd.getColumnName(i), currentRecord.getObject(i)); - } - } - player.play(document); - } - player.end(); - - // releasing the resources - queryResult.close(); - } + for (Map.Entry entry : entity2count.entrySet()) { + Entity currentEntity = entry.getKey(); + final String tableName = entry.getKey().getName(); + String query = "select * from " + tableName; + if (datasource.getType().equals("RDBMS_DATA_WORLD")) { + query = "select " + tableName + ".*, row_index from " + tableName; + } + // String tableName = query.substring(query.lastIndexOf("from ") + 5); + int count = entry.getValue(); + log.info( + "fetching data from source'{}', table '{}' with query '{}' - total records '{}' ", + connectionUrl, + tableName, + query, + count); + + QueryResult queryResult = dbQueryEngine.executeQuery(query, datasource); + ResultSet result = queryResult.getResult(); + + while (result.next()) { + ResultSet currentRecord = result; + + ResultSetMetaData rsmd = currentRecord.getMetaData(); + int columnCount = rsmd.getColumnCount(); + + String id = getCytoIdFromPrimaryKey(currentRecord, currentEntity); + String vertexClassName = mapper.getVertexTypeByEntity(currentEntity).getName(); + Sprite document = + new Sprite() + .add("@class", vertexClassName) + .add(com.arcadeanalytics.provider.IndexConstants.ARCADE_ID, id) + .add( + com.arcadeanalytics.provider.IndexConstants.ARCADE_TYPE, + com.arcadeanalytics.provider.IndexConstants.ARCADE_NODE_TYPE); + for (int i = 1; i <= columnCount; i++) { + document.add(rsmd.getColumnName(i), currentRecord.getObject(i)); + } + player.play(document); + } + player.end(); + + // releasing the resources + queryResult.close(); + } + player.end(); + + if (datasource.isAggregationEnabled()) { + final Map jointTable2count = countJoinTables(datasource, mapper); + // we have to index just the aggregator edges + for (Map.Entry entry : jointTable2count.entrySet()) { + Entity currentEntity = entry.getKey(); + if (currentEntity.isAggregableJoinTable()) { + String query = "select * from " + entry.getKey().getName(); + String tableName = query.substring(query.lastIndexOf("from ") + 5); + int count = entry.getValue(); + log.info( + "fetching data from source'{}', table '{}' with query '{}' - total records '{}' ", + connectionUrl, + tableName, + query, + count); + + QueryResult queryResult = dbQueryEngine.executeQuery(query, datasource); + ResultSet result = queryResult.getResult(); + + while (result.next()) { + ResultSet currentRecord = result; + + ResultSetMetaData rsmd = currentRecord.getMetaData(); + int columnCount = rsmd.getColumnCount(); + + String id = getCytoIdFromPrimaryKey(currentRecord, currentEntity); + VertexType vertextype = mapper.getVertexTypeByEntity(currentEntity); + String edgeClassName = + mapper + .getAggregatorEdgeByJoinVertexTypeName(vertextype.getName()) + .getEdgeType() + .getName(); + Sprite document = + new Sprite() + .add("@class", edgeClassName) + .add(com.arcadeanalytics.provider.IndexConstants.ARCADE_ID, id) + .add( + com.arcadeanalytics.provider.IndexConstants.ARCADE_TYPE, + com.arcadeanalytics.provider.IndexConstants.ARCADE_EDGE_TYPE); + List pkColumnsNames = + currentEntity.getPrimaryKey().getInvolvedAttributes().stream() + .map(attribute -> attribute.getName()) + .collect(Collectors.toList()); + for (int i = 1; i <= columnCount; i++) { + if (!pkColumnsNames.contains(rsmd.getColumnName(i))) { + document.add(rsmd.getColumnName(i), currentRecord.getObject(i)); } + } + player.play(document); } player.end(); - dbQueryEngine.close(); - } catch (Exception e) { - log.error("error while connecting to " + datasource, e); + // releasing the resources + queryResult.close(); + } } - } + } + player.end(); - public ER2GraphMapper prepareMapperAndDataFetcher(DataSourceInfo datasource, Statistics statistics) { - DBQueryEngine dbQueryEngine = new DBQueryEngine(datasource, 300); - - final Boolean aggregate = datasource.isAggregationEnabled(); - - String chosenStrategy = aggregate ? "interactive-aggr" : "interactive"; - - DataTypeHandlerFactory dataTypeHandlerFactory = new DataTypeHandlerFactory(); - DBMSDataTypeHandler handler = dataTypeHandlerFactory.buildDataTypeHandler(datasource.getType()); - - NameResolverFactory nameResolverFactory = new NameResolverFactory(); - NameResolver nameResolver = nameResolverFactory.buildNameResolver("original"); - - StrategyFactory strategyFactory = new StrategyFactory(); - try { - ER2GraphMapper mapper = - ((AbstractDBMSModelBuildingStrategy) strategyFactory.buildStrategy(chosenStrategy)).createSchemaMapper( - datasource, - null, - "basicDBMapper", - null, - nameResolver, - handler, - null, - null, - chosenStrategy, - dbQueryEngine, - statistics - ); - return mapper; - } catch (RDBMSProviderIOException e) { - throw new RuntimeException(e); - } + dbQueryEngine.close(); + } catch (Exception e) { + log.error("error while connecting to " + datasource, e); } - - public Map countEntities(DataSourceInfo datasource, ER2GraphMapper mapper) throws Exception { - // get all table names - try (Connection connection = DBSourceConnection.getConnection(datasource)) { - Map entity2count = new LinkedHashMap<>(); - - List entities = mapper.getDataBaseSchema().getEntities(); - if (datasource.isAggregationEnabled()) { - // filtering out the join tables - entities = - entities - .stream() - .filter( - entity -> { - if (!entity.isAggregableJoinTable()) { - return true; - } - return false; - } - ) - .collect(Collectors.toList()); - } - - // Giving db's table names and building all the queries, then adding them to the instance variable - for (Entity currEntity : entities) { - String tableName = currEntity.getName(); - String countQuery = "select count(*) from " + tableName; - - Statement countStatement = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); - ResultSet resultCount = countStatement.executeQuery(countQuery); - resultCount.next(); - int count = resultCount.getInt(1); - entity2count.put(currEntity, count); - - resultCount.close(); - countStatement.close(); - } - - return entity2count; - } catch (SQLException e) { - throw new RDBMSProviderRuntimeException(e); - } + } + + public ER2GraphMapper prepareMapperAndDataFetcher( + DataSourceInfo datasource, Statistics statistics) { + DBQueryEngine dbQueryEngine = new DBQueryEngine(datasource, 300); + + final Boolean aggregate = datasource.isAggregationEnabled(); + + String chosenStrategy = aggregate ? "interactive-aggr" : "interactive"; + + DataTypeHandlerFactory dataTypeHandlerFactory = new DataTypeHandlerFactory(); + DBMSDataTypeHandler handler = dataTypeHandlerFactory.buildDataTypeHandler(datasource.getType()); + + NameResolverFactory nameResolverFactory = new NameResolverFactory(); + NameResolver nameResolver = nameResolverFactory.buildNameResolver("original"); + + StrategyFactory strategyFactory = new StrategyFactory(); + try { + ER2GraphMapper mapper = + ((AbstractDBMSModelBuildingStrategy) strategyFactory.buildStrategy(chosenStrategy)) + .createSchemaMapper( + datasource, + null, + "basicDBMapper", + null, + nameResolver, + handler, + null, + null, + chosenStrategy, + dbQueryEngine, + statistics); + return mapper; + } catch (RDBMSProviderIOException e) { + throw new RuntimeException(e); } - - public Map countJoinTables(DataSourceInfo datasource, ER2GraphMapper mapper) throws Exception { - // get all table names - try (Connection connection = DBSourceConnection.getConnection(datasource)) { - Map jointTable2count = new LinkedHashMap<>(); - Statement countStatement = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); - - Set joinVertices = mapper.getJoinVertex2aggregatorEdges().keySet(); - for (VertexType currJoinVertexType : joinVertices) { - Entity currEntity = mapper.getEntityByVertexType(currJoinVertexType); - String tableName = currEntity.getName(); - String countQuery = "select count(*) from " + tableName; - ResultSet resultCount = countStatement.executeQuery(countQuery); - resultCount.next(); - int count = resultCount.getInt(1); - resultCount.close(); - jointTable2count.put(currEntity, count); - } - return jointTable2count; - } catch (SQLException e) { - throw new RDBMSProviderRuntimeException(e); - } + } + + public Map countEntities(DataSourceInfo datasource, ER2GraphMapper mapper) + throws Exception { + // get all table names + try (Connection connection = DBSourceConnection.getConnection(datasource)) { + Map entity2count = new LinkedHashMap<>(); + + List entities = mapper.getDataBaseSchema().getEntities(); + if (datasource.isAggregationEnabled()) { + // filtering out the join tables + entities = + entities.stream() + .filter( + entity -> { + if (!entity.isAggregableJoinTable()) { + return true; + } + return false; + }) + .collect(Collectors.toList()); + } + + // Giving db's table names and building all the queries, then adding them to the instance + // variable + for (Entity currEntity : entities) { + String tableName = currEntity.getName(); + String countQuery = "select count(*) from " + tableName; + + Statement countStatement = + connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); + ResultSet resultCount = countStatement.executeQuery(countQuery); + resultCount.next(); + int count = resultCount.getInt(1); + entity2count.put(currEntity, count); + + resultCount.close(); + countStatement.close(); + } + + return entity2count; + } catch (SQLException e) { + throw new RDBMSProviderRuntimeException(e); } - - private String getCytoIdFromPrimaryKey(ResultSet sourceRecord, Entity entity) throws SQLException { - PrimaryKey primaryKey = entity.getPrimaryKey(); - String id = entity.getSchemaPosition() + "_"; - - for (Attribute attribute : primaryKey.getInvolvedAttributes()) { - id += sourceRecord.getString(attribute.getName()) + "_"; - } - id = id.substring(0, id.lastIndexOf("_")); - return id; + } + + public Map countJoinTables(DataSourceInfo datasource, ER2GraphMapper mapper) + throws Exception { + // get all table names + try (Connection connection = DBSourceConnection.getConnection(datasource)) { + Map jointTable2count = new LinkedHashMap<>(); + Statement countStatement = + connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); + + Set joinVertices = mapper.getJoinVertex2aggregatorEdges().keySet(); + for (VertexType currJoinVertexType : joinVertices) { + Entity currEntity = mapper.getEntityByVertexType(currJoinVertexType); + String tableName = currEntity.getName(); + String countQuery = "select count(*) from " + tableName; + ResultSet resultCount = countStatement.executeQuery(countQuery); + resultCount.next(); + int count = resultCount.getInt(1); + resultCount.close(); + jointTable2count.put(currEntity, count); + } + return jointTable2count; + } catch (SQLException e) { + throw new RDBMSProviderRuntimeException(e); } + } + + private String getCytoIdFromPrimaryKey(ResultSet sourceRecord, Entity entity) + throws SQLException { + PrimaryKey primaryKey = entity.getPrimaryKey(); + String id = entity.getSchemaPosition() + "_"; - @NotNull - @Override - public Set supportedDataSourceTypes() { - return Sets.newHashSet("RDBMS_POSTGRESQL", "RDBMS_MYSQL", "RDBMS_MSSQLSERVER", "RDBMS_HSQL", "RDBMS_ORACLE", "RDBMS_DATA_WORLD"); + for (Attribute attribute : primaryKey.getInvolvedAttributes()) { + id += sourceRecord.getString(attribute.getName()) + "_"; } + id = id.substring(0, id.lastIndexOf("_")); + return id; + } + + @NotNull + @Override + public Set supportedDataSourceTypes() { + return Sets.newHashSet( + "RDBMS_POSTGRESQL", + "RDBMS_MYSQL", + "RDBMS_MSSQLSERVER", + "RDBMS_HSQL", + "RDBMS_ORACLE", + "RDBMS_DATA_WORLD"); + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dbengine/CommonQueryBuilder.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dbengine/CommonQueryBuilder.java index 74e60142..13eee894 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dbengine/CommonQueryBuilder.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dbengine/CommonQueryBuilder.java @@ -32,190 +32,294 @@ * * @author Gabriele Ponzi */ - public class CommonQueryBuilder implements QueryBuilder { - protected String quote; - - public CommonQueryBuilder() { - this.quote = "\""; - } + protected String quote; - @Override - public String countTableRecords(String currentTableName, String currentTableSchema) { - String query; + public CommonQueryBuilder() { + this.quote = "\""; + } - if (currentTableSchema != null) query = "select count(*) from " + currentTableSchema + "." + this.quote + currentTableName + this.quote; else query = - "select count(*) from " + quote + currentTableName + this.quote; + @Override + public String countTableRecords(String currentTableName, String currentTableSchema) { + String query; - return query; - } + if (currentTableSchema != null) + query = + "select count(*) from " + + currentTableSchema + + "." + + this.quote + + currentTableName + + this.quote; + else query = "select count(*) from " + quote + currentTableName + this.quote; - @Override - public String getRecordById(Entity entity, String[] propertyOfKey, String[] valueOfKey) { - String query; + return query; + } - String entityName = entity.getName(); - String entitySchema = entity.getSchemaName(); + @Override + public String getRecordById(Entity entity, String[] propertyOfKey, String[] valueOfKey) { + String query; - if (entitySchema != null) query = "select * from " + entitySchema + "." + this.quote + entityName + this.quote + " where "; else query = - "select * from " + this.quote + entityName + this.quote + " where "; + String entityName = entity.getName(); + String entitySchema = entity.getSchemaName(); - query += this.quote + propertyOfKey[0] + this.quote + " = '" + valueOfKey[0] + "'"; + if (entitySchema != null) + query = + "select * from " + entitySchema + "." + this.quote + entityName + this.quote + " where "; + else query = "select * from " + this.quote + entityName + this.quote + " where "; - if (propertyOfKey.length > 1) { - for (int i = 1; i < propertyOfKey.length; i++) { - query += " and " + this.quote + propertyOfKey[i] + this.quote + " = '" + valueOfKey[i] + "'"; - } - } + query += this.quote + propertyOfKey[0] + this.quote + " = '" + valueOfKey[0] + "'"; - return query; + if (propertyOfKey.length > 1) { + for (int i = 1; i < propertyOfKey.length; i++) { + query += + " and " + this.quote + propertyOfKey[i] + this.quote + " = '" + valueOfKey[i] + "'"; + } } - @Override - public String getRecordsByEntity(Entity entity) { - String query; - - String entityName = entity.getName(); - String entitySchema = entity.getSchemaName(); - - if (entitySchema != null) query = "select * from " + entitySchema + "." + this.quote + entityName + this.quote; else query = - "select * from " + this.quote + entityName + this.quote; - - return query; + return query; + } + + @Override + public String getRecordsByEntity(Entity entity) { + String query; + + String entityName = entity.getName(); + String entitySchema = entity.getSchemaName(); + + if (entitySchema != null) + query = "select * from " + entitySchema + "." + this.quote + entityName + this.quote; + else query = "select * from " + this.quote + entityName + this.quote; + + return query; + } + + @Override + public String getRecordsFromMultipleEntities(List mappedEntities, String[][] columns) { + String query; + + Entity first = mappedEntities.get(0); + if (first.getSchemaName() != null) + query = + "select * from " + + first.getSchemaName() + + "." + + this.quote + + first.getName() + + this.quote + + " as t0\n"; + else query = "select * from " + this.quote + first.getName() + this.quote + " as t0\n"; + + for (int i = 1; i < mappedEntities.size(); i++) { + Entity currentEntity = mappedEntities.get(i); + query += + " full outer join " + + currentEntity.getSchemaName() + + "." + + this.quote + + currentEntity.getName() + + this.quote + + " as t" + + i; + query += + " on t" + + (i - 1) + + "." + + this.quote + + columns[i - 1][0] + + this.quote + + " = t" + + i + + "." + + this.quote + + columns[i][0] + + this.quote; + + for (int k = 1; k < columns[i].length; k++) { + query += + " and t" + + (i - 1) + + "." + + this.quote + + columns[i - 1][k] + + this.quote + + " = t" + + i + + "." + + this.quote + + columns[i][k] + + this.quote; + } + + query += "\n"; } - @Override - public String getRecordsFromMultipleEntities(List mappedEntities, String[][] columns) { - String query; - - Entity first = mappedEntities.get(0); - if (first.getSchemaName() != null) query = - "select * from " + first.getSchemaName() + "." + this.quote + first.getName() + this.quote + " as t0\n"; else query = - "select * from " + this.quote + first.getName() + this.quote + " as t0\n"; - - for (int i = 1; i < mappedEntities.size(); i++) { - Entity currentEntity = mappedEntities.get(i); - query += " full outer join " + currentEntity.getSchemaName() + "." + this.quote + currentEntity.getName() + this.quote + " as t" + i; - query += " on t" + (i - 1) + "." + this.quote + columns[i - 1][0] + this.quote + " = t" + i + "." + this.quote + columns[i][0] + this.quote; - - for (int k = 1; k < columns[i].length; k++) { - query += " and t" + (i - 1) + "." + this.quote + columns[i - 1][k] + this.quote + " = t" + i + "." + this.quote + columns[i][k] + this.quote; - } - - query += "\n"; - } - - return query; + return query; + } + + @Override + public String getRecordsFromSingleTableByDiscriminatorValue( + String discriminatorColumn, String currentDiscriminatorValue, Entity entity) { + String query; + + String entityName = entity.getName(); + String entitySchema = entity.getSchemaName(); + + if (entitySchema != null) + query = "select * from " + entitySchema + "." + this.quote + entityName + this.quote; + else query = "select * from " + this.quote + entityName + this.quote; + + query += + " where " + + this.quote + + discriminatorColumn + + this.quote + + "='" + + currentDiscriminatorValue + + "'"; + + return query; + } + + @Override + public String getEntityTypeFromSingleTable( + String discriminatorColumn, + Entity physicalEntity, + String[] propertyOfKey, + String[] valueOfKey) { + String query; + + String physicalEntityName = physicalEntity.getName(); + String entitySchema = physicalEntity.getSchemaName(); + + if (entitySchema != null) + query = + "select " + + discriminatorColumn + + " from " + + entitySchema + + "." + + this.quote + + physicalEntityName + + this.quote + + " where "; + else + query = + "select " + + discriminatorColumn + + " from " + + this.quote + + physicalEntityName + + this.quote + + " where "; + + query += this.quote + propertyOfKey[0] + this.quote + " = '" + valueOfKey[0] + "'"; + + if (propertyOfKey.length > 1) { + for (int i = 1; i < propertyOfKey.length; i++) { + query += + " and " + this.quote + propertyOfKey[i] + this.quote + " = '" + valueOfKey[i] + "'"; + } } - @Override - public String getRecordsFromSingleTableByDiscriminatorValue(String discriminatorColumn, String currentDiscriminatorValue, Entity entity) { - String query; - - String entityName = entity.getName(); - String entitySchema = entity.getSchemaName(); - - if (entitySchema != null) query = "select * from " + entitySchema + "." + this.quote + entityName + this.quote; else query = - "select * from " + this.quote + entityName + this.quote; - - query += " where " + this.quote + discriminatorColumn + this.quote + "='" + currentDiscriminatorValue + "'"; - - return query; + return query; + } + + @Override + public String buildAggregateTableFromHierarchicalBag(HierarchicalBag bag) { + String query; + + Iterator it = bag.getDepth2entities().get(0).iterator(); + Entity rootEntity = it.next(); + + if (rootEntity.getSchemaName() != null) + query = + "select * from " + + rootEntity.getSchemaName() + + "." + + this.quote + + rootEntity.getName() + + this.quote + + " as t0\n"; + else query = "select * from " + this.quote + rootEntity.getName() + this.quote + " as t0\n"; + + String[] rootEntityPropertyOfKey = + new String + [rootEntity + .getPrimaryKey() + .getInvolvedAttributes() + .size()]; // collects the attributes of the root-entity's primary key + + // filling the rootPropertyOfKey from the primary key of the rootEntity + for (int j = 0; j < rootEntity.getPrimaryKey().getInvolvedAttributes().size(); j++) { + rootEntityPropertyOfKey[j] = + rootEntity.getPrimaryKey().getInvolvedAttributes().get(j).getName(); } - @Override - public String getEntityTypeFromSingleTable(String discriminatorColumn, Entity physicalEntity, String[] propertyOfKey, String[] valueOfKey) { - String query; - - String physicalEntityName = physicalEntity.getName(); - String entitySchema = physicalEntity.getSchemaName(); - - if (entitySchema != null) query = - "select " + discriminatorColumn + " from " + entitySchema + "." + this.quote + physicalEntityName + this.quote + " where "; else query = - "select " + discriminatorColumn + " from " + this.quote + physicalEntityName + this.quote + " where "; - - query += this.quote + propertyOfKey[0] + this.quote + " = '" + valueOfKey[0] + "'"; - - if (propertyOfKey.length > 1) { - for (int i = 1; i < propertyOfKey.length; i++) { - query += " and " + this.quote + propertyOfKey[i] + this.quote + " = '" + valueOfKey[i] + "'"; - } + String[] currentEntityPropertyOfKey = + new String + [rootEntity + .getPrimaryKey() + .getInvolvedAttributes() + .size()]; // collects the attributes of the current-entity's primary key + + Entity currentEntity; + int thTable = 1; + for (int i = 1; i < bag.getDepth2entities().size(); i++) { + it = bag.getDepth2entities().get(i).iterator(); + + while (it.hasNext()) { + currentEntity = it.next(); + int index = 0; + for (Attribute attribute : currentEntity.getPrimaryKey().getInvolvedAttributes()) { + currentEntityPropertyOfKey[index] = attribute.getName(); + index++; } - return query; - } - - @Override - public String buildAggregateTableFromHierarchicalBag(HierarchicalBag bag) { - String query; - - Iterator it = bag.getDepth2entities().get(0).iterator(); - Entity rootEntity = it.next(); - - if (rootEntity.getSchemaName() != null) query = - "select * from " + rootEntity.getSchemaName() + "." + this.quote + rootEntity.getName() + this.quote + " as t0\n"; else query = - "select * from " + this.quote + rootEntity.getName() + this.quote + " as t0\n"; - - String[] rootEntityPropertyOfKey = new String[rootEntity.getPrimaryKey().getInvolvedAttributes().size()]; // collects the attributes of the root-entity's primary key - - // filling the rootPropertyOfKey from the primary key of the rootEntity - for (int j = 0; j < rootEntity.getPrimaryKey().getInvolvedAttributes().size(); j++) { - rootEntityPropertyOfKey[j] = rootEntity.getPrimaryKey().getInvolvedAttributes().get(j).getName(); + if (currentEntity.getSchemaName() != null) + query += + "left join " + + currentEntity.getSchemaName() + + "." + + this.quote + + currentEntity.getName() + + this.quote; + else query += "left join " + this.quote + currentEntity.getName() + this.quote; + + query += + " as t" + + thTable + + " on t0." + + this.quote + + rootEntityPropertyOfKey[0] + + this.quote + + " = t" + + thTable + + "." + + this.quote + + currentEntityPropertyOfKey[0] + + this.quote; + + for (int k = 1; k < currentEntityPropertyOfKey.length; k++) { + query += + " and " + + this.quote + + rootEntityPropertyOfKey[k] + + this.quote + + " = t" + + thTable + + "." + + this.quote + + currentEntityPropertyOfKey[0] + + this.quote; } - String[] currentEntityPropertyOfKey = new String[rootEntity.getPrimaryKey().getInvolvedAttributes().size()]; // collects the attributes of the current-entity's primary key - - Entity currentEntity; - int thTable = 1; - for (int i = 1; i < bag.getDepth2entities().size(); i++) { - it = bag.getDepth2entities().get(i).iterator(); - - while (it.hasNext()) { - currentEntity = it.next(); - int index = 0; - for (Attribute attribute : currentEntity.getPrimaryKey().getInvolvedAttributes()) { - currentEntityPropertyOfKey[index] = attribute.getName(); - index++; - } - - if (currentEntity.getSchemaName() != null) query += - "left join " + currentEntity.getSchemaName() + "." + this.quote + currentEntity.getName() + this.quote; else query += - "left join " + this.quote + currentEntity.getName() + this.quote; - - query += - " as t" + - thTable + - " on t0." + - this.quote + - rootEntityPropertyOfKey[0] + - this.quote + - " = t" + - thTable + - "." + - this.quote + - currentEntityPropertyOfKey[0] + - this.quote; - - for (int k = 1; k < currentEntityPropertyOfKey.length; k++) { - query += - " and " + - this.quote + - rootEntityPropertyOfKey[k] + - this.quote + - " = t" + - thTable + - "." + - this.quote + - currentEntityPropertyOfKey[0] + - this.quote; - } - - query += "\n"; - thTable++; - } - } - - return query; + query += "\n"; + thTable++; + } } + + return query; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dbengine/DBQueryEngine.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dbengine/DBQueryEngine.java index 1dd08b82..725113ba 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dbengine/DBQueryEngine.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dbengine/DBQueryEngine.java @@ -43,321 +43,396 @@ import org.slf4j.LoggerFactory; /** - * Implementation of DataSourceQueryEngine. It executes the necessary queries for the source DB records fetching. + * Implementation of DataSourceQueryEngine. It executes the necessary queries for the source DB + * records fetching. * * @author Gabriele Ponzi */ - public class DBQueryEngine implements DataSourceQueryEngine { - private static final Logger log = LoggerFactory.getLogger(DBQueryEngine.class); - - private final QueryBuilder queryBuilder; - private final DataSourceInfo dataSource; - private final int maxElements; - private final Connection dbConnection; - - public DBQueryEngine(DataSourceInfo dataSource, int maxElements) { - this.dataSource = dataSource; - this.maxElements = maxElements; - QueryBuilderFactory queryBuilderFactory = new QueryBuilderFactory(); - this.queryBuilder = queryBuilderFactory.buildQueryBuilder(dataSource.getType()); - dbConnection = DBSourceConnection.getConnection(dataSource); - } - - public Connection getDbConnection() { - return dbConnection; - } - - public QueryResult countTableRecords(String currentTableName, String currentTableSchema) throws SQLException { - String query = queryBuilder.countTableRecords(currentTableName, currentTableSchema); - return this.executeQuery(query, dataSource); - } - - public QueryResult countTableRecords(String tableName) throws SQLException { - String query = "select count(*) from " + tableName; - return this.executeQuery(query, dataSource); - } - - public QueryResult getRecordById(Entity entity, String[] propertyOfKey, String[] valueOfKey) throws SQLException { - // TODO: queryBuilder fetching - String query = queryBuilder.getRecordById(entity, propertyOfKey, valueOfKey); - return executeQuery(query, entity.getDataSource()); - } - - public QueryResult getRecordsByEntity(Entity entity) throws SQLException { - // TODO: queryBuilder fetching - String query = queryBuilder.getRecordsByEntity(entity); - return executeQuery(query, entity.getDataSource()); - } - - public QueryResult getRecordsFromMultipleEntities(List mappedEntities, String[][] columns) throws SQLException { - DataSourceInfo sourceDBInfo = mappedEntities.get(0).getDataSource(); // all the entities belong to the same source database - // TODO: queryBuilder fetching - String query = queryBuilder.getRecordsFromMultipleEntities(mappedEntities, columns); - return executeQuery(query, sourceDBInfo); + private static final Logger log = LoggerFactory.getLogger(DBQueryEngine.class); + + private final QueryBuilder queryBuilder; + private final DataSourceInfo dataSource; + private final int maxElements; + private final Connection dbConnection; + + public DBQueryEngine(DataSourceInfo dataSource, int maxElements) { + this.dataSource = dataSource; + this.maxElements = maxElements; + QueryBuilderFactory queryBuilderFactory = new QueryBuilderFactory(); + this.queryBuilder = queryBuilderFactory.buildQueryBuilder(dataSource.getType()); + dbConnection = DBSourceConnection.getConnection(dataSource); + } + + public Connection getDbConnection() { + return dbConnection; + } + + public QueryResult countTableRecords(String currentTableName, String currentTableSchema) + throws SQLException { + String query = queryBuilder.countTableRecords(currentTableName, currentTableSchema); + return this.executeQuery(query, dataSource); + } + + public QueryResult countTableRecords(String tableName) throws SQLException { + String query = "select count(*) from " + tableName; + return this.executeQuery(query, dataSource); + } + + public QueryResult getRecordById(Entity entity, String[] propertyOfKey, String[] valueOfKey) + throws SQLException { + // TODO: queryBuilder fetching + String query = queryBuilder.getRecordById(entity, propertyOfKey, valueOfKey); + return executeQuery(query, entity.getDataSource()); + } + + public QueryResult getRecordsByEntity(Entity entity) throws SQLException { + // TODO: queryBuilder fetching + String query = queryBuilder.getRecordsByEntity(entity); + return executeQuery(query, entity.getDataSource()); + } + + public QueryResult getRecordsFromMultipleEntities(List mappedEntities, String[][] columns) + throws SQLException { + DataSourceInfo sourceDBInfo = + mappedEntities + .get(0) + .getDataSource(); // all the entities belong to the same source database + // TODO: queryBuilder fetching + String query = queryBuilder.getRecordsFromMultipleEntities(mappedEntities, columns); + return executeQuery(query, sourceDBInfo); + } + + public QueryResult getRecordsFromSingleTableByDiscriminatorValue( + String discriminatorColumn, String currentDiscriminatorValue, Entity entity) + throws SQLException { + // TODO: queryBuilder fetching + String query = + queryBuilder.getRecordsFromSingleTableByDiscriminatorValue( + discriminatorColumn, currentDiscriminatorValue, entity); + return executeQuery(query, entity.getDataSource()); + } + + public QueryResult getEntityTypeFromSingleTable( + String discriminatorColumn, Entity entity, String[] propertyOfKey, String[] valueOfKey) + throws SQLException { + // TODO: queryBuilder fetching + String query = + queryBuilder.getEntityTypeFromSingleTable( + discriminatorColumn, entity, propertyOfKey, valueOfKey); + return executeQuery(query, entity.getDataSource()); + } + + public QueryResult buildAggregateTableFromHierarchicalBag(HierarchicalBag bag) + throws SQLException { + // TODO: queryBuilder fetching + String query = queryBuilder.buildAggregateTableFromHierarchicalBag(bag); + return executeQuery(query, bag.getSourceDataseInfo()); + } + + public QueryResult executeQuery(String query, DataSourceInfo dataSource) throws SQLException { + log.debug("query:: {}", query); + + Statement statement = + dbConnection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); + ResultSet result = statement.executeQuery(query); + + return new QueryResult(dbConnection, statement, result, query); + } + + public QueryResult scanTableAndOrder( + String query, int limit, Entity entity, DataSourceInfo dataSource) throws SQLException { + Statement statement = + dbConnection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); + + // setting the threshold for the number of rows + statement.setMaxRows(limit); + + String limitStatement = null; + String sqlQuery = query; + if (sqlQuery.contains("LIMIT")) { + int index = sqlQuery.lastIndexOf(" LIMIT"); + limitStatement = sqlQuery.substring(index); + sqlQuery = sqlQuery.substring(0, index); } - public QueryResult getRecordsFromSingleTableByDiscriminatorValue(String discriminatorColumn, String currentDiscriminatorValue, Entity entity) - throws SQLException { - // TODO: queryBuilder fetching - String query = queryBuilder.getRecordsFromSingleTableByDiscriminatorValue(discriminatorColumn, currentDiscriminatorValue, entity); - return executeQuery(query, entity.getDataSource()); + // adding ordering to the query by primary key columns + if (entity.getPrimaryKey() != null) { + if (!sqlQuery.contains("ORDER BY")) { + log.info("adds order by"); + sqlQuery += "\nORDER BY "; + for (Attribute currentAttribute : entity.getPrimaryKey().getInvolvedAttributes()) { + sqlQuery += entity.getName() + "." + currentAttribute.getName() + ", "; + } + sqlQuery = StringUtils.removeEnd(sqlQuery, ", "); + } } - public QueryResult getEntityTypeFromSingleTable(String discriminatorColumn, Entity entity, String[] propertyOfKey, String[] valueOfKey) - throws SQLException { - // TODO: queryBuilder fetching - String query = queryBuilder.getEntityTypeFromSingleTable(discriminatorColumn, entity, propertyOfKey, valueOfKey); - return executeQuery(query, entity.getDataSource()); + if (limitStatement != null) { + sqlQuery += limitStatement; } - public QueryResult buildAggregateTableFromHierarchicalBag(HierarchicalBag bag) throws SQLException { - // TODO: queryBuilder fetching - String query = queryBuilder.buildAggregateTableFromHierarchicalBag(bag); - return executeQuery(query, bag.getSourceDataseInfo()); + log.debug("sqlQuery :: {} ", sqlQuery); + + ResultSet result = statement.executeQuery(sqlQuery); + QueryResult queryResult = new QueryResult(dbConnection, statement, result, sqlQuery); + return queryResult; + } + + // /** + // * Returns a count of 'joinable' records for each record of the pivot table, that is the + // table for which we are collecting the counts. + // * + // * @param relationship + // * @param pivotTableName + // * @param filteringIds + // * @param dataSource + // * @return relationa result + // */ + public RelationshipQueryResult performConnectionCountQueryGroupedByElement( + Relationship relationship, + String pivotTableName, + List filteringColumns, + List filteringIds, + DataSourceInfo dataSource, + String relationshipName) + throws SQLException { + Statement statement = + dbConnection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); + + // setting the threshold for the number of rows + // contract.getMaxElements() + statement.setMaxRows(1000); + + String query = "select "; + Entity foreignTable = relationship.getForeignEntity(); + Entity parentTable = relationship.getParentEntity(); + + String primaryKeyFields = ""; + if (pivotTableName.equals("foreignTable")) { + primaryKeyFields = this.buildPrimaryKeyColumnsStatement(foreignTable); + query += primaryKeyFields + ", "; + } else if (pivotTableName.equals("parentTable")) { + primaryKeyFields = this.buildPrimaryKeyColumnsStatement(parentTable); + query += primaryKeyFields + ", "; } - - public QueryResult executeQuery(String query, DataSourceInfo dataSource) throws SQLException { - log.debug("query:: {}", query); - - Statement statement = dbConnection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); - ResultSet result = statement.executeQuery(query); - - return new QueryResult(dbConnection, statement, result, query); - } - - public QueryResult scanTableAndOrder(String query, int limit, Entity entity, DataSourceInfo dataSource) throws SQLException { - Statement statement = dbConnection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); - - // setting the threshold for the number of rows - statement.setMaxRows(limit); - - String limitStatement = null; - String sqlQuery = query; - if (sqlQuery.contains("LIMIT")) { - int index = sqlQuery.lastIndexOf(" LIMIT"); - limitStatement = sqlQuery.substring(index); - sqlQuery = sqlQuery.substring(0, index); - } - - // adding ordering to the query by primary key columns - if (entity.getPrimaryKey() != null) { - if (!sqlQuery.contains("ORDER BY")) { - log.info("adds order by"); - sqlQuery += "\nORDER BY "; - for (Attribute currentAttribute : entity.getPrimaryKey().getInvolvedAttributes()) { - sqlQuery += entity.getName() + "." + currentAttribute.getName() + ", "; - } - sqlQuery = StringUtils.removeEnd(sqlQuery, ", "); - } - } - - if (limitStatement != null) { - sqlQuery += limitStatement; - } - - log.debug("sqlQuery :: {} ", sqlQuery); - - ResultSet result = statement.executeQuery(sqlQuery); - QueryResult queryResult = new QueryResult(dbConnection, statement, result, sqlQuery); - return queryResult; + query += + "count(*) as connectionsCount from \n" + + parentTable.getName() + + " join " + + foreignTable.getName() + + " on "; + + query += + buildJoinConditionStatement( + relationship.getFromColumns(), + relationship.getToColumns(), + foreignTable.getName(), + parentTable.getName()) + + "\n"; + + if (filteringColumns != null && filteringIds != null) { + if (pivotTableName.equals("foreignTable")) { + query += + " and \n" + + this.buildIdsINStatement(foreignTable.getName(), filteringColumns, filteringIds) + + " "; + } else if (pivotTableName.equals("parentTable")) { + query += + " and \n" + + this.buildIdsINStatement(parentTable.getName(), filteringColumns, filteringIds) + + " "; + } } - - // /** - // * Returns a count of 'joinable' records for each record of the pivot table, that is the table for which we are collecting the counts. - // * - // * @param relationship - // * @param pivotTableName - // * @param filteringIds - // * @param dataSource - // * @return relationa result - // */ - public RelationshipQueryResult performConnectionCountQueryGroupedByElement( - Relationship relationship, - String pivotTableName, - List filteringColumns, - List filteringIds, - DataSourceInfo dataSource, - String relationshipName - ) throws SQLException { - Statement statement = dbConnection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); - - // setting the threshold for the number of rows - //contract.getMaxElements() - statement.setMaxRows(1000); - - String query = "select "; - Entity foreignTable = relationship.getForeignEntity(); - Entity parentTable = relationship.getParentEntity(); - - String primaryKeyFields = ""; - if (pivotTableName.equals("foreignTable")) { - primaryKeyFields = this.buildPrimaryKeyColumnsStatement(foreignTable); - query += primaryKeyFields + ", "; - } else if (pivotTableName.equals("parentTable")) { - primaryKeyFields = this.buildPrimaryKeyColumnsStatement(parentTable); - query += primaryKeyFields + ", "; - } - query += "count(*) as connectionsCount from \n" + parentTable.getName() + " join " + foreignTable.getName() + " on "; - - query += buildJoinConditionStatement(relationship.getFromColumns(), relationship.getToColumns(), foreignTable.getName(), parentTable.getName()) + "\n"; - - if (filteringColumns != null && filteringIds != null) { - if (pivotTableName.equals("foreignTable")) { - query += " and \n" + this.buildIdsINStatement(foreignTable.getName(), filteringColumns, filteringIds) + " "; - } else if (pivotTableName.equals("parentTable")) { - query += " and \n" + this.buildIdsINStatement(parentTable.getName(), filteringColumns, filteringIds) + " "; - } - } - query += "group by " + primaryKeyFields + "\n"; - query += "order by " + primaryKeyFields; - - log.debug("query :: {} ", query); - ResultSet result = statement.executeQuery(query); - return new RelationshipQueryResult(dbConnection, statement, result, query, relationshipName); + query += "group by " + primaryKeyFields + "\n"; + query += "order by " + primaryKeyFields; + + log.debug("query :: {} ", query); + ResultSet result = statement.executeQuery(query); + return new RelationshipQueryResult(dbConnection, statement, result, query, relationshipName); + } + + public RelationshipQueryResult computeRelationshipCardinality( + Relationship relationship, DataSourceInfo dataSource, String relationshipName) + throws SQLException { + Statement statement = + dbConnection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); + + // setting the threshold for the number of rows + statement.setMaxRows(1000); + + String query = "select "; + Entity foreignTable = relationship.getForeignEntity(); + Entity parentTable = relationship.getParentEntity(); + + query += + "count(*) as connectionsCount from \n" + + parentTable.getName() + + " join " + + foreignTable.getName() + + " on "; + + query += + buildJoinConditionStatement( + relationship.getFromColumns(), + relationship.getToColumns(), + foreignTable.getName(), + parentTable.getName()) + + "\n"; + + log.debug("query :: {} ", query); + ResultSet result = statement.executeQuery(query); + return new RelationshipQueryResult(dbConnection, statement, result, query, relationshipName); + } + + public QueryResult expandRelationship( + Entity enteringEntity, + Entity rootEntity, + List fromColumns, + List toColumns, + List rootNodeIds, + String direction, + DataSourceInfo dataSource) + throws SQLException { + Statement statement = + dbConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + + // setting the threshold for the number of rows + // FIXMW + // statement.setMaxRows(sourceDBInfo.getMaxRowsThreshold()); + + String enteringEntityName = enteringEntity.getName(); + String rootEntityName = rootEntity.getName(); + + // building the query + String query = "select "; + query += this.buildPrimaryKeyColumnsStatement(rootEntity) + ", "; + for (Attribute currColumn : enteringEntity.getAttributes()) { + query += enteringEntityName + "." + currColumn.getName() + ", "; } - - public RelationshipQueryResult computeRelationshipCardinality(Relationship relationship, DataSourceInfo dataSource, String relationshipName) - throws SQLException { - Statement statement = dbConnection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); - - // setting the threshold for the number of rows - statement.setMaxRows(1000); - - String query = "select "; - Entity foreignTable = relationship.getForeignEntity(); - Entity parentTable = relationship.getParentEntity(); - - query += "count(*) as connectionsCount from \n" + parentTable.getName() + " join " + foreignTable.getName() + " on "; - - query += buildJoinConditionStatement(relationship.getFromColumns(), relationship.getToColumns(), foreignTable.getName(), parentTable.getName()) + "\n"; - - log.debug("query :: {} ", query); - ResultSet result = statement.executeQuery(query); - return new RelationshipQueryResult(dbConnection, statement, result, query, relationshipName); + query = query.substring(0, query.lastIndexOf(", ")); + query += " from \n " + enteringEntityName + " join " + rootEntityName + " on "; + if (direction.equals("in")) { + query += + this.buildJoinConditionStatement( + fromColumns, toColumns, enteringEntityName, rootEntityName) + + "\n "; // tables order not relevant + } else if (direction.equals("out")) { + query += + this.buildJoinConditionStatement( + fromColumns, toColumns, rootEntityName, enteringEntityName) + + "\n "; // tables order not relevant } - public QueryResult expandRelationship( - Entity enteringEntity, - Entity rootEntity, - List fromColumns, - List toColumns, - List rootNodeIds, - String direction, - DataSourceInfo dataSource - ) throws SQLException { - Statement statement = dbConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - - // setting the threshold for the number of rows - //FIXMW - // statement.setMaxRows(sourceDBInfo.getMaxRowsThreshold()); - - String enteringEntityName = enteringEntity.getName(); - String rootEntityName = rootEntity.getName(); - - // building the query - String query = "select "; - query += this.buildPrimaryKeyColumnsStatement(rootEntity) + ", "; - for (Attribute currColumn : enteringEntity.getAttributes()) { - query += enteringEntityName + "." + currColumn.getName() + ", "; - } - query = query.substring(0, query.lastIndexOf(", ")); - query += " from \n " + enteringEntityName + " join " + rootEntityName + " on "; - if (direction.equals("in")) { - query += this.buildJoinConditionStatement(fromColumns, toColumns, enteringEntityName, rootEntityName) + "\n "; // tables order not relevant - } else if (direction.equals("out")) { - query += this.buildJoinConditionStatement(fromColumns, toColumns, rootEntityName, enteringEntityName) + "\n "; // tables order not relevant - } + Map> tableName2ids = new LinkedHashMap>(); + tableName2ids.put(rootEntity, rootNodeIds); + query += "where " + this.buildPrimaryKeyIdsINStatement(rootEntity, tableName2ids) + "\n"; + query += "order by " + this.buildPrimaryKeyColumnsStatement(rootEntity); - Map> tableName2ids = new LinkedHashMap>(); - tableName2ids.put(rootEntity, rootNodeIds); - query += "where " + this.buildPrimaryKeyIdsINStatement(rootEntity, tableName2ids) + "\n"; - query += "order by " + this.buildPrimaryKeyColumnsStatement(rootEntity); + log.debug("query :: {} ", query); - log.debug("query :: {} ", query); + ResultSet result = statement.executeQuery(query); + QueryResult queryResult = new QueryResult(dbConnection, statement, result, query); + return queryResult; + } - ResultSet result = statement.executeQuery(query); - QueryResult queryResult = new QueryResult(dbConnection, statement, result, query); - return queryResult; - } - - public List buildLoadQueries(Map> tableName2ids) { - List queryDtos = new ArrayList<>(); - for (Entity currentTable : tableName2ids.keySet()) { - String currentTableName = currentTable.getName(); + public List buildLoadQueries(Map> tableName2ids) { + List queryDtos = new ArrayList<>(); + for (Entity currentTable : tableName2ids.keySet()) { + String currentTableName = currentTable.getName(); - String query = "select * from " + currentTableName + " where "; - query += buildPrimaryKeyIdsINStatement(currentTable, tableName2ids); - query += "\n order by "; - query += buildPrimaryKeyColumnsStatement(currentTable); + String query = "select * from " + currentTableName + " where "; + query += buildPrimaryKeyIdsINStatement(currentTable, tableName2ids); + query += "\n order by "; + query += buildPrimaryKeyColumnsStatement(currentTable); - queryDtos.add(query); - } - return queryDtos; + queryDtos.add(query); } - - // tables order not relevant - private String buildJoinConditionStatement(List fromColumns, List toColumns, String foreignTableName, String parentTableName) { - int numberOfJoinColumns = fromColumns.size(); - String joinCondition = parentTableName + "." + toColumns.get(0).getName() + "=" + foreignTableName + "." + fromColumns.get(0).getName(); - if (numberOfJoinColumns > 1) { - for (int i = 1; i < fromColumns.size(); i++) { - joinCondition += ", " + parentTableName + "." + toColumns.get(i).getName() + "=" + foreignTableName + "." + fromColumns.get(0); - } - } - return joinCondition; + return queryDtos; + } + + // tables order not relevant + private String buildJoinConditionStatement( + List fromColumns, + List toColumns, + String foreignTableName, + String parentTableName) { + int numberOfJoinColumns = fromColumns.size(); + String joinCondition = + parentTableName + + "." + + toColumns.get(0).getName() + + "=" + + foreignTableName + + "." + + fromColumns.get(0).getName(); + if (numberOfJoinColumns > 1) { + for (int i = 1; i < fromColumns.size(); i++) { + joinCondition += + ", " + + parentTableName + + "." + + toColumns.get(i).getName() + + "=" + + foreignTableName + + "." + + fromColumns.get(0); + } } - - private String buildPrimaryKeyColumnsStatement(Entity table) { - String statement = ""; - String tableName = table.getName(); - for (Attribute a : table.getPrimaryKey().getInvolvedAttributes()) { - statement += tableName + "." + a.getName() + ", "; - } - statement = statement.substring(0, statement.lastIndexOf(", ")); - return statement; + return joinCondition; + } + + private String buildPrimaryKeyColumnsStatement(Entity table) { + String statement = ""; + String tableName = table.getName(); + for (Attribute a : table.getPrimaryKey().getInvolvedAttributes()) { + statement += tableName + "." + a.getName() + ", "; } - - private String buildPrimaryKeyIdsINStatement(Entity table, Map> tableName2ids) { - String statement = ""; - String tableName = table.getName(); - PrimaryKey primaryKey = table.getPrimaryKey(); - - for (Attribute a : primaryKey.getInvolvedAttributes()) { - statement += tableName + "." + a.getName() + " in ("; - for (String currentId : tableName2ids.get(table)) { - String[] currentIdSplit = currentId.split("_"); - statement += "'" + currentIdSplit[a.getOrdinalPosition() - 1] + "', "; - } - statement = statement.substring(0, statement.lastIndexOf(", ")); - statement += ") and "; - } - statement = statement.substring(0, statement.lastIndexOf(" and ")); - return statement; + statement = statement.substring(0, statement.lastIndexOf(", ")); + return statement; + } + + private String buildPrimaryKeyIdsINStatement( + Entity table, Map> tableName2ids) { + String statement = ""; + String tableName = table.getName(); + PrimaryKey primaryKey = table.getPrimaryKey(); + + for (Attribute a : primaryKey.getInvolvedAttributes()) { + statement += tableName + "." + a.getName() + " in ("; + for (String currentId : tableName2ids.get(table)) { + String[] currentIdSplit = currentId.split("_"); + statement += "'" + currentIdSplit[a.getOrdinalPosition() - 1] + "', "; + } + statement = statement.substring(0, statement.lastIndexOf(", ")); + statement += ") and "; } - - private String buildIdsINStatement(String tableName, List columns, List ids) { - String statement = ""; - - for (Attribute currColumn : columns) { - statement += tableName + "." + currColumn.getName() + " in ("; - for (String currentId : ids) { - statement += "'" + currentId + "', "; - } - statement = statement.substring(0, statement.lastIndexOf(", ")); - statement += ") and "; - } - statement = statement.substring(0, statement.lastIndexOf(" and ")); - return statement; + statement = statement.substring(0, statement.lastIndexOf(" and ")); + return statement; + } + + private String buildIdsINStatement(String tableName, List columns, List ids) { + String statement = ""; + + for (Attribute currColumn : columns) { + statement += tableName + "." + currColumn.getName() + " in ("; + for (String currentId : ids) { + statement += "'" + currentId + "', "; + } + statement = statement.substring(0, statement.lastIndexOf(", ")); + statement += ") and "; } - - public void close() { - try { - log.debug(" closing connection"); - dbConnection.close(); - } catch (SQLException e) { - log.error("", e); - } + statement = statement.substring(0, statement.lastIndexOf(" and ")); + return statement; + } + + public void close() { + try { + log.debug(" closing connection"); + dbConnection.close(); + } catch (SQLException e) { + log.error("", e); } + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dbengine/DataSourceQueryEngine.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dbengine/DataSourceQueryEngine.java index 4e216829..b9982740 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dbengine/DataSourceQueryEngine.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dbengine/DataSourceQueryEngine.java @@ -45,5 +45,4 @@ * * @author Gabriele Ponzi */ - public interface DataSourceQueryEngine {} diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dbengine/MysqlQueryBuilder.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dbengine/MysqlQueryBuilder.java index 9d54ee21..6461f6f9 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dbengine/MysqlQueryBuilder.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dbengine/MysqlQueryBuilder.java @@ -24,64 +24,142 @@ import java.util.List; /** - * Query Builder for MySQL DBMS. It extends the CommonQueryBuilder class and overrides only the needed methods. + * Query Builder for MySQL DBMS. It extends the CommonQueryBuilder class and overrides only the + * needed methods. * * @author Gabriele Ponzi */ - public class MysqlQueryBuilder extends CommonQueryBuilder { - public MysqlQueryBuilder() { - this.quote = "`"; + public MysqlQueryBuilder() { + this.quote = "`"; + } + + /** + * MySQL does not allow full outer join, so this query is expressed as UNION of LEFT and RIGHT + * JOIN. + * + * @param mappedEntities the mapped entities + * @param columns colums + * @return query produced + */ + @Override + public String getRecordsFromMultipleEntities(List mappedEntities, String[][] columns) { + String query; + + Entity first = mappedEntities.get(0); + if (first.getSchemaName() != null) + query = + "select * from " + + first.getSchemaName() + + "." + + this.quote + + first.getName() + + this.quote + + " as t0\n"; + else query = "select * from " + this.quote + first.getName() + this.quote + " as t0\n"; + + for (int i = 1; i < mappedEntities.size(); i++) { + Entity currentEntity = mappedEntities.get(i); + query += + " left join " + + currentEntity.getSchemaName() + + "." + + this.quote + + currentEntity.getName() + + this.quote + + " as t" + + i; + query += + " on t" + + (i - 1) + + "." + + this.quote + + columns[i - 1][0] + + this.quote + + " = t" + + i + + "." + + this.quote + + columns[i][0] + + this.quote; + + for (int k = 1; k < columns[i].length; k++) { + query += + " and t" + + (i - 1) + + "." + + this.quote + + columns[i - 1][k] + + this.quote + + " = t" + + i + + "." + + this.quote + + columns[i][k] + + this.quote; + } + + query += "\n"; } - /** - * MySQL does not allow full outer join, so this query is expressed as UNION of LEFT and RIGHT JOIN. - * - * @param mappedEntities the mapped entities - * @param columns colums - * @return query produced - */ - - @Override - public String getRecordsFromMultipleEntities(List mappedEntities, String[][] columns) { - String query; - - Entity first = mappedEntities.get(0); - if (first.getSchemaName() != null) query = - "select * from " + first.getSchemaName() + "." + this.quote + first.getName() + this.quote + " as t0\n"; else query = - "select * from " + this.quote + first.getName() + this.quote + " as t0\n"; - - for (int i = 1; i < mappedEntities.size(); i++) { - Entity currentEntity = mappedEntities.get(i); - query += " left join " + currentEntity.getSchemaName() + "." + this.quote + currentEntity.getName() + this.quote + " as t" + i; - query += " on t" + (i - 1) + "." + this.quote + columns[i - 1][0] + this.quote + " = t" + i + "." + this.quote + columns[i][0] + this.quote; - - for (int k = 1; k < columns[i].length; k++) { - query += " and t" + (i - 1) + "." + this.quote + columns[i - 1][k] + this.quote + " = t" + i + "." + this.quote + columns[i][k] + this.quote; - } - - query += "\n"; - } - - query += "UNION\n"; - - if (first.getSchemaName() != null) query += - "select * from " + first.getSchemaName() + "." + this.quote + first.getName() + this.quote + " as t0\n"; else query += - "select * from " + this.quote + first.getName() + this.quote + " as t0\n"; - - for (int i = 1; i < mappedEntities.size(); i++) { - Entity currentEntity = mappedEntities.get(i); - query += " right join " + currentEntity.getSchemaName() + "." + this.quote + currentEntity.getName() + this.quote + " as t" + i; - query += " on t" + (i - 1) + "." + this.quote + columns[i - 1][0] + this.quote + " = t" + i + "." + this.quote + columns[i][0] + this.quote; - - for (int k = 1; k < columns[i].length; k++) { - query += " and t" + (i - 1) + "." + this.quote + columns[i - 1][k] + this.quote + " = t" + i + "." + this.quote + columns[i][k] + this.quote; - } - - query += "\n"; - } - - return query; + query += "UNION\n"; + + if (first.getSchemaName() != null) + query += + "select * from " + + first.getSchemaName() + + "." + + this.quote + + first.getName() + + this.quote + + " as t0\n"; + else query += "select * from " + this.quote + first.getName() + this.quote + " as t0\n"; + + for (int i = 1; i < mappedEntities.size(); i++) { + Entity currentEntity = mappedEntities.get(i); + query += + " right join " + + currentEntity.getSchemaName() + + "." + + this.quote + + currentEntity.getName() + + this.quote + + " as t" + + i; + query += + " on t" + + (i - 1) + + "." + + this.quote + + columns[i - 1][0] + + this.quote + + " = t" + + i + + "." + + this.quote + + columns[i][0] + + this.quote; + + for (int k = 1; k < columns[i].length; k++) { + query += + " and t" + + (i - 1) + + "." + + this.quote + + columns[i - 1][k] + + this.quote + + " = t" + + i + + "." + + this.quote + + columns[i][k] + + this.quote; + } + + query += "\n"; } + + return query; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dbengine/PostgreSQLQueryBuilder.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dbengine/PostgreSQLQueryBuilder.java index a29b4d54..ff5118cf 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dbengine/PostgreSQLQueryBuilder.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dbengine/PostgreSQLQueryBuilder.java @@ -25,32 +25,41 @@ import java.util.List; /** - * Query Builder for PostgreSQL DBMS. It extends the CommonQueryBuilder class and overrides only the needed methods. + * Query Builder for PostgreSQL DBMS. It extends the CommonQueryBuilder class and overrides only the + * needed methods. * * @author Gabriele Ponzi */ public class PostgreSQLQueryBuilder extends CommonQueryBuilder { - public String buildGeospatialQuery(Entity entity, List geospatialTypes) { - String query = "select "; + public String buildGeospatialQuery(Entity entity, List geospatialTypes) { + String query = "select "; - for (Attribute currentAttribute : entity.getAllAttributes()) { - if (this.isGeospatial(geospatialTypes, currentAttribute.getDataType())) query += - "ST_AsText(" + quote + currentAttribute.getName() + quote + ") as " + currentAttribute.getName() + ","; else query += - quote + currentAttribute.getName() + quote + ","; - } + for (Attribute currentAttribute : entity.getAllAttributes()) { + if (this.isGeospatial(geospatialTypes, currentAttribute.getDataType())) + query += + "ST_AsText(" + + quote + + currentAttribute.getName() + + quote + + ") as " + + currentAttribute.getName() + + ","; + else query += quote + currentAttribute.getName() + quote + ","; + } - query = query.substring(0, query.length() - 1); + query = query.substring(0, query.length() - 1); - String entitySchema = entity.getSchemaName(); + String entitySchema = entity.getSchemaName(); - if (entitySchema != null) query += " from " + entitySchema + "." + quote + entity.getName() + quote; else query += - " from " + quote + entity.getName() + quote; + if (entitySchema != null) + query += " from " + entitySchema + "." + quote + entity.getName() + quote; + else query += " from " + quote + entity.getName() + quote; - return query; - } + return query; + } - public boolean isGeospatial(List geospatialTypes, String type) { - return geospatialTypes.contains(type); - } + public boolean isGeospatial(List geospatialTypes, String type) { + return geospatialTypes.contains(type); + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dbengine/QueryBuilder.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dbengine/QueryBuilder.java index 7ec3e4a2..ff02b64b 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dbengine/QueryBuilder.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/dbengine/QueryBuilder.java @@ -25,23 +25,25 @@ import java.util.List; /** - * Interface representing the query builder used by the DB Query Engine, hiding specific implementation for each DBMS. + * Interface representing the query builder used by the DB Query Engine, hiding specific + * implementation for each DBMS. * * @author Gabriele Ponzi */ - public interface QueryBuilder { - String countTableRecords(String currentTableName, String currentTableSchema); + String countTableRecords(String currentTableName, String currentTableSchema); - String getRecordById(Entity entity, String[] propertyOfKey, String[] valueOfKey); + String getRecordById(Entity entity, String[] propertyOfKey, String[] valueOfKey); - String getRecordsByEntity(Entity entity); + String getRecordsByEntity(Entity entity); - String getRecordsFromMultipleEntities(List mappedEntities, String[][] columns); + String getRecordsFromMultipleEntities(List mappedEntities, String[][] columns); - String getRecordsFromSingleTableByDiscriminatorValue(String discriminatorColumn, String currentDiscriminatorValue, Entity entity); + String getRecordsFromSingleTableByDiscriminatorValue( + String discriminatorColumn, String currentDiscriminatorValue, Entity entity); - String getEntityTypeFromSingleTable(String discriminatorColumn, Entity entity, String[] propertyOfKey, String[] valueOfKey); + String getEntityTypeFromSingleTable( + String discriminatorColumn, Entity entity, String[] propertyOfKey, String[] valueOfKey); - String buildAggregateTableFromHierarchicalBag(HierarchicalBag bag); + String buildAggregateTableFromHierarchicalBag(HierarchicalBag bag); } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/exception/RDBMSProviderAggregationException.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/exception/RDBMSProviderAggregationException.java index 58b30f3a..3b8d3754 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/exception/RDBMSProviderAggregationException.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/exception/RDBMSProviderAggregationException.java @@ -25,21 +25,20 @@ * * @author Gabriele Ponzi */ - @SuppressWarnings("serial") public class RDBMSProviderAggregationException extends Exception { - public RDBMSProviderAggregationException() {} + public RDBMSProviderAggregationException() {} - public RDBMSProviderAggregationException(String message) { - super(message); - } + public RDBMSProviderAggregationException(String message) { + super(message); + } - public RDBMSProviderAggregationException(String message, Throwable cause) { - super(message, cause); - } + public RDBMSProviderAggregationException(String message, Throwable cause) { + super(message, cause); + } - public RDBMSProviderAggregationException(Throwable cause) { - super(cause); - } + public RDBMSProviderAggregationException(Throwable cause) { + super(cause); + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/exception/RDBMSProviderIOException.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/exception/RDBMSProviderIOException.java index 4802ca59..29d644d7 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/exception/RDBMSProviderIOException.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/exception/RDBMSProviderIOException.java @@ -27,21 +27,20 @@ * * @author Gabriele Ponzi */ - @SuppressWarnings("serial") public class RDBMSProviderIOException extends IOException { - public RDBMSProviderIOException() {} + public RDBMSProviderIOException() {} - public RDBMSProviderIOException(String message) { - super(message); - } + public RDBMSProviderIOException(String message) { + super(message); + } - public RDBMSProviderIOException(String message, Throwable cause) { - super(message, cause); - } + public RDBMSProviderIOException(String message, Throwable cause) { + super(message, cause); + } - public RDBMSProviderIOException(Throwable cause) { - super(cause); - } + public RDBMSProviderIOException(Throwable cause) { + super(cause); + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/exception/RDBMSProviderOperationNotAllowedException.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/exception/RDBMSProviderOperationNotAllowedException.java index 365ecdf0..ab31c708 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/exception/RDBMSProviderOperationNotAllowedException.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/exception/RDBMSProviderOperationNotAllowedException.java @@ -22,19 +22,19 @@ public class RDBMSProviderOperationNotAllowedException extends RuntimeException { - public RDBMSProviderOperationNotAllowedException() { - super(); - } + public RDBMSProviderOperationNotAllowedException() { + super(); + } - public RDBMSProviderOperationNotAllowedException(String message) { - super(message); - } + public RDBMSProviderOperationNotAllowedException(String message) { + super(message); + } - public RDBMSProviderOperationNotAllowedException(String message, Throwable cause) { - super(message, cause); - } + public RDBMSProviderOperationNotAllowedException(String message, Throwable cause) { + super(message, cause); + } - public RDBMSProviderOperationNotAllowedException(Throwable cause) { - super(cause); - } + public RDBMSProviderOperationNotAllowedException(Throwable cause) { + super(cause); + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/exception/RDBMSProviderRuntimeException.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/exception/RDBMSProviderRuntimeException.java index 9a534fd7..0306ff8a 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/exception/RDBMSProviderRuntimeException.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/exception/RDBMSProviderRuntimeException.java @@ -25,23 +25,22 @@ * * @author Gabriele Ponzi */ - @SuppressWarnings("serial") public class RDBMSProviderRuntimeException extends RuntimeException { - public RDBMSProviderRuntimeException() { - super(); - } + public RDBMSProviderRuntimeException() { + super(); + } - public RDBMSProviderRuntimeException(String message) { - super(message); - } + public RDBMSProviderRuntimeException(String message) { + super(message); + } - public RDBMSProviderRuntimeException(String message, Throwable cause) { - super(message, cause); - } + public RDBMSProviderRuntimeException(String message, Throwable cause) { + super(message, cause); + } - public RDBMSProviderRuntimeException(Throwable cause) { - super(cause); - } + public RDBMSProviderRuntimeException(Throwable cause) { + super(cause); + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/factory/DataTypeHandlerFactory.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/factory/DataTypeHandlerFactory.java index 985fcd5e..66f7f438 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/factory/DataTypeHandlerFactory.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/factory/DataTypeHandlerFactory.java @@ -28,28 +28,27 @@ import com.arcadeanalytics.provider.rdbms.persistence.handler.SQLServerDataTypeHandler; /** - * Factory used to instantiate a specific DataTypeHandler according to the driver of the - * DBMS from which the import is performed. + * Factory used to instantiate a specific DataTypeHandler according to the driver of the DBMS from + * which the import is performed. * * @author Gabriele Ponzi */ - public class DataTypeHandlerFactory { - public DBMSDataTypeHandler buildDataTypeHandler(String type) { - switch (type) { - case "RDBMS_ORACLE": - return new OracleDataTypeHandler(); - case "RDBMS_MSQSLSERVER": - return new SQLServerDataTypeHandler(); - case "RDBMS_MYSQL": - return new MySQLDataTypeHandler(); - case "RDBMS_POSTGRESQL": - return new PostgreSQLDataTypeHandler(); - case "RDBMS_HSQL": - return new HSQLDBDataTypeHandler(); - default: - return new DBMSDataTypeHandler(); - } + public DBMSDataTypeHandler buildDataTypeHandler(String type) { + switch (type) { + case "RDBMS_ORACLE": + return new OracleDataTypeHandler(); + case "RDBMS_MSQSLSERVER": + return new SQLServerDataTypeHandler(); + case "RDBMS_MYSQL": + return new MySQLDataTypeHandler(); + case "RDBMS_POSTGRESQL": + return new PostgreSQLDataTypeHandler(); + case "RDBMS_HSQL": + return new HSQLDBDataTypeHandler(); + default: + return new DBMSDataTypeHandler(); } + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/factory/MapperFactory.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/factory/MapperFactory.java index e913607f..b93cc1bd 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/factory/MapperFactory.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/factory/MapperFactory.java @@ -30,40 +30,46 @@ import java.util.List; /** - * Factory used to instantiate the chosen 'Mapper' which will be adopted for the source schema building. + * Factory used to instantiate the chosen 'Mapper' which will be adopted for the source schema + * building. * * @author Gabriele Ponzi */ - public class MapperFactory { - public ER2GraphMapper buildMapper( - String chosenMapper, - DataSourceInfo dataSource, - String xmlPath, - List includedTables, - List excludedTables, - String executionStrategy, - DBQueryEngine queryEngine, - DBMSDataTypeHandler handler, - NameResolver nameResolver, - Statistics statistics - ) { - switch (chosenMapper) { - case "hibernate": - return new Hibernate2GraphMapper( - dataSource, - xmlPath, - includedTables, - excludedTables, - queryEngine, - handler, - executionStrategy, - nameResolver, - statistics - ); - default: - return new ER2GraphMapper(dataSource, includedTables, excludedTables, queryEngine, handler, executionStrategy, nameResolver, statistics); - } + public ER2GraphMapper buildMapper( + String chosenMapper, + DataSourceInfo dataSource, + String xmlPath, + List includedTables, + List excludedTables, + String executionStrategy, + DBQueryEngine queryEngine, + DBMSDataTypeHandler handler, + NameResolver nameResolver, + Statistics statistics) { + switch (chosenMapper) { + case "hibernate": + return new Hibernate2GraphMapper( + dataSource, + xmlPath, + includedTables, + excludedTables, + queryEngine, + handler, + executionStrategy, + nameResolver, + statistics); + default: + return new ER2GraphMapper( + dataSource, + includedTables, + excludedTables, + queryEngine, + handler, + executionStrategy, + nameResolver, + statistics); } + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/factory/NameResolverFactory.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/factory/NameResolverFactory.java index dadfa691..e3b47700 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/factory/NameResolverFactory.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/factory/NameResolverFactory.java @@ -25,26 +25,25 @@ import com.arcadeanalytics.provider.rdbms.nameresolver.OriginalConventionNameResolver; /** - * Factory used to instantiate a specific NameResolver starting from its name. - * If the name is not specified (null value) a JavaConventionNameResolver is instantiated. + * Factory used to instantiate a specific NameResolver starting from its name. If the name is not + * specified (null value) a JavaConventionNameResolver is instantiated. * * @author Gabriele Ponzi */ - public class NameResolverFactory { - public NameResolver buildNameResolver(String nameResolverConvention) { - if (nameResolverConvention == null) { - return new OriginalConventionNameResolver(); - } else { - switch (nameResolverConvention) { - case "java": - return new JavaConventionNameResolver(); - case "original": - return new OriginalConventionNameResolver(); - default: - return new OriginalConventionNameResolver(); - } - } + public NameResolver buildNameResolver(String nameResolverConvention) { + if (nameResolverConvention == null) { + return new OriginalConventionNameResolver(); + } else { + switch (nameResolverConvention) { + case "java": + return new JavaConventionNameResolver(); + case "original": + return new OriginalConventionNameResolver(); + default: + return new OriginalConventionNameResolver(); + } } + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/factory/QueryBuilderFactory.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/factory/QueryBuilderFactory.java index 936c55f1..cc4fd11b 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/factory/QueryBuilderFactory.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/factory/QueryBuilderFactory.java @@ -28,33 +28,32 @@ /** * @author Gabriele Ponzi */ - public class QueryBuilderFactory { - public QueryBuilder buildQueryBuilder(String type) { - QueryBuilder queryBuilder; - - switch (type) { - case "RDBMS_ORACLE": - queryBuilder = new CommonQueryBuilder(); - break; - case "RDBMS_MSQSLSERVER": - queryBuilder = new CommonQueryBuilder(); - break; - case "RDBMS_MYSQL": - queryBuilder = new MysqlQueryBuilder(); - break; - case "RDBMS_POSTGRESQL": - queryBuilder = new PostgreSQLQueryBuilder(); - break; - case "RDBMS_HSQL": - queryBuilder = new CommonQueryBuilder(); - break; - default: - queryBuilder = new CommonQueryBuilder(); - break; - } + public QueryBuilder buildQueryBuilder(String type) { + QueryBuilder queryBuilder; - return queryBuilder; + switch (type) { + case "RDBMS_ORACLE": + queryBuilder = new CommonQueryBuilder(); + break; + case "RDBMS_MSQSLSERVER": + queryBuilder = new CommonQueryBuilder(); + break; + case "RDBMS_MYSQL": + queryBuilder = new MysqlQueryBuilder(); + break; + case "RDBMS_POSTGRESQL": + queryBuilder = new PostgreSQLQueryBuilder(); + break; + case "RDBMS_HSQL": + queryBuilder = new CommonQueryBuilder(); + break; + default: + queryBuilder = new CommonQueryBuilder(); + break; } + + return queryBuilder; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/factory/StrategyFactory.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/factory/StrategyFactory.java index b4acae5a..65be71a3 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/factory/StrategyFactory.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/factory/StrategyFactory.java @@ -32,35 +32,35 @@ * * @author Gabriele Ponzi */ - public class StrategyFactory { - private final Logger log = LoggerFactory.getLogger(StrategyFactory.class); + private final Logger log = LoggerFactory.getLogger(StrategyFactory.class); - public StrategyFactory() {} + public StrategyFactory() {} - public WorkflowStrategy buildStrategy(String chosenStrategy) throws RDBMSProviderIOException { - WorkflowStrategy strategy = null; + public WorkflowStrategy buildStrategy(String chosenStrategy) throws RDBMSProviderIOException { + WorkflowStrategy strategy = null; - // choosing strategy for migration from RDBSs + // choosing strategy for migration from RDBSs - if (chosenStrategy == null) { - strategy = new DBMSSimpleModelBuildingStrategy(); - } else { - switch (chosenStrategy) { - case "interactive": - strategy = new DBMSSimpleModelBuildingStrategy(); - break; - case "interactive-aggr": - strategy = new DBMSModelBuildingAggregationStrategy(); - break; - default: - log.error("The typed strategy doesn't exist for migration from the chosen RDBMS.\n"); - } - } + if (chosenStrategy == null) { + strategy = new DBMSSimpleModelBuildingStrategy(); + } else { + switch (chosenStrategy) { + case "interactive": + strategy = new DBMSSimpleModelBuildingStrategy(); + break; + case "interactive-aggr": + strategy = new DBMSModelBuildingAggregationStrategy(); + break; + default: + log.error("The typed strategy doesn't exist for migration from the chosen RDBMS.\n"); + } + } - if (strategy == null) throw new RDBMSProviderIOException("Strategy not available for the chosen source."); + if (strategy == null) + throw new RDBMSProviderIOException("Strategy not available for the chosen source."); - return strategy; - } + return strategy; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/mapper/rdbms/AggregatorEdge.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/mapper/rdbms/AggregatorEdge.java index 99d61183..f879e4ca 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/mapper/rdbms/AggregatorEdge.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/mapper/rdbms/AggregatorEdge.java @@ -25,28 +25,27 @@ /** * @author Gabriele Ponzi */ - public class AggregatorEdge { - private final String outVertexClassName; - private final String inVertexClassName; - private final EdgeType edgeType; + private final String outVertexClassName; + private final String inVertexClassName; + private final EdgeType edgeType; - public AggregatorEdge(String outVertexClassName, String inVertexClassName, EdgeType edgeType) { - this.outVertexClassName = outVertexClassName; - this.inVertexClassName = inVertexClassName; - this.edgeType = edgeType; - } + public AggregatorEdge(String outVertexClassName, String inVertexClassName, EdgeType edgeType) { + this.outVertexClassName = outVertexClassName; + this.inVertexClassName = inVertexClassName; + this.edgeType = edgeType; + } - public String getOutVertexClassName() { - return outVertexClassName; - } + public String getOutVertexClassName() { + return outVertexClassName; + } - public String getInVertexClassName() { - return inVertexClassName; - } + public String getInVertexClassName() { + return inVertexClassName; + } - public EdgeType getEdgeType() { - return edgeType; - } + public EdgeType getEdgeType() { + return edgeType; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/mapper/rdbms/ER2GraphMapper.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/mapper/rdbms/ER2GraphMapper.java index 3036672f..c63aea67 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/mapper/rdbms/ER2GraphMapper.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/mapper/rdbms/ER2GraphMapper.java @@ -64,1185 +64,1273 @@ import org.slf4j.LoggerFactory; /** - * Implementation of Source2GraphMapper that manages the source DB schema and the destination graph model with their - * correspondences. It has the responsibility to build in memory the two models: the first is built from the source DB meta-data - * through the JDBC driver, the second from the source DB schema just created. + * Implementation of Source2GraphMapper that manages the source DB schema and the destination graph + * model with their correspondences. It has the responsibility to build in memory the two models: + * the first is built from the source DB meta-data through the JDBC driver, the second from the + * source DB schema just created. * * @author Gabriele Ponzi */ - public class ER2GraphMapper { - public final int DEFAULT_CLASS_MAPPER_INDEX = 0; - // rules - protected final Map> entity2EVClassMappers; - protected final Map> vertexType2EVClassMappers; - protected final Map> entity2EEClassMappers; - protected final Map> edgeType2EEClassMappers; - protected final Map relationship2edgeType; - protected final Map> edgeType2relationships; - protected final Map edgeTypeName2count; - protected final Map joinVertex2aggregatorEdges; - // supplementary migrationConfigDoc - protected final DataSourceInfo dataSource; - private final DBQueryEngine queryEngine; - private final String executionStrategy; - private final DBMSDataTypeHandler dataTypeHandler; - private final NameResolver nameResolver; - private final Statistics statistics; - private final Logger log = LoggerFactory.getLogger(ER2GraphMapper.class); - // graph model - protected GraphModel graphModel; - // source model - protected DataBaseSchema dataBaseSchema; - // filters - protected List includedTables; - protected List excludedTables; - - public ER2GraphMapper( - DataSourceInfo dataSource, - List includedTables, - List excludedTables, - DBQueryEngine queryEngine, - DBMSDataTypeHandler dataTypeHandler, - String executionStrategy, - NameResolver nameResolver, - Statistics statistics - ) { - this.dataSource = dataSource; - this.queryEngine = queryEngine; - this.executionStrategy = executionStrategy; - this.dataTypeHandler = dataTypeHandler; - this.nameResolver = nameResolver; - this.statistics = statistics; - - // new maps - this.entity2EVClassMappers = new IdentityHashMap<>(); - this.vertexType2EVClassMappers = new IdentityHashMap<>(); - - this.relationship2edgeType = new IdentityHashMap<>(); - this.edgeType2relationships = new IdentityHashMap<>(); - this.edgeTypeName2count = new TreeMap<>(); - this.joinVertex2aggregatorEdges = new LinkedHashMap<>(); - this.entity2EEClassMappers = new LinkedHashMap<>(); - this.edgeType2EEClassMappers = new LinkedHashMap<>(); - - if (includedTables != null) this.includedTables = includedTables; else this.includedTables = new ArrayList<>(); - - if (excludedTables != null) this.excludedTables = excludedTables; else this.excludedTables = new ArrayList<>(); - - // creating the two empty models - this.dataBaseSchema = new DataBaseSchema(); - this.graphModel = new GraphModel(); - } - - public GraphModel getGraphModel() { - return this.graphModel; - } - - // old map managing - public void upsertRelationshipEdgeRules(Relationship currentRelationship, EdgeType currentEdgeType) { - relationship2edgeType.put(currentRelationship, currentEdgeType); - - LinkedList representedRelationships = edgeType2relationships.get(currentEdgeType); - if (representedRelationships == null) { - representedRelationships = new LinkedList<>(); - } - representedRelationships.add(currentRelationship); - edgeType2relationships.put(currentEdgeType, representedRelationships); - } - - public void upsertEVClassMappingRules(Entity currentEntity, VertexType currentVertexType, EVClassMapper classMapper) { - List classMappings = entity2EVClassMappers.get(currentEntity); - if (classMappings == null) { - classMappings = new LinkedList<>(); - } - classMappings.add(classMapper); - entity2EVClassMappers.put(currentEntity, classMappings); - - classMappings = vertexType2EVClassMappers.get(currentVertexType); - if (classMappings == null) { - classMappings = new LinkedList<>(); - } - classMappings.add(classMapper); - vertexType2EVClassMappers.put(currentVertexType, classMappings); - } - - public void upsertEEClassMappingRules(Entity currentEntity, EdgeType currentEdgeType, EEClassMapper classMapper) { - List classMappings = entity2EEClassMappers.get(currentEntity.getName()); - if (classMappings == null) { - classMappings = new LinkedList<>(); - } - classMappings.add(classMapper); - entity2EEClassMappers.put(currentEntity.getName(), classMappings); - - classMappings = edgeType2EEClassMappers.get(currentEdgeType.getName()); - if (classMappings == null) { - classMappings = new LinkedList(); - } - classMappings.add(classMapper); - edgeType2EEClassMappers.put(currentEdgeType.getName(), classMappings); - } - - public List getEVClassMappersByVertex(VertexType vertexType) { - return vertexType2EVClassMappers.get(vertexType); - } - - public List getEVClassMappersByEntity(Entity entity) { - return entity2EVClassMappers.get(entity); + public final int DEFAULT_CLASS_MAPPER_INDEX = 0; + // rules + protected final Map> entity2EVClassMappers; + protected final Map> vertexType2EVClassMappers; + protected final Map> entity2EEClassMappers; + protected final Map> edgeType2EEClassMappers; + protected final Map relationship2edgeType; + protected final Map> edgeType2relationships; + protected final Map edgeTypeName2count; + protected final Map joinVertex2aggregatorEdges; + // supplementary migrationConfigDoc + protected final DataSourceInfo dataSource; + private final DBQueryEngine queryEngine; + private final String executionStrategy; + private final DBMSDataTypeHandler dataTypeHandler; + private final NameResolver nameResolver; + private final Statistics statistics; + private final Logger log = LoggerFactory.getLogger(ER2GraphMapper.class); + // graph model + protected GraphModel graphModel; + // source model + protected DataBaseSchema dataBaseSchema; + // filters + protected List includedTables; + protected List excludedTables; + + public ER2GraphMapper( + DataSourceInfo dataSource, + List includedTables, + List excludedTables, + DBQueryEngine queryEngine, + DBMSDataTypeHandler dataTypeHandler, + String executionStrategy, + NameResolver nameResolver, + Statistics statistics) { + this.dataSource = dataSource; + this.queryEngine = queryEngine; + this.executionStrategy = executionStrategy; + this.dataTypeHandler = dataTypeHandler; + this.nameResolver = nameResolver; + this.statistics = statistics; + + // new maps + this.entity2EVClassMappers = new IdentityHashMap<>(); + this.vertexType2EVClassMappers = new IdentityHashMap<>(); + + this.relationship2edgeType = new IdentityHashMap<>(); + this.edgeType2relationships = new IdentityHashMap<>(); + this.edgeTypeName2count = new TreeMap<>(); + this.joinVertex2aggregatorEdges = new LinkedHashMap<>(); + this.entity2EEClassMappers = new LinkedHashMap<>(); + this.edgeType2EEClassMappers = new LinkedHashMap<>(); + + if (includedTables != null) this.includedTables = includedTables; + else this.includedTables = new ArrayList<>(); + + if (excludedTables != null) this.excludedTables = excludedTables; + else this.excludedTables = new ArrayList<>(); + + // creating the two empty models + this.dataBaseSchema = new DataBaseSchema(); + this.graphModel = new GraphModel(); + } + + public GraphModel getGraphModel() { + return this.graphModel; + } + + // old map managing + public void upsertRelationshipEdgeRules( + Relationship currentRelationship, EdgeType currentEdgeType) { + relationship2edgeType.put(currentRelationship, currentEdgeType); + + LinkedList representedRelationships = edgeType2relationships.get(currentEdgeType); + if (representedRelationships == null) { + representedRelationships = new LinkedList<>(); } - - public List getEEClassMappersByEntity(Entity entity) { - return entity2EEClassMappers.get(entity.getName()); + representedRelationships.add(currentRelationship); + edgeType2relationships.put(currentEdgeType, representedRelationships); + } + + public void upsertEVClassMappingRules( + Entity currentEntity, VertexType currentVertexType, EVClassMapper classMapper) { + List classMappings = entity2EVClassMappers.get(currentEntity); + if (classMappings == null) { + classMappings = new LinkedList<>(); } + classMappings.add(classMapper); + entity2EVClassMappers.put(currentEntity, classMappings); - public List getEEClassMappersByEdge(EdgeType edgeType) { - return edgeType2EEClassMappers.get(edgeType.getName()); + classMappings = vertexType2EVClassMappers.get(currentVertexType); + if (classMappings == null) { + classMappings = new LinkedList<>(); } - - public Map> getEntity2EVClassMappers() { - return entity2EVClassMappers; + classMappings.add(classMapper); + vertexType2EVClassMappers.put(currentVertexType, classMappings); + } + + public void upsertEEClassMappingRules( + Entity currentEntity, EdgeType currentEdgeType, EEClassMapper classMapper) { + List classMappings = entity2EEClassMappers.get(currentEntity.getName()); + if (classMappings == null) { + classMappings = new LinkedList<>(); } + classMappings.add(classMapper); + entity2EEClassMappers.put(currentEntity.getName(), classMappings); - public Map> getVertexType2EVClassMappers() { - return vertexType2EVClassMappers; + classMappings = edgeType2EEClassMappers.get(currentEdgeType.getName()); + if (classMappings == null) { + classMappings = new LinkedList(); } - - public Map> getEntity2EEClassMappers() { - return entity2EEClassMappers; + classMappings.add(classMapper); + edgeType2EEClassMappers.put(currentEdgeType.getName(), classMappings); + } + + public List getEVClassMappersByVertex(VertexType vertexType) { + return vertexType2EVClassMappers.get(vertexType); + } + + public List getEVClassMappersByEntity(Entity entity) { + return entity2EVClassMappers.get(entity); + } + + public List getEEClassMappersByEntity(Entity entity) { + return entity2EEClassMappers.get(entity.getName()); + } + + public List getEEClassMappersByEdge(EdgeType edgeType) { + return edgeType2EEClassMappers.get(edgeType.getName()); + } + + public Map> getEntity2EVClassMappers() { + return entity2EVClassMappers; + } + + public Map> getVertexType2EVClassMappers() { + return vertexType2EVClassMappers; + } + + public Map> getEntity2EEClassMappers() { + return entity2EEClassMappers; + } + + public Map> getEdgeType2EEClassMappers() { + return edgeType2EEClassMappers; + } + + public String getAttributeByPropertyAboveMappers( + String propertyName, List classMappers) { + for (EVClassMapper currClassMapper : classMappers) { + String attributeName = currClassMapper.getAttributeByProperty(propertyName); + if (attributeName != null) { + return attributeName; + } } - - public Map> getEdgeType2EEClassMappers() { - return edgeType2EEClassMappers; + return null; + } + + /** + * MACRO EXECUTION BLOCK: BUILD SOURCE DATABASE SCHEMA Builds the database schema and the rules + * for the mapping with the graph model through 3 micro execution blocks: - Build Entities - Build + * Out-Relationships - Build In-Relationships + */ + public void buildSourceDatabaseSchema() { + statistics.startWork1Time = new Date(); + statistics.runningStepNumber = 1; + + try { + Connection connection = queryEngine.getDbConnection(); + DatabaseMetaData databaseMetaData = connection.getMetaData(); + + log.debug("databaseMetaData:: {} ", databaseMetaData); + /* + * General DB Info and table filtering + */ + + dataBaseSchema.setMajorVersion(databaseMetaData.getDatabaseMajorVersion()); + dataBaseSchema.setMinorVersion(databaseMetaData.getDatabaseMinorVersion()); + dataBaseSchema.setDriverMajorVersion(databaseMetaData.getDriverMajorVersion()); + dataBaseSchema.setDriverMinorVersion(databaseMetaData.getDriverMinorVersion()); + dataBaseSchema.setProductName(databaseMetaData.getDatabaseProductName()); + dataBaseSchema.setProductVersion(databaseMetaData.getDatabaseProductVersion()); + + /* + * Entity building + */ + + int numberOfTables = buildEntities(databaseMetaData, connection); + + /* + * Building Out-relationships + */ + + buildOutRelationships(databaseMetaData, numberOfTables); + + /* + * Building In-relationships + */ + + buildInRelationships(); + } catch (SQLException e) { + throw new RDBMSProviderRuntimeException(e); } - public String getAttributeByPropertyAboveMappers(String propertyName, List classMappers) { - for (EVClassMapper currClassMapper : classMappers) { - String attributeName = currClassMapper.getAttributeByProperty(propertyName); - if (attributeName != null) { - return attributeName; - } + statistics.runningStepNumber = -1; + } + + /** + * MICRO EXECUTION BLOCK: BUILD SOURCE DATABASE SCHEMA - BUILD ENTITIES Builds the Entities + * starting from the source database metadata. + * + * @param databaseMetaData + * @param sourceDBConnection + * @return + * @throws SQLException + */ + private int buildEntities(DatabaseMetaData databaseMetaData, Connection sourceDBConnection) + throws SQLException { + Map tablesName2schema = new LinkedHashMap<>(); + + String tableCatalog = null; + String tableSchemaPattern = null; + String tableNamePattern = null; + String[] tableTypes = {"TABLE"}; + if (dataSource.getType().equals("RDBMS_ORACLE")) { + ResultSet schemas = databaseMetaData.getSchemas(); + while (schemas.next()) { + if (schemas.getString(1).equalsIgnoreCase(dataSource.getUsername())) { + tableSchemaPattern = schemas.getString(1); + break; } - return null; + } } /** - * MACRO EXECUTION BLOCK: BUILD SOURCE DATABASE SCHEMA - * Builds the database schema and the rules for the mapping with the graph model through 3 micro execution blocks: - * - Build Entities - * - Build Out-Relationships - * - Build In-Relationships + * MySQL Hack: retrieving info about tables contained in the schema called with the database + * name */ - - public void buildSourceDatabaseSchema() { - statistics.startWork1Time = new Date(); - statistics.runningStepNumber = 1; - - try { - Connection connection = queryEngine.getDbConnection(); - DatabaseMetaData databaseMetaData = connection.getMetaData(); - - log.debug("databaseMetaData:: {} ", databaseMetaData); - /* - * General DB Info and table filtering - */ - - dataBaseSchema.setMajorVersion(databaseMetaData.getDatabaseMajorVersion()); - dataBaseSchema.setMinorVersion(databaseMetaData.getDatabaseMinorVersion()); - dataBaseSchema.setDriverMajorVersion(databaseMetaData.getDriverMajorVersion()); - dataBaseSchema.setDriverMinorVersion(databaseMetaData.getDriverMinorVersion()); - dataBaseSchema.setProductName(databaseMetaData.getDatabaseProductName()); - dataBaseSchema.setProductVersion(databaseMetaData.getDatabaseProductVersion()); - - /* - * Entity building - */ - - int numberOfTables = buildEntities(databaseMetaData, connection); - - /* - * Building Out-relationships - */ - - buildOutRelationships(databaseMetaData, numberOfTables); - - /* - * Building In-relationships - */ - - buildInRelationships(); - } catch (SQLException e) { - throw new RDBMSProviderRuntimeException(e); - } - - statistics.runningStepNumber = -1; + if (dataSource.getType().equals("RDBMS_MYSQL")) { + tableCatalog = dataSource.getDatabase(); + if (tableSchemaPattern == null) { + tableSchemaPattern = dataSource.getDatabase(); + } + } + ResultSet resultTable = + databaseMetaData.getTables(tableCatalog, tableSchemaPattern, tableNamePattern, tableTypes); + + // Giving db's table names + while (resultTable.next()) { + String tableSchema = resultTable.getString("TABLE_SCHEM"); + String tableName = resultTable.getString("TABLE_NAME"); + + if (isTableAllowed(tableName)) + tablesName2schema.put( + tableName, + tableSchema); // filtering tables according to "include-list" and "exclude-list" } - /** - * MICRO EXECUTION BLOCK: BUILD SOURCE DATABASE SCHEMA - BUILD ENTITIES - * Builds the Entities starting from the source database metadata. - * - * @param databaseMetaData - * @param sourceDBConnection - * @return - * @throws SQLException - */ - - private int buildEntities(DatabaseMetaData databaseMetaData, Connection sourceDBConnection) throws SQLException { - Map tablesName2schema = new LinkedHashMap<>(); - - String tableCatalog = null; - String tableSchemaPattern = null; - String tableNamePattern = null; - String[] tableTypes = { "TABLE" }; - if (dataSource.getType().equals("RDBMS_ORACLE")) { - ResultSet schemas = databaseMetaData.getSchemas(); - while (schemas.next()) { - if (schemas.getString(1).equalsIgnoreCase(dataSource.getUsername())) { - tableSchemaPattern = schemas.getString(1); - break; - } - } + int numberOfTables = tablesName2schema.size(); + statistics.totalNumberOfEntities = numberOfTables; + + // closing resultTable + closeCursor(resultTable); + log.debug("{} tables found:: {} ", numberOfTables, tablesName2schema); + + // Variables for records counting + Statement statement = sourceDBConnection.createStatement(); + int totalNumberOfRecord = 0; + + int iteration = 1; + for (String currentTableName : tablesName2schema.keySet()) { + // Counting current-table's record + String currentTableSchema = tablesName2schema.get(currentTableName); + log.debug( + "Building '{}' entity on schema {} ({}/{})...", + currentTableName, + currentTableSchema, + iteration, + numberOfTables); + + // QueryResult queryResult = dbQueryEngine.countTableRecords(currentTableName, + // currentTableSchema); + // + // ResultSet currentTableRecordAmount = queryResult.getResult(); + // if (currentTableRecordAmount.next()) { + // totalNumberOfRecord += currentTableRecordAmount.getInt(1); + // } + // closeCursor(currentTableRecordAmount); + + // creating entity + Entity currentEntity = new Entity(currentTableName, currentTableSchema, dataSource); + currentEntity.setSchemaPosition(iteration); + + // adding attributes and primary keys + PrimaryKey pKey = new PrimaryKey(currentEntity, new ArrayList<>()); + + String columnCatalog = null; + String columnSchemaPattern = null; + String columnNamePattern = null; + + String primaryKeyCatalog = null; + String primaryKeySchema = currentTableSchema; + + /** MySQL Hack */ + if (dataSource.getType().equals("RDBMS_MYSQL")) { + primaryKeyCatalog = dataSource.getDatabase(); + if (primaryKeySchema == null) { + primaryKeySchema = dataSource.getDatabase(); } - - /** - * MySQL Hack: retrieving info about tables contained in the schema called with the database name - */ - if (dataSource.getType().equals("RDBMS_MYSQL")) { - tableCatalog = dataSource.getDatabase(); - if (tableSchemaPattern == null) { - tableSchemaPattern = dataSource.getDatabase(); - } + } + + ResultSet resultColumns = + databaseMetaData.getColumns( + columnCatalog, columnSchemaPattern, currentTableName, columnNamePattern); + + log.debug("primaryKeyCatalog ::: {} ", primaryKeySchema); + ResultSet resultPrimaryKeys = + databaseMetaData.getPrimaryKeys(primaryKeyCatalog, primaryKeySchema, currentTableName); + + List currentPrimaryKeys = getPrimaryKeysFromResulset(resultPrimaryKeys); + + while (resultColumns.next()) { + Attribute currentAttribute = + new Attribute( + resultColumns.getString("COLUMN_NAME"), + resultColumns.getInt("ORDINAL_POSITION"), + resultColumns.getString("TYPE_NAME"), + currentEntity); + currentEntity.addAttribute(currentAttribute); + + // if the current attribute is involved in the primary key, it will be added to the + // attributes of pKey. + if (currentPrimaryKeys.contains(currentAttribute.getName())) { + pKey.addAttribute(currentAttribute); } - ResultSet resultTable = databaseMetaData.getTables(tableCatalog, tableSchemaPattern, tableNamePattern, tableTypes); - - // Giving db's table names - while (resultTable.next()) { - String tableSchema = resultTable.getString("TABLE_SCHEM"); - String tableName = resultTable.getString("TABLE_NAME"); - - if (isTableAllowed(tableName)) tablesName2schema.put(tableName, tableSchema); // filtering tables according to "include-list" and "exclude-list" + } + + /** dataWorkd Hack */ + if (dataSource.getType().equals("RDBMS_DATA_WORLD")) { + currentPrimaryKeys.add("row_index"); + + final OptionalInt maxOrdinal = + currentEntity.getAttributes().stream().mapToInt(a -> a.getOrdinalPosition()).max(); + + Attribute currentAttribute = + new Attribute( + "row_index", + maxOrdinal.getAsInt() + 1, + " http://www.w3.org/2001/XMLSchema#integer", + currentEntity); + currentEntity.addAttribute(currentAttribute); + + pKey.addAttribute(currentAttribute); + } + + closeCursor(resultColumns); + closeCursor(resultPrimaryKeys); + + currentEntity.setPrimaryKey(pKey); + + // if the primary key doesn't involve any attribute, a warning message is generated + if (pKey.getInvolvedAttributes().size() == 0) + log.warn( + "It's not declared a primary key for the Entity " + + currentEntity.getName() + + ", might lead to issues during the migration or the sync executions " + + "(the first importing is quite safe)."); + + // adding entity to db schema + dataBaseSchema.getEntities().add(currentEntity); + + iteration++; + log.debug("Entity {} built.", currentTableName); + statistics.builtEntities++; + statistics.totalNumberOfRecords = totalNumberOfRecord; + // releasing resources + // queryResult.closeAll(); + } + statement.close(); + + return numberOfTables; + } + + /** + * MICRO EXECUTION BLOCK: BUILD SOURCE DATABASE SCHEMA - BUILD OUT-RELATIONSHIPS Builds the + * references to the "Out Relationships" starting from the source database metadata. + * + * @param databaseMetaData metadata of database + * @param numberOfTables number of tables + * @throws SQLException in case of error + */ + private void buildOutRelationships(DatabaseMetaData databaseMetaData, int numberOfTables) + throws SQLException { + int iteration = 1; + for (Entity currentForeignEntity : dataBaseSchema.getEntities()) { + String currentForeignEntityName = currentForeignEntity.getName(); + String foreignSchema = currentForeignEntity.getSchemaName(); + log.debug( + "Building OUT relationships starting from '{}' entity ({}/{})...", + currentForeignEntityName, + iteration, + numberOfTables); + + String foreignCatalog = null; + ResultSet resultForeignKeys = + databaseMetaData.getImportedKeys(foreignCatalog, foreignSchema, currentForeignEntityName); + + // copy of Resultset in a HashLinkedMap + List> currentEntityRelationships1 = + fromResultSetToList(resultForeignKeys); + List> currentEntityRelationships2 = + new LinkedList>(); + + for (LinkedHashMap row : currentEntityRelationships1) { + currentEntityRelationships2.add(row); + } + + closeCursor(resultForeignKeys); + + Iterator> it1 = currentEntityRelationships1.iterator(); + Iterator> it2 = currentEntityRelationships2.iterator(); + + while (it1.hasNext()) { + LinkedHashMap currentExternalRow = it1.next(); + + // current row has Key_Seq equals to '2' then algorithm is finished and is stopped + if (currentExternalRow.get("key_seq").equals("2")) { + break; } - int numberOfTables = tablesName2schema.size(); - statistics.totalNumberOfEntities = numberOfTables; - - // closing resultTable - closeCursor(resultTable); - log.debug("{} tables found:: {} ", numberOfTables, tablesName2schema); - - // Variables for records counting - Statement statement = sourceDBConnection.createStatement(); - int totalNumberOfRecord = 0; - - int iteration = 1; - for (String currentTableName : tablesName2schema.keySet()) { - // Counting current-table's record - String currentTableSchema = tablesName2schema.get(currentTableName); - log.debug("Building '{}' entity on schema {} ({}/{})...", currentTableName, currentTableSchema, iteration, numberOfTables); - - // QueryResult queryResult = dbQueryEngine.countTableRecords(currentTableName, currentTableSchema); - // - // ResultSet currentTableRecordAmount = queryResult.getResult(); - // if (currentTableRecordAmount.next()) { - // totalNumberOfRecord += currentTableRecordAmount.getInt(1); - // } - // closeCursor(currentTableRecordAmount); - - // creating entity - Entity currentEntity = new Entity(currentTableName, currentTableSchema, dataSource); - currentEntity.setSchemaPosition(iteration); - - // adding attributes and primary keys - PrimaryKey pKey = new PrimaryKey(currentEntity, new ArrayList<>()); - - String columnCatalog = null; - String columnSchemaPattern = null; - String columnNamePattern = null; - - String primaryKeyCatalog = null; - String primaryKeySchema = currentTableSchema; - - /** - * MySQL Hack - */ - if (dataSource.getType().equals("RDBMS_MYSQL")) { - primaryKeyCatalog = dataSource.getDatabase(); - if (primaryKeySchema == null) { - primaryKeySchema = dataSource.getDatabase(); - } - } - - ResultSet resultColumns = databaseMetaData.getColumns(columnCatalog, columnSchemaPattern, currentTableName, columnNamePattern); - - log.debug("primaryKeyCatalog ::: {} ", primaryKeySchema); - ResultSet resultPrimaryKeys = databaseMetaData.getPrimaryKeys(primaryKeyCatalog, primaryKeySchema, currentTableName); - - List currentPrimaryKeys = getPrimaryKeysFromResulset(resultPrimaryKeys); - - while (resultColumns.next()) { - Attribute currentAttribute = new Attribute( - resultColumns.getString("COLUMN_NAME"), - resultColumns.getInt("ORDINAL_POSITION"), - resultColumns.getString("TYPE_NAME"), - currentEntity - ); - currentEntity.addAttribute(currentAttribute); - - // if the current attribute is involved in the primary key, it will be added to the attributes of pKey. - if (currentPrimaryKeys.contains(currentAttribute.getName())) { - pKey.addAttribute(currentAttribute); - } - } - - /** - *dataWorkd Hack - */ - if (dataSource.getType().equals("RDBMS_DATA_WORLD")) { - currentPrimaryKeys.add("row_index"); - - final OptionalInt maxOrdinal = currentEntity.getAttributes().stream().mapToInt(a -> a.getOrdinalPosition()).max(); - - Attribute currentAttribute = new Attribute("row_index", maxOrdinal.getAsInt() + 1, " http://www.w3.org/2001/XMLSchema#integer", currentEntity); - currentEntity.addAttribute(currentAttribute); - - pKey.addAttribute(currentAttribute); - } - - closeCursor(resultColumns); - closeCursor(resultPrimaryKeys); - - currentEntity.setPrimaryKey(pKey); - - // if the primary key doesn't involve any attribute, a warning message is generated - if (pKey.getInvolvedAttributes().size() == 0) log.warn( - "It's not declared a primary key for the Entity " + - currentEntity.getName() + - ", might lead to issues during the migration or the sync executions " + - "(the first importing is quite safe)." - ); - - // adding entity to db schema - dataBaseSchema.getEntities().add(currentEntity); - - iteration++; - log.debug("Entity {} built.", currentTableName); - statistics.builtEntities++; - statistics.totalNumberOfRecords = totalNumberOfRecord; - // releasing resources - // queryResult.closeAll(); + // the original relationship is fetched from the record through the 'parent table' and the + // 'key sequence numbers' + String currentParentTableName = currentExternalRow.get("pktable_name"); + int currentKeySeq = Integer.parseInt(currentExternalRow.get("key_seq")); + + // building each single relationship from each correspondent foreign key + Entity currentParentTable = dataBaseSchema.getEntityByName(currentParentTableName); + ForeignKey currentFk = new ForeignKey(currentForeignEntity, new ArrayList<>()); + while (it2.hasNext()) { + LinkedHashMap row = it2.next(); + if (row.get("pktable_name").equals(currentParentTableName) + && Integer.parseInt(row.get("key_seq")) == currentKeySeq) { + currentFk.addAttribute( + currentForeignEntity.getAttributeByName((String) row.get("fkcolumn_name"))); + it2.remove(); + currentKeySeq++; + } } - statement.close(); - return numberOfTables; + // iterator reset + it2 = currentEntityRelationships2.iterator(); + + // searching correspondent primary key + PrimaryKey currentPk = + dataBaseSchema.getEntityByName(currentParentTableName).getPrimaryKey(); + + // adding foreign key to the entity and the relationship, and adding the foreign key to the + // 'foreign entity' + CanonicalRelationship currentRelationship = + new CanonicalRelationship( + currentForeignEntity, currentParentTable, currentFk, currentPk); + currentForeignEntity.getForeignKeys().add(currentFk); + + // adding the relationship to the db schema + dataBaseSchema.getCanonicalRelationships().add(currentRelationship); + // adding relationship to the current entity + currentForeignEntity.getOutCanonicalRelationships().add(currentRelationship); + // updating statistics + statistics.builtRelationships += 1; + } + + iteration++; + log.debug("OUT Relationships from {} built.", currentForeignEntityName); + statistics.entitiesAnalyzedForRelationship++; } - /** - * MICRO EXECUTION BLOCK: BUILD SOURCE DATABASE SCHEMA - BUILD OUT-RELATIONSHIPS - * Builds the references to the "Out Relationships" starting from the source database metadata. - * - * @param databaseMetaData metadata of database - * @param numberOfTables number of tables - * @throws SQLException in case of error - */ - - private void buildOutRelationships(DatabaseMetaData databaseMetaData, int numberOfTables) throws SQLException { - int iteration = 1; - for (Entity currentForeignEntity : dataBaseSchema.getEntities()) { - String currentForeignEntityName = currentForeignEntity.getName(); - String foreignSchema = currentForeignEntity.getSchemaName(); - log.debug("Building OUT relationships starting from '{}' entity ({}/{})...", currentForeignEntityName, iteration, numberOfTables); - - String foreignCatalog = null; - ResultSet resultForeignKeys = databaseMetaData.getImportedKeys(foreignCatalog, foreignSchema, currentForeignEntityName); - - // copy of Resultset in a HashLinkedMap - List> currentEntityRelationships1 = fromResultSetToList(resultForeignKeys); - List> currentEntityRelationships2 = new LinkedList>(); - - for (LinkedHashMap row : currentEntityRelationships1) { - currentEntityRelationships2.add(row); - } - - closeCursor(resultForeignKeys); - - Iterator> it1 = currentEntityRelationships1.iterator(); - Iterator> it2 = currentEntityRelationships2.iterator(); - - while (it1.hasNext()) { - LinkedHashMap currentExternalRow = it1.next(); - - // current row has Key_Seq equals to '2' then algorithm is finished and is stopped - if (currentExternalRow.get("key_seq").equals("2")) { - break; - } - - // the original relationship is fetched from the record through the 'parent table' and the 'key sequence numbers' - String currentParentTableName = currentExternalRow.get("pktable_name"); - int currentKeySeq = Integer.parseInt(currentExternalRow.get("key_seq")); - - // building each single relationship from each correspondent foreign key - Entity currentParentTable = dataBaseSchema.getEntityByName(currentParentTableName); - ForeignKey currentFk = new ForeignKey(currentForeignEntity, new ArrayList<>()); - while (it2.hasNext()) { - LinkedHashMap row = it2.next(); - if (row.get("pktable_name").equals(currentParentTableName) && Integer.parseInt(row.get("key_seq")) == currentKeySeq) { - currentFk.addAttribute(currentForeignEntity.getAttributeByName((String) row.get("fkcolumn_name"))); - it2.remove(); - currentKeySeq++; - } - } - - // iterator reset - it2 = currentEntityRelationships2.iterator(); - - // searching correspondent primary key - PrimaryKey currentPk = dataBaseSchema.getEntityByName(currentParentTableName).getPrimaryKey(); - - // adding foreign key to the entity and the relationship, and adding the foreign key to the 'foreign entity' - CanonicalRelationship currentRelationship = new CanonicalRelationship(currentForeignEntity, currentParentTable, currentFk, currentPk); - currentForeignEntity.getForeignKeys().add(currentFk); - - // adding the relationship to the db schema - dataBaseSchema.getCanonicalRelationships().add(currentRelationship); - // adding relationship to the current entity - currentForeignEntity.getOutCanonicalRelationships().add(currentRelationship); - // updating statistics - statistics.builtRelationships += 1; - } - - iteration++; - log.debug("OUT Relationships from {} built.", currentForeignEntityName); - statistics.entitiesAnalyzedForRelationship++; - } - - statistics.totalNumberOfRelationships = dataBaseSchema.getCanonicalRelationships().size(); + statistics.totalNumberOfRelationships = dataBaseSchema.getCanonicalRelationships().size(); + } + + /** + * MICRO EXECUTION BLOCK: BUILD SOURCE DATABASE SCHEMA - BUILD IN-RELATIONSHIPS Builds the + * references to the "In Relationships" starting from the references to the "Out Relationships". + */ + private void buildInRelationships() { + int iteration = 1; + log.debug("Connecting IN relationships..."); + + for (Relationship currentRelationship : dataBaseSchema.getCanonicalRelationships()) { + Entity currentInEntity = + getDataBaseSchema().getEntityByName(currentRelationship.getParentEntity().getName()); + currentInEntity + .getInCanonicalRelationships() + .add((CanonicalRelationship) currentRelationship); } - /** - * MICRO EXECUTION BLOCK: BUILD SOURCE DATABASE SCHEMA - BUILD IN-RELATIONSHIPS - * Builds the references to the "In Relationships" starting from the references to the "Out Relationships". - */ + log.debug("IN relationships built."); + } - private void buildInRelationships() { - int iteration = 1; - log.debug("Connecting IN relationships..."); - - for (Relationship currentRelationship : dataBaseSchema.getCanonicalRelationships()) { - Entity currentInEntity = getDataBaseSchema().getEntityByName(currentRelationship.getParentEntity().getName()); - currentInEntity.getInCanonicalRelationships().add((CanonicalRelationship) currentRelationship); - } + private List getPrimaryKeysFromResulset(ResultSet resultPrimaryKeys) throws SQLException { + List currentPrimaryKeys = new LinkedList(); - log.debug("IN relationships built."); + while (resultPrimaryKeys.next()) { + currentPrimaryKeys.add(resultPrimaryKeys.getString(4)); } - - private List getPrimaryKeysFromResulset(ResultSet resultPrimaryKeys) throws SQLException { - List currentPrimaryKeys = new LinkedList(); - - while (resultPrimaryKeys.next()) { - currentPrimaryKeys.add(resultPrimaryKeys.getString(4)); - } - return currentPrimaryKeys; + return currentPrimaryKeys; + } + + private void closeCursor(ResultSet result) { + try { + if (result != null) result.close(); + } catch (SQLException e) { + log.error("", e); } - - private void closeCursor(ResultSet result) { - try { - if (result != null) result.close(); - } catch (SQLException e) { - log.error("", e); + } + + /* + * Transforms a ResultSet in a List, filtering relationships according to "include/exclude-lists" + */ + + private List> fromResultSetToList(ResultSet resultForeignKeys) { + List> rows = new LinkedList>(); + + try { + int columnsAmount = resultForeignKeys.getMetaData().getColumnCount(); + + while (resultForeignKeys.next()) { + if (isTableAllowed(resultForeignKeys.getString("pktable_name")) + && dataBaseSchema.getEntityByName(resultForeignKeys.getString("pktable_name")) + != null) { + // if(isTableAllowed(resultForeignKeys.getString("pktable_name")) && + // dataBaseSchema.getEntityByName(resultForeignKeys.getString("pktable_name")) != null) { + + LinkedHashMap row = new LinkedHashMap(); + for (int i = 1; i <= columnsAmount; i++) { + row.put( + resultForeignKeys.getMetaData().getColumnName(i).toLowerCase(Locale.ENGLISH), + resultForeignKeys.getString(i)); + } + rows.add(row); } + } + } catch (SQLException e) { + throw new RDBMSProviderRuntimeException(e); } + return rows; + } + + /** + * MACRO EXECUTION BLOCK: BUILD GRAPH MODEL Builds the graph model and the rules for the mapping + * with the source database schema through 2 micro execution blocks: - Build Vertex Types - Build + * Edge Types + * + * @param nameResolver the name resolver + */ + public void buildGraphModel(NameResolver nameResolver) { + statistics.startWork2Time = new Date(); + statistics.runningStepNumber = 2; /* - * Transforms a ResultSet in a List, filtering relationships according to "include/exclude-lists" - */ - - private List> fromResultSetToList(ResultSet resultForeignKeys) { - List> rows = new LinkedList>(); - - try { - int columnsAmount = resultForeignKeys.getMetaData().getColumnCount(); - - while (resultForeignKeys.next()) { - if ( - isTableAllowed(resultForeignKeys.getString("pktable_name")) && - dataBaseSchema.getEntityByName(resultForeignKeys.getString("pktable_name")) != null - ) { - // if(isTableAllowed(resultForeignKeys.getString("pktable_name")) && dataBaseSchema.getEntityByName(resultForeignKeys.getString("pktable_name")) != null) { - - LinkedHashMap row = new LinkedHashMap(); - for (int i = 1; i <= columnsAmount; i++) { - row.put(resultForeignKeys.getMetaData().getColumnName(i).toLowerCase(Locale.ENGLISH), resultForeignKeys.getString(i)); - } - rows.add(row); - } - } - } catch (SQLException e) { - throw new RDBMSProviderRuntimeException(e); - } - return rows; - } - - /** - * MACRO EXECUTION BLOCK: BUILD GRAPH MODEL - * Builds the graph model and the rules for the mapping with the source database schema through 2 micro execution blocks: - * - Build Vertex Types - * - Build Edge Types - * - * @param nameResolver the name resolver + * Vertex-types building */ - public void buildGraphModel(NameResolver nameResolver) { - statistics.startWork2Time = new Date(); - statistics.runningStepNumber = 2; - - /* - * Vertex-types building - */ + buildVertexTypes(nameResolver); - buildVertexTypes(nameResolver); - - /* - * Edge-types building - */ - - buildEdgeTypes(nameResolver); - - statistics.runningStepNumber = -1; - } - - /** - * MICRO EXECUTION BLOCK: BUILD GRAPH MODEL - BUILD VERTEX TYPES - * Builds the Vertex Types starting from the Entities in the source database schema. - * - * @param nameResolver the name Resolver + /* + * Edge-types building */ - private void buildVertexTypes(NameResolver nameResolver) { - int numberOfVertexType = dataBaseSchema.getEntities().size(); - statistics.totalNumberOfModelVertices = numberOfVertexType; - int iteration = 1; - for (Entity currentEntity : dataBaseSchema.getEntities()) { - log.debug("Building '{}' vertex-type ({}/{})...", currentEntity.getName(), iteration, numberOfVertexType); - - // building correspondent vertex-type - String currentVertexTypeName = nameResolver.resolveVertexName(currentEntity.getName()); - - // fetch the vertex type from the graph model (empty vertex, only name defined), if does not exist create it. - boolean alreadyPresentInGraphModel = true; - VertexType currentVertexType = graphModel.getVertexTypeByName(currentVertexTypeName); - if (currentVertexType == null) { - currentVertexType = new VertexType(currentVertexTypeName); - alreadyPresentInGraphModel = false; - } - - // recognizing joint tables of dimension 2 - if (currentEntity.isAggregableJoinTable()) currentVertexType.setIsFromJoinTable(true); else currentVertexType.setIsFromJoinTable(false); - - // adding attributes to vertex-type - Map attribute2property = new LinkedHashMap<>(); // map to maintain the mapping between the attributes of the current entity and the properties of the correspondent vertex type - Map property2attribute = new LinkedHashMap<>(); // map to maintain the mapping between the properties of the current vertex type and the attributes of the correspondent entity - for (Attribute currentAttribute : currentEntity.getAttributes()) { - String orientdbDataType = TypeMapperKt.mapType(currentAttribute.getDataType().toLowerCase(Locale.ENGLISH)); - ModelProperty currentProperty = new ModelProperty( - nameResolver.resolveVertexProperty(currentAttribute.getName()), - currentAttribute.getOrdinalPosition(), - currentAttribute.getDataType(), - currentEntity.getPrimaryKey().getInvolvedAttributes().contains(currentAttribute), - currentVertexType - ); - currentProperty.setOrientdbType(orientdbDataType); - currentVertexType.getProperties().add(currentProperty); - - attribute2property.put(currentAttribute.getName(), currentProperty.getName()); - property2attribute.put(currentProperty.getName(), currentAttribute.getName()); - } - - // adding inherited attributes to vertex-type - for (Attribute attribute : currentEntity.getInheritedAttributes()) { - ModelProperty currentProperty = new ModelProperty( - nameResolver.resolveVertexProperty(attribute.getName()), - attribute.getOrdinalPosition(), - attribute.getDataType(), - currentEntity.getPrimaryKey().getInvolvedAttributes().contains(attribute), - currentVertexType - ); - currentVertexType.getInheritedProperties().add(currentProperty); - // TODO: Adding inherited attributes and props to the maps? - } - - // setting externalKey - Set externalKey = new LinkedHashSet(); - for (ModelProperty currentProperty : currentVertexType.getAllProperties()) { - // only attribute coming from the primary key are given - if (currentProperty.isFromPrimaryKey()) { - externalKey.add(currentProperty.getName()); - } - } - currentVertexType.setExternalKey(externalKey); - - // adding parent vertex if the corresponding entity has a parent - if (currentEntity.getParentEntity() != null) { - ElementType currentParentElement = graphModel.getVertexTypeByNameIgnoreCase(currentEntity.getParentEntity().getName()); - currentVertexType.setParentType(currentParentElement); - currentVertexType.setInheritanceLevel(currentEntity.getInheritanceLevel()); - } - - // adding vertex to the graph model - if (!alreadyPresentInGraphModel) { - graphModel.getVerticesType().add(currentVertexType); - } - - // rules updating - EVClassMapper classMapper = new EVClassMapper(currentEntity, currentVertexType, attribute2property, property2attribute); - upsertEVClassMappingRules(currentEntity, currentVertexType, classMapper); - - iteration++; - log.debug("Vertex-type {} built.", currentVertexTypeName); - statistics.builtModelVertexTypes++; + buildEdgeTypes(nameResolver); + + statistics.runningStepNumber = -1; + } + + /** + * MICRO EXECUTION BLOCK: BUILD GRAPH MODEL - BUILD VERTEX TYPES Builds the Vertex Types starting + * from the Entities in the source database schema. + * + * @param nameResolver the name Resolver + */ + private void buildVertexTypes(NameResolver nameResolver) { + int numberOfVertexType = dataBaseSchema.getEntities().size(); + statistics.totalNumberOfModelVertices = numberOfVertexType; + int iteration = 1; + for (Entity currentEntity : dataBaseSchema.getEntities()) { + log.debug( + "Building '{}' vertex-type ({}/{})...", + currentEntity.getName(), + iteration, + numberOfVertexType); + + // building correspondent vertex-type + String currentVertexTypeName = nameResolver.resolveVertexName(currentEntity.getName()); + + // fetch the vertex type from the graph model (empty vertex, only name defined), if does not + // exist create it. + boolean alreadyPresentInGraphModel = true; + VertexType currentVertexType = graphModel.getVertexTypeByName(currentVertexTypeName); + if (currentVertexType == null) { + currentVertexType = new VertexType(currentVertexTypeName); + alreadyPresentInGraphModel = false; + } + + // recognizing joint tables of dimension 2 + if (currentEntity.isAggregableJoinTable()) currentVertexType.setIsFromJoinTable(true); + else currentVertexType.setIsFromJoinTable(false); + + // adding attributes to vertex-type + Map attribute2property = + new LinkedHashMap<>(); // map to maintain the mapping between the attributes of the + // current entity and the properties of the correspondent vertex + // type + Map property2attribute = + new LinkedHashMap<>(); // map to maintain the mapping between the properties of the + // current vertex type and the attributes of the correspondent + // entity + for (Attribute currentAttribute : currentEntity.getAttributes()) { + String orientdbDataType = + TypeMapperKt.mapType(currentAttribute.getDataType().toLowerCase(Locale.ENGLISH)); + ModelProperty currentProperty = + new ModelProperty( + nameResolver.resolveVertexProperty(currentAttribute.getName()), + currentAttribute.getOrdinalPosition(), + currentAttribute.getDataType(), + currentEntity.getPrimaryKey().getInvolvedAttributes().contains(currentAttribute), + currentVertexType); + currentProperty.setOrientdbType(orientdbDataType); + currentVertexType.getProperties().add(currentProperty); + + attribute2property.put(currentAttribute.getName(), currentProperty.getName()); + property2attribute.put(currentProperty.getName(), currentAttribute.getName()); + } + + // adding inherited attributes to vertex-type + for (Attribute attribute : currentEntity.getInheritedAttributes()) { + ModelProperty currentProperty = + new ModelProperty( + nameResolver.resolveVertexProperty(attribute.getName()), + attribute.getOrdinalPosition(), + attribute.getDataType(), + currentEntity.getPrimaryKey().getInvolvedAttributes().contains(attribute), + currentVertexType); + currentVertexType.getInheritedProperties().add(currentProperty); + // TODO: Adding inherited attributes and props to the maps? + } + + // setting externalKey + Set externalKey = new LinkedHashSet(); + for (ModelProperty currentProperty : currentVertexType.getAllProperties()) { + // only attribute coming from the primary key are given + if (currentProperty.isFromPrimaryKey()) { + externalKey.add(currentProperty.getName()); } - - // sorting vertices type for inheritance level and then for name - Collections.sort(graphModel.getVerticesType()); + } + currentVertexType.setExternalKey(externalKey); + + // adding parent vertex if the corresponding entity has a parent + if (currentEntity.getParentEntity() != null) { + ElementType currentParentElement = + graphModel.getVertexTypeByNameIgnoreCase(currentEntity.getParentEntity().getName()); + currentVertexType.setParentType(currentParentElement); + currentVertexType.setInheritanceLevel(currentEntity.getInheritanceLevel()); + } + + // adding vertex to the graph model + if (!alreadyPresentInGraphModel) { + graphModel.getVerticesType().add(currentVertexType); + } + + // rules updating + EVClassMapper classMapper = + new EVClassMapper( + currentEntity, currentVertexType, attribute2property, property2attribute); + upsertEVClassMappingRules(currentEntity, currentVertexType, classMapper); + + iteration++; + log.debug("Vertex-type {} built.", currentVertexTypeName); + statistics.builtModelVertexTypes++; } - /** - * MICRO EXECUTION BLOCK: BUILD GRAPH MODEL - BUILD EDGE TYPES - * Builds the Edge Types starting from the Relationships in the source database schema. - * - * @param nameResolver the name resolver - */ - - private void buildEdgeTypes(NameResolver nameResolver) { - int numberOfEdgeType = dataBaseSchema.getCanonicalRelationships().size(); - statistics.totalNumberOfModelEdges = numberOfEdgeType; - String edgeType = null; - int iteration = 1; - - if (numberOfEdgeType > 0) { - // edges added through relationships (foreign keys of db) - for (Entity currentEntity : dataBaseSchema.getEntities()) { - for (CanonicalRelationship relationship : currentEntity.getOutCanonicalRelationships()) { - VertexType currentOutVertex = getVertexTypeByEntity(relationship.getForeignEntity()); - VertexType currentInVertex = getVertexTypeByEntity(relationship.getParentEntity()); - - log.debug( - "Building edge-type from '{}' to '{}' ({}/{})...", - currentOutVertex.getName(), - currentInVertex.getName(), - iteration, - numberOfEdgeType - ); - - if (currentOutVertex != null && currentInVertex != null) { - // check on the presence of the relationship in the map performed in order to avoid generating several edgeTypes for the same relationship. - // when the edge was built before from the migrationConfigDoc and the relationship was inserted with that edgeType in the map, the relationships - // mustn't be analyzed at point! CHANGE IT when you'll implement the pipeline - if (!relationship2edgeType.containsKey(relationship)) { - // relationships which represents inheritance between different entities don't generate new edge-types, - // thus new edge type is created iff the parent-table's name (of the relationship) does not coincide - // with the name of the parent entity of the current entity. - if ( - currentEntity.getParentEntity() == null || - !currentEntity.getParentEntity().getName().equals(relationship.getParentEntity().getName()) - ) { - // if the class edge doesn't exists, it will be created - edgeType = nameResolver.resolveEdgeName(relationship); - - EdgeType currentEdgeType = graphModel.getEdgeTypeByName(edgeType); - if (currentEdgeType == null) { - currentEdgeType = new EdgeType(edgeType, null, currentInVertex); - graphModel.getEdgesType().add(currentEdgeType); - - log.debug("Edge-type {} built.", currentEdgeType.getName()); - statistics.builtModelEdgeTypes++; - } else { - // edge already present, the counter of relationships represented by the edge is incremented - currentEdgeType.setNumberRelationshipsRepresented(currentEdgeType.getNumberRelationshipsRepresented() + 1); - } - - // adding the edge to the two vertices - if (!currentOutVertex.getOutEdgesType().contains(currentEdgeType)) { - currentOutVertex.getOutEdgesType().add(currentEdgeType); - } - if (!currentInVertex.getInEdgesType().contains(currentEdgeType)) { - currentInVertex.getInEdgesType().add(currentEdgeType); - } - - // rules updating - upsertRelationshipEdgeRules(relationship, currentEdgeType); - } - } - } else { - log.error("Error during graph model building phase: information loss, relationship missed. Edge-type not built.\n"); - } - - iteration++; + // sorting vertices type for inheritance level and then for name + Collections.sort(graphModel.getVerticesType()); + } + + /** + * MICRO EXECUTION BLOCK: BUILD GRAPH MODEL - BUILD EDGE TYPES Builds the Edge Types starting from + * the Relationships in the source database schema. + * + * @param nameResolver the name resolver + */ + private void buildEdgeTypes(NameResolver nameResolver) { + int numberOfEdgeType = dataBaseSchema.getCanonicalRelationships().size(); + statistics.totalNumberOfModelEdges = numberOfEdgeType; + String edgeType = null; + int iteration = 1; + + if (numberOfEdgeType > 0) { + // edges added through relationships (foreign keys of db) + for (Entity currentEntity : dataBaseSchema.getEntities()) { + for (CanonicalRelationship relationship : currentEntity.getOutCanonicalRelationships()) { + VertexType currentOutVertex = getVertexTypeByEntity(relationship.getForeignEntity()); + VertexType currentInVertex = getVertexTypeByEntity(relationship.getParentEntity()); + + log.debug( + "Building edge-type from '{}' to '{}' ({}/{})...", + currentOutVertex.getName(), + currentInVertex.getName(), + iteration, + numberOfEdgeType); + + if (currentOutVertex != null && currentInVertex != null) { + // check on the presence of the relationship in the map performed in order to avoid + // generating several edgeTypes for the same relationship. + // when the edge was built before from the migrationConfigDoc and the relationship was + // inserted with that edgeType in the map, the relationships + // mustn't be analyzed at point! CHANGE IT when you'll implement the pipeline + if (!relationship2edgeType.containsKey(relationship)) { + // relationships which represents inheritance between different entities don't + // generate new edge-types, + // thus new edge type is created iff the parent-table's name (of the relationship) + // does not coincide + // with the name of the parent entity of the current entity. + if (currentEntity.getParentEntity() == null + || !currentEntity + .getParentEntity() + .getName() + .equals(relationship.getParentEntity().getName())) { + // if the class edge doesn't exists, it will be created + edgeType = nameResolver.resolveEdgeName(relationship); + + EdgeType currentEdgeType = graphModel.getEdgeTypeByName(edgeType); + if (currentEdgeType == null) { + currentEdgeType = new EdgeType(edgeType, null, currentInVertex); + graphModel.getEdgesType().add(currentEdgeType); + + log.debug("Edge-type {} built.", currentEdgeType.getName()); + statistics.builtModelEdgeTypes++; + } else { + // edge already present, the counter of relationships represented by the edge is + // incremented + currentEdgeType.setNumberRelationshipsRepresented( + currentEdgeType.getNumberRelationshipsRepresented() + 1); } - // building edges starting from inherited relationships - - for (CanonicalRelationship relationship : currentEntity.getInheritedOutCanonicalRelationships()) { - VertexType currentOutVertex = getVertexTypeByEntity(currentEntity); - VertexType currentInVertex = getVertexTypeByEntity(relationship.getParentEntity()); - - log.debug( - "Building edge-type from '{}' to '{}' ({}/{})...", - currentOutVertex.getName(), - currentInVertex.getName(), - iteration, - numberOfEdgeType - ); - - if (currentOutVertex != null && currentInVertex != null) { - EdgeType currentEdgeType = graphModel.getEdgeTypeByName(edgeType); - - // adding the edge to the two vertices - currentOutVertex.getOutEdgesType().add(currentEdgeType); - currentInVertex.getInEdgesType().add(currentEdgeType); - - log.debug("Edge-type built."); - } else { - log.error("Error during graph model building phase: information loss, relationship missed. Edge-type not built.\n"); - } + // adding the edge to the two vertices + if (!currentOutVertex.getOutEdgesType().contains(currentEdgeType)) { + currentOutVertex.getOutEdgesType().add(currentEdgeType); } + if (!currentInVertex.getInEdgesType().contains(currentEdgeType)) { + currentInVertex.getInEdgesType().add(currentEdgeType); + } + + // rules updating + upsertRelationshipEdgeRules(relationship, currentEdgeType); + } } + } else { + log.error( + "Error during graph model building phase: information loss, relationship missed." + + " Edge-type not built.\n"); + } - // Updating the total number of model edges with the actual number of built model edges since it was initialized with the number of relationships in the source db schema. - // In fact if there are relationships representing hierarchy then the number of built edges is less than the number of relationships. - statistics.totalNumberOfModelEdges = statistics.builtModelEdgeTypes; + iteration++; } - } - /** - * MACRO EXECUTION BLOCK: PERFORM AGGREGATIONS - * Performs aggregation strategies on the graph model through the following micro execution blocks: - * - Many-To-Many Aggregation - */ + // building edges starting from inherited relationships + + for (CanonicalRelationship relationship : + currentEntity.getInheritedOutCanonicalRelationships()) { + VertexType currentOutVertex = getVertexTypeByEntity(currentEntity); + VertexType currentInVertex = getVertexTypeByEntity(relationship.getParentEntity()); + + log.debug( + "Building edge-type from '{}' to '{}' ({}/{})...", + currentOutVertex.getName(), + currentInVertex.getName(), + iteration, + numberOfEdgeType); + + if (currentOutVertex != null && currentInVertex != null) { + EdgeType currentEdgeType = graphModel.getEdgeTypeByName(edgeType); + + // adding the edge to the two vertices + currentOutVertex.getOutEdgesType().add(currentEdgeType); + currentInVertex.getInEdgesType().add(currentEdgeType); + + log.debug("Edge-type built."); + } else { + log.error( + "Error during graph model building phase: information loss, relationship missed." + + " Edge-type not built.\n"); + } + } + } - public void performAggregations() { - /* - * Many-To-Many Aggregation - */ - performMany2ManyAggregation(); + // Updating the total number of model edges with the actual number of built model edges since + // it was initialized with the number of relationships in the source db schema. + // In fact if there are relationships representing hierarchy then the number of built edges is + // less than the number of relationships. + statistics.totalNumberOfModelEdges = statistics.builtModelEdgeTypes; } + } - /** - * MICRO EXECUTION BLOCK: PERFORM AGGREGATIONS - MANY TO MANY AGGREGATION - * Aggregates Many-To-Many Relationships represented by join tables of dimension == 2. + /** + * MACRO EXECUTION BLOCK: PERFORM AGGREGATIONS Performs aggregation strategies on the graph model + * through the following micro execution blocks: - Many-To-Many Aggregation + */ + public void performAggregations() { + /* + * Many-To-Many Aggregation */ + performMany2ManyAggregation(); + } + + /** + * MICRO EXECUTION BLOCK: PERFORM AGGREGATIONS - MANY TO MANY AGGREGATION Aggregates Many-To-Many + * Relationships represented by join tables of dimension == 2. + */ + public void performMany2ManyAggregation() { + Iterator it = graphModel.getVerticesType().iterator(); + + log.debug("Join Table aggregation phase..."); + + while (it.hasNext()) { + VertexType currentVertexType = it.next(); + + // if vertex is obtained from a join table of dimension 2, + // then aggregation is performed + if (currentVertexType.isFromJoinTable() && currentVertexType.getOutEdgesType().size() == 2) { + // building new edge + EdgeType currentOutEdge1 = currentVertexType.getOutEdgesType().get(0); + EdgeType currentOutEdge2 = currentVertexType.getOutEdgesType().get(1); + + VertexType outVertexType; + VertexType inVertexType; + String direction = + getEntityByVertexType(currentVertexType).getDirectionOfN2NRepresentedRelationship(); + if (direction.equals("direct")) { + outVertexType = currentOutEdge1.getInVertexType(); + inVertexType = currentOutEdge2.getInVertexType(); + } else { + outVertexType = currentOutEdge2.getInVertexType(); + inVertexType = currentOutEdge1.getInVertexType(); + } - public void performMany2ManyAggregation() { - Iterator it = graphModel.getVerticesType().iterator(); - - log.debug("Join Table aggregation phase..."); - - while (it.hasNext()) { - VertexType currentVertexType = it.next(); - - // if vertex is obtained from a join table of dimension 2, - // then aggregation is performed - if (currentVertexType.isFromJoinTable() && currentVertexType.getOutEdgesType().size() == 2) { - // building new edge - EdgeType currentOutEdge1 = currentVertexType.getOutEdgesType().get(0); - EdgeType currentOutEdge2 = currentVertexType.getOutEdgesType().get(1); - - VertexType outVertexType; - VertexType inVertexType; - String direction = getEntityByVertexType(currentVertexType).getDirectionOfN2NRepresentedRelationship(); - if (direction.equals("direct")) { - outVertexType = currentOutEdge1.getInVertexType(); - inVertexType = currentOutEdge2.getInVertexType(); - } else { - outVertexType = currentOutEdge2.getInVertexType(); - inVertexType = currentOutEdge1.getInVertexType(); - } - - Entity joinTable = getEntityByVertexType(currentVertexType); - String nameOfRelationship = joinTable.getNameOfN2NRepresentedRelationship(); - String edgeType; - if (nameOfRelationship != null) edgeType = nameOfRelationship; else edgeType = currentVertexType.getName(); - - EdgeType newAggregatorEdge = new EdgeType(edgeType, outVertexType, inVertexType); - newAggregatorEdge.setIsAggregatorEdge(true); - - int position = 1; - // adding to the edge all properties not belonging to the primary key - for (ModelProperty currentProperty : currentVertexType.getProperties()) { - // if property does not belong to the primary key add it to the aggregator edge - if (!currentProperty.isFromPrimaryKey()) { - ModelProperty newProperty = new ModelProperty( - currentProperty.getName(), - position, - currentProperty.getOriginalType(), - currentProperty.isFromPrimaryKey(), - newAggregatorEdge - ); - newProperty.setOrientdbType(currentProperty.getOrientdbType()); - if (currentProperty.isMandatory() != null) newProperty.setMandatory(currentProperty.isMandatory()); - if (currentProperty.isReadOnly() != null) newProperty.setReadOnly(currentProperty.isReadOnly()); - if (currentProperty.isNotNull() != null) newProperty.setNotNull(currentProperty.isNotNull()); - newAggregatorEdge.getProperties().add(newProperty); - position++; - } - } - - // adding to the edge all properties belonging to the old edges - for (ModelProperty currentProperty : currentOutEdge1.getProperties()) { - if (newAggregatorEdge.getPropertyByName(currentProperty.getName()) == null) { - ModelProperty newProperty = new ModelProperty( - currentProperty.getName(), - position, - currentProperty.getOriginalType(), - currentProperty.isFromPrimaryKey(), - newAggregatorEdge - ); - newProperty.setOrientdbType(currentProperty.getOrientdbType()); - if (currentProperty.isMandatory() != null) newProperty.setMandatory(currentProperty.isMandatory()); - if (currentProperty.isReadOnly() != null) newProperty.setReadOnly(currentProperty.isReadOnly()); - if (currentProperty.isNotNull() != null) newProperty.setNotNull(currentProperty.isNotNull()); - newAggregatorEdge.getProperties().add(newProperty); - position++; - } - } - for (ModelProperty currentProperty : currentOutEdge2.getProperties()) { - if (newAggregatorEdge.getPropertyByName(currentProperty.getName()) == null) { - ModelProperty newProperty = new ModelProperty( - currentProperty.getName(), - position, - currentProperty.getOriginalType(), - currentProperty.isFromPrimaryKey(), - newAggregatorEdge - ); - newProperty.setOrientdbType(currentProperty.getOrientdbType()); - if (currentProperty.isMandatory() != null) newProperty.setMandatory(currentProperty.isMandatory()); - if (currentProperty.isReadOnly() != null) newProperty.setReadOnly(currentProperty.isReadOnly()); - if (currentProperty.isNotNull() != null) newProperty.setNotNull(currentProperty.isNotNull()); - newAggregatorEdge.getProperties().add(newProperty); - position++; - } - } - - // removing old edges from graph model and from vertices' "in-edges" collection - currentOutEdge1.setNumberRelationshipsRepresented(currentOutEdge1.getNumberRelationshipsRepresented() - 1); - currentOutEdge2.setNumberRelationshipsRepresented(currentOutEdge2.getNumberRelationshipsRepresented() - 1); - - if (currentOutEdge1.getNumberRelationshipsRepresented() == 0) { - graphModel.getEdgesType().remove(currentOutEdge1); - statistics.builtModelEdgeTypes--; - statistics.totalNumberOfModelEdges--; - } - if (currentOutEdge2.getNumberRelationshipsRepresented() == 0) { - graphModel.getEdgesType().remove(currentOutEdge2); - statistics.builtModelEdgeTypes--; - statistics.totalNumberOfModelEdges--; - } - if (direction.equals("direct")) { - outVertexType.getInEdgesType().remove(currentOutEdge1); - inVertexType.getInEdgesType().remove(currentOutEdge2); - } else { - outVertexType.getInEdgesType().remove(currentOutEdge2); - inVertexType.getInEdgesType().remove(currentOutEdge1); - } - - // adding entry to the map - joinVertex2aggregatorEdges.put(currentVertexType, new AggregatorEdge(outVertexType.getName(), inVertexType.getName(), newAggregatorEdge)); + Entity joinTable = getEntityByVertexType(currentVertexType); + String nameOfRelationship = joinTable.getNameOfN2NRepresentedRelationship(); + String edgeType; + if (nameOfRelationship != null) edgeType = nameOfRelationship; + else edgeType = currentVertexType.getName(); + + EdgeType newAggregatorEdge = new EdgeType(edgeType, outVertexType, inVertexType); + newAggregatorEdge.setIsAggregatorEdge(true); + + int position = 1; + // adding to the edge all properties not belonging to the primary key + for (ModelProperty currentProperty : currentVertexType.getProperties()) { + // if property does not belong to the primary key add it to the aggregator edge + if (!currentProperty.isFromPrimaryKey()) { + ModelProperty newProperty = + new ModelProperty( + currentProperty.getName(), + position, + currentProperty.getOriginalType(), + currentProperty.isFromPrimaryKey(), + newAggregatorEdge); + newProperty.setOrientdbType(currentProperty.getOrientdbType()); + if (currentProperty.isMandatory() != null) + newProperty.setMandatory(currentProperty.isMandatory()); + if (currentProperty.isReadOnly() != null) + newProperty.setReadOnly(currentProperty.isReadOnly()); + if (currentProperty.isNotNull() != null) + newProperty.setNotNull(currentProperty.isNotNull()); + newAggregatorEdge.getProperties().add(newProperty); + position++; + } + } - // removing old vertex - it.remove(); - statistics.builtModelVertexTypes--; - statistics.totalNumberOfModelVertices--; + // adding to the edge all properties belonging to the old edges + for (ModelProperty currentProperty : currentOutEdge1.getProperties()) { + if (newAggregatorEdge.getPropertyByName(currentProperty.getName()) == null) { + ModelProperty newProperty = + new ModelProperty( + currentProperty.getName(), + position, + currentProperty.getOriginalType(), + currentProperty.isFromPrimaryKey(), + newAggregatorEdge); + newProperty.setOrientdbType(currentProperty.getOrientdbType()); + if (currentProperty.isMandatory() != null) + newProperty.setMandatory(currentProperty.isMandatory()); + if (currentProperty.isReadOnly() != null) + newProperty.setReadOnly(currentProperty.isReadOnly()); + if (currentProperty.isNotNull() != null) + newProperty.setNotNull(currentProperty.isNotNull()); + newAggregatorEdge.getProperties().add(newProperty); + position++; + } + } + for (ModelProperty currentProperty : currentOutEdge2.getProperties()) { + if (newAggregatorEdge.getPropertyByName(currentProperty.getName()) == null) { + ModelProperty newProperty = + new ModelProperty( + currentProperty.getName(), + position, + currentProperty.getOriginalType(), + currentProperty.isFromPrimaryKey(), + newAggregatorEdge); + newProperty.setOrientdbType(currentProperty.getOrientdbType()); + if (currentProperty.isMandatory() != null) + newProperty.setMandatory(currentProperty.isMandatory()); + if (currentProperty.isReadOnly() != null) + newProperty.setReadOnly(currentProperty.isReadOnly()); + if (currentProperty.isNotNull() != null) + newProperty.setNotNull(currentProperty.isNotNull()); + newAggregatorEdge.getProperties().add(newProperty); + position++; + } + } - // adding new edge to graph model - graphModel.getEdgesType().add(newAggregatorEdge); - statistics.builtModelEdgeTypes++; - statistics.totalNumberOfModelEdges++; + // removing old edges from graph model and from vertices' "in-edges" collection + currentOutEdge1.setNumberRelationshipsRepresented( + currentOutEdge1.getNumberRelationshipsRepresented() - 1); + currentOutEdge2.setNumberRelationshipsRepresented( + currentOutEdge2.getNumberRelationshipsRepresented() - 1); - // adding new edge to the vertices' "in/out-edges" collections - outVertexType.getOutEdgesType().add(newAggregatorEdge); - inVertexType.getInEdgesType().add(newAggregatorEdge); - } + if (currentOutEdge1.getNumberRelationshipsRepresented() == 0) { + graphModel.getEdgesType().remove(currentOutEdge1); + statistics.builtModelEdgeTypes--; + statistics.totalNumberOfModelEdges--; + } + if (currentOutEdge2.getNumberRelationshipsRepresented() == 0) { + graphModel.getEdgesType().remove(currentOutEdge2); + statistics.builtModelEdgeTypes--; + statistics.totalNumberOfModelEdges--; + } + if (direction.equals("direct")) { + outVertexType.getInEdgesType().remove(currentOutEdge1); + inVertexType.getInEdgesType().remove(currentOutEdge2); + } else { + outVertexType.getInEdgesType().remove(currentOutEdge2); + inVertexType.getInEdgesType().remove(currentOutEdge1); } - log.debug("Aggregation performed."); + // adding entry to the map + joinVertex2aggregatorEdges.put( + currentVertexType, + new AggregatorEdge(outVertexType.getName(), inVertexType.getName(), newAggregatorEdge)); + + // removing old vertex + it.remove(); + statistics.builtModelVertexTypes--; + statistics.totalNumberOfModelVertices--; + + // adding new edge to graph model + graphModel.getEdgesType().add(newAggregatorEdge); + statistics.builtModelEdgeTypes++; + statistics.totalNumberOfModelEdges++; + + // adding new edge to the vertices' "in/out-edges" collections + outVertexType.getOutEdgesType().add(newAggregatorEdge); + inVertexType.getInEdgesType().add(newAggregatorEdge); + } } - public DataBaseSchema getDataBaseSchema() { - return dataBaseSchema; - } + log.debug("Aggregation performed."); + } - public void setDataBaseSchema(DataBaseSchema dataBaseSchema) { - dataBaseSchema = dataBaseSchema; - } + public DataBaseSchema getDataBaseSchema() { + return dataBaseSchema; + } - public Entity getEntityByVertexType(VertexType vertexType) { - return getEntityByVertexType(vertexType, DEFAULT_CLASS_MAPPER_INDEX); - } + public void setDataBaseSchema(DataBaseSchema dataBaseSchema) { + dataBaseSchema = dataBaseSchema; + } - public Entity getEntityByVertexType(VertexType vertexType, int classMapperIndex) { - return getEVClassMappersByVertex(vertexType).get(classMapperIndex).getEntity(); - } + public Entity getEntityByVertexType(VertexType vertexType) { + return getEntityByVertexType(vertexType, DEFAULT_CLASS_MAPPER_INDEX); + } - public Entity getEntityByNameIgnoreCase(String entityName) { - for (Entity currentEntity : entity2EVClassMappers.keySet()) { - if (entityName.equalsIgnoreCase(currentEntity.getName())) { - return currentEntity; - } - } - return null; - } + public Entity getEntityByVertexType(VertexType vertexType, int classMapperIndex) { + return getEVClassMappersByVertex(vertexType).get(classMapperIndex).getEntity(); + } - public Entity getEntityBySchemaPosition(int schemaPosition) { - for (Entity currentEntity : entity2EVClassMappers.keySet()) { - if (schemaPosition == currentEntity.getSchemaPosition()) { - return currentEntity; - } - } - return null; + public Entity getEntityByNameIgnoreCase(String entityName) { + for (Entity currentEntity : entity2EVClassMappers.keySet()) { + if (entityName.equalsIgnoreCase(currentEntity.getName())) { + return currentEntity; + } } - - public VertexType getVertexTypeByEntity(Entity entity) { - return getVertexTypeByEntity(entity, DEFAULT_CLASS_MAPPER_INDEX); + return null; + } + + public Entity getEntityBySchemaPosition(int schemaPosition) { + for (Entity currentEntity : entity2EVClassMappers.keySet()) { + if (schemaPosition == currentEntity.getSchemaPosition()) { + return currentEntity; + } } - - public VertexType getVertexTypeByEntity(Entity entity, int classMapperIndex) { - return getEVClassMappersByEntity(entity).get(classMapperIndex).getVertexType(); + return null; + } + + public VertexType getVertexTypeByEntity(Entity entity) { + return getVertexTypeByEntity(entity, DEFAULT_CLASS_MAPPER_INDEX); + } + + public VertexType getVertexTypeByEntity(Entity entity, int classMapperIndex) { + return getEVClassMappersByEntity(entity).get(classMapperIndex).getVertexType(); + } + + public VertexType getVertexTypeByEntityNameIgnoreCase(String entityName) { + for (Entity currentEntity : entity2EVClassMappers.keySet()) { + if (entityName.equalsIgnoreCase(currentEntity.getName())) { + return entity2EVClassMappers.get(currentEntity).get(0).getVertexType(); + } } - - public VertexType getVertexTypeByEntityNameIgnoreCase(String entityName) { - for (Entity currentEntity : entity2EVClassMappers.keySet()) { - if (entityName.equalsIgnoreCase(currentEntity.getName())) { - return entity2EVClassMappers.get(currentEntity).get(0).getVertexType(); - } + return null; + } + + public VertexType getVertexTypeByEntityAndRelationship( + Entity currentParentEntity, Relationship currentRelationship) { + List classMappers = getEVClassMappersByEntity(currentParentEntity); + + if (classMappers.size() == 1) { + return getVertexTypeByEntity(currentParentEntity); + } else { + List toAttributes = currentRelationship.getToColumns(); + VertexType correspondentVertexType = null; + + for (EVClassMapper classMapper : classMappers) { + boolean found = true; + for (Attribute currAttribute : toAttributes) { + if (classMapper.getAttribute2property().get(currAttribute.getName()) == null) { + found = false; + break; + } } - return null; - } - - public VertexType getVertexTypeByEntityAndRelationship(Entity currentParentEntity, Relationship currentRelationship) { - List classMappers = getEVClassMappersByEntity(currentParentEntity); - - if (classMappers.size() == 1) { - return getVertexTypeByEntity(currentParentEntity); - } else { - List toAttributes = currentRelationship.getToColumns(); - VertexType correspondentVertexType = null; - - for (EVClassMapper classMapper : classMappers) { - boolean found = true; - for (Attribute currAttribute : toAttributes) { - if (classMapper.getAttribute2property().get(currAttribute.getName()) == null) { - found = false; - break; - } - } - if (found) { - correspondentVertexType = classMapper.getVertexType(); - break; - } - } - return correspondentVertexType; + if (found) { + correspondentVertexType = classMapper.getVertexType(); + break; } + } + return correspondentVertexType; } + } - public String getAttributeNameByVertexTypeAndProperty(VertexType vertexType, String propertyName) { - String attributeName = null; + public String getAttributeNameByVertexTypeAndProperty( + VertexType vertexType, String propertyName) { + String attributeName = null; - for (EVClassMapper cm : getEVClassMappersByVertex(vertexType)) { - attributeName = cm.getAttributeByProperty(propertyName); - if (attributeName != null) { - break; - } - } - - if (attributeName == null) { - VertexType parentType = (VertexType) vertexType.getParentType(); - if (parentType != null) { - return getAttributeNameByVertexTypeAndProperty(parentType, propertyName); - } - } - - return attributeName; + for (EVClassMapper cm : getEVClassMappersByVertex(vertexType)) { + attributeName = cm.getAttributeByProperty(propertyName); + if (attributeName != null) { + break; + } } - public String getPropertyNameByVertexTypeAndAttribute(VertexType vertexType, String attributeName) { - List classMappers = getEVClassMappersByVertex(vertexType); - - String propertyName = null; - for (EVClassMapper currentClassMapper : classMappers) { - propertyName = currentClassMapper.getPropertyByAttribute(attributeName); - if (propertyName != null) { - // the right class mapper was found and the right property name with it - break; - } - } - - if (propertyName == null) { - VertexType parentType = (VertexType) vertexType.getParentType(); - if (parentType != null) { - return getPropertyNameByVertexTypeAndAttribute(parentType, attributeName); - } - } - - return propertyName; + if (attributeName == null) { + VertexType parentType = (VertexType) vertexType.getParentType(); + if (parentType != null) { + return getAttributeNameByVertexTypeAndProperty(parentType, propertyName); + } } - public String getAttributeNameByEdgeTypeAndProperty(EdgeType edgeType, String propertyName) { - String attributeName = null; + return attributeName; + } - for (EEClassMapper cm : getEEClassMappersByEdge(edgeType)) { - attributeName = cm.getAttributeByProperty(propertyName); - if (attributeName != null) { - break; - } - } + public String getPropertyNameByVertexTypeAndAttribute( + VertexType vertexType, String attributeName) { + List classMappers = getEVClassMappersByVertex(vertexType); - if (attributeName == null) { - VertexType parentType = (VertexType) edgeType.getParentType(); - if (parentType != null) { - return getAttributeNameByVertexTypeAndProperty(parentType, propertyName); - } - } - - return attributeName; + String propertyName = null; + for (EVClassMapper currentClassMapper : classMappers) { + propertyName = currentClassMapper.getPropertyByAttribute(attributeName); + if (propertyName != null) { + // the right class mapper was found and the right property name with it + break; + } } - public String getPropertyNameByEntityAndAttribute(Entity entity, String attributeName) { - List classMappers = getEVClassMappersByEntity(entity); - - String propertyName = null; - for (EVClassMapper currentClassMapper : classMappers) { - propertyName = currentClassMapper.getPropertyByAttribute(attributeName); - if (propertyName != null) { - // the right class mapper was found and the right property name with it - break; - } - } - - if (propertyName == null) { - Entity parentEntity = (Entity) entity.getParentEntity(); - if (parentEntity != null) { - return getPropertyNameByEntityAndAttribute(parentEntity, attributeName); - } - } - - return propertyName; + if (propertyName == null) { + VertexType parentType = (VertexType) vertexType.getParentType(); + if (parentType != null) { + return getPropertyNameByVertexTypeAndAttribute(parentType, attributeName); + } } - /** - * It returns the vertex type mapped with the aggregator edge correspondent to the original join table. - * - * @param edgeType edgeType - * @return vetex type - */ + return propertyName; + } - public VertexType getJoinVertexTypeByAggregatorEdge(String edgeType) { - for (Map.Entry entry : joinVertex2aggregatorEdges.entrySet()) { - if (entry.getValue().getEdgeType().getName().equals(edgeType)) { - VertexType joinVertexType = entry.getKey(); - return joinVertexType; - } - } - return null; - } + public String getAttributeNameByEdgeTypeAndProperty(EdgeType edgeType, String propertyName) { + String attributeName = null; - public AggregatorEdge getAggregatorEdgeByJoinVertexTypeName(String vertexTypeName) { - for (VertexType currentVertexType : joinVertex2aggregatorEdges.keySet()) { - if (currentVertexType.getName().equals(vertexTypeName)) { - return joinVertex2aggregatorEdges.get(currentVertexType); - } - } - return null; + for (EEClassMapper cm : getEEClassMappersByEdge(edgeType)) { + attributeName = cm.getAttributeByProperty(propertyName); + if (attributeName != null) { + break; + } } - public VertexType getJoinVertexTypeByAggregatorEdgeName(String aggregatorEdgeName) { - for (VertexType currentVertexType : joinVertex2aggregatorEdges.keySet()) { - if (joinVertex2aggregatorEdges.get(currentVertexType).getEdgeType().getName().equals(aggregatorEdgeName)) { - return currentVertexType; - } - } - return null; + if (attributeName == null) { + VertexType parentType = (VertexType) edgeType.getParentType(); + if (parentType != null) { + return getAttributeNameByVertexTypeAndProperty(parentType, propertyName); + } } - public AggregatorEdge getAggregatorEdgeByEdgeTypeName(String edgeTypeName) { - for (AggregatorEdge currAggregatorEdge : joinVertex2aggregatorEdges.values()) { - if (currAggregatorEdge.getEdgeType().getName().equals(edgeTypeName)) { - return currAggregatorEdge; - } - } - return null; - } + return attributeName; + } - public List getRelationshipsByForeignAndParentTables(String currentForeignEntity, String currentParentEntity) { - List relationships = new LinkedList(); + public String getPropertyNameByEntityAndAttribute(Entity entity, String attributeName) { + List classMappers = getEVClassMappersByEntity(entity); - for (Relationship currentRelationship : dataBaseSchema.getCanonicalRelationships()) { - if ( - currentRelationship.getForeignEntity().getName().equals(currentForeignEntity) && - currentRelationship.getParentEntity().getName().equals(currentParentEntity) - ) { - relationships.add(currentRelationship); - } - } - return relationships; + String propertyName = null; + for (EVClassMapper currentClassMapper : classMappers) { + propertyName = currentClassMapper.getPropertyByAttribute(attributeName); + if (propertyName != null) { + // the right class mapper was found and the right property name with it + break; + } } - public Map getRelationship2edgeType() { - return relationship2edgeType; + if (propertyName == null) { + Entity parentEntity = (Entity) entity.getParentEntity(); + if (parentEntity != null) { + return getPropertyNameByEntityAndAttribute(parentEntity, attributeName); + } } - public Map> getEdgeType2relationships() { - return edgeType2relationships; + return propertyName; + } + + /** + * It returns the vertex type mapped with the aggregator edge correspondent to the original join + * table. + * + * @param edgeType edgeType + * @return vetex type + */ + public VertexType getJoinVertexTypeByAggregatorEdge(String edgeType) { + for (Map.Entry entry : joinVertex2aggregatorEdges.entrySet()) { + if (entry.getValue().getEdgeType().getName().equals(edgeType)) { + VertexType joinVertexType = entry.getKey(); + return joinVertexType; + } } - - public Map getEdgeTypeName2count() { - return edgeTypeName2count; + return null; + } + + public AggregatorEdge getAggregatorEdgeByJoinVertexTypeName(String vertexTypeName) { + for (VertexType currentVertexType : joinVertex2aggregatorEdges.keySet()) { + if (currentVertexType.getName().equals(vertexTypeName)) { + return joinVertex2aggregatorEdges.get(currentVertexType); + } } - - public Map getJoinVertex2aggregatorEdges() { - return joinVertex2aggregatorEdges; + return null; + } + + public VertexType getJoinVertexTypeByAggregatorEdgeName(String aggregatorEdgeName) { + for (VertexType currentVertexType : joinVertex2aggregatorEdges.keySet()) { + if (joinVertex2aggregatorEdges + .get(currentVertexType) + .getEdgeType() + .getName() + .equals(aggregatorEdgeName)) { + return currentVertexType; + } } - - public List getIncludedTables() { - return includedTables; + return null; + } + + public AggregatorEdge getAggregatorEdgeByEdgeTypeName(String edgeTypeName) { + for (AggregatorEdge currAggregatorEdge : joinVertex2aggregatorEdges.values()) { + if (currAggregatorEdge.getEdgeType().getName().equals(edgeTypeName)) { + return currAggregatorEdge; + } } - - public void setIncludedTables(List includedTables) { - includedTables = includedTables; + return null; + } + + public List getRelationshipsByForeignAndParentTables( + String currentForeignEntity, String currentParentEntity) { + List relationships = new LinkedList(); + + for (Relationship currentRelationship : dataBaseSchema.getCanonicalRelationships()) { + if (currentRelationship.getForeignEntity().getName().equals(currentForeignEntity) + && currentRelationship.getParentEntity().getName().equals(currentParentEntity)) { + relationships.add(currentRelationship); + } } - - public List getExcludedTables() { - return excludedTables; + return relationships; + } + + public Map getRelationship2edgeType() { + return relationship2edgeType; + } + + public Map> getEdgeType2relationships() { + return edgeType2relationships; + } + + public Map getEdgeTypeName2count() { + return edgeTypeName2count; + } + + public Map getJoinVertex2aggregatorEdges() { + return joinVertex2aggregatorEdges; + } + + public List getIncludedTables() { + return includedTables; + } + + public void setIncludedTables(List includedTables) { + includedTables = includedTables; + } + + public List getExcludedTables() { + return excludedTables; + } + + public void setExcludedTables(List excludedTables) { + excludedTables = excludedTables; + } + + public boolean isTableAllowed(String tableName) { + if (includedTables.size() > 0) return includedTables.contains(tableName); + else if (excludedTables.size() > 0) return !excludedTables.contains(tableName); + else return true; + } + + public String toString() { + String s = + "\n\n\n" + + "------------------------------ MAPPER DESCRIPTION" + + " ------------------------------\n\n\n"; + s += "RULES\n\n"; + s += "- Class mappings:\n\n"; + for (List classMappers : entity2EVClassMappers.values()) { + for (EVClassMapper classMapper : classMappers) { + s += classMapper.toString() + "\n"; + } } - - public void setExcludedTables(List excludedTables) { - excludedTables = excludedTables; + s += "\n\n- Relaionship2EdgeType Rules:\n\n"; + for (Relationship relationship : relationship2edgeType.keySet()) { + s += + relationship.getForeignEntity() + + "2" + + relationship.getParentEntity() + + " --> " + + relationship2edgeType.get(relationship).getName() + + "\n"; } - - public boolean isTableAllowed(String tableName) { - if (includedTables.size() > 0) return includedTables.contains(tableName); else if (excludedTables.size() > 0) return !excludedTables.contains( - tableName - ); else return true; + s += "\n\n- EdgeTypeName2Count Rules:\n\n"; + for (String edgeName : edgeTypeName2count.keySet()) { + s += edgeName + " --> " + edgeTypeName2count.get(edgeName) + "\n"; } + s += "\n"; - public String toString() { - String s = "\n\n\n------------------------------ MAPPER DESCRIPTION ------------------------------\n\n\n"; - s += "RULES\n\n"; - s += "- Class mappings:\n\n"; - for (List classMappers : entity2EVClassMappers.values()) { - for (EVClassMapper classMapper : classMappers) { - s += classMapper.toString() + "\n"; - } - } - s += "\n\n- Relaionship2EdgeType Rules:\n\n"; - for (Relationship relationship : relationship2edgeType.keySet()) { - s += relationship.getForeignEntity() + "2" + relationship.getParentEntity() + " --> " + relationship2edgeType.get(relationship).getName() + "\n"; - } - s += "\n\n- EdgeTypeName2Count Rules:\n\n"; - for (String edgeName : edgeTypeName2count.keySet()) { - s += edgeName + " --> " + edgeTypeName2count.get(edgeName) + "\n"; - } - s += "\n"; - - return s; - } + return s; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/mapper/rdbms/Hibernate2GraphMapper.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/mapper/rdbms/Hibernate2GraphMapper.java index 5e87e4c9..9205a088 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/mapper/rdbms/Hibernate2GraphMapper.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/mapper/rdbms/Hibernate2GraphMapper.java @@ -44,340 +44,388 @@ import org.w3c.dom.NodeList; /** - * Extends ER2GraphMapper thus manages the source DB schema and the destination graph model with their correspondences. - * Unlike the superclass, this class builds the source DB schema starting from Hibernate's XML migrationConfigDoc file. + * Extends ER2GraphMapper thus manages the source DB schema and the destination graph model with + * their correspondences. Unlike the superclass, this class builds the source DB schema starting + * from Hibernate's XML migrationConfigDoc file. * * @author Gabriele Ponzi */ - public class Hibernate2GraphMapper extends ER2GraphMapper { - private static final Logger log = LoggerFactory.getLogger(Hibernate2GraphMapper.class); - private final String xmlPath; - - public Hibernate2GraphMapper( - DataSourceInfo dataSource, - String xmlPath, - List includedTables, - List excludedTables, - DBQueryEngine queryEngine, - DBMSDataTypeHandler dataTypeHandler, - String executionStrategy, - NameResolver nameResolver, - Statistics statistics - ) { - super(dataSource, includedTables, excludedTables, queryEngine, dataTypeHandler, executionStrategy, nameResolver, statistics); - this.xmlPath = xmlPath; - } - - @Override - public void buildSourceDatabaseSchema() { - try { - /* - * Building Info from DB Schema - */ - - super.buildSourceDatabaseSchema(); - - /* - * XML Checking and Inheritance - */ - - // XML parsing and DOM building - - File xmlFile = new File(this.xmlPath); - DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); - Document dom = dBuilder.parse(xmlFile); - - NodeList entities = dom.getElementsByTagName("class"); - Element currentEntityElement; - Entity currentEntity = null; - - for (int i = 0; i < entities.getLength(); i++) { - currentEntityElement = (Element) entities.item(i); - - if (currentEntityElement.hasAttribute("table")) currentEntity = - super.dataBaseSchema.getEntityByNameIgnoreCase(currentEntityElement.getAttribute("table")); else { - log.error("XML Format error: problem in class definition, table attribute missing in the class node.\n"); - throw new RDBMSProviderRuntimeException(); - } + private static final Logger log = LoggerFactory.getLogger(Hibernate2GraphMapper.class); + private final String xmlPath; + + public Hibernate2GraphMapper( + DataSourceInfo dataSource, + String xmlPath, + List includedTables, + List excludedTables, + DBQueryEngine queryEngine, + DBMSDataTypeHandler dataTypeHandler, + String executionStrategy, + NameResolver nameResolver, + Statistics statistics) { + super( + dataSource, + includedTables, + excludedTables, + queryEngine, + dataTypeHandler, + executionStrategy, + nameResolver, + statistics); + this.xmlPath = xmlPath; + } + + @Override + public void buildSourceDatabaseSchema() { + try { + /* + * Building Info from DB Schema + */ + + super.buildSourceDatabaseSchema(); + + /* + * XML Checking and Inheritance + */ + + // XML parsing and DOM building + + File xmlFile = new File(this.xmlPath); + DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); + Document dom = dBuilder.parse(xmlFile); + + NodeList entities = dom.getElementsByTagName("class"); + Element currentEntityElement; + Entity currentEntity = null; + + for (int i = 0; i < entities.getLength(); i++) { + currentEntityElement = (Element) entities.item(i); + + if (currentEntityElement.hasAttribute("table")) + currentEntity = + super.dataBaseSchema.getEntityByNameIgnoreCase( + currentEntityElement.getAttribute("table")); + else { + log.error( + "XML Format error: problem in class definition, table attribute missing in the class" + + " node.\n"); + throw new RDBMSProviderRuntimeException(); + } - // inheritance - if (currentEntity != null) this.detectInheritanceAndUpdateSchema(currentEntity, currentEntityElement); - } + // inheritance + if (currentEntity != null) + this.detectInheritanceAndUpdateSchema(currentEntity, currentEntityElement); + } - // sorting tables for inheritance level and then for name - Collections.sort(super.dataBaseSchema.getEntities()); - } catch (Exception e) { - throw new RDBMSProviderRuntimeException(e); - } + // sorting tables for inheritance level and then for name + Collections.sort(super.dataBaseSchema.getEntities()); + } catch (Exception e) { + throw new RDBMSProviderRuntimeException(e); + } + } + + private void detectInheritanceAndUpdateSchema(Entity parentEntity, Element parentEntityElement) { + NodeList subclassElements = parentEntityElement.getElementsByTagName("subclass"); + NodeList joinedSubclassElements = parentEntityElement.getElementsByTagName("joined-subclass"); + NodeList unionSubclassElements = parentEntityElement.getElementsByTagName("union-subclass"); + Element discriminatorElement = + (Element) parentEntityElement.getElementsByTagName("discriminator").item(0); + + HierarchicalBag hierarchicalBag = new HierarchicalBag(); + String rootDiscriminatorValue = null; + + // TABLE PER CLASS Hierarchy or Table per Subclass Inheritance + if (subclassElements.getLength() > 0) { + if (parentEntityElement.hasAttribute("discriminator-value")) + rootDiscriminatorValue = parentEntityElement.getAttribute("discriminator-value"); + this.performSubclassTagInheritance( + hierarchicalBag, + parentEntity, + subclassElements, + discriminatorElement, + rootDiscriminatorValue); } - private void detectInheritanceAndUpdateSchema(Entity parentEntity, Element parentEntityElement) { - NodeList subclassElements = parentEntityElement.getElementsByTagName("subclass"); - NodeList joinedSubclassElements = parentEntityElement.getElementsByTagName("joined-subclass"); - NodeList unionSubclassElements = parentEntityElement.getElementsByTagName("union-subclass"); - Element discriminatorElement = (Element) parentEntityElement.getElementsByTagName("discriminator").item(0); - - HierarchicalBag hierarchicalBag = new HierarchicalBag(); - String rootDiscriminatorValue = null; + // TABLE PER SUBCLASS Inheritance + if (joinedSubclassElements.getLength() > 0) { + // initializing the hierarchical bag + hierarchicalBag.setInheritancePattern("table-per-type"); + super.dataBaseSchema.getHierarchicalBags().add(hierarchicalBag); + if (hierarchicalBag.getDepth2entities().get(parentEntity.getInheritanceLevel()) == null) { + Set tmp = new LinkedHashSet(); + tmp.add(parentEntity); + hierarchicalBag.getDepth2entities().put(parentEntity.getInheritanceLevel(), tmp); + parentEntity.setHierarchicalBag(hierarchicalBag); + } + if (discriminatorElement != null) { + hierarchicalBag.setDiscriminatorColumn(discriminatorElement.getAttribute("column")); + } + + this.performJoinedSubclassTagInheritance( + hierarchicalBag, parentEntity, joinedSubclassElements); + } - // TABLE PER CLASS Hierarchy or Table per Subclass Inheritance - if (subclassElements.getLength() > 0) { - if (parentEntityElement.hasAttribute("discriminator-value")) rootDiscriminatorValue = parentEntityElement.getAttribute("discriminator-value"); - this.performSubclassTagInheritance(hierarchicalBag, parentEntity, subclassElements, discriminatorElement, rootDiscriminatorValue); + // TABLE PER CONCRETE CLASS Inheritance + if (unionSubclassElements.getLength() > 0) { + // initializing the hierarchical bag + hierarchicalBag.setInheritancePattern("table-per-concrete-type"); + super.dataBaseSchema.getHierarchicalBags().add(hierarchicalBag); + if (hierarchicalBag.getDepth2entities().get(parentEntity.getInheritanceLevel()) == null) { + Set tmp = new LinkedHashSet(); + tmp.add(parentEntity); + hierarchicalBag.getDepth2entities().put(parentEntity.getInheritanceLevel(), tmp); + parentEntity.setHierarchicalBag(hierarchicalBag); + } + if (discriminatorElement != null) { + hierarchicalBag.setDiscriminatorColumn(discriminatorElement.getAttribute("column")); + } + + this.performUnionSubclassTagInheritance(hierarchicalBag, parentEntity, unionSubclassElements); + } + } + + // Table per Class Hierarchy or Table per Subclass Inheritance + private void performSubclassTagInheritance( + HierarchicalBag hierarchicalBag, + Entity parentEntity, + NodeList subclassElements, + Element discriminatorElement, + String rootDiscriminatorValue) { + NodeList joinElements; + Element currentEntityElement; + String currentEntityElementName = null; + Entity currentChildEntity; + + // distinguishing between "Table Per Class Hierarchy" and "Table Per Subclass" inheritance + currentEntityElement = (Element) subclassElements.item(0); + joinElements = currentEntityElement.getElementsByTagName("join"); + + // Table Per Subclass inheritance when join elements are present + if (joinElements.getLength() > 0) { + // initializing the hierarchical bag + hierarchicalBag.setInheritancePattern("table-per-type"); + super.dataBaseSchema.getHierarchicalBags().add(hierarchicalBag); + if (hierarchicalBag.getDepth2entities().get(parentEntity.getInheritanceLevel()) == null) { + Set tmp = new LinkedHashSet(); + tmp.add(parentEntity); + hierarchicalBag.getDepth2entities().put(parentEntity.getInheritanceLevel(), tmp); + parentEntity.setHierarchicalBag(hierarchicalBag); + } + if (discriminatorElement != null) { + hierarchicalBag.setDiscriminatorColumn(discriminatorElement.getAttribute("column")); + } + + for (int j = 0; j < subclassElements.getLength(); j++) { + currentEntityElement = (Element) subclassElements.item(j); + joinElements = currentEntityElement.getElementsByTagName("join"); + performJoinedSubclassTagInheritance(hierarchicalBag, parentEntity, joinElements); + } + } + // Table per Class Hierarchy + else { + // initializing the hierarchical bag + hierarchicalBag.setInheritancePattern("table-per-hierarchy"); + super.dataBaseSchema.getHierarchicalBags().add(hierarchicalBag); + if (hierarchicalBag.getDepth2entities().get(parentEntity.getInheritanceLevel()) == null) { + Set tmp = new LinkedHashSet(); + tmp.add(parentEntity); + hierarchicalBag.getDepth2entities().put(parentEntity.getInheritanceLevel(), tmp); + parentEntity.setHierarchicalBag(hierarchicalBag); + } + if (discriminatorElement != null) { + hierarchicalBag.setDiscriminatorColumn(discriminatorElement.getAttribute("column")); + } + hierarchicalBag + .getEntityName2discriminatorValue() + .put(parentEntity.getName(), rootDiscriminatorValue); + + for (int i = 0; i < subclassElements.getLength(); i++) { + currentEntityElement = (Element) subclassElements.item(i); + + if (currentEntityElement.hasAttribute("name")) + currentEntityElementName = currentEntityElement.getAttribute("name"); + else { + log.error( + "XML Format error: problem in subclass definition, table attribute missing in the" + + " joined-subclass nodes.\n"); + throw new RDBMSProviderRuntimeException(); } - - // TABLE PER SUBCLASS Inheritance - if (joinedSubclassElements.getLength() > 0) { - // initializing the hierarchical bag - hierarchicalBag.setInheritancePattern("table-per-type"); - super.dataBaseSchema.getHierarchicalBags().add(hierarchicalBag); - if (hierarchicalBag.getDepth2entities().get(parentEntity.getInheritanceLevel()) == null) { - Set tmp = new LinkedHashSet(); - tmp.add(parentEntity); - hierarchicalBag.getDepth2entities().put(parentEntity.getInheritanceLevel(), tmp); - parentEntity.setHierarchicalBag(hierarchicalBag); - } - if (discriminatorElement != null) { - hierarchicalBag.setDiscriminatorColumn(discriminatorElement.getAttribute("column")); - } - - this.performJoinedSubclassTagInheritance(hierarchicalBag, parentEntity, joinedSubclassElements); + currentChildEntity = new Entity(currentEntityElementName, null, dataSource); + + // entity's attributes setting + String discriminatorColumnName = discriminatorElement.getAttribute("column"); + parentEntity.removeAttributeByNameIgnoreCase(discriminatorColumnName); + parentEntity.renumberAttributesOrdinalPositions(); + + // primary key setting + currentChildEntity.setPrimaryKey(parentEntity.getPrimaryKey()); + + NodeList propertiesElements = currentEntityElement.getElementsByTagName("property"); + Element currentPropertyElement; + Attribute currentChildAttribute; + Attribute currentParentCorrespondingAttribute; + + for (int j = 0; j < propertiesElements.getLength(); j++) { + currentPropertyElement = (Element) propertiesElements.item(j); + currentParentCorrespondingAttribute = + parentEntity.getAttributeByNameIgnoreCase( + currentPropertyElement.getAttribute("column")); + + // building child's attribute and removing the corresponding attribute from the parent + // entity + currentChildAttribute = + new Attribute( + currentParentCorrespondingAttribute.getName(), + j + 1, + currentParentCorrespondingAttribute.getDataType(), + currentChildEntity); + currentChildEntity.addAttribute(currentChildAttribute); + parentEntity.getAttributes().remove(currentParentCorrespondingAttribute); } - // TABLE PER CONCRETE CLASS Inheritance - if (unionSubclassElements.getLength() > 0) { - // initializing the hierarchical bag - hierarchicalBag.setInheritancePattern("table-per-concrete-type"); - super.dataBaseSchema.getHierarchicalBags().add(hierarchicalBag); - if (hierarchicalBag.getDepth2entities().get(parentEntity.getInheritanceLevel()) == null) { - Set tmp = new LinkedHashSet(); - tmp.add(parentEntity); - hierarchicalBag.getDepth2entities().put(parentEntity.getInheritanceLevel(), tmp); - parentEntity.setHierarchicalBag(hierarchicalBag); - } - if (discriminatorElement != null) { - hierarchicalBag.setDiscriminatorColumn(discriminatorElement.getAttribute("column")); - } - - this.performUnionSubclassTagInheritance(hierarchicalBag, parentEntity, unionSubclassElements); + parentEntity.renumberAttributesOrdinalPositions(); + + super.dataBaseSchema.getEntities().add(currentChildEntity); + currentChildEntity.setParentEntity(parentEntity); + currentChildEntity.setInheritanceLevel(parentEntity.getInheritanceLevel() + 1); + + // updating hierarchical bag + if (hierarchicalBag.getDepth2entities().get(currentChildEntity.getInheritanceLevel()) + == null) { + Set tmp = new LinkedHashSet(); + tmp.add(currentChildEntity); + hierarchicalBag.getDepth2entities().put(currentChildEntity.getInheritanceLevel(), tmp); + } else { + Set tmp = + hierarchicalBag.getDepth2entities().get(currentChildEntity.getInheritanceLevel()); + tmp.add(currentChildEntity); + hierarchicalBag.getDepth2entities().put(currentChildEntity.getInheritanceLevel(), tmp); } + currentChildEntity.setHierarchicalBag(hierarchicalBag); + hierarchicalBag + .getEntityName2discriminatorValue() + .put( + currentChildEntity.getName(), + currentEntityElement.getAttribute("discriminator-value")); + } } - - // Table per Class Hierarchy or Table per Subclass Inheritance - private void performSubclassTagInheritance( - HierarchicalBag hierarchicalBag, - Entity parentEntity, - NodeList subclassElements, - Element discriminatorElement, - String rootDiscriminatorValue - ) { - NodeList joinElements; - Element currentEntityElement; - String currentEntityElementName = null; - Entity currentChildEntity; - - // distinguishing between "Table Per Class Hierarchy" and "Table Per Subclass" inheritance - currentEntityElement = (Element) subclassElements.item(0); - joinElements = currentEntityElement.getElementsByTagName("join"); - - // Table Per Subclass inheritance when join elements are present - if (joinElements.getLength() > 0) { - // initializing the hierarchical bag - hierarchicalBag.setInheritancePattern("table-per-type"); - super.dataBaseSchema.getHierarchicalBags().add(hierarchicalBag); - if (hierarchicalBag.getDepth2entities().get(parentEntity.getInheritanceLevel()) == null) { - Set tmp = new LinkedHashSet(); - tmp.add(parentEntity); - hierarchicalBag.getDepth2entities().put(parentEntity.getInheritanceLevel(), tmp); - parentEntity.setHierarchicalBag(hierarchicalBag); - } - if (discriminatorElement != null) { - hierarchicalBag.setDiscriminatorColumn(discriminatorElement.getAttribute("column")); - } - - for (int j = 0; j < subclassElements.getLength(); j++) { - currentEntityElement = (Element) subclassElements.item(j); - joinElements = currentEntityElement.getElementsByTagName("join"); - performJoinedSubclassTagInheritance(hierarchicalBag, parentEntity, joinElements); - } - } - // Table per Class Hierarchy - else { - // initializing the hierarchical bag - hierarchicalBag.setInheritancePattern("table-per-hierarchy"); - super.dataBaseSchema.getHierarchicalBags().add(hierarchicalBag); - if (hierarchicalBag.getDepth2entities().get(parentEntity.getInheritanceLevel()) == null) { - Set tmp = new LinkedHashSet(); - tmp.add(parentEntity); - hierarchicalBag.getDepth2entities().put(parentEntity.getInheritanceLevel(), tmp); - parentEntity.setHierarchicalBag(hierarchicalBag); - } - if (discriminatorElement != null) { - hierarchicalBag.setDiscriminatorColumn(discriminatorElement.getAttribute("column")); - } - hierarchicalBag.getEntityName2discriminatorValue().put(parentEntity.getName(), rootDiscriminatorValue); - - for (int i = 0; i < subclassElements.getLength(); i++) { - currentEntityElement = (Element) subclassElements.item(i); - - if (currentEntityElement.hasAttribute("name")) currentEntityElementName = currentEntityElement.getAttribute("name"); else { - log.error("XML Format error: problem in subclass definition, table attribute missing in the joined-subclass nodes.\n"); - throw new RDBMSProviderRuntimeException(); - } - currentChildEntity = new Entity(currentEntityElementName, null, dataSource); - - // entity's attributes setting - String discriminatorColumnName = discriminatorElement.getAttribute("column"); - parentEntity.removeAttributeByNameIgnoreCase(discriminatorColumnName); - parentEntity.renumberAttributesOrdinalPositions(); - - // primary key setting - currentChildEntity.setPrimaryKey(parentEntity.getPrimaryKey()); - - NodeList propertiesElements = currentEntityElement.getElementsByTagName("property"); - Element currentPropertyElement; - Attribute currentChildAttribute; - Attribute currentParentCorrespondingAttribute; - - for (int j = 0; j < propertiesElements.getLength(); j++) { - currentPropertyElement = (Element) propertiesElements.item(j); - currentParentCorrespondingAttribute = parentEntity.getAttributeByNameIgnoreCase(currentPropertyElement.getAttribute("column")); - - // building child's attribute and removing the corresponding attribute from the parent entity - currentChildAttribute = - new Attribute( - currentParentCorrespondingAttribute.getName(), - j + 1, - currentParentCorrespondingAttribute.getDataType(), - currentChildEntity - ); - currentChildEntity.addAttribute(currentChildAttribute); - parentEntity.getAttributes().remove(currentParentCorrespondingAttribute); - } - - parentEntity.renumberAttributesOrdinalPositions(); - - super.dataBaseSchema.getEntities().add(currentChildEntity); - currentChildEntity.setParentEntity(parentEntity); - currentChildEntity.setInheritanceLevel(parentEntity.getInheritanceLevel() + 1); - - // updating hierarchical bag - if (hierarchicalBag.getDepth2entities().get(currentChildEntity.getInheritanceLevel()) == null) { - Set tmp = new LinkedHashSet(); - tmp.add(currentChildEntity); - hierarchicalBag.getDepth2entities().put(currentChildEntity.getInheritanceLevel(), tmp); - } else { - Set tmp = hierarchicalBag.getDepth2entities().get(currentChildEntity.getInheritanceLevel()); - tmp.add(currentChildEntity); - hierarchicalBag.getDepth2entities().put(currentChildEntity.getInheritanceLevel(), tmp); - } - currentChildEntity.setHierarchicalBag(hierarchicalBag); - hierarchicalBag.getEntityName2discriminatorValue().put(currentChildEntity.getName(), currentEntityElement.getAttribute("discriminator-value")); - } + } + + // Table per Subclass Inheritance + private void performJoinedSubclassTagInheritance( + HierarchicalBag hierarchicalBag, Entity parentEntity, NodeList joinedSubclassElements) { + Element currentChildElement; + Entity currentChildEntity; + String currentChildEntityName = null; + + for (int i = 0; i < joinedSubclassElements.getLength(); i++) { + currentChildElement = (Element) joinedSubclassElements.item(i); + if (currentChildElement.hasAttribute("table")) + currentChildEntityName = currentChildElement.getAttribute("table"); + else { + log.error( + "XML Format error: problem in subclass definition, table attribute missing in the" + + " joined-subclass nodes.\n"); + throw new RDBMSProviderRuntimeException(); + } + currentChildEntity = super.dataBaseSchema.getEntityByNameIgnoreCase(currentChildEntityName); + currentChildEntity.setParentEntity(parentEntity); + currentChildEntity.setInheritanceLevel(parentEntity.getInheritanceLevel() + 1); + + // removing attributes belonging to the primary key + Attribute currentAttribute; + Iterator it = currentChildEntity.getAttributes().iterator(); + while (it.hasNext()) { + currentAttribute = it.next(); + if (currentChildEntity.getPrimaryKey().getInvolvedAttributes().contains(currentAttribute)) { + it.remove(); } + } + currentChildEntity.renumberAttributesOrdinalPositions(); + + // updating hierarchical bag + if (hierarchicalBag.getDepth2entities().get(currentChildEntity.getInheritanceLevel()) + == null) { + Set tmp = new LinkedHashSet(); + tmp.add(currentChildEntity); + hierarchicalBag.getDepth2entities().put(currentChildEntity.getInheritanceLevel(), tmp); + } else { + Set tmp = + hierarchicalBag.getDepth2entities().get(currentChildEntity.getInheritanceLevel()); + tmp.add(currentChildEntity); + hierarchicalBag.getDepth2entities().put(currentChildEntity.getInheritanceLevel(), tmp); + } + currentChildEntity.setHierarchicalBag(hierarchicalBag); + + // recursive call on the node + this.detectInheritanceAndUpdateSchema(currentChildEntity, currentChildElement); } - - // Table per Subclass Inheritance - private void performJoinedSubclassTagInheritance(HierarchicalBag hierarchicalBag, Entity parentEntity, NodeList joinedSubclassElements) { - Element currentChildElement; - Entity currentChildEntity; - String currentChildEntityName = null; - - for (int i = 0; i < joinedSubclassElements.getLength(); i++) { - currentChildElement = (Element) joinedSubclassElements.item(i); - if (currentChildElement.hasAttribute("table")) currentChildEntityName = currentChildElement.getAttribute("table"); else { - log.error("XML Format error: problem in subclass definition, table attribute missing in the joined-subclass nodes.\n"); - throw new RDBMSProviderRuntimeException(); - } - currentChildEntity = super.dataBaseSchema.getEntityByNameIgnoreCase(currentChildEntityName); - currentChildEntity.setParentEntity(parentEntity); - currentChildEntity.setInheritanceLevel(parentEntity.getInheritanceLevel() + 1); - - // removing attributes belonging to the primary key - Attribute currentAttribute; - Iterator it = currentChildEntity.getAttributes().iterator(); - while (it.hasNext()) { - currentAttribute = it.next(); - if (currentChildEntity.getPrimaryKey().getInvolvedAttributes().contains(currentAttribute)) { - it.remove(); - } - } - currentChildEntity.renumberAttributesOrdinalPositions(); - - // updating hierarchical bag - if (hierarchicalBag.getDepth2entities().get(currentChildEntity.getInheritanceLevel()) == null) { - Set tmp = new LinkedHashSet(); - tmp.add(currentChildEntity); - hierarchicalBag.getDepth2entities().put(currentChildEntity.getInheritanceLevel(), tmp); - } else { - Set tmp = hierarchicalBag.getDepth2entities().get(currentChildEntity.getInheritanceLevel()); - tmp.add(currentChildEntity); - hierarchicalBag.getDepth2entities().put(currentChildEntity.getInheritanceLevel(), tmp); - } - currentChildEntity.setHierarchicalBag(hierarchicalBag); - - // recursive call on the node - this.detectInheritanceAndUpdateSchema(currentChildEntity, currentChildElement); + } + + // Table per Concrete Class + void performUnionSubclassTagInheritance( + HierarchicalBag hierarchicalBag, Entity parentEntity, NodeList unionSubclassElements) { + Element currentChildElement; + Entity currentChildEntity; + String currentChildEntityName = null; + + for (int i = 0; i < unionSubclassElements.getLength(); i++) { + currentChildElement = (Element) unionSubclassElements.item(i); + + if (currentChildElement.hasAttribute("table")) + currentChildEntityName = currentChildElement.getAttribute("table"); + else { + log.error( + "XML Format error: problem in subclass definition, table attribute missing in the" + + " joined-subclass nodes.\n"); + throw new RDBMSProviderRuntimeException(); + } + + currentChildEntity = super.dataBaseSchema.getEntityByNameIgnoreCase(currentChildEntityName); + currentChildEntity.setParentEntity(parentEntity); + currentChildEntity.setInheritanceLevel(parentEntity.getInheritanceLevel() + 1); + + // removing attributes belonging to the primary key + Attribute currentAttribute; + Iterator it = currentChildEntity.getAttributes().iterator(); + while (it.hasNext()) { + currentAttribute = it.next(); + if (currentChildEntity.getPrimaryKey().getInvolvedAttributes().contains(currentAttribute)) { + it.remove(); } - } - - // Table per Concrete Class - void performUnionSubclassTagInheritance(HierarchicalBag hierarchicalBag, Entity parentEntity, NodeList unionSubclassElements) { - Element currentChildElement; - Entity currentChildEntity; - String currentChildEntityName = null; - - for (int i = 0; i < unionSubclassElements.getLength(); i++) { - currentChildElement = (Element) unionSubclassElements.item(i); - - if (currentChildElement.hasAttribute("table")) currentChildEntityName = currentChildElement.getAttribute("table"); else { - log.error("XML Format error: problem in subclass definition, table attribute missing in the joined-subclass nodes.\n"); - throw new RDBMSProviderRuntimeException(); - } - - currentChildEntity = super.dataBaseSchema.getEntityByNameIgnoreCase(currentChildEntityName); - currentChildEntity.setParentEntity(parentEntity); - currentChildEntity.setInheritanceLevel(parentEntity.getInheritanceLevel() + 1); - - // removing attributes belonging to the primary key - Attribute currentAttribute; - Iterator it = currentChildEntity.getAttributes().iterator(); - while (it.hasNext()) { - currentAttribute = it.next(); - if (currentChildEntity.getPrimaryKey().getInvolvedAttributes().contains(currentAttribute)) { - it.remove(); - } - } - currentChildEntity.renumberAttributesOrdinalPositions(); - - // updating hierarchical bag - if (hierarchicalBag.getDepth2entities().get(currentChildEntity.getInheritanceLevel()) == null) { - Set tmp = new LinkedHashSet(); - tmp.add(currentChildEntity); - hierarchicalBag.getDepth2entities().put(currentChildEntity.getInheritanceLevel(), tmp); - } else { - Set tmp = hierarchicalBag.getDepth2entities().get(currentChildEntity.getInheritanceLevel()); - tmp.add(currentChildEntity); - hierarchicalBag.getDepth2entities().put(currentChildEntity.getInheritanceLevel(), tmp); - } - currentChildEntity.setHierarchicalBag(hierarchicalBag); - - // recursive call on the node - this.detectInheritanceAndUpdateSchema(currentChildEntity, currentChildElement); - - // removing inherited attributes - it = currentChildEntity.getAttributes().iterator(); - while (it.hasNext()) { - currentAttribute = it.next(); - if (parentEntity.getAttributes().contains(currentAttribute)) { - it.remove(); - currentChildEntity.getInheritedAttributes().add(currentAttribute); - } - } - currentChildEntity.renumberAttributesOrdinalPositions(); + } + currentChildEntity.renumberAttributesOrdinalPositions(); + + // updating hierarchical bag + if (hierarchicalBag.getDepth2entities().get(currentChildEntity.getInheritanceLevel()) + == null) { + Set tmp = new LinkedHashSet(); + tmp.add(currentChildEntity); + hierarchicalBag.getDepth2entities().put(currentChildEntity.getInheritanceLevel(), tmp); + } else { + Set tmp = + hierarchicalBag.getDepth2entities().get(currentChildEntity.getInheritanceLevel()); + tmp.add(currentChildEntity); + hierarchicalBag.getDepth2entities().put(currentChildEntity.getInheritanceLevel(), tmp); + } + currentChildEntity.setHierarchicalBag(hierarchicalBag); + + // recursive call on the node + this.detectInheritanceAndUpdateSchema(currentChildEntity, currentChildElement); + + // removing inherited attributes + it = currentChildEntity.getAttributes().iterator(); + while (it.hasNext()) { + currentAttribute = it.next(); + if (parentEntity.getAttributes().contains(currentAttribute)) { + it.remove(); + currentChildEntity.getInheritedAttributes().add(currentAttribute); } + } + currentChildEntity.renumberAttributesOrdinalPositions(); } + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/mapper/rdbms/classmapper/EEClassMapper.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/mapper/rdbms/classmapper/EEClassMapper.java index 9df9a306..bd1f4e70 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/mapper/rdbms/classmapper/EEClassMapper.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/mapper/rdbms/classmapper/EEClassMapper.java @@ -25,62 +25,70 @@ import java.util.Map; /** - * This class is responsible to map 2 classes of objects: Entity and EdgeType. - * the following values are mapped: - * - name of the entity -> name of the edge type - * - each attribute of the entity -> correspondent property of the edge type - * - each property of the edge type -> correspondent attribute of the entity + * This class is responsible to map 2 classes of objects: Entity and EdgeType. the following values + * are mapped: - name of the entity -> name of the edge type - each attribute of the entity -> + * correspondent property of the edge type - each property of the edge type -> correspondent + * attribute of the entity * * @author Gabriele Ponzi */ - public class EEClassMapper extends EntityClassMapper { - private EdgeType edgeType; + private EdgeType edgeType; - public EEClassMapper(Entity entity, EdgeType edgeType, Map attribute2property, Map property2attribute) { - super(entity, attribute2property, property2attribute); - this.edgeType = edgeType; - } + public EEClassMapper( + Entity entity, + EdgeType edgeType, + Map attribute2property, + Map property2attribute) { + super(entity, attribute2property, property2attribute); + this.edgeType = edgeType; + } - public EdgeType getEdgeType() { - return edgeType; - } + public EdgeType getEdgeType() { + return edgeType; + } - public void setEdgeType(EdgeType edgeType) { - this.edgeType = edgeType; - } + public void setEdgeType(EdgeType edgeType) { + this.edgeType = edgeType; + } - @Override - public int hashCode() { - int result = entity.hashCode(); - result = 31 * result + edgeType.hashCode(); - return result; - } + @Override + public int hashCode() { + int result = entity.hashCode(); + result = 31 * result + edgeType.hashCode(); + return result; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; - EEClassMapper that = (EEClassMapper) o; + EEClassMapper that = (EEClassMapper) o; - if (!entity.equals(that.entity)) return false; - if (!edgeType.equals(that.edgeType)) return false; - if (!attribute2property.equals(that.attribute2property)) return false; - return property2attribute.equals(that.property2attribute); - } + if (!entity.equals(that.entity)) return false; + if (!edgeType.equals(that.edgeType)) return false; + if (!attribute2property.equals(that.attribute2property)) return false; + return property2attribute.equals(that.property2attribute); + } - @Override - public String toString() { - String s = "{" + "Entity = " + entity.getName() + ", Edge-Type = " + edgeType.getName() + ", attributes2properties: "; + @Override + public String toString() { + String s = + "{" + + "Entity = " + + entity.getName() + + ", Edge-Type = " + + edgeType.getName() + + ", attributes2properties: "; - s += "["; - for (String attribute : this.attribute2property.keySet()) { - s += attribute + " --> " + attribute2property.get(attribute) + ", "; - } - s = s.substring(0, s.length() - 1); - s += "]}"; - return s; + s += "["; + for (String attribute : this.attribute2property.keySet()) { + s += attribute + " --> " + attribute2property.get(attribute) + ", "; } + s = s.substring(0, s.length() - 1); + s += "]}"; + return s; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/mapper/rdbms/classmapper/EVClassMapper.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/mapper/rdbms/classmapper/EVClassMapper.java index 165e0472..b08f1413 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/mapper/rdbms/classmapper/EVClassMapper.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/mapper/rdbms/classmapper/EVClassMapper.java @@ -25,62 +25,70 @@ import java.util.Map; /** - * This class is responsible to map 2 classes of objects: Entity and VertexType. - * the following values are mapped: - * - name of the entity -> name of the vertex type - * - each attribute of the entity -> correspondent property of the vertex type - * - each property of the vertex type -> correspondent attribute of the entity + * This class is responsible to map 2 classes of objects: Entity and VertexType. the following + * values are mapped: - name of the entity -> name of the vertex type - each attribute of the + * entity -> correspondent property of the vertex type - each property of the vertex type -> + * correspondent attribute of the entity * * @author Gabriele Ponzi */ - public class EVClassMapper extends EntityClassMapper { - private VertexType vertexType; + private VertexType vertexType; - public EVClassMapper(Entity entity, VertexType vertexType, Map attribute2property, Map property2attribute) { - super(entity, attribute2property, property2attribute); - this.vertexType = vertexType; - } + public EVClassMapper( + Entity entity, + VertexType vertexType, + Map attribute2property, + Map property2attribute) { + super(entity, attribute2property, property2attribute); + this.vertexType = vertexType; + } - public VertexType getVertexType() { - return vertexType; - } + public VertexType getVertexType() { + return vertexType; + } - public void setVertexType(VertexType vertexType) { - this.vertexType = vertexType; - } + public void setVertexType(VertexType vertexType) { + this.vertexType = vertexType; + } - @Override - public int hashCode() { - int result = entity.hashCode(); - result = 31 * result + vertexType.hashCode(); - return result; - } + @Override + public int hashCode() { + int result = entity.hashCode(); + result = 31 * result + vertexType.hashCode(); + return result; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; - EVClassMapper that = (EVClassMapper) o; + EVClassMapper that = (EVClassMapper) o; - if (!entity.equals(that.entity)) return false; - if (!vertexType.equals(that.vertexType)) return false; - if (!attribute2property.equals(that.attribute2property)) return false; - return property2attribute.equals(that.property2attribute); - } + if (!entity.equals(that.entity)) return false; + if (!vertexType.equals(that.vertexType)) return false; + if (!attribute2property.equals(that.attribute2property)) return false; + return property2attribute.equals(that.property2attribute); + } - @Override - public String toString() { - String s = "{" + "Entity = " + entity.getName() + ", Vertex-Type = " + vertexType.getName() + ", attributes2properties: "; + @Override + public String toString() { + String s = + "{" + + "Entity = " + + entity.getName() + + ", Vertex-Type = " + + vertexType.getName() + + ", attributes2properties: "; - s += "["; - for (String attribute : this.attribute2property.keySet()) { - s += attribute + " --> " + attribute2property.get(attribute) + ", "; - } - s = s.substring(0, s.length() - 1); - s += "]}"; - return s; + s += "["; + for (String attribute : this.attribute2property.keySet()) { + s += attribute + " --> " + attribute2property.get(attribute) + ", "; } + s = s.substring(0, s.length() - 1); + s += "]}"; + return s; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/mapper/rdbms/classmapper/EntityClassMapper.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/mapper/rdbms/classmapper/EntityClassMapper.java index 2b33b925..ffa71d03 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/mapper/rdbms/classmapper/EntityClassMapper.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/mapper/rdbms/classmapper/EntityClassMapper.java @@ -24,63 +24,64 @@ import java.util.Map; /** - * This abstract class is extended by all the classes responsible to map 2 classes of objects where one of them is an Entity. - * Subclasses: - * - EVClassMapper: Entity --> VertexType - * - EEClassMapper: Entity --> EdgeType + * This abstract class is extended by all the classes responsible to map 2 classes of objects where + * one of them is an Entity. Subclasses: - EVClassMapper: Entity --> VertexType - EEClassMapper: + * Entity --> EdgeType * * @author Gabriele Ponzi */ - public abstract class EntityClassMapper { - protected Entity entity; - protected Map attribute2property; - protected Map property2attribute; - - public EntityClassMapper(Entity entity, Map attribute2property, Map property2attribute) { - this.entity = entity; - this.attribute2property = attribute2property; - this.property2attribute = property2attribute; - } - - public Entity getEntity() { - return entity; - } - - public void setEntity(Entity entity) { - this.entity = entity; - } - - public Map getAttribute2property() { - return attribute2property; - } - - public void setAttribute2property(Map attribute2property) { - this.attribute2property = attribute2property; - } - - public Map getProperty2attribute() { - return property2attribute; - } - - public void setProperty2attribute(Map property2attribute) { - this.property2attribute = property2attribute; - } - - public String getAttributeByProperty(String property) { - return this.property2attribute.get(property); - } - - public String getPropertyByAttribute(String attribute) { - return this.attribute2property.get(attribute); - } - - public boolean containsAttribute(String attributeName) { - return this.attribute2property.containsKey(attributeName); - } - - public boolean containsProperty(String propertyName) { - return this.property2attribute.containsKey(propertyName); - } + protected Entity entity; + protected Map attribute2property; + protected Map property2attribute; + + public EntityClassMapper( + Entity entity, + Map attribute2property, + Map property2attribute) { + this.entity = entity; + this.attribute2property = attribute2property; + this.property2attribute = property2attribute; + } + + public Entity getEntity() { + return entity; + } + + public void setEntity(Entity entity) { + this.entity = entity; + } + + public Map getAttribute2property() { + return attribute2property; + } + + public void setAttribute2property(Map attribute2property) { + this.attribute2property = attribute2property; + } + + public Map getProperty2attribute() { + return property2attribute; + } + + public void setProperty2attribute(Map property2attribute) { + this.property2attribute = property2attribute; + } + + public String getAttributeByProperty(String property) { + return this.property2attribute.get(property); + } + + public String getPropertyByAttribute(String attribute) { + return this.attribute2property.get(attribute); + } + + public boolean containsAttribute(String attributeName) { + return this.attribute2property.containsKey(attributeName); + } + + public boolean containsProperty(String propertyName) { + return this.property2attribute.containsKey(propertyName); + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/DataSourceSchemaInfo.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/DataSourceSchemaInfo.java index f0b8a29f..4a0640ba 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/DataSourceSchemaInfo.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/DataSourceSchemaInfo.java @@ -25,5 +25,4 @@ * * @author Gabriele Ponzi */ - public interface DataSourceSchemaInfo {} diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/Attribute.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/Attribute.java index 45a82661..f276eb9b 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/Attribute.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/Attribute.java @@ -25,68 +25,67 @@ * * @author Gabriele Ponzi */ - public class Attribute implements Comparable { - private final String name; - private final String dataType; - private final Entity belongingEntity; - private int ordinalPosition; + private final String name; + private final String dataType; + private final Entity belongingEntity; + private int ordinalPosition; - public Attribute(String name, int ordinalPosition, String dataType, Entity belongingEntity) { - this.name = name; - this.ordinalPosition = ordinalPosition; - this.dataType = dataType; - this.belongingEntity = belongingEntity; - } + public Attribute(String name, int ordinalPosition, String dataType, Entity belongingEntity) { + this.name = name; + this.ordinalPosition = ordinalPosition; + this.dataType = dataType; + this.belongingEntity = belongingEntity; + } - public String getName() { - return this.name; - } + public String getName() { + return this.name; + } - public int getOrdinalPosition() { - return this.ordinalPosition; - } + public int getOrdinalPosition() { + return this.ordinalPosition; + } - //FIXME: why the hell it should be updated after creation? - public void setOrdinalPosition(int ordinalPosition) { - this.ordinalPosition = ordinalPosition; - } + // FIXME: why the hell it should be updated after creation? + public void setOrdinalPosition(int ordinalPosition) { + this.ordinalPosition = ordinalPosition; + } - public String getDataType() { - return this.dataType; - } + public String getDataType() { + return this.dataType; + } - public Entity getBelongingEntity() { - return this.belongingEntity; - } + public Entity getBelongingEntity() { + return this.belongingEntity; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((dataType == null) ? 0 : dataType.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((dataType == null) ? 0 : dataType.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } - public boolean equals(Object o) { - Attribute that = (Attribute) o; - if (this.name.equals(that.getName()) && this.dataType.equals(that.getDataType())) { - return true; - } else return false; - } + public boolean equals(Object o) { + Attribute that = (Attribute) o; + if (this.name.equals(that.getName()) && this.dataType.equals(that.getDataType())) { + return true; + } else return false; + } - @Override - public int compareTo(Attribute attributeToCompare) { - if (this.ordinalPosition > attributeToCompare.getOrdinalPosition()) return 0; else if ( - this.ordinalPosition < attributeToCompare.getOrdinalPosition() - ) return -1; else return 1; - } + @Override + public int compareTo(Attribute attributeToCompare) { + if (this.ordinalPosition > attributeToCompare.getOrdinalPosition()) return 0; + else if (this.ordinalPosition < attributeToCompare.getOrdinalPosition()) return -1; + else return 1; + } - public String toString() { - String s = ""; - s += this.ordinalPosition + ": " + this.name + " ( " + this.dataType + " )"; - return s; - } + public String toString() { + String s = ""; + s += this.ordinalPosition + ": " + this.name + " ( " + this.dataType + " )"; + return s; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/CanonicalRelationship.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/CanonicalRelationship.java index 4cbfdefb..96fe5c14 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/CanonicalRelationship.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/CanonicalRelationship.java @@ -23,80 +23,80 @@ import java.util.List; /** - * It represents a canonical relationship between two entities (foreign and parent entity) - * based on the importing of a single primary key (composite or not) through a foreign key. + * It represents a canonical relationship between two entities (foreign and parent entity) based on + * the importing of a single primary key (composite or not) through a foreign key. * * @author Gabriele Ponzi */ - public class CanonicalRelationship extends Relationship { - private ForeignKey foreignKey; - private PrimaryKey primaryKey; + private ForeignKey foreignKey; + private PrimaryKey primaryKey; - public CanonicalRelationship(Entity foreignEntity, Entity parentEntity) { - this.foreignEntity = foreignEntity; - this.parentEntity = parentEntity; - this.direction = "direct"; - } + public CanonicalRelationship(Entity foreignEntity, Entity parentEntity) { + this.foreignEntity = foreignEntity; + this.parentEntity = parentEntity; + this.direction = "direct"; + } - public CanonicalRelationship(Entity foreignEntity, Entity parentEntity, ForeignKey foreignKey, PrimaryKey primaryKey) { - this.foreignEntity = foreignEntity; - this.parentEntity = parentEntity; - this.foreignKey = foreignKey; - this.primaryKey = primaryKey; - this.direction = "direct"; - } + public CanonicalRelationship( + Entity foreignEntity, Entity parentEntity, ForeignKey foreignKey, PrimaryKey primaryKey) { + this.foreignEntity = foreignEntity; + this.parentEntity = parentEntity; + this.foreignKey = foreignKey; + this.primaryKey = primaryKey; + this.direction = "direct"; + } - @Override - public List getFromColumns() { - return this.foreignKey.getInvolvedAttributes(); - } + @Override + public List getFromColumns() { + return this.foreignKey.getInvolvedAttributes(); + } - @Override - public List getToColumns() { - return this.primaryKey.getInvolvedAttributes(); - } + @Override + public List getToColumns() { + return this.primaryKey.getInvolvedAttributes(); + } - public ForeignKey getForeignKey() { - return foreignKey; - } + public ForeignKey getForeignKey() { + return foreignKey; + } - public void setForeignKey(ForeignKey foreignKey) { - this.foreignKey = foreignKey; - } + public void setForeignKey(ForeignKey foreignKey) { + this.foreignKey = foreignKey; + } - public PrimaryKey getPrimaryKey() { - return primaryKey; - } + public PrimaryKey getPrimaryKey() { + return primaryKey; + } - public void setPrimaryKey(PrimaryKey primaryKey) { - this.primaryKey = primaryKey; - } + public void setPrimaryKey(PrimaryKey primaryKey) { + this.primaryKey = primaryKey; + } - @Override - public boolean equals(Object obj) { - CanonicalRelationship that = (CanonicalRelationship) obj; - if (this.foreignEntity.equals(that.getForeignEntity()) && this.parentEntity.equals(that.getParentEntity())) { - if (this.foreignKey.equals(that.getForeignKey()) && this.primaryKey.equals(that.getPrimaryKey())) { - return true; - } - } - return false; + @Override + public boolean equals(Object obj) { + CanonicalRelationship that = (CanonicalRelationship) obj; + if (this.foreignEntity.equals(that.getForeignEntity()) + && this.parentEntity.equals(that.getParentEntity())) { + if (this.foreignKey.equals(that.getForeignKey()) + && this.primaryKey.equals(that.getPrimaryKey())) { + return true; + } } + return false; + } - @Override - public String toString() { - return ( - "CanonicalRelationship [foreignEntity=" + - foreignEntity.getName() + - ", parentEntity=" + - parentEntity.getName() + - ", Foreign key=" + - this.foreignKey.toString() + - ", Primary key=" + - this.primaryKey.toString() + - "]" - ); - } + @Override + public String toString() { + return ("CanonicalRelationship [foreignEntity=" + + foreignEntity.getName() + + ", parentEntity=" + + parentEntity.getName() + + ", Foreign key=" + + this.foreignKey.toString() + + ", Primary key=" + + this.primaryKey.toString() + + "]"); + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/DataBaseSchema.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/DataBaseSchema.java index 8183cd63..9a5a0e3a 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/DataBaseSchema.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/DataBaseSchema.java @@ -29,215 +29,227 @@ * * @author Gabriele Ponzi */ - public class DataBaseSchema implements DataSourceSchemaInfo { - private int majorVersion; - private int minorVersion; - private int driverMajorVersion; - private int driverMinorVersion; - private String productName; - private String productVersion; - private List entities; - private List canonicalRelationships; - private List logicalRelationships; - private List hierarchicalBags; - - public DataBaseSchema(int majorVersion, int minorVersion, int driverMajorVersion, int driverMinorVersion, String productName, String productVersion) { - this.majorVersion = majorVersion; - this.minorVersion = minorVersion; - this.driverMajorVersion = driverMajorVersion; - this.driverMinorVersion = driverMinorVersion; - this.productName = productName; - this.productVersion = productVersion; - this.entities = new ArrayList(); - this.canonicalRelationships = new ArrayList(); - this.logicalRelationships = new ArrayList(); - this.hierarchicalBags = new ArrayList(); - } - - public DataBaseSchema() { - this.entities = new ArrayList(); - this.canonicalRelationships = new ArrayList(); - this.logicalRelationships = new ArrayList(); - this.hierarchicalBags = new ArrayList(); - } - - public int getMajorVersion() { - return majorVersion; - } - - public void setMajorVersion(int majorVersion) { - this.majorVersion = majorVersion; - } - - public int getMinorVersion() { - return minorVersion; - } - - public void setMinorVersion(int minorVersion) { - this.minorVersion = minorVersion; - } - - public int getDriverMajorVersion() { - return driverMajorVersion; - } - - public void setDriverMajorVersion(int driverMajorVersion) { - this.driverMajorVersion = driverMajorVersion; + private int majorVersion; + private int minorVersion; + private int driverMajorVersion; + private int driverMinorVersion; + private String productName; + private String productVersion; + private List entities; + private List canonicalRelationships; + private List logicalRelationships; + private List hierarchicalBags; + + public DataBaseSchema( + int majorVersion, + int minorVersion, + int driverMajorVersion, + int driverMinorVersion, + String productName, + String productVersion) { + this.majorVersion = majorVersion; + this.minorVersion = minorVersion; + this.driverMajorVersion = driverMajorVersion; + this.driverMinorVersion = driverMinorVersion; + this.productName = productName; + this.productVersion = productVersion; + this.entities = new ArrayList(); + this.canonicalRelationships = new ArrayList(); + this.logicalRelationships = new ArrayList(); + this.hierarchicalBags = new ArrayList(); + } + + public DataBaseSchema() { + this.entities = new ArrayList(); + this.canonicalRelationships = new ArrayList(); + this.logicalRelationships = new ArrayList(); + this.hierarchicalBags = new ArrayList(); + } + + public int getMajorVersion() { + return majorVersion; + } + + public void setMajorVersion(int majorVersion) { + this.majorVersion = majorVersion; + } + + public int getMinorVersion() { + return minorVersion; + } + + public void setMinorVersion(int minorVersion) { + this.minorVersion = minorVersion; + } + + public int getDriverMajorVersion() { + return driverMajorVersion; + } + + public void setDriverMajorVersion(int driverMajorVersion) { + this.driverMajorVersion = driverMajorVersion; + } + + public int getDriverMinorVersion() { + return driverMinorVersion; + } + + public void setDriverMinorVersion(int driverMinorVersion) { + this.driverMinorVersion = driverMinorVersion; + } + + public String getProductName() { + return productName; + } + + public void setProductName(String productName) { + this.productName = productName; + } + + public String getProductVersion() { + return productVersion; + } + + public void setProductVersion(String productVersion) { + this.productVersion = productVersion; + } + + public List getEntities() { + return entities; + } + + public void setEntities(List entitiess) { + this.entities = entitiess; + } + + public List getCanonicalRelationships() { + return canonicalRelationships; + } + + public void setCanonicalRelationships(List canonicalRelationships) { + this.canonicalRelationships = canonicalRelationships; + } + + public List getLogicalRelationships() { + return logicalRelationships; + } + + public void setLogicalRelationships(List logicalRelationships) { + this.logicalRelationships = logicalRelationships; + } + + public List getHierarchicalBags() { + return hierarchicalBags; + } + + public void setHierarchicalBags(List hierarchicalBags) { + this.hierarchicalBags = hierarchicalBags; + } + + public Entity getEntityByName(String entityName) { + for (Entity currentEntity : this.entities) { + if (currentEntity.getName().equals(entityName)) return currentEntity; + } + + return null; + } + + public Entity getEntityByNameIgnoreCase(String entityName) { + for (Entity currentEntity : this.entities) { + if (currentEntity.getName().equalsIgnoreCase(entityName)) return currentEntity; } - public int getDriverMinorVersion() { - return driverMinorVersion; - } - - public void setDriverMinorVersion(int driverMinorVersion) { - this.driverMinorVersion = driverMinorVersion; - } - - public String getProductName() { - return productName; - } - - public void setProductName(String productName) { - this.productName = productName; - } + return null; + } - public String getProductVersion() { - return productVersion; + public Entity getEntityByPosition(int position) { + for (Entity currentEntity : this.entities) { + if (currentEntity.getSchemaPosition() == position) return currentEntity; } - public void setProductVersion(String productVersion) { - this.productVersion = productVersion; - } + return null; + } - public List getEntities() { - return entities; - } - - public void setEntities(List entitiess) { - this.entities = entitiess; - } - - public List getCanonicalRelationships() { - return canonicalRelationships; - } - - public void setCanonicalRelationships(List canonicalRelationships) { - this.canonicalRelationships = canonicalRelationships; - } - - public List getLogicalRelationships() { - return logicalRelationships; - } - - public void setLogicalRelationships(List logicalRelationships) { - this.logicalRelationships = logicalRelationships; - } - - public List getHierarchicalBags() { - return hierarchicalBags; - } - - public void setHierarchicalBags(List hierarchicalBags) { - this.hierarchicalBags = hierarchicalBags; - } - - public Entity getEntityByName(String entityName) { - for (Entity currentEntity : this.entities) { - if (currentEntity.getName().equals(entityName)) return currentEntity; + public Relationship getRelationshipByInvolvedEntitiesAndAttributes( + Entity currentForeignEntity, + Entity currentParentEntity, + List fromColumns, + List toColumns) { + for (Relationship currentRelationship : this.canonicalRelationships) { + if (currentRelationship.getForeignEntity().getName().equals(currentForeignEntity.getName()) + && currentRelationship + .getParentEntity() + .getName() + .equals(currentParentEntity.getName())) { + if (sameAttributesInvolved(currentRelationship.getFromColumns(), fromColumns) + && sameAttributesInvolved(currentRelationship.getToColumns(), toColumns)) { + return currentRelationship; } - - return null; - } - - public Entity getEntityByNameIgnoreCase(String entityName) { - for (Entity currentEntity : this.entities) { - if (currentEntity.getName().equalsIgnoreCase(entityName)) return currentEntity; + } + } + return null; + } + + /** + * It checks if the attributes of a Key passed as parameter correspond to the string names in the + * array columns. Order is not relevant. + * + * @param columns columns + * @param columnsName names + * @return true or false + */ + private boolean sameAttributesInvolved(List columns, List columnsName) { + if (columns.size() != columnsName.size()) { + return false; + } + + for (String column : columnsName) { + boolean present = false; + for (Attribute attribute : columns) { + if (attribute.getName().equals(column)) { + present = true; + break; } - - return null; - } - - public Entity getEntityByPosition(int position) { - for (Entity currentEntity : this.entities) { - if (currentEntity.getSchemaPosition() == position) return currentEntity; - } - - return null; - } - - public Relationship getRelationshipByInvolvedEntitiesAndAttributes( - Entity currentForeignEntity, - Entity currentParentEntity, - List fromColumns, - List toColumns - ) { - for (Relationship currentRelationship : this.canonicalRelationships) { - if ( - currentRelationship.getForeignEntity().getName().equals(currentForeignEntity.getName()) && - currentRelationship.getParentEntity().getName().equals(currentParentEntity.getName()) - ) { - if ( - sameAttributesInvolved(currentRelationship.getFromColumns(), fromColumns) && - sameAttributesInvolved(currentRelationship.getToColumns(), toColumns) - ) { - return currentRelationship; - } - } - } - return null; - } - - /** - * It checks if the attributes of a Key passed as parameter correspond to the string names in the array columns. - * Order is not relevant. - * - * @param columns columns - * @param columnsName names - * @return true or false - */ - private boolean sameAttributesInvolved(List columns, List columnsName) { - if (columns.size() != columnsName.size()) { - return false; - } - - for (String column : columnsName) { - boolean present = false; - for (Attribute attribute : columns) { - if (attribute.getName().equals(column)) { - present = true; - break; - } - } - if (!present) { - return false; - } - } - - return true; - } - - public String toString() { - String s = - "\n\n\n------------------------------ DB SCHEMA DESCRIPTION ------------------------------\n\n" + - "\nProduct name: " + - this.productName + - "\tProduct version: " + - this.productVersion + - "\nMajor version: " + - this.majorVersion + - "\tMinor Version: " + - this.minorVersion + - "\nDriver major version: " + - this.driverMajorVersion + - "\tDriver minor version: " + - this.driverMinorVersion + - "\n\n\n"; - - s += "Number of Entities: " + this.entities.size() + ".\n" + "Number of Relationship: " + this.canonicalRelationships.size() + ".\n\n\n"; - - for (Entity e : this.entities) s += e.toString(); - return s; - } + } + if (!present) { + return false; + } + } + + return true; + } + + public String toString() { + String s = + "\n\n\n" + + "------------------------------ DB SCHEMA DESCRIPTION" + + " ------------------------------\n\n" + + "\n" + + "Product name: " + + this.productName + + "\tProduct version: " + + this.productVersion + + "\nMajor version: " + + this.majorVersion + + "\tMinor Version: " + + this.minorVersion + + "\nDriver major version: " + + this.driverMajorVersion + + "\tDriver minor version: " + + this.driverMinorVersion + + "\n\n\n"; + + s += + "Number of Entities: " + + this.entities.size() + + ".\n" + + "Number of Relationship: " + + this.canonicalRelationships.size() + + ".\n\n\n"; + + for (Entity e : this.entities) s += e.toString(); + return s; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/Entity.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/Entity.java index c60314af..1b060505 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/Entity.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/Entity.java @@ -33,456 +33,471 @@ * * @author Gabriele Ponzi */ - public class Entity implements Comparable { - private final String name; - private final DataSourceInfo dataSource; - private final String schemaName; - private final Set attributes; - private final List foreignKeys; - - // Canonical relationships - private final Set outCanonicalRelationships; - private final Set inCanonicalRelationships; - // Logical relationships - private final Set outLogicalRelationships; - private final Set inLogicalRelationships; - private Boolean isSplitEntity; - - //STATE!!!! - private Set inheritedInCanonicalRelationships; - private boolean inheritedInCanonicalRelationshipsRecovered; - private Set inheritedOutCanonicalRelationships; - private boolean inheritedOutCanonicalRelationshipsRecovered; - //FIXME: all Boolean or boolean, please - private Boolean isAggregable; - private Set inheritedAttributes; - private boolean inheritedAttributesRecovered; - private int schemaPosition; - private PrimaryKey primaryKey; - private String directionOfN2NRepresentedRelationship; // when the entity corresponds to an aggregable - // join table it's 'direct' by default (at the - // first invocation of 'isAggregableJoinTable()') - private String nameOfN2NRepresentedRelationship; // we can have this parameter only in a join table - // and with the manual migrationConfigDoc of its - // represented relationship - private Entity parentEntity; - private int inheritanceLevel; - private HierarchicalBag hierarchicalBag; - - public Entity(String name, String schemaName, DataSourceInfo dataSource) { - this.name = name; - this.dataSource = dataSource; - this.schemaName = schemaName; - this.attributes = new LinkedHashSet<>(); - this.inheritedAttributes = new LinkedHashSet<>(); - this.inheritedAttributesRecovered = false; - this.foreignKeys = new LinkedList<>(); - - // canonical relationships - this.outCanonicalRelationships = new LinkedHashSet<>(); - this.inheritedOutCanonicalRelationships = new LinkedHashSet<>(); - this.inheritedOutCanonicalRelationshipsRecovered = false; - this.inCanonicalRelationships = new LinkedHashSet<>(); - this.inheritedInCanonicalRelationships = new LinkedHashSet<>(); - this.inheritedInCanonicalRelationshipsRecovered = false; - - // logical relationships - this.outLogicalRelationships = new LinkedHashSet<>(); - this.inLogicalRelationships = new LinkedHashSet<>(); - - this.isAggregable = null; - this.isSplitEntity = false; - this.inheritanceLevel = 0; - } - - /* - * It's possible to aggregate an entity iff (i) It's a junction (or join) table of dimension 2. (ii) It has not exported keys, - * that is it's not referenced by other entities. - */ - public boolean isAggregableJoinTable() { - // if already known, just retrieve the info - if (isAggregable != null) { - return isAggregable; - } else { - // (i) preliminar check - if (foreignKeys.size() != 2) { - return false; - } else { - boolean aggregable = isJunctionTable(); - isAggregable = aggregable; - - // if the entity is an aggregable join table then the direction of the N-N represented relationship is set to 'direct' by - // default. - if (isAggregable && directionOfN2NRepresentedRelationship == null) { - directionOfN2NRepresentedRelationship = "direct"; - } - - return isAggregable; - } - } - } - - private boolean isJunctionTable() { - boolean isJunctionTable = true; - - // (i) it's a junction table iff each attribute belonging to the primary key is involved also in a foreign key that imports all - // the attributes of the primary key of the referenced table. - for (ForeignKey currentFk : this.foreignKeys) { - for (Attribute attribute : currentFk.getInvolvedAttributes()) { - if (!this.primaryKey.getInvolvedAttributes().contains(attribute)) { - isJunctionTable = false; - break; - } - } - } - - // (ii) check - if (isJunctionTable) { - if (this.getAllInCanonicalRelationships().size() > 0) isJunctionTable = false; + private final String name; + private final DataSourceInfo dataSource; + private final String schemaName; + private final Set attributes; + private final List foreignKeys; + + // Canonical relationships + private final Set outCanonicalRelationships; + private final Set inCanonicalRelationships; + // Logical relationships + private final Set outLogicalRelationships; + private final Set inLogicalRelationships; + private Boolean isSplitEntity; + + // STATE!!!! + private Set inheritedInCanonicalRelationships; + private boolean inheritedInCanonicalRelationshipsRecovered; + private Set inheritedOutCanonicalRelationships; + private boolean inheritedOutCanonicalRelationshipsRecovered; + // FIXME: all Boolean or boolean, please + private Boolean isAggregable; + private Set inheritedAttributes; + private boolean inheritedAttributesRecovered; + private int schemaPosition; + private PrimaryKey primaryKey; + private String + directionOfN2NRepresentedRelationship; // when the entity corresponds to an aggregable + // join table it's 'direct' by default (at the + // first invocation of 'isAggregableJoinTable()') + private String + nameOfN2NRepresentedRelationship; // we can have this parameter only in a join table + // and with the manual migrationConfigDoc of its + // represented relationship + private Entity parentEntity; + private int inheritanceLevel; + private HierarchicalBag hierarchicalBag; + + public Entity(String name, String schemaName, DataSourceInfo dataSource) { + this.name = name; + this.dataSource = dataSource; + this.schemaName = schemaName; + this.attributes = new LinkedHashSet<>(); + this.inheritedAttributes = new LinkedHashSet<>(); + this.inheritedAttributesRecovered = false; + this.foreignKeys = new LinkedList<>(); + + // canonical relationships + this.outCanonicalRelationships = new LinkedHashSet<>(); + this.inheritedOutCanonicalRelationships = new LinkedHashSet<>(); + this.inheritedOutCanonicalRelationshipsRecovered = false; + this.inCanonicalRelationships = new LinkedHashSet<>(); + this.inheritedInCanonicalRelationships = new LinkedHashSet<>(); + this.inheritedInCanonicalRelationshipsRecovered = false; + + // logical relationships + this.outLogicalRelationships = new LinkedHashSet<>(); + this.inLogicalRelationships = new LinkedHashSet<>(); + + this.isAggregable = null; + this.isSplitEntity = false; + this.inheritanceLevel = 0; + } + + /* + * It's possible to aggregate an entity iff (i) It's a junction (or join) table of dimension 2. (ii) It has not exported keys, + * that is it's not referenced by other entities. + */ + public boolean isAggregableJoinTable() { + // if already known, just retrieve the info + if (isAggregable != null) { + return isAggregable; + } else { + // (i) preliminar check + if (foreignKeys.size() != 2) { + return false; + } else { + boolean aggregable = isJunctionTable(); + isAggregable = aggregable; + + // if the entity is an aggregable join table then the direction of the N-N represented + // relationship is set to 'direct' by + // default. + if (isAggregable && directionOfN2NRepresentedRelationship == null) { + directionOfN2NRepresentedRelationship = "direct"; } - return isJunctionTable; - } - - public Boolean isSplitEntity() { - return this.isSplitEntity; - } - - public void setIsSplitEntity(Boolean splitEntity) { - isSplitEntity = splitEntity; - } - - public void setIsAggregableJoinTable(boolean isAggregable) { - this.isAggregable = isAggregable; - } - - public String getDirectionOfN2NRepresentedRelationship() { - return this.directionOfN2NRepresentedRelationship; - } - - public void setDirectionOfN2NRepresentedRelationship(String directionOfN2NRepresentedRelationship) { - this.directionOfN2NRepresentedRelationship = directionOfN2NRepresentedRelationship; - } - - public String getNameOfN2NRepresentedRelationship() { - return this.nameOfN2NRepresentedRelationship; - } - - public void setNameOfN2NRepresentedRelationship(String nameOfN2NRepresentedRelationship) { - this.nameOfN2NRepresentedRelationship = nameOfN2NRepresentedRelationship; - } - - public String getName() { - return this.name; - } - - public DataSourceInfo getDataSource() { - return dataSource; - } - - public String getSchemaName() { - return this.schemaName; - } - public int getSchemaPosition() { - return this.schemaPosition; + return isAggregable; + } } + } - public void setSchemaPosition(int schemaPosition) { - this.schemaPosition = schemaPosition; - } - - public Set getAttributes() { - return this.attributes; - } - - public Set getInheritedAttributes() { - if (inheritedAttributesRecovered) return this.inheritedAttributes; else if (parentEntity != null) { - this.inheritedAttributes = parentEntity.getAllAttributes(); - this.inheritedAttributesRecovered = true; - return this.inheritedAttributes; - } else return this.inheritedAttributes; - } - - // Returns attributes and inherited attributes - public Set getAllAttributes() { - Set allAttributes = new LinkedHashSet(); - allAttributes.addAll(this.getInheritedAttributes()); - allAttributes.addAll(this.attributes); - - return allAttributes; - } + private boolean isJunctionTable() { + boolean isJunctionTable = true; - public boolean isInheritedAttributesRecovered() { - return inheritedAttributesRecovered; - } - - public PrimaryKey getPrimaryKey() { - return this.primaryKey; - } - - public void setPrimaryKey(PrimaryKey primaryKey) { - this.primaryKey = primaryKey; - } - - public List getForeignKeys() { - return foreignKeys; - } - - public boolean addAttribute(Attribute attribute) { - boolean added = this.attributes.add(attribute); - List temp = new LinkedList(this.attributes); - - if (added) { - Collections.sort(temp); + // (i) it's a junction table iff each attribute belonging to the primary key is involved also in + // a foreign key that imports all + // the attributes of the primary key of the referenced table. + for (ForeignKey currentFk : this.foreignKeys) { + for (Attribute attribute : currentFk.getInvolvedAttributes()) { + if (!this.primaryKey.getInvolvedAttributes().contains(attribute)) { + isJunctionTable = false; + break; } - this.attributes.clear(); - this.attributes.addAll(temp); - return added; + } } - public void removeAttributeByNameIgnoreCase(String toRemove) { - Attribute currentAttribute; - Iterator it = this.attributes.iterator(); - while (it.hasNext()) { - currentAttribute = it.next(); - if (currentAttribute.getName().equalsIgnoreCase(toRemove)) { - it.remove(); - break; - } - } + // (ii) check + if (isJunctionTable) { + if (this.getAllInCanonicalRelationships().size() > 0) isJunctionTable = false; } + return isJunctionTable; + } - public Attribute getAttributeByName(String name) { - Attribute toReturn = null; + public Boolean isSplitEntity() { + return this.isSplitEntity; + } + + public void setIsSplitEntity(Boolean splitEntity) { + isSplitEntity = splitEntity; + } + + public void setIsAggregableJoinTable(boolean isAggregable) { + this.isAggregable = isAggregable; + } + + public String getDirectionOfN2NRepresentedRelationship() { + return this.directionOfN2NRepresentedRelationship; + } + + public void setDirectionOfN2NRepresentedRelationship( + String directionOfN2NRepresentedRelationship) { + this.directionOfN2NRepresentedRelationship = directionOfN2NRepresentedRelationship; + } + + public String getNameOfN2NRepresentedRelationship() { + return this.nameOfN2NRepresentedRelationship; + } + + public void setNameOfN2NRepresentedRelationship(String nameOfN2NRepresentedRelationship) { + this.nameOfN2NRepresentedRelationship = nameOfN2NRepresentedRelationship; + } + + public String getName() { + return this.name; + } + + public DataSourceInfo getDataSource() { + return dataSource; + } + + public String getSchemaName() { + return this.schemaName; + } + + public int getSchemaPosition() { + return this.schemaPosition; + } - for (Attribute a : this.attributes) { - if (a.getName().equals(name)) { - toReturn = a; - break; - } - } - return toReturn; - } + public void setSchemaPosition(int schemaPosition) { + this.schemaPosition = schemaPosition; + } - public Attribute getAttributeByNameIgnoreCase(String name) { - Attribute toReturn = null; + public Set getAttributes() { + return this.attributes; + } - for (Attribute a : this.attributes) { - if (a.getName().equalsIgnoreCase(name)) { - toReturn = a; - break; - } - } - return toReturn; - } + public Set getInheritedAttributes() { + if (inheritedAttributesRecovered) return this.inheritedAttributes; + else if (parentEntity != null) { + this.inheritedAttributes = parentEntity.getAllAttributes(); + this.inheritedAttributesRecovered = true; + return this.inheritedAttributes; + } else return this.inheritedAttributes; + } - public Attribute getAttributeByOrdinalPosition(int position) { - Attribute toReturn = null; + // Returns attributes and inherited attributes + public Set getAllAttributes() { + Set allAttributes = new LinkedHashSet(); + allAttributes.addAll(this.getInheritedAttributes()); + allAttributes.addAll(this.attributes); - for (Attribute a : this.attributes) { - if (a.getOrdinalPosition() == position) { - toReturn = a; - break; - } - } + return allAttributes; + } - return toReturn; - } + public boolean isInheritedAttributesRecovered() { + return inheritedAttributesRecovered; + } - public Attribute getInheritedAttributeByName(String name) { - Attribute toReturn = null; + public PrimaryKey getPrimaryKey() { + return this.primaryKey; + } - for (Attribute a : this.getInheritedAttributes()) { - if (a.getName().equals(name)) { - toReturn = a; - break; - } - } + public void setPrimaryKey(PrimaryKey primaryKey) { + this.primaryKey = primaryKey; + } - return toReturn; - } + public List getForeignKeys() { + return foreignKeys; + } - public Attribute getInheritedAttributeByNameIgnoreCase(String name) { - Attribute toReturn = null; + public boolean addAttribute(Attribute attribute) { + boolean added = this.attributes.add(attribute); + List temp = new LinkedList(this.attributes); - for (Attribute a : this.getInheritedAttributes()) { - if (a.getName().equalsIgnoreCase(name)) { - toReturn = a; - break; - } - } + if (added) { + Collections.sort(temp); + } + this.attributes.clear(); + this.attributes.addAll(temp); + return added; + } + + public void removeAttributeByNameIgnoreCase(String toRemove) { + Attribute currentAttribute; + Iterator it = this.attributes.iterator(); + while (it.hasNext()) { + currentAttribute = it.next(); + if (currentAttribute.getName().equalsIgnoreCase(toRemove)) { + it.remove(); + break; + } + } + } + + public Attribute getAttributeByName(String name) { + Attribute toReturn = null; + + for (Attribute a : this.attributes) { + if (a.getName().equals(name)) { + toReturn = a; + break; + } + } + return toReturn; + } + + public Attribute getAttributeByNameIgnoreCase(String name) { + Attribute toReturn = null; + + for (Attribute a : this.attributes) { + if (a.getName().equalsIgnoreCase(name)) { + toReturn = a; + break; + } + } + return toReturn; + } + + public Attribute getAttributeByOrdinalPosition(int position) { + Attribute toReturn = null; + + for (Attribute a : this.attributes) { + if (a.getOrdinalPosition() == position) { + toReturn = a; + break; + } + } + + return toReturn; + } + + public Attribute getInheritedAttributeByName(String name) { + Attribute toReturn = null; + + for (Attribute a : this.getInheritedAttributes()) { + if (a.getName().equals(name)) { + toReturn = a; + break; + } + } + + return toReturn; + } + + public Attribute getInheritedAttributeByNameIgnoreCase(String name) { + Attribute toReturn = null; + + for (Attribute a : this.getInheritedAttributes()) { + if (a.getName().equalsIgnoreCase(name)) { + toReturn = a; + break; + } + } + + return toReturn; + } + + // Getter and Setter Out Relationships + + public Set getOutCanonicalRelationships() { + return this.outCanonicalRelationships; + } + + public Set getInheritedOutCanonicalRelationships() { + if (inheritedOutCanonicalRelationshipsRecovered) return this.inheritedOutCanonicalRelationships; + else if (parentEntity != null) { + this.inheritedOutCanonicalRelationships = parentEntity.getAllOutCanonicalRelationships(); + this.inheritedOutCanonicalRelationshipsRecovered = true; + return this.inheritedOutCanonicalRelationships; + } else return this.inheritedOutCanonicalRelationships; + } + + // Returns relationships and inherited relationships (OUT) + public Set getAllOutCanonicalRelationships() { + Set allRelationships = new LinkedHashSet(); + allRelationships.addAll(this.getInheritedOutCanonicalRelationships()); + allRelationships.addAll(this.outCanonicalRelationships); + + return allRelationships; + } + + public boolean isInheritedOutCanonicalRelationshipsRecovered() { + return inheritedOutCanonicalRelationshipsRecovered; + } + + public void setInheritedOutCanonicalRelationshipsRecovered( + boolean inheritedOutCanonicalRelationshipsRecovered) { + this.inheritedOutCanonicalRelationshipsRecovered = inheritedOutCanonicalRelationshipsRecovered; + } - return toReturn; - } + // Getter and Setter In Relationships - // Getter and Setter Out Relationships + public Set getInCanonicalRelationships() { + return this.inCanonicalRelationships; + } - public Set getOutCanonicalRelationships() { - return this.outCanonicalRelationships; - } - - public Set getInheritedOutCanonicalRelationships() { - if (inheritedOutCanonicalRelationshipsRecovered) return this.inheritedOutCanonicalRelationships; else if (parentEntity != null) { - this.inheritedOutCanonicalRelationships = parentEntity.getAllOutCanonicalRelationships(); - this.inheritedOutCanonicalRelationshipsRecovered = true; - return this.inheritedOutCanonicalRelationships; - } else return this.inheritedOutCanonicalRelationships; - } - - // Returns relationships and inherited relationships (OUT) - public Set getAllOutCanonicalRelationships() { - Set allRelationships = new LinkedHashSet(); - allRelationships.addAll(this.getInheritedOutCanonicalRelationships()); - allRelationships.addAll(this.outCanonicalRelationships); - - return allRelationships; - } - - public boolean isInheritedOutCanonicalRelationshipsRecovered() { - return inheritedOutCanonicalRelationshipsRecovered; - } - - public void setInheritedOutCanonicalRelationshipsRecovered(boolean inheritedOutCanonicalRelationshipsRecovered) { - this.inheritedOutCanonicalRelationshipsRecovered = inheritedOutCanonicalRelationshipsRecovered; - } - - // Getter and Setter In Relationships - - public Set getInCanonicalRelationships() { - return this.inCanonicalRelationships; - } - - public Set getInheritedInCanonicalRelationships() { - if (inheritedInCanonicalRelationshipsRecovered) return this.inheritedInCanonicalRelationships; else if (parentEntity != null) { - this.inheritedInCanonicalRelationships = parentEntity.getAllInCanonicalRelationships(); - this.inheritedInCanonicalRelationshipsRecovered = true; - return this.inheritedInCanonicalRelationships; - } else return this.inheritedInCanonicalRelationships; - } - - public void setInheritedInCanonicalRelationships(Set inheritedInCanonicalRelationships) { - this.inheritedInCanonicalRelationships = inheritedInCanonicalRelationships; - } - - // Returns relationships and inherited relationships (IN) - public Set getAllInCanonicalRelationships() { - Set allRelationships = new LinkedHashSet(); - allRelationships.addAll(this.getInheritedInCanonicalRelationships()); - allRelationships.addAll(this.inCanonicalRelationships); - - return allRelationships; - } - - public boolean isInheritedInCanonicalRelationshipsRecovered() { - return inheritedInCanonicalRelationshipsRecovered; - } - - public Set getOutLogicalRelationships() { - return outLogicalRelationships; - } - - public Set getInLogicalRelationships() { - return inLogicalRelationships; - } - - public Entity getParentEntity() { - return this.parentEntity; - } - - public void setParentEntity(Entity parentEntity) { - this.parentEntity = parentEntity; - } - - public int getInheritanceLevel() { - return this.inheritanceLevel; - } - - public void setInheritanceLevel(int inheritanceLevel) { - this.inheritanceLevel = inheritanceLevel; - } - - public HierarchicalBag getHierarchicalBag() { - return hierarchicalBag; - } - - public void setHierarchicalBag(HierarchicalBag hierarchicalBag) { - this.hierarchicalBag = hierarchicalBag; - } - - public void renumberAttributesOrdinalPositions() { - int i = 1; - for (Attribute attribute : this.attributes) { - attribute.setOrdinalPosition(i); - i++; - } - } - - @Override - public int compareTo(Entity toCompare) { - if (this.inheritanceLevel > toCompare.getInheritanceLevel()) return 1; else if ( - this.inheritanceLevel < toCompare.getInheritanceLevel() - ) return -1; else return this.name.compareTo(toCompare.getName()); - } - - @Override - public String toString() { - String s = "Entity [name = " + this.name + ", number of attributes = " + this.attributes.size() + "]"; - - if (this.isAggregableJoinTable()) s += "\t\t\tJoin Entity (Aggregable Join Table)"; - - s += "\n|| "; - - for (Attribute a : this.attributes) s += a.getOrdinalPosition() + ": " + a.getName() + " ( " + a.getDataType() + " ) || "; - - s += "\nPrimary Key (" + this.primaryKey.getInvolvedAttributes().size() + " involved attributes): "; - - int cont = 1; - int size = this.primaryKey.getInvolvedAttributes().size(); - for (Attribute a : this.primaryKey.getInvolvedAttributes()) { - if (cont < size) s += a.getName() + ", "; else s += a.getName() + "."; - cont++; - } - - if (this.outCanonicalRelationships.size() > 0) { - s += "\nForeign Keys (" + outCanonicalRelationships.size() + "):\n"; - int index = 1; - - for (CanonicalRelationship relationship : this.outCanonicalRelationships) { - s += index + ". "; - s += - "Foreign Entity: " + - relationship.getForeignEntity().getName() + - ", Foreign Key: " + - relationship.getForeignKey().toString() + - "\t||\t" + - "Parent Entity: " + - relationship.getParentEntity().getName() + - ", Primary Key: " + - relationship.getForeignKey().toString() + - "\n"; - index++; - } - } else { - s += "\nForeign Key: Not Present\n"; - } - - s += "\n\n"; - return s; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - Entity that = (Entity) obj; - return this.name.equals(that.getName()) && this.getDataSource().equals(that.getDataSource()); - } + public Set getInheritedInCanonicalRelationships() { + if (inheritedInCanonicalRelationshipsRecovered) return this.inheritedInCanonicalRelationships; + else if (parentEntity != null) { + this.inheritedInCanonicalRelationships = parentEntity.getAllInCanonicalRelationships(); + this.inheritedInCanonicalRelationshipsRecovered = true; + return this.inheritedInCanonicalRelationships; + } else return this.inheritedInCanonicalRelationships; + } + + public void setInheritedInCanonicalRelationships( + Set inheritedInCanonicalRelationships) { + this.inheritedInCanonicalRelationships = inheritedInCanonicalRelationships; + } + + // Returns relationships and inherited relationships (IN) + public Set getAllInCanonicalRelationships() { + Set allRelationships = new LinkedHashSet(); + allRelationships.addAll(this.getInheritedInCanonicalRelationships()); + allRelationships.addAll(this.inCanonicalRelationships); + + return allRelationships; + } + + public boolean isInheritedInCanonicalRelationshipsRecovered() { + return inheritedInCanonicalRelationshipsRecovered; + } + + public Set getOutLogicalRelationships() { + return outLogicalRelationships; + } + + public Set getInLogicalRelationships() { + return inLogicalRelationships; + } + + public Entity getParentEntity() { + return this.parentEntity; + } + + public void setParentEntity(Entity parentEntity) { + this.parentEntity = parentEntity; + } + + public int getInheritanceLevel() { + return this.inheritanceLevel; + } + + public void setInheritanceLevel(int inheritanceLevel) { + this.inheritanceLevel = inheritanceLevel; + } + + public HierarchicalBag getHierarchicalBag() { + return hierarchicalBag; + } + + public void setHierarchicalBag(HierarchicalBag hierarchicalBag) { + this.hierarchicalBag = hierarchicalBag; + } + + public void renumberAttributesOrdinalPositions() { + int i = 1; + for (Attribute attribute : this.attributes) { + attribute.setOrdinalPosition(i); + i++; + } + } + + @Override + public int compareTo(Entity toCompare) { + if (this.inheritanceLevel > toCompare.getInheritanceLevel()) return 1; + else if (this.inheritanceLevel < toCompare.getInheritanceLevel()) return -1; + else return this.name.compareTo(toCompare.getName()); + } + + @Override + public String toString() { + String s = + "Entity [name = " + this.name + ", number of attributes = " + this.attributes.size() + "]"; + + if (this.isAggregableJoinTable()) s += "\t\t\tJoin Entity (Aggregable Join Table)"; + + s += "\n|| "; + + for (Attribute a : this.attributes) + s += a.getOrdinalPosition() + ": " + a.getName() + " ( " + a.getDataType() + " ) || "; + + s += + "\nPrimary Key (" + + this.primaryKey.getInvolvedAttributes().size() + + " involved attributes): "; + + int cont = 1; + int size = this.primaryKey.getInvolvedAttributes().size(); + for (Attribute a : this.primaryKey.getInvolvedAttributes()) { + if (cont < size) s += a.getName() + ", "; + else s += a.getName() + "."; + cont++; + } + + if (this.outCanonicalRelationships.size() > 0) { + s += "\nForeign Keys (" + outCanonicalRelationships.size() + "):\n"; + int index = 1; + + for (CanonicalRelationship relationship : this.outCanonicalRelationships) { + s += index + ". "; + s += + "Foreign Entity: " + + relationship.getForeignEntity().getName() + + ", Foreign Key: " + + relationship.getForeignKey().toString() + + "\t||\t" + + "Parent Entity: " + + relationship.getParentEntity().getName() + + ", Primary Key: " + + relationship.getForeignKey().toString() + + "\n"; + index++; + } + } else { + s += "\nForeign Key: Not Present\n"; + } + + s += "\n\n"; + return s; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + Entity that = (Entity) obj; + return this.name.equals(that.getName()) && this.getDataSource().equals(that.getDataSource()); + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/ForeignKey.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/ForeignKey.java index 6258c780..4979e6b9 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/ForeignKey.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/ForeignKey.java @@ -27,10 +27,9 @@ * * @author Gabriele Ponzi */ - public class ForeignKey extends Key { - public ForeignKey(Entity belongingEntity, List involvedAttributes) { - super(belongingEntity, involvedAttributes); - } + public ForeignKey(Entity belongingEntity, List involvedAttributes) { + super(belongingEntity, involvedAttributes); + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/HierarchicalBag.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/HierarchicalBag.java index f9801098..1577a8c1 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/HierarchicalBag.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/HierarchicalBag.java @@ -28,98 +28,98 @@ import java.util.Set; /** - * It represents a hierarchical tree of entities. - * It collects the involved entities, the "inheritance strategy" adopted at the lower level (DBMS level) and other - * meta-data useful for records importing. + * It represents a hierarchical tree of entities. It collects the involved entities, the + * "inheritance strategy" adopted at the lower level (DBMS level) and other meta-data useful for + * records importing. * * @author Gabriele Ponzi */ - public class HierarchicalBag { - private Map> depth2entities; - private String inheritancePattern; + private Map> depth2entities; + private String inheritancePattern; - private String discriminatorColumn; - private Map entityName2discriminatorValue; + private String discriminatorColumn; + private Map entityName2discriminatorValue; - public HierarchicalBag() { - this.depth2entities = new LinkedHashMap>(); - this.entityName2discriminatorValue = new HashMap(); - } + public HierarchicalBag() { + this.depth2entities = new LinkedHashMap>(); + this.entityName2discriminatorValue = new HashMap(); + } - public HierarchicalBag(String inheritancePattern) { - this.inheritancePattern = inheritancePattern; - this.depth2entities = new HashMap>(); - this.entityName2discriminatorValue = new HashMap(); - } + public HierarchicalBag(String inheritancePattern) { + this.inheritancePattern = inheritancePattern; + this.depth2entities = new HashMap>(); + this.entityName2discriminatorValue = new HashMap(); + } - public Map> getDepth2entities() { - return this.depth2entities; - } + public Map> getDepth2entities() { + return this.depth2entities; + } - public void setDepth2entities(Map> depth2entities) { - this.depth2entities = depth2entities; - } + public void setDepth2entities(Map> depth2entities) { + this.depth2entities = depth2entities; + } - public String getInheritancePattern() { - return this.inheritancePattern; - } + public String getInheritancePattern() { + return this.inheritancePattern; + } - public void setInheritancePattern(String inheritancePattern) { - this.inheritancePattern = inheritancePattern; - } + public void setInheritancePattern(String inheritancePattern) { + this.inheritancePattern = inheritancePattern; + } - public String getDiscriminatorColumn() { - return this.discriminatorColumn; - } + public String getDiscriminatorColumn() { + return this.discriminatorColumn; + } - public void setDiscriminatorColumn(String discriminatorColumn) { - this.discriminatorColumn = discriminatorColumn; - } + public void setDiscriminatorColumn(String discriminatorColumn) { + this.discriminatorColumn = discriminatorColumn; + } - public Map getEntityName2discriminatorValue() { - return this.entityName2discriminatorValue; - } + public Map getEntityName2discriminatorValue() { + return this.entityName2discriminatorValue; + } - public void setEntityName2discriminatorValue(Map entityName2discriminatorValue) { - this.entityName2discriminatorValue = entityName2discriminatorValue; - } + public void setEntityName2discriminatorValue(Map entityName2discriminatorValue) { + this.entityName2discriminatorValue = entityName2discriminatorValue; + } - @Override - public int hashCode() { - Iterator it = getDepth2entities().get(0).iterator(); - Entity rootEntity = it.next(); + @Override + public int hashCode() { + Iterator it = getDepth2entities().get(0).iterator(); + Entity rootEntity = it.next(); - final int prime = 31; - int result = 1; - result = prime * result + ((rootEntity == null) ? 0 : rootEntity.getName().hashCode()); - result = prime * result + ((inheritancePattern == null) ? 0 : inheritancePattern.hashCode()); - return result; - } + final int prime = 31; + int result = 1; + result = prime * result + ((rootEntity == null) ? 0 : rootEntity.getName().hashCode()); + result = prime * result + ((inheritancePattern == null) ? 0 : inheritancePattern.hashCode()); + return result; + } - @Override - public boolean equals(Object obj) { - HierarchicalBag that = (HierarchicalBag) obj; + @Override + public boolean equals(Object obj) { + HierarchicalBag that = (HierarchicalBag) obj; - Iterator it = this.getDepth2entities().get(0).iterator(); - Entity rootEntity = it.next(); + Iterator it = this.getDepth2entities().get(0).iterator(); + Entity rootEntity = it.next(); - it = that.getDepth2entities().get(0).iterator(); - Entity thatRootEntity = it.next(); + it = that.getDepth2entities().get(0).iterator(); + Entity thatRootEntity = it.next(); - if (this.inheritancePattern.equals(that.getInheritancePattern()) && rootEntity.getName().equals(thatRootEntity.getName())) { - return true; - } - return false; + if (this.inheritancePattern.equals(that.getInheritancePattern()) + && rootEntity.getName().equals(thatRootEntity.getName())) { + return true; } - - public DataSourceInfo getSourceDataseInfo() { - Set entities = this.getDepth2entities().get(0); - Iterator it = entities.iterator(); - if (it.hasNext()) { - return it.next().getDataSource(); - } - return null; + return false; + } + + public DataSourceInfo getSourceDataseInfo() { + Set entities = this.getDepth2entities().get(0); + Iterator it = entities.iterator(); + if (it.hasNext()) { + return it.next().getDataSource(); } + return null; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/Key.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/Key.java index 74e92a15..41e24554 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/Key.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/Key.java @@ -23,92 +23,92 @@ import java.util.List; /** - * It represents a generic key of the source DB. It's extended from PrimaryKey - * and ForeignKey that differ each other only by their usage. + * It represents a generic key of the source DB. It's extended from PrimaryKey and ForeignKey that + * differ each other only by their usage. * * @author Gabriele Ponzi */ - public class Key { - protected final Entity belongingEntity; - protected final List involvedAttributes; + protected final Entity belongingEntity; + protected final List involvedAttributes; - public Key(Entity belongingEntity, List involvedAttributes) { - this.belongingEntity = belongingEntity; - this.involvedAttributes = involvedAttributes; - } + public Key(Entity belongingEntity, List involvedAttributes) { + this.belongingEntity = belongingEntity; + this.involvedAttributes = involvedAttributes; + } - public Entity getBelongingEntity() { - return this.belongingEntity; - } + public Entity getBelongingEntity() { + return this.belongingEntity; + } - public List getInvolvedAttributes() { - return this.involvedAttributes; - } + public List getInvolvedAttributes() { + return this.involvedAttributes; + } - public void addAttribute(Attribute attribute) { - this.involvedAttributes.add(attribute); - } + public void addAttribute(Attribute attribute) { + this.involvedAttributes.add(attribute); + } - public boolean removeAttribute(Attribute toRemove) { - return this.involvedAttributes.remove(toRemove); - } + public boolean removeAttribute(Attribute toRemove) { + return this.involvedAttributes.remove(toRemove); + } - public Attribute getAttributeByName(String name) { - Attribute toReturn = null; + public Attribute getAttributeByName(String name) { + Attribute toReturn = null; - for (Attribute a : this.involvedAttributes) { - if (a.getName().equals(name)) { - toReturn = a; - break; - } - } - return toReturn; + for (Attribute a : this.involvedAttributes) { + if (a.getName().equals(name)) { + toReturn = a; + break; + } } + return toReturn; + } - public Attribute getAttributeByNameIgnoreCase(String name) { - Attribute toReturn = null; + public Attribute getAttributeByNameIgnoreCase(String name) { + Attribute toReturn = null; - for (Attribute a : this.involvedAttributes) { - if (a.getName().equalsIgnoreCase(name)) { - toReturn = a; - break; - } - } - return toReturn; + for (Attribute a : this.involvedAttributes) { + if (a.getName().equalsIgnoreCase(name)) { + toReturn = a; + break; + } } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((belongingEntity == null) ? 0 : belongingEntity.getName().hashCode()); - result = prime * result + ((involvedAttributes == null) ? 0 : involvedAttributes.hashCode()); - return result; + return toReturn; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = + prime * result + ((belongingEntity == null) ? 0 : belongingEntity.getName().hashCode()); + result = prime * result + ((involvedAttributes == null) ? 0 : involvedAttributes.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + Key that = (Key) obj; + + if (this.belongingEntity.getName().equals(that.belongingEntity.getName())) { + if (this.involvedAttributes.equals(that.getInvolvedAttributes())) { + return true; + } } - @Override - public boolean equals(Object obj) { - Key that = (Key) obj; - - if (this.belongingEntity.getName().equals(that.belongingEntity.getName())) { - if (this.involvedAttributes.equals(that.getInvolvedAttributes())) { - return true; - } - } + return false; + } - return false; + public String toString() { + String s = "["; + for (Attribute attribute : this.involvedAttributes) { + s += attribute.getName() + ","; } + s = s.substring(0, s.length() - 1); + s += "]"; - public String toString() { - String s = "["; - for (Attribute attribute : this.involvedAttributes) { - s += attribute.getName() + ","; - } - s = s.substring(0, s.length() - 1); - s += "]"; - - return s; - } + return s; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/LogicalRelationship.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/LogicalRelationship.java index b53676eb..76e71405 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/LogicalRelationship.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/LogicalRelationship.java @@ -28,81 +28,84 @@ * * @author Gabriele Ponzi */ - public class LogicalRelationship extends Relationship { - private List fromColumns; - private List toColumns; + private List fromColumns; + private List toColumns; - public LogicalRelationship(Entity foreignEntity, Entity parentEntity) { - this.foreignEntity = foreignEntity; - this.parentEntity = parentEntity; - this.direction = "direct"; - } + public LogicalRelationship(Entity foreignEntity, Entity parentEntity) { + this.foreignEntity = foreignEntity; + this.parentEntity = parentEntity; + this.direction = "direct"; + } - public LogicalRelationship(Entity foreignEntity, Entity parentEntity, List fromColumns, List toColumns) { - this.foreignEntity = foreignEntity; - this.parentEntity = parentEntity; - this.fromColumns = fromColumns; - this.toColumns = toColumns; - this.direction = "direct"; - } + public LogicalRelationship( + Entity foreignEntity, + Entity parentEntity, + List fromColumns, + List toColumns) { + this.foreignEntity = foreignEntity; + this.parentEntity = parentEntity; + this.fromColumns = fromColumns; + this.toColumns = toColumns; + this.direction = "direct"; + } - @Override - public List getFromColumns() { - return fromColumns; - } + @Override + public List getFromColumns() { + return fromColumns; + } - public void setFromColumns(List columns) { - this.fromColumns = columns; - } + public void setFromColumns(List columns) { + this.fromColumns = columns; + } - @Override - public List getToColumns() { - return this.toColumns; - } + @Override + public List getToColumns() { + return this.toColumns; + } - public void setToColumns(List columns) { - this.toColumns = columns; - } + public void setToColumns(List columns) { + this.toColumns = columns; + } - @Override - public boolean equals(Object obj) { - CanonicalRelationship that = (CanonicalRelationship) obj; - if (this.foreignEntity.equals(that.getForeignEntity()) && this.parentEntity.equals(that.getParentEntity())) { - if (this.fromColumns.equals(that.getFromColumns()) && this.toColumns.equals(that.getToColumns())) { - return true; - } - } - return false; + @Override + public boolean equals(Object obj) { + CanonicalRelationship that = (CanonicalRelationship) obj; + if (this.foreignEntity.equals(that.getForeignEntity()) + && this.parentEntity.equals(that.getParentEntity())) { + if (this.fromColumns.equals(that.getFromColumns()) + && this.toColumns.equals(that.getToColumns())) { + return true; + } } + return false; + } - @Override - public String toString() { - String fromColumns = "["; - for (Attribute attribute : this.fromColumns) { - fromColumns += attribute.getName() + ","; - } - fromColumns = fromColumns.substring(0, fromColumns.length() - 1); - fromColumns += "]"; - - String toColumns = "["; - for (Attribute attribute : this.toColumns) { - toColumns += attribute.getName() + ","; - } - toColumns = toColumns.substring(0, toColumns.length() - 1); - toColumns += "]"; + @Override + public String toString() { + String fromColumns = "["; + for (Attribute attribute : this.fromColumns) { + fromColumns += attribute.getName() + ","; + } + fromColumns = fromColumns.substring(0, fromColumns.length() - 1); + fromColumns += "]"; - return ( - "LogicalRelationship [foreignEntity=" + - foreignEntity.getName() + - ", parentEntity=" + - parentEntity.getName() + - ", From Columns=" + - fromColumns + - ", To Columns=" + - toColumns + - " ]" - ); + String toColumns = "["; + for (Attribute attribute : this.toColumns) { + toColumns += attribute.getName() + ","; } + toColumns = toColumns.substring(0, toColumns.length() - 1); + toColumns += "]"; + + return ("LogicalRelationship [foreignEntity=" + + foreignEntity.getName() + + ", parentEntity=" + + parentEntity.getName() + + ", From Columns=" + + fromColumns + + ", To Columns=" + + toColumns + + " ]"); + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/PrimaryKey.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/PrimaryKey.java index 4508c7f1..f08ed71a 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/PrimaryKey.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/PrimaryKey.java @@ -27,20 +27,19 @@ * * @author Gabriele Ponzi */ - public class PrimaryKey extends Key { - public PrimaryKey(Entity belongingEntity, List involvedAttributes) { - super(belongingEntity, involvedAttributes); - } + public PrimaryKey(Entity belongingEntity, List involvedAttributes) { + super(belongingEntity, involvedAttributes); + } - public Attribute getAttributeByOrdinalPosition(int ordinalPosition) { - // overflow - if (ordinalPosition > super.getInvolvedAttributes().size()) return null; + public Attribute getAttributeByOrdinalPosition(int ordinalPosition) { + // overflow + if (ordinalPosition > super.getInvolvedAttributes().size()) return null; - for (Attribute attribute : super.involvedAttributes) { - if (attribute.getOrdinalPosition() == ordinalPosition) return attribute; - } - return null; + for (Attribute attribute : super.involvedAttributes) { + if (attribute.getOrdinalPosition() == ordinalPosition) return attribute; } + return null; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/Relationship.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/Relationship.java index bb56ee0a..cdfadca3 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/Relationship.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/Relationship.java @@ -27,39 +27,38 @@ * * @author Gabriele Ponzi */ - public abstract class Relationship { - protected Entity foreignEntity; // Entity importing the key (starting entity) - protected Entity parentEntity; // Entity exporting the key (arrival entity) - protected String direction; // represents the direction of the relationship + protected Entity foreignEntity; // Entity importing the key (starting entity) + protected Entity parentEntity; // Entity exporting the key (arrival entity) + protected String direction; // represents the direction of the relationship - public Entity getForeignEntity() { - return this.foreignEntity; - } + public Entity getForeignEntity() { + return this.foreignEntity; + } - public Entity getParentEntity() { - return this.parentEntity; - } + public Entity getParentEntity() { + return this.parentEntity; + } - public String getDirection() { - return this.direction; - } + public String getDirection() { + return this.direction; + } - public void setDirection(String direction) { - this.direction = direction; - } + public void setDirection(String direction) { + this.direction = direction; + } - public abstract List getFromColumns(); + public abstract List getFromColumns(); - public abstract List getToColumns(); + public abstract List getToColumns(); - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((foreignEntity == null) ? 0 : foreignEntity.hashCode()); - result = prime * result + ((parentEntity == null) ? 0 : parentEntity.hashCode()); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((foreignEntity == null) ? 0 : foreignEntity.hashCode()); + result = prime * result + ((parentEntity == null) ? 0 : parentEntity.hashCode()); + return result; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/SourceDatabaseInfo.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/SourceDatabaseInfo.java index cdaa5731..4be10d06 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/SourceDatabaseInfo.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/dbschema/SourceDatabaseInfo.java @@ -23,104 +23,115 @@ import java.util.LinkedHashMap; import java.util.Map; -/** - * Represents a source database with all its related info for accessing it. - */ - +/** Represents a source database with all its related info for accessing it. */ public class SourceDatabaseInfo { - private final String sourceId; - private final String sourceDBName; - private final String sourceRDBMS; - private final String driverName; - private final String url; - private final String username; - private final String password; - private final Map connectionProperties; - - private int maxRowsThreshold; - - public SourceDatabaseInfo(String sourceId, String sourceDBName, String sourceRDBMS, String driverName, String url, String username, String password) { - this(sourceId, sourceDBName, sourceRDBMS, driverName, url, username, password, new LinkedHashMap()); - } - - public SourceDatabaseInfo( - String sourceId, - String sourceDBName, - String sourceRDBMS, - String driverName, - String url, - String username, - String password, - Map connectionProperties - ) { - this.sourceId = sourceId; - this.sourceDBName = sourceDBName; - this.sourceRDBMS = sourceRDBMS; - this.driverName = driverName; - this.url = url; - this.username = username; - this.password = password; - this.connectionProperties = connectionProperties; - } - - public String getSourceId() { - return this.sourceId; - } - - public String getSourceDBName() { - return sourceDBName; - } - - public String getSourceRDBMS() { - return sourceRDBMS; - } - - public String getDriverName() { - return this.driverName; - } - - public String getUrl() { - return this.url; - } - - public String getUsername() { - return this.username; - } - - public String getPassword() { - return this.password; - } - - public Map getConnectionProperties() { - return connectionProperties; - } - - public int getMaxRowsThreshold() { - return this.maxRowsThreshold; - } - - public void setMaxRowsThreshold(int maxRowsThreshold) { - this.maxRowsThreshold = maxRowsThreshold; - } - - @Override - public int hashCode() { - int result = sourceId.hashCode(); - result = 31 * result + driverName.hashCode(); - result = 31 * result + url.hashCode(); - return result; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - SourceDatabaseInfo that = (SourceDatabaseInfo) o; - - if (!sourceId.equals(that.sourceId)) return false; - if (!driverName.equals(that.driverName)) return false; - return url.equals(that.url); - } + private final String sourceId; + private final String sourceDBName; + private final String sourceRDBMS; + private final String driverName; + private final String url; + private final String username; + private final String password; + private final Map connectionProperties; + + private int maxRowsThreshold; + + public SourceDatabaseInfo( + String sourceId, + String sourceDBName, + String sourceRDBMS, + String driverName, + String url, + String username, + String password) { + this( + sourceId, + sourceDBName, + sourceRDBMS, + driverName, + url, + username, + password, + new LinkedHashMap()); + } + + public SourceDatabaseInfo( + String sourceId, + String sourceDBName, + String sourceRDBMS, + String driverName, + String url, + String username, + String password, + Map connectionProperties) { + this.sourceId = sourceId; + this.sourceDBName = sourceDBName; + this.sourceRDBMS = sourceRDBMS; + this.driverName = driverName; + this.url = url; + this.username = username; + this.password = password; + this.connectionProperties = connectionProperties; + } + + public String getSourceId() { + return this.sourceId; + } + + public String getSourceDBName() { + return sourceDBName; + } + + public String getSourceRDBMS() { + return sourceRDBMS; + } + + public String getDriverName() { + return this.driverName; + } + + public String getUrl() { + return this.url; + } + + public String getUsername() { + return this.username; + } + + public String getPassword() { + return this.password; + } + + public Map getConnectionProperties() { + return connectionProperties; + } + + public int getMaxRowsThreshold() { + return this.maxRowsThreshold; + } + + public void setMaxRowsThreshold(int maxRowsThreshold) { + this.maxRowsThreshold = maxRowsThreshold; + } + + @Override + public int hashCode() { + int result = sourceId.hashCode(); + result = 31 * result + driverName.hashCode(); + result = 31 * result + url.hashCode(); + return result; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + SourceDatabaseInfo that = (SourceDatabaseInfo) o; + + if (!sourceId.equals(that.sourceId)) return false; + if (!driverName.equals(that.driverName)) return false; + return url.equals(that.url); + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/graphmodel/EdgeType.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/graphmodel/EdgeType.java index b44febd8..774cdcd9 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/graphmodel/EdgeType.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/graphmodel/EdgeType.java @@ -21,136 +21,137 @@ */ /** - * It represents an Orient class of a specific type that extends the Orient Edge Class. - * It's a simple edge-type in the graph model. + * It represents an Orient class of a specific type that extends the Orient Edge Class. It's a + * simple edge-type in the graph model. * * @author Gabriele Ponzi */ - public class EdgeType extends ElementType { - private VertexType inVertexType; - private VertexType outVertexType; - private int numberRelationshipsRepresented; // the number of relationships represented by the edge - private boolean isSplittingEdge; - private boolean isAggregatorEdge; - - public EdgeType(String edgeType) { - super(edgeType); - this.numberRelationshipsRepresented = 1; - this.isSplittingEdge = false; - } - - public EdgeType(String edgeType, VertexType outVertexType, VertexType inVertexType) { - super(edgeType); - this.outVertexType = outVertexType; - this.inVertexType = inVertexType; - numberRelationshipsRepresented = 1; - this.isSplittingEdge = false; - this.isAggregatorEdge = false; - } - - public EdgeType( - String edgeType, - VertexType outVertexType, - VertexType inVertexType, - int numberRelationshipsRepresented, - boolean isSplittingEdge, - boolean isAggregatorEdge - ) { - super(edgeType); - this.outVertexType = outVertexType; - this.inVertexType = inVertexType; - this.numberRelationshipsRepresented = numberRelationshipsRepresented; - this.isSplittingEdge = isSplittingEdge; - this.isAggregatorEdge = isAggregatorEdge; - } - - public VertexType getInVertexType() { - return this.inVertexType; - } - - public void setInVertexType(VertexType inVertexType) { - this.inVertexType = inVertexType; - } - - public VertexType getOutVertexType() { - return outVertexType; - } - - public void setOutVertexType(VertexType outVertexType) { - this.outVertexType = outVertexType; - } - - public int getNumberRelationshipsRepresented() { - return this.numberRelationshipsRepresented; - } - - public void setNumberRelationshipsRepresented(int numberRelationshipsRepresented) { - this.numberRelationshipsRepresented = numberRelationshipsRepresented; - } - - public boolean isSplittingEdge() { - return this.isSplittingEdge; - } - - public void setSplittingEdge(boolean splittingEdge) { - isSplittingEdge = splittingEdge; - } - - public boolean isAggregatorEdge() { - return isAggregatorEdge; - } - - public void setIsAggregatorEdge(boolean aggregatorEdge) { - isAggregatorEdge = aggregatorEdge; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((super.name == null) ? 0 : super.name.hashCode()); - result = prime * result + ((inVertexType == null) ? 0 : inVertexType.hashCode()); - result = prime * result + ((outVertexType == null) ? 0 : outVertexType.hashCode()); - result = prime * result + ((properties == null) ? 0 : properties.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - EdgeType that = (EdgeType) obj; - - // check on type and in/out vertex - if (!(super.name.equals(that.getName()) && this.inVertexType.getName().equals(that.getInVertexType().getName()))) return false; - - // check on properties - for (ModelProperty currentProperty : this.properties) { - if (!(that.getProperties().contains(currentProperty))) return false; - } - - return true; - } - - public String toString() { - String s = ""; - - if (this.outVertexType != null && this.inVertexType != null) s = - "Edge-type [type = " + - super.name + - ", out-vertex-type = " + - this.getOutVertexType().getName() + - ", in-vertex-type = " + - this.getInVertexType().getName() + - " ]"; else s = "Edge-type [type = " + super.name + " ]"; - - if (this.properties.size() > 0) { - s += "\nEdge's properties (" + this.properties.size() + "):\n"; - for (ModelProperty property : this.properties) { - s += property.getName() + " --> " + property.toString() + "\n"; - } - } - s += "\n"; - return s; - } + private VertexType inVertexType; + private VertexType outVertexType; + private int numberRelationshipsRepresented; // the number of relationships represented by the edge + private boolean isSplittingEdge; + private boolean isAggregatorEdge; + + public EdgeType(String edgeType) { + super(edgeType); + this.numberRelationshipsRepresented = 1; + this.isSplittingEdge = false; + } + + public EdgeType(String edgeType, VertexType outVertexType, VertexType inVertexType) { + super(edgeType); + this.outVertexType = outVertexType; + this.inVertexType = inVertexType; + numberRelationshipsRepresented = 1; + this.isSplittingEdge = false; + this.isAggregatorEdge = false; + } + + public EdgeType( + String edgeType, + VertexType outVertexType, + VertexType inVertexType, + int numberRelationshipsRepresented, + boolean isSplittingEdge, + boolean isAggregatorEdge) { + super(edgeType); + this.outVertexType = outVertexType; + this.inVertexType = inVertexType; + this.numberRelationshipsRepresented = numberRelationshipsRepresented; + this.isSplittingEdge = isSplittingEdge; + this.isAggregatorEdge = isAggregatorEdge; + } + + public VertexType getInVertexType() { + return this.inVertexType; + } + + public void setInVertexType(VertexType inVertexType) { + this.inVertexType = inVertexType; + } + + public VertexType getOutVertexType() { + return outVertexType; + } + + public void setOutVertexType(VertexType outVertexType) { + this.outVertexType = outVertexType; + } + + public int getNumberRelationshipsRepresented() { + return this.numberRelationshipsRepresented; + } + + public void setNumberRelationshipsRepresented(int numberRelationshipsRepresented) { + this.numberRelationshipsRepresented = numberRelationshipsRepresented; + } + + public boolean isSplittingEdge() { + return this.isSplittingEdge; + } + + public void setSplittingEdge(boolean splittingEdge) { + isSplittingEdge = splittingEdge; + } + + public boolean isAggregatorEdge() { + return isAggregatorEdge; + } + + public void setIsAggregatorEdge(boolean aggregatorEdge) { + isAggregatorEdge = aggregatorEdge; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((super.name == null) ? 0 : super.name.hashCode()); + result = prime * result + ((inVertexType == null) ? 0 : inVertexType.hashCode()); + result = prime * result + ((outVertexType == null) ? 0 : outVertexType.hashCode()); + result = prime * result + ((properties == null) ? 0 : properties.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + EdgeType that = (EdgeType) obj; + + // check on type and in/out vertex + if (!(super.name.equals(that.getName()) + && this.inVertexType.getName().equals(that.getInVertexType().getName()))) return false; + + // check on properties + for (ModelProperty currentProperty : this.properties) { + if (!(that.getProperties().contains(currentProperty))) return false; + } + + return true; + } + + public String toString() { + String s = ""; + + if (this.outVertexType != null && this.inVertexType != null) + s = + "Edge-type [type = " + + super.name + + ", out-vertex-type = " + + this.getOutVertexType().getName() + + ", in-vertex-type = " + + this.getInVertexType().getName() + + " ]"; + else s = "Edge-type [type = " + super.name + " ]"; + + if (this.properties.size() > 0) { + s += "\nEdge's properties (" + this.properties.size() + "):\n"; + for (ModelProperty property : this.properties) { + s += property.getName() + " --> " + property.toString() + "\n"; + } + } + s += "\n"; + return s; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/graphmodel/ElementType.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/graphmodel/ElementType.java index 6930a895..71bae30c 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/graphmodel/ElementType.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/graphmodel/ElementType.java @@ -27,129 +27,127 @@ import java.util.Set; /** - * It represents an Orient class. It could be a Vertex-Type or an Edge-Type in - * the graph model. + * It represents an Orient class. It could be a Vertex-Type or an Edge-Type in the graph model. * * @author Gabriele Ponzi */ - public class ElementType implements Comparable { - protected String name; - protected List properties; - protected List inheritedProperties; - protected Set allProperties; - protected ElementType parentType; - protected int inheritanceLevel; - - public ElementType(String type) { - this.name = type; - this.properties = new LinkedList<>(); - this.inheritedProperties = new LinkedList<>(); - this.allProperties = null; - } - - public String getName() { - return this.name; - } - - public void setName(String type) { - this.name = type; - } - - public List getProperties() { - return this.properties; - } - - public void setProperties(List properties) { - this.properties = properties; - } - - public List getInheritedProperties() { - return this.inheritedProperties; - } - - public void setInheritedProperties(List inheritedProperties) { - this.inheritedProperties = inheritedProperties; - } - - public ElementType getParentType() { - return this.parentType; - } - - public void setParentType(ElementType parentType) { - this.parentType = parentType; - } - - public int getInheritanceLevel() { - return this.inheritanceLevel; - } - - public void setInheritanceLevel(int inheritanceLevel) { - this.inheritanceLevel = inheritanceLevel; - } - - public ModelProperty getPropertyByOrdinalPosition(int position) { - for (ModelProperty property : this.properties) { - if (property.getOrdinalPosition() == position) { - return property; - } - } - return null; - } - - public void removePropertyByName(String toRemove) { - Iterator it = this.properties.iterator(); - ModelProperty currentProperty = null; - - while (it.hasNext()) { - currentProperty = it.next(); - if (currentProperty.getName().equals(toRemove)) it.remove(); - } - } - - public ModelProperty getPropertyByName(String name) { - for (ModelProperty property : this.properties) { - if (property.getName().equals(name)) { - return property; - } - } - return null; - } - - public ModelProperty getInheritedPropertyByName(String name) { - for (ModelProperty property : this.inheritedProperties) { - if (property.getName().equals(name)) { - return property; - } - } - return null; - } - - public ModelProperty getPropertyByNameAmongAll(String name) { - for (ModelProperty property : this.getAllProperties()) { - if (property.getName().equals(name)) { - return property; - } - } - return null; - } - - // Returns properties and inherited properties - public Set getAllProperties() { - if (allProperties == null) { - allProperties = new LinkedHashSet(); - allProperties.addAll(this.inheritedProperties); - allProperties.addAll(this.properties); - } - - return allProperties; - } - - @Override - public int compareTo(ElementType toCompare) { - if (this.inheritanceLevel > toCompare.getInheritanceLevel()) return 1; else if ( - this.inheritanceLevel < toCompare.getInheritanceLevel() - ) return -1; else return this.name.compareTo(toCompare.getName()); - } + protected String name; + protected List properties; + protected List inheritedProperties; + protected Set allProperties; + protected ElementType parentType; + protected int inheritanceLevel; + + public ElementType(String type) { + this.name = type; + this.properties = new LinkedList<>(); + this.inheritedProperties = new LinkedList<>(); + this.allProperties = null; + } + + public String getName() { + return this.name; + } + + public void setName(String type) { + this.name = type; + } + + public List getProperties() { + return this.properties; + } + + public void setProperties(List properties) { + this.properties = properties; + } + + public List getInheritedProperties() { + return this.inheritedProperties; + } + + public void setInheritedProperties(List inheritedProperties) { + this.inheritedProperties = inheritedProperties; + } + + public ElementType getParentType() { + return this.parentType; + } + + public void setParentType(ElementType parentType) { + this.parentType = parentType; + } + + public int getInheritanceLevel() { + return this.inheritanceLevel; + } + + public void setInheritanceLevel(int inheritanceLevel) { + this.inheritanceLevel = inheritanceLevel; + } + + public ModelProperty getPropertyByOrdinalPosition(int position) { + for (ModelProperty property : this.properties) { + if (property.getOrdinalPosition() == position) { + return property; + } + } + return null; + } + + public void removePropertyByName(String toRemove) { + Iterator it = this.properties.iterator(); + ModelProperty currentProperty = null; + + while (it.hasNext()) { + currentProperty = it.next(); + if (currentProperty.getName().equals(toRemove)) it.remove(); + } + } + + public ModelProperty getPropertyByName(String name) { + for (ModelProperty property : this.properties) { + if (property.getName().equals(name)) { + return property; + } + } + return null; + } + + public ModelProperty getInheritedPropertyByName(String name) { + for (ModelProperty property : this.inheritedProperties) { + if (property.getName().equals(name)) { + return property; + } + } + return null; + } + + public ModelProperty getPropertyByNameAmongAll(String name) { + for (ModelProperty property : this.getAllProperties()) { + if (property.getName().equals(name)) { + return property; + } + } + return null; + } + + // Returns properties and inherited properties + public Set getAllProperties() { + if (allProperties == null) { + allProperties = new LinkedHashSet(); + allProperties.addAll(this.inheritedProperties); + allProperties.addAll(this.properties); + } + + return allProperties; + } + + @Override + public int compareTo(ElementType toCompare) { + if (this.inheritanceLevel > toCompare.getInheritanceLevel()) return 1; + else if (this.inheritanceLevel < toCompare.getInheritanceLevel()) return -1; + else return this.name.compareTo(toCompare.getName()); + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/graphmodel/GraphModel.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/graphmodel/GraphModel.java index 48c243f6..f82d5fe5 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/graphmodel/GraphModel.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/graphmodel/GraphModel.java @@ -29,122 +29,136 @@ * * @author Gabriele Ponzi */ - public class GraphModel { - private List verticesType; - private List edgesType; + private List verticesType; + private List edgesType; - public GraphModel() { - this.verticesType = new ArrayList<>(); - this.edgesType = new ArrayList<>(); - } + public GraphModel() { + this.verticesType = new ArrayList<>(); + this.edgesType = new ArrayList<>(); + } - public VertexType getVertexTypeByName(String name) { - VertexType vertex = null; + public VertexType getVertexTypeByName(String name) { + VertexType vertex = null; - for (VertexType currentVertex : this.verticesType) { - if (currentVertex.getName().equals(name)) { - vertex = currentVertex; - break; - } - } - return vertex; + for (VertexType currentVertex : this.verticesType) { + if (currentVertex.getName().equals(name)) { + vertex = currentVertex; + break; + } } + return vertex; + } - public VertexType getVertexTypeByNameIgnoreCase(String name) { - VertexType vertex = null; + public VertexType getVertexTypeByNameIgnoreCase(String name) { + VertexType vertex = null; - for (VertexType currentVertex : this.verticesType) { - if (currentVertex.getName().equalsIgnoreCase(name)) { - vertex = currentVertex; - break; - } - } - return vertex; + for (VertexType currentVertex : this.verticesType) { + if (currentVertex.getName().equalsIgnoreCase(name)) { + vertex = currentVertex; + break; + } } - - public List getVerticesType() { - return this.verticesType; + return vertex; + } + + public List getVerticesType() { + return this.verticesType; + } + + public List getEdgesType() { + return this.edgesType; + } + + public EdgeType getEdgeTypeByName(String name) { + for (EdgeType currentEdgetype : this.edgesType) { + if (currentEdgetype.getName().equals(name)) { + return currentEdgetype; + } } - - public List getEdgesType() { - return this.edgesType; + return null; + } + + public EdgeType getEdgeTypeByNameIgnoreCase(String name) { + for (EdgeType currentEdgetype : this.edgesType) { + if (currentEdgetype.getName().equalsIgnoreCase(name)) { + return currentEdgetype; + } } - - public EdgeType getEdgeTypeByName(String name) { - for (EdgeType currentEdgetype : this.edgesType) { - if (currentEdgetype.getName().equals(name)) { - return currentEdgetype; - } + return null; + } + + public boolean removeVertexTypeByName(String vertexName) { + Iterator iterator = this.verticesType.iterator(); + + while (iterator.hasNext()) { + VertexType currVertexType = iterator.next(); + if (currVertexType.getName().equals(vertexName)) { + // removing references from the in edges + for (EdgeType currInEdgeType : currVertexType.getInEdgesType()) { + currInEdgeType.setInVertexType(null); } - return null; - } - public EdgeType getEdgeTypeByNameIgnoreCase(String name) { - for (EdgeType currentEdgetype : this.edgesType) { - if (currentEdgetype.getName().equalsIgnoreCase(name)) { - return currentEdgetype; - } - } - return null; + // removing the vertex + iterator.remove(); + return true; + } } - - public boolean removeVertexTypeByName(String vertexName) { - Iterator iterator = this.verticesType.iterator(); - - while (iterator.hasNext()) { - VertexType currVertexType = iterator.next(); - if (currVertexType.getName().equals(vertexName)) { - // removing references from the in edges - for (EdgeType currInEdgeType : currVertexType.getInEdgesType()) { - currInEdgeType.setInVertexType(null); - } - - // removing the vertex - iterator.remove(); - return true; - } - } - return false; + return false; + } + + public boolean removeEdgeTypeByName(String vertexName) { + Iterator iterator = this.edgesType.iterator(); + + while (iterator.hasNext()) { + EdgeType currEdgeType = iterator.next(); + if (currEdgeType.getName().equals(vertexName)) { + iterator.remove(); + return true; + } } - - public boolean removeEdgeTypeByName(String vertexName) { - Iterator iterator = this.edgesType.iterator(); - - while (iterator.hasNext()) { - EdgeType currEdgeType = iterator.next(); - if (currEdgeType.getName().equals(vertexName)) { - iterator.remove(); - return true; - } - } - return false; + return false; + } + + public String toString() { + String s = + "\n\n\n" + + "------------------------------ MODEL GRAPH DESCRIPTION" + + " ------------------------------\n\n\n"; + + s += + "Number of Vertex-type: " + + this.verticesType.size() + + ".\nNumber of Edge-type: " + + this.edgesType.size() + + ".\n\n"; + + // info about vertices + s += "Vertex-type:\n\n"; + for (VertexType v : this.verticesType) s += v.toString() + "\n\n"; + + s += "\n\n"; + + // info about edges + s += "Edge-type:\n\n"; + for (EdgeType e : this.edgesType) s += e.toString() + "\n"; + + s += "\n\n"; + + // graph structure + s += "Graph structure:\n\n"; + for (VertexType v : this.verticesType) { + for (EdgeType e : v.getOutEdgesType()) + s += + v.getName() + + " -----------[" + + e.getName() + + "]-----------> " + + e.getInVertexType().getName() + + "\n"; } - public String toString() { - String s = "\n\n\n------------------------------ MODEL GRAPH DESCRIPTION ------------------------------\n\n\n"; - - s += "Number of Vertex-type: " + this.verticesType.size() + ".\nNumber of Edge-type: " + this.edgesType.size() + ".\n\n"; - - // info about vertices - s += "Vertex-type:\n\n"; - for (VertexType v : this.verticesType) s += v.toString() + "\n\n"; - - s += "\n\n"; - - // info about edges - s += "Edge-type:\n\n"; - for (EdgeType e : this.edgesType) s += e.toString() + "\n"; - - s += "\n\n"; - - // graph structure - s += "Graph structure:\n\n"; - for (VertexType v : this.verticesType) { - for (EdgeType e : v.getOutEdgesType()) s += v.getName() + " -----------[" + e.getName() + "]-----------> " + e.getInVertexType().getName() + "\n"; - } - - return s; - } + return s; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/graphmodel/ModelProperty.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/graphmodel/ModelProperty.java index 115403eb..d6b858ad 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/graphmodel/ModelProperty.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/graphmodel/ModelProperty.java @@ -21,177 +21,182 @@ */ /** - * Class which holds all the attributes of a vertex property obtained from - * the transformation of an attribute belonging to an entity of the source DB schema. + * Class which holds all the attributes of a vertex property obtained from the transformation of an + * attribute belonging to an entity of the source DB schema. * * @author Gabriele Ponzi */ - public class ModelProperty { - private String name; - private int ordinalPosition; - private String originalType; - private String orientdbType; - private boolean fromPrimaryKey; - private ElementType belongingElementType; - private boolean includedInMigration; - - // costraints - private Boolean mandatory; - private Boolean readOnly; - private Boolean notNull; - - public ModelProperty(String name, int ordinalPosition, String originalType, boolean fromPrimaryKey, ElementType belongingElementType) { - this.name = name; - this.ordinalPosition = ordinalPosition; - this.originalType = originalType; - this.orientdbType = null; - this.fromPrimaryKey = fromPrimaryKey; - this.belongingElementType = belongingElementType; - this.includedInMigration = true; - } - - public ModelProperty( - String name, - int ordinalPosition, - String originalType, - String orientdbType, - boolean fromPrimaryKey, - ElementType belongingElementType, - boolean mandatory, - boolean readOnly, - boolean notNull - ) { - this.name = name; - this.ordinalPosition = ordinalPosition; - this.originalType = originalType; - this.orientdbType = orientdbType; - this.fromPrimaryKey = fromPrimaryKey; - this.belongingElementType = belongingElementType; - this.mandatory = mandatory; - this.readOnly = readOnly; - this.notNull = notNull; - this.includedInMigration = true; - } - - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - } - - public int getOrdinalPosition() { - return ordinalPosition; - } - - public void setOrdinalPosition(int ordinalPosition) { - this.ordinalPosition = ordinalPosition; - } - - public String getOriginalType() { - return this.originalType; - } - - public void setOriginalType(String attributeType) { - this.originalType = attributeType; - } - - public String getOrientdbType() { - return orientdbType; - } - - public void setOrientdbType(String orientdbType) { - this.orientdbType = orientdbType; - } - - public boolean isFromPrimaryKey() { - return this.fromPrimaryKey; - } - - public void setFromPrimaryKey(boolean fromPrimaryKey) { - this.fromPrimaryKey = fromPrimaryKey; - } - - public ElementType getBelongingElementType() { - return belongingElementType; - } - - public void setBelongingElementType(ElementType belongingElementType) { - this.belongingElementType = belongingElementType; - } - - public Boolean isMandatory() { - return this.mandatory; - } - - public void setMandatory(Boolean mandatory) { - this.mandatory = mandatory; - } - - public Boolean isReadOnly() { - return this.readOnly; - } - - public void setReadOnly(Boolean readOnly) { - this.readOnly = readOnly; - } - - public Boolean isNotNull() { - return this.notNull; - } - - public void setNotNull(Boolean notNull) { - this.notNull = notNull; - } - - public boolean isIncludedInMigration() { - return includedInMigration; - } - - public void setIncludedInMigration(boolean includedInMigration) { - this.includedInMigration = includedInMigration; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((originalType == null) ? 0 : originalType.hashCode()); - result = prime * result + (fromPrimaryKey ? 1231 : 1237); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ordinalPosition; - return result; - } - - @Override - public boolean equals(Object obj) { - ModelProperty that = (ModelProperty) obj; - if (!(this.name.equals(that.getName()) && this.ordinalPosition == that.getOrdinalPosition() && this.isFromPrimaryKey() == that.isFromPrimaryKey())) { - return false; - } - if (this.originalType != null && that.originalType != null) { - if (!this.originalType.equals(that.originalType)) { - return false; - } - } - if (this.orientdbType != null && that.orientdbType != null) { - if (!this.orientdbType.equals(that.orientdbType)) { - return false; - } - } - return true; - } - - public String toString() { - String s = ""; - if (this.orientdbType != null) { - s += this.ordinalPosition + ": " + this.name + " ( " + this.orientdbType + " )"; - } else { - s += this.ordinalPosition + ": " + this.name; - } - return s; - } + private String name; + private int ordinalPosition; + private String originalType; + private String orientdbType; + private boolean fromPrimaryKey; + private ElementType belongingElementType; + private boolean includedInMigration; + + // costraints + private Boolean mandatory; + private Boolean readOnly; + private Boolean notNull; + + public ModelProperty( + String name, + int ordinalPosition, + String originalType, + boolean fromPrimaryKey, + ElementType belongingElementType) { + this.name = name; + this.ordinalPosition = ordinalPosition; + this.originalType = originalType; + this.orientdbType = null; + this.fromPrimaryKey = fromPrimaryKey; + this.belongingElementType = belongingElementType; + this.includedInMigration = true; + } + + public ModelProperty( + String name, + int ordinalPosition, + String originalType, + String orientdbType, + boolean fromPrimaryKey, + ElementType belongingElementType, + boolean mandatory, + boolean readOnly, + boolean notNull) { + this.name = name; + this.ordinalPosition = ordinalPosition; + this.originalType = originalType; + this.orientdbType = orientdbType; + this.fromPrimaryKey = fromPrimaryKey; + this.belongingElementType = belongingElementType; + this.mandatory = mandatory; + this.readOnly = readOnly; + this.notNull = notNull; + this.includedInMigration = true; + } + + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + public int getOrdinalPosition() { + return ordinalPosition; + } + + public void setOrdinalPosition(int ordinalPosition) { + this.ordinalPosition = ordinalPosition; + } + + public String getOriginalType() { + return this.originalType; + } + + public void setOriginalType(String attributeType) { + this.originalType = attributeType; + } + + public String getOrientdbType() { + return orientdbType; + } + + public void setOrientdbType(String orientdbType) { + this.orientdbType = orientdbType; + } + + public boolean isFromPrimaryKey() { + return this.fromPrimaryKey; + } + + public void setFromPrimaryKey(boolean fromPrimaryKey) { + this.fromPrimaryKey = fromPrimaryKey; + } + + public ElementType getBelongingElementType() { + return belongingElementType; + } + + public void setBelongingElementType(ElementType belongingElementType) { + this.belongingElementType = belongingElementType; + } + + public Boolean isMandatory() { + return this.mandatory; + } + + public void setMandatory(Boolean mandatory) { + this.mandatory = mandatory; + } + + public Boolean isReadOnly() { + return this.readOnly; + } + + public void setReadOnly(Boolean readOnly) { + this.readOnly = readOnly; + } + + public Boolean isNotNull() { + return this.notNull; + } + + public void setNotNull(Boolean notNull) { + this.notNull = notNull; + } + + public boolean isIncludedInMigration() { + return includedInMigration; + } + + public void setIncludedInMigration(boolean includedInMigration) { + this.includedInMigration = includedInMigration; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((originalType == null) ? 0 : originalType.hashCode()); + result = prime * result + (fromPrimaryKey ? 1231 : 1237); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ordinalPosition; + return result; + } + + @Override + public boolean equals(Object obj) { + ModelProperty that = (ModelProperty) obj; + if (!(this.name.equals(that.getName()) + && this.ordinalPosition == that.getOrdinalPosition() + && this.isFromPrimaryKey() == that.isFromPrimaryKey())) { + return false; + } + if (this.originalType != null && that.originalType != null) { + if (!this.originalType.equals(that.originalType)) { + return false; + } + } + if (this.orientdbType != null && that.orientdbType != null) { + if (!this.orientdbType.equals(that.orientdbType)) { + return false; + } + } + return true; + } + + public String toString() { + String s = ""; + if (this.orientdbType != null) { + s += this.ordinalPosition + ": " + this.name + " ( " + this.orientdbType + " )"; + } else { + s += this.ordinalPosition + ": " + this.name; + } + return s; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/graphmodel/VertexType.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/graphmodel/VertexType.java index 84c78723..cbf93838 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/graphmodel/VertexType.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/model/graphmodel/VertexType.java @@ -27,143 +27,149 @@ import java.util.Set; /** - * It represents an Orient class of a specific type that extends the Orient Vertex Class. - * It's a simple vertex-type in the graph model. + * It represents an Orient class of a specific type that extends the Orient Vertex Class. It's a + * simple vertex-type in the graph model. * * @author Gabriele Ponzi */ - public class VertexType extends ElementType { - private List inEdgesType; - private List outEdgesType; - private boolean isFromJoinTable; - private Set externalKey; - private boolean analyzedInLastMigration; - - public VertexType(String vertexType) { - super(vertexType); - this.inEdgesType = new ArrayList(); - this.outEdgesType = new ArrayList(); - this.externalKey = new LinkedHashSet(); - this.analyzedInLastMigration = false; - } - - public List getInEdgesType() { - return this.inEdgesType; - } - - public void setInEdgesType(List inEdgesType) { - this.inEdgesType = inEdgesType; - } - - public List getOutEdgesType() { - return this.outEdgesType; - } - - public void setOutEdgesType(List outEdgesType) { - this.outEdgesType = outEdgesType; - } - - public Set getExternalKey() { - return this.externalKey; - } - - public void setExternalKey(Set externalKey) { - this.externalKey = externalKey; - } - - public boolean isAnalyzedInLastMigration() { - return this.analyzedInLastMigration; - } - - public void setAnalyzedInLastMigration(boolean analyzedInLastMigration) { - this.analyzedInLastMigration = analyzedInLastMigration; - } - - public EdgeType getEdgeByName(String edgeName) { - for (EdgeType currentEdgeType : this.inEdgesType) { - if (currentEdgeType.getName().equals(edgeName)) return currentEdgeType; - } + private List inEdgesType; + private List outEdgesType; + private boolean isFromJoinTable; + private Set externalKey; + private boolean analyzedInLastMigration; - for (EdgeType currentEdgeType : this.outEdgesType) { - if (currentEdgeType.getName().equals(edgeName)) return currentEdgeType; - } + public VertexType(String vertexType) { + super(vertexType); + this.inEdgesType = new ArrayList(); + this.outEdgesType = new ArrayList(); + this.externalKey = new LinkedHashSet(); + this.analyzedInLastMigration = false; + } - return null; - } - - public EdgeType getEdgeByName(String name, Direction direction) { - if (direction.equals(Direction.IN)) { - for (EdgeType currentEdgeType : this.inEdgesType) { - if (currentEdgeType.getName().equals(name)) return currentEdgeType; - } - } else if (direction.equals(Direction.OUT)) { - for (EdgeType currentEdgeType : this.outEdgesType) { - if (currentEdgeType.getName().equals(name)) return currentEdgeType; - } - } else if (direction.equals(Direction.BOTH)) { - return this.getEdgeByName(name); - } - - return null; - } - - public boolean isFromJoinTable() { - return this.isFromJoinTable; - } - - public void setFromJoinTable(boolean fromJoinTable) { - isFromJoinTable = fromJoinTable; - } - - public void setIsFromJoinTable(boolean isFromJoinTable) { - this.isFromJoinTable = isFromJoinTable; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((super.name == null) ? 0 : super.name.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - VertexType that = (VertexType) obj; - - // check on type and many-to-many variables - if (!(super.name.equals(that.getName()) && this.isFromJoinTable == that.isFromJoinTable())) return false; - - // check on properties - if (!(this.properties.equals(that.getProperties()))) return false; - - // in&out edges - if (!(this.inEdgesType.equals(that.getInEdgesType()) && this.outEdgesType.equals(that.getOutEdgesType()))) return false; - - return true; - } - - public String toString() { - String s = - "Vertex-type [type = " + - super.name + - ", # attributes = " + - this.properties.size() + - ", # inEdges: " + - this.inEdgesType.size() + - ", # outEdges: " + - this.outEdgesType.size() + - "]\nAttributes:\n"; - - for (ModelProperty currentProperty : this.properties) { - s += currentProperty.getOrdinalPosition() + ": " + currentProperty.getName() + " --> " + currentProperty.toString(); - - if (currentProperty.isFromPrimaryKey()) s += "(from PK)"; - - s += "\t"; - } - return s; - } + public List getInEdgesType() { + return this.inEdgesType; + } + + public void setInEdgesType(List inEdgesType) { + this.inEdgesType = inEdgesType; + } + + public List getOutEdgesType() { + return this.outEdgesType; + } + + public void setOutEdgesType(List outEdgesType) { + this.outEdgesType = outEdgesType; + } + + public Set getExternalKey() { + return this.externalKey; + } + + public void setExternalKey(Set externalKey) { + this.externalKey = externalKey; + } + + public boolean isAnalyzedInLastMigration() { + return this.analyzedInLastMigration; + } + + public void setAnalyzedInLastMigration(boolean analyzedInLastMigration) { + this.analyzedInLastMigration = analyzedInLastMigration; + } + + public EdgeType getEdgeByName(String edgeName) { + for (EdgeType currentEdgeType : this.inEdgesType) { + if (currentEdgeType.getName().equals(edgeName)) return currentEdgeType; + } + + for (EdgeType currentEdgeType : this.outEdgesType) { + if (currentEdgeType.getName().equals(edgeName)) return currentEdgeType; + } + + return null; + } + + public EdgeType getEdgeByName(String name, Direction direction) { + if (direction.equals(Direction.IN)) { + for (EdgeType currentEdgeType : this.inEdgesType) { + if (currentEdgeType.getName().equals(name)) return currentEdgeType; + } + } else if (direction.equals(Direction.OUT)) { + for (EdgeType currentEdgeType : this.outEdgesType) { + if (currentEdgeType.getName().equals(name)) return currentEdgeType; + } + } else if (direction.equals(Direction.BOTH)) { + return this.getEdgeByName(name); + } + + return null; + } + + public boolean isFromJoinTable() { + return this.isFromJoinTable; + } + + public void setFromJoinTable(boolean fromJoinTable) { + isFromJoinTable = fromJoinTable; + } + + public void setIsFromJoinTable(boolean isFromJoinTable) { + this.isFromJoinTable = isFromJoinTable; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((super.name == null) ? 0 : super.name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + VertexType that = (VertexType) obj; + + // check on type and many-to-many variables + if (!(super.name.equals(that.getName()) && this.isFromJoinTable == that.isFromJoinTable())) + return false; + + // check on properties + if (!(this.properties.equals(that.getProperties()))) return false; + + // in&out edges + if (!(this.inEdgesType.equals(that.getInEdgesType()) + && this.outEdgesType.equals(that.getOutEdgesType()))) return false; + + return true; + } + + public String toString() { + String s = + "Vertex-type [type = " + + super.name + + ", # attributes = " + + this.properties.size() + + ", # inEdges: " + + this.inEdgesType.size() + + ", # outEdges: " + + this.outEdgesType.size() + + "]\nAttributes:\n"; + + for (ModelProperty currentProperty : this.properties) { + s += + currentProperty.getOrdinalPosition() + + ": " + + currentProperty.getName() + + " --> " + + currentProperty.toString(); + + if (currentProperty.isFromPrimaryKey()) s += "(from PK)"; + + s += "\t"; + } + return s; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/nameresolver/JavaConventionNameResolver.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/nameresolver/JavaConventionNameResolver.java index 519df2bc..32048a61 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/nameresolver/JavaConventionNameResolver.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/nameresolver/JavaConventionNameResolver.java @@ -27,180 +27,199 @@ import org.apache.commons.lang3.StringUtils; /** - * Implementation of NameResolver that performs name transformations on the elements - * of the data source according to the Java convention. + * Implementation of NameResolver that performs name transformations on the elements of the data + * source according to the Java convention. * * @author Gabriele Ponzi */ - public class JavaConventionNameResolver implements NameResolver { - @Override - public String resolveVertexName(String candidateName) { - if (isCompliantToJavaClassConvention(candidateName)) { - return candidateName; - } else { - candidateName = toJavaClassConvention(candidateName); + @Override + public String resolveVertexName(String candidateName) { + if (isCompliantToJavaClassConvention(candidateName)) { + return candidateName; + } else { + candidateName = toJavaClassConvention(candidateName); - return candidateName; - } + return candidateName; } + } - @Override - public String resolveVertexProperty(String candidateName) { - if (isCompliantToJavaVariableConvention(candidateName)) { - return candidateName; - } else { - candidateName = this.toJavaVariableConvention(candidateName); + @Override + public String resolveVertexProperty(String candidateName) { + if (isCompliantToJavaVariableConvention(candidateName)) { + return candidateName; + } else { + candidateName = this.toJavaVariableConvention(candidateName); - return candidateName; - } + return candidateName; } - - @Override - public String resolveEdgeName(CanonicalRelationship relationship) { - String finalName; - - // Foreign Key composed of 1 attribute - if (relationship.getFromColumns().size() == 1) { - String columnName = relationship.getFromColumns().get(0).getName(); - columnName = columnName.replace("_id", ""); - columnName = columnName.replace("_ID", ""); - columnName = columnName.replace("_oid", ""); - columnName = columnName.replace("_OID", ""); - columnName = columnName.replace("_eid", ""); - columnName = columnName.replace("_EID", ""); - - if (!this.isCompliantToJavaClassConvention(columnName)) { - // manipulating name (Java Convention) - columnName = this.toJavaClassConvention(columnName); - } - - finalName = "Has" + columnName; - } - // Foreign Key composed of multiple attribute - else { - finalName = - this.toJavaClassConvention(relationship.getForeignEntity().getName()) + - "2" + - this.toJavaClassConvention(relationship.getParentEntity().getName()); - } - - return finalName; + } + + @Override + public String resolveEdgeName(CanonicalRelationship relationship) { + String finalName; + + // Foreign Key composed of 1 attribute + if (relationship.getFromColumns().size() == 1) { + String columnName = relationship.getFromColumns().get(0).getName(); + columnName = columnName.replace("_id", ""); + columnName = columnName.replace("_ID", ""); + columnName = columnName.replace("_oid", ""); + columnName = columnName.replace("_OID", ""); + columnName = columnName.replace("_eid", ""); + columnName = columnName.replace("_EID", ""); + + if (!this.isCompliantToJavaClassConvention(columnName)) { + // manipulating name (Java Convention) + columnName = this.toJavaClassConvention(columnName); + } + + finalName = "Has" + columnName; + } + // Foreign Key composed of multiple attribute + else { + finalName = + this.toJavaClassConvention(relationship.getForeignEntity().getName()) + + "2" + + this.toJavaClassConvention(relationship.getParentEntity().getName()); } - public String toJavaClassConvention(String name) { - // if all chars are uppercase, then name is transformed in a lowercase version + return finalName; + } - boolean allUpperCase = true; - for (int i = 0; i < name.length(); i++) { - if (Character.isLowerCase(name.charAt(i))) { - allUpperCase = false; - break; - } - } + public String toJavaClassConvention(String name) { + // if all chars are uppercase, then name is transformed in a lowercase version - if (allUpperCase) { - name = name.toLowerCase(Locale.ENGLISH); - } + boolean allUpperCase = true; + for (int i = 0; i < name.length(); i++) { + if (Character.isLowerCase(name.charAt(i))) { + allUpperCase = false; + break; + } + } - if (name.contains(" ")) { - int pos; - while (name.contains(" ")) { - pos = name.indexOf(" "); - name = name.substring(0, pos) + (name.charAt(pos + 1) + "").toUpperCase(Locale.ENGLISH) + name.substring(pos + 2); - } - } + if (allUpperCase) { + name = name.toLowerCase(Locale.ENGLISH); + } - if (name.contains("_")) { - int pos; - while (name.contains("_")) { - pos = name.indexOf("_"); - if (pos < name.length() - 1) { - // the '_' char is not in last position - name = name.substring(0, pos) + (name.charAt(pos + 1) + "").toUpperCase(Locale.ENGLISH) + name.substring(pos + 2); - } else { - // the '_' char is in last position - name = name.substring(0, name.length() - 1); - } - } - } + if (name.contains(" ")) { + int pos; + while (name.contains(" ")) { + pos = name.indexOf(" "); + name = + name.substring(0, pos) + + (name.charAt(pos + 1) + "").toUpperCase(Locale.ENGLISH) + + name.substring(pos + 2); + } + } - if (name.contains("-")) { - int pos; - while (name.contains("-")) { - pos = name.indexOf("-"); - name = name.substring(0, pos) + (name.charAt(pos + 1) + "").toUpperCase(Locale.ENGLISH) + name.substring(pos + 2); - } + if (name.contains("_")) { + int pos; + while (name.contains("_")) { + pos = name.indexOf("_"); + if (pos < name.length() - 1) { + // the '_' char is not in last position + name = + name.substring(0, pos) + + (name.charAt(pos + 1) + "").toUpperCase(Locale.ENGLISH) + + name.substring(pos + 2); + } else { + // the '_' char is in last position + name = name.substring(0, name.length() - 1); } + } + } - // First char must be uppercase - if (Character.isLowerCase(name.charAt(0))) name = name.substring(0, 1).toUpperCase(Locale.ENGLISH) + name.substring(1); - - return name; + if (name.contains("-")) { + int pos; + while (name.contains("-")) { + pos = name.indexOf("-"); + name = + name.substring(0, pos) + + (name.charAt(pos + 1) + "").toUpperCase(Locale.ENGLISH) + + name.substring(pos + 2); + } } - public String toJavaVariableConvention(String name) { - // if all chars are uppercase, then name is transformed in a lowercase version + // First char must be uppercase + if (Character.isLowerCase(name.charAt(0))) + name = name.substring(0, 1).toUpperCase(Locale.ENGLISH) + name.substring(1); - boolean allUpperCase = true; - for (int i = 0; i < name.length(); i++) { - if (Character.isLowerCase(name.charAt(i))) { - allUpperCase = false; - break; - } - } + return name; + } - if (allUpperCase) { - name = name.toLowerCase(Locale.ENGLISH); - } + public String toJavaVariableConvention(String name) { + // if all chars are uppercase, then name is transformed in a lowercase version - if (name.contains(SPACE)) { - int pos; - while (name.contains(SPACE)) { - pos = name.indexOf(SPACE); - name = name.substring(0, pos) + (name.charAt(pos + 1) + "").toUpperCase(Locale.ENGLISH) + name.substring(pos + 2); - } - } + boolean allUpperCase = true; + for (int i = 0; i < name.length(); i++) { + if (Character.isLowerCase(name.charAt(i))) { + allUpperCase = false; + break; + } + } - if (name.contains("_")) { - int pos; - while (name.contains("_")) { - pos = name.indexOf("_"); - name = name.substring(0, pos) + (name.charAt(pos + 1) + "").toUpperCase(Locale.ENGLISH) + name.substring(pos + 2); - } - } + if (allUpperCase) { + name = name.toLowerCase(Locale.ENGLISH); + } - if (name.contains("-")) { - int pos; - while (name.contains("-")) { - pos = name.indexOf("-"); - name = name.substring(0, pos) + (name.charAt(pos + 1) + "").toUpperCase(Locale.ENGLISH) + name.substring(pos + 2); - } - } + if (name.contains(SPACE)) { + int pos; + while (name.contains(SPACE)) { + pos = name.indexOf(SPACE); + name = + name.substring(0, pos) + + (name.charAt(pos + 1) + "").toUpperCase(Locale.ENGLISH) + + name.substring(pos + 2); + } + } - // First char must be lowercase - if (Character.isUpperCase(name.charAt(0))) name = name.substring(0, 1).toLowerCase(Locale.ENGLISH) + name.substring(1); + if (name.contains("_")) { + int pos; + while (name.contains("_")) { + pos = name.indexOf("_"); + name = + name.substring(0, pos) + + (name.charAt(pos + 1) + "").toUpperCase(Locale.ENGLISH) + + name.substring(pos + 2); + } + } - return name; + if (name.contains("-")) { + int pos; + while (name.contains("-")) { + pos = name.indexOf("-"); + name = + name.substring(0, pos) + + (name.charAt(pos + 1) + "").toUpperCase(Locale.ENGLISH) + + name.substring(pos + 2); + } } - public boolean isCompliantToJavaClassConvention(String candidateName) { - if (!(candidateName.contains(" ") || candidateName.contains("_") || candidateName.contains("-")) && Character.isUpperCase(candidateName.charAt(0))) { - if (StringUtils.isAllUpperCase(candidateName)) { - return false; - } + // First char must be lowercase + if (Character.isUpperCase(name.charAt(0))) + name = name.substring(0, 1).toLowerCase(Locale.ENGLISH) + name.substring(1); - return true; - } + return name; + } + + public boolean isCompliantToJavaClassConvention(String candidateName) { + if (!(candidateName.contains(" ") || candidateName.contains("_") || candidateName.contains("-")) + && Character.isUpperCase(candidateName.charAt(0))) { + if (StringUtils.isAllUpperCase(candidateName)) { return false; + } + + return true; } + return false; + } - public boolean isCompliantToJavaVariableConvention(String candidateName) { - if ( - !(candidateName.contains(" ") || candidateName.contains("_") || candidateName.contains("-")) && Character.isLowerCase(candidateName.charAt(0)) - ) return true; + public boolean isCompliantToJavaVariableConvention(String candidateName) { + if (!(candidateName.contains(" ") || candidateName.contains("_") || candidateName.contains("-")) + && Character.isLowerCase(candidateName.charAt(0))) return true; - return false; - } + return false; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/nameresolver/NameResolver.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/nameresolver/NameResolver.java index 57ef62bb..12ba3fc6 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/nameresolver/NameResolver.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/nameresolver/NameResolver.java @@ -23,16 +23,15 @@ import com.arcadeanalytics.provider.rdbms.model.dbschema.CanonicalRelationship; /** - * Interface that performs name transformations on the elements - * of the data source according to a specific convention. + * Interface that performs name transformations on the elements of the data source according to a + * specific convention. * * @author Gabriele Ponzi */ - public interface NameResolver { - String resolveVertexName(String candidateName); + String resolveVertexName(String candidateName); - String resolveVertexProperty(String candidateName); + String resolveVertexProperty(String candidateName); - String resolveEdgeName(CanonicalRelationship relationship); + String resolveEdgeName(CanonicalRelationship relationship); } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/nameresolver/OriginalConventionNameResolver.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/nameresolver/OriginalConventionNameResolver.java index 7034966a..f19760cd 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/nameresolver/OriginalConventionNameResolver.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/nameresolver/OriginalConventionNameResolver.java @@ -27,43 +27,45 @@ * * @author Gabriele Ponzi */ - public class OriginalConventionNameResolver implements NameResolver { - @Override - public String resolveVertexName(String candidateName) { - candidateName = candidateName.replace(" ", "_"); - return candidateName; - } - - @Override - public String resolveVertexProperty(String candidateName) { - candidateName = candidateName.replace(" ", "_"); - return candidateName; - } + @Override + public String resolveVertexName(String candidateName) { + candidateName = candidateName.replace(" ", "_"); + return candidateName; + } - @Override - public String resolveEdgeName(CanonicalRelationship relationship) { - String finalName; + @Override + public String resolveVertexProperty(String candidateName) { + candidateName = candidateName.replace(" ", "_"); + return candidateName; + } - // Foreign Key composed of 1 attribute - if (relationship.getFromColumns().size() == 1) { - String columnName = relationship.getFromColumns().get(0).getName(); - columnName = columnName.replace("_id", ""); - columnName = columnName.replace("_ID", ""); - columnName = columnName.replace("_oid", ""); - columnName = columnName.replace("_OID", ""); - columnName = columnName.replace("_eid", ""); - columnName = columnName.replace("_EID", ""); + @Override + public String resolveEdgeName(CanonicalRelationship relationship) { + String finalName; - // manipulating name (Java Convention) - finalName = "has_" + columnName; - } - // Foreign Key composed of multiple attribute - else { - finalName = relationship.getForeignEntity().getName() + "2" + relationship.getParentEntity().getName(); - } + // Foreign Key composed of 1 attribute + if (relationship.getFromColumns().size() == 1) { + String columnName = relationship.getFromColumns().get(0).getName(); + columnName = columnName.replace("_id", ""); + columnName = columnName.replace("_ID", ""); + columnName = columnName.replace("_oid", ""); + columnName = columnName.replace("_OID", ""); + columnName = columnName.replace("_eid", ""); + columnName = columnName.replace("_EID", ""); - return finalName; + // manipulating name (Java Convention) + finalName = "has_" + columnName; + } + // Foreign Key composed of multiple attribute + else { + finalName = + relationship.getForeignEntity().getName() + + "2" + + relationship.getParentEntity().getName(); } + + return finalName; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/handler/DBMSDataTypeHandler.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/handler/DBMSDataTypeHandler.java index 1ca2a07d..525e5367 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/handler/DBMSDataTypeHandler.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/handler/DBMSDataTypeHandler.java @@ -33,94 +33,93 @@ * * @author Gabriele Ponzi */ - public class DBMSDataTypeHandler { - protected final Logger log = LoggerFactory.getLogger(DBMSDataTypeHandler.class); - - public boolean jsonImplemented; - public boolean geospatialImplemented; - protected Map dbmsType2OrientType; - - public DBMSDataTypeHandler() { - this.dbmsType2OrientType = this.fillTypesMap(); - this.jsonImplemented = false; - this.geospatialImplemented = false; - } - - private Map fillTypesMap() { - Map dbmsType2OrientType = new HashMap(); - - /* - * Character Types - */ - dbmsType2OrientType.put("text", OType.STRING); - dbmsType2OrientType.put("character", OType.STRING); - dbmsType2OrientType.put("character varying", OType.STRING); - dbmsType2OrientType.put("char", OType.STRING); - dbmsType2OrientType.put("varchar", OType.STRING); - dbmsType2OrientType.put("varchar2", OType.STRING); - - /* - * Numeric Types - */ - dbmsType2OrientType.put("int2", OType.SHORT); - dbmsType2OrientType.put("int", OType.INTEGER); - dbmsType2OrientType.put("integer", OType.INTEGER); - dbmsType2OrientType.put("int4", OType.INTEGER); - dbmsType2OrientType.put("int8", OType.LONG); - dbmsType2OrientType.put("real", OType.LONG); - dbmsType2OrientType.put("float", OType.LONG); - dbmsType2OrientType.put("float4", OType.LONG); - dbmsType2OrientType.put("float8", OType.DOUBLE); - dbmsType2OrientType.put("double", OType.DOUBLE); - dbmsType2OrientType.put("double precision", OType.DOUBLE); - dbmsType2OrientType.put("numeric", OType.DECIMAL); - dbmsType2OrientType.put("decimal", OType.DECIMAL); - - /* - * Date/Time Types - */ - dbmsType2OrientType.put("date", OType.DATE); - dbmsType2OrientType.put("datetime", OType.DATETIME); - dbmsType2OrientType.put("timestamp", OType.DATETIME); - dbmsType2OrientType.put("timestamp with time zone", OType.DATETIME); - dbmsType2OrientType.put("timestamp with local time zone", OType.DATETIME); - - /* - * Boolean Type - */ - dbmsType2OrientType.put("boolean", OType.BOOLEAN); - dbmsType2OrientType.put("bool", OType.BOOLEAN); - - /* - * Binary Data Types - */ - dbmsType2OrientType.put("blob", OType.BINARY); - - /* - * User Defined Types (Object data types and object views) - */ - // TODO! in EMBEDDED - - return dbmsType2OrientType; - } - - public ODocument convertJSONToDocument(String currentProperty, String currentAttributeValue) { - ODocument document = new ODocument(currentProperty); - if (currentAttributeValue != null && currentAttributeValue.length() > 0) { - document.fromJSON(currentAttributeValue, "noMap"); - } - return document; - } - - public boolean isGeospatial(String currentOriginalType) { - // TODO Auto-generated method stub - return false; - } - - public String buildGeospatialQuery(Entity entity) { - // TODO Auto-generated method stub - return null; + protected final Logger log = LoggerFactory.getLogger(DBMSDataTypeHandler.class); + + public boolean jsonImplemented; + public boolean geospatialImplemented; + protected Map dbmsType2OrientType; + + public DBMSDataTypeHandler() { + this.dbmsType2OrientType = this.fillTypesMap(); + this.jsonImplemented = false; + this.geospatialImplemented = false; + } + + private Map fillTypesMap() { + Map dbmsType2OrientType = new HashMap(); + + /* + * Character Types + */ + dbmsType2OrientType.put("text", OType.STRING); + dbmsType2OrientType.put("character", OType.STRING); + dbmsType2OrientType.put("character varying", OType.STRING); + dbmsType2OrientType.put("char", OType.STRING); + dbmsType2OrientType.put("varchar", OType.STRING); + dbmsType2OrientType.put("varchar2", OType.STRING); + + /* + * Numeric Types + */ + dbmsType2OrientType.put("int2", OType.SHORT); + dbmsType2OrientType.put("int", OType.INTEGER); + dbmsType2OrientType.put("integer", OType.INTEGER); + dbmsType2OrientType.put("int4", OType.INTEGER); + dbmsType2OrientType.put("int8", OType.LONG); + dbmsType2OrientType.put("real", OType.LONG); + dbmsType2OrientType.put("float", OType.LONG); + dbmsType2OrientType.put("float4", OType.LONG); + dbmsType2OrientType.put("float8", OType.DOUBLE); + dbmsType2OrientType.put("double", OType.DOUBLE); + dbmsType2OrientType.put("double precision", OType.DOUBLE); + dbmsType2OrientType.put("numeric", OType.DECIMAL); + dbmsType2OrientType.put("decimal", OType.DECIMAL); + + /* + * Date/Time Types + */ + dbmsType2OrientType.put("date", OType.DATE); + dbmsType2OrientType.put("datetime", OType.DATETIME); + dbmsType2OrientType.put("timestamp", OType.DATETIME); + dbmsType2OrientType.put("timestamp with time zone", OType.DATETIME); + dbmsType2OrientType.put("timestamp with local time zone", OType.DATETIME); + + /* + * Boolean Type + */ + dbmsType2OrientType.put("boolean", OType.BOOLEAN); + dbmsType2OrientType.put("bool", OType.BOOLEAN); + + /* + * Binary Data Types + */ + dbmsType2OrientType.put("blob", OType.BINARY); + + /* + * User Defined Types (Object data types and object views) + */ + // TODO! in EMBEDDED + + return dbmsType2OrientType; + } + + public ODocument convertJSONToDocument(String currentProperty, String currentAttributeValue) { + ODocument document = new ODocument(currentProperty); + if (currentAttributeValue != null && currentAttributeValue.length() > 0) { + document.fromJSON(currentAttributeValue, "noMap"); } + return document; + } + + public boolean isGeospatial(String currentOriginalType) { + // TODO Auto-generated method stub + return false; + } + + public String buildGeospatialQuery(Entity entity) { + // TODO Auto-generated method stub + return null; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/handler/HSQLDBDataTypeHandler.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/handler/HSQLDBDataTypeHandler.java index 3cd42a98..b5e8ea94 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/handler/HSQLDBDataTypeHandler.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/handler/HSQLDBDataTypeHandler.java @@ -25,90 +25,89 @@ import java.util.Map; /** - * Handler that executes type conversions from HSQLDB DBMS to the OrientDB types. - * No Geospatial implementable (HSQLDB doesn't support this feature). + * Handler that executes type conversions from HSQLDB DBMS to the OrientDB types. No Geospatial + * implementable (HSQLDB doesn't support this feature). * * @author Gabriele Ponzi */ - public class HSQLDBDataTypeHandler extends DBMSDataTypeHandler { - public HSQLDBDataTypeHandler() { - this.dbmsType2OrientType = this.fillTypesMap(); - super.jsonImplemented = false; - super.geospatialImplemented = false; - } + public HSQLDBDataTypeHandler() { + this.dbmsType2OrientType = this.fillTypesMap(); + super.jsonImplemented = false; + super.geospatialImplemented = false; + } - private Map fillTypesMap() { - Map dbmsType2OrientType = new HashMap(); + private Map fillTypesMap() { + Map dbmsType2OrientType = new HashMap(); - /* - * Character Types - * (doc at http://hsqldb.org/doc/guide/guide.html#sgc_char_types ) - */ - dbmsType2OrientType.put("character", OType.STRING); - dbmsType2OrientType.put("character varying", OType.STRING); - dbmsType2OrientType.put("clob", OType.STRING); - dbmsType2OrientType.put("char", OType.STRING); - dbmsType2OrientType.put("char varying", OType.STRING); - dbmsType2OrientType.put("varchar", OType.STRING); - dbmsType2OrientType.put("longvarchar", OType.STRING); - dbmsType2OrientType.put("character large object", OType.STRING); + /* + * Character Types + * (doc at http://hsqldb.org/doc/guide/guide.html#sgc_char_types ) + */ + dbmsType2OrientType.put("character", OType.STRING); + dbmsType2OrientType.put("character varying", OType.STRING); + dbmsType2OrientType.put("clob", OType.STRING); + dbmsType2OrientType.put("char", OType.STRING); + dbmsType2OrientType.put("char varying", OType.STRING); + dbmsType2OrientType.put("varchar", OType.STRING); + dbmsType2OrientType.put("longvarchar", OType.STRING); + dbmsType2OrientType.put("character large object", OType.STRING); - /* - * Numeric Types - * (doc at http://hsqldb.org/doc/guide/guide.html#sgc_numeric_types ) - */ - dbmsType2OrientType.put("tinyint", OType.SHORT); - dbmsType2OrientType.put("smallint", OType.SHORT); - dbmsType2OrientType.put("integer", OType.INTEGER); - dbmsType2OrientType.put("bigint", OType.LONG); - dbmsType2OrientType.put("real", OType.DOUBLE); - dbmsType2OrientType.put("float", OType.DOUBLE); - dbmsType2OrientType.put("double", OType.DOUBLE); - dbmsType2OrientType.put("double precision", OType.DOUBLE); - dbmsType2OrientType.put("numeric", OType.DECIMAL); - dbmsType2OrientType.put("decimal", OType.DECIMAL); + /* + * Numeric Types + * (doc at http://hsqldb.org/doc/guide/guide.html#sgc_numeric_types ) + */ + dbmsType2OrientType.put("tinyint", OType.SHORT); + dbmsType2OrientType.put("smallint", OType.SHORT); + dbmsType2OrientType.put("integer", OType.INTEGER); + dbmsType2OrientType.put("bigint", OType.LONG); + dbmsType2OrientType.put("real", OType.DOUBLE); + dbmsType2OrientType.put("float", OType.DOUBLE); + dbmsType2OrientType.put("double", OType.DOUBLE); + dbmsType2OrientType.put("double precision", OType.DOUBLE); + dbmsType2OrientType.put("numeric", OType.DECIMAL); + dbmsType2OrientType.put("decimal", OType.DECIMAL); - /* - * Bit String Types - * (doc at http://hsqldb.org/doc/guide/guide.html#sgc_bit_types ) - */ - dbmsType2OrientType.put("bit", OType.STRING); - dbmsType2OrientType.put("bit varying", OType.STRING); + /* + * Bit String Types + * (doc at http://hsqldb.org/doc/guide/guide.html#sgc_bit_types ) + */ + dbmsType2OrientType.put("bit", OType.STRING); + dbmsType2OrientType.put("bit varying", OType.STRING); - /* - * Date/Time Types - * (doc at http://hsqldb.org/doc/guide/guide.html#sgc_datetime_types ) - */ - dbmsType2OrientType.put("date", OType.DATE); - dbmsType2OrientType.put("time", OType.STRING); - dbmsType2OrientType.put("time with time zone", OType.STRING); - dbmsType2OrientType.put("timestamp", OType.DATETIME); - dbmsType2OrientType.put("timestamp with time zone", OType.DATETIME); + /* + * Date/Time Types + * (doc at http://hsqldb.org/doc/guide/guide.html#sgc_datetime_types ) + */ + dbmsType2OrientType.put("date", OType.DATE); + dbmsType2OrientType.put("time", OType.STRING); + dbmsType2OrientType.put("time with time zone", OType.STRING); + dbmsType2OrientType.put("timestamp", OType.DATETIME); + dbmsType2OrientType.put("timestamp with time zone", OType.DATETIME); - /* - * Boolean Type - * (doc at http://hsqldb.org/doc/guide/guide.html#sgc_boolean_type ) - */ - dbmsType2OrientType.put("boolean", OType.BOOLEAN); + /* + * Boolean Type + * (doc at http://hsqldb.org/doc/guide/guide.html#sgc_boolean_type ) + */ + dbmsType2OrientType.put("boolean", OType.BOOLEAN); - /* - * Binary Data Types - * (doc at http://hsqldb.org/doc/guide/guide.html#sgc_binary_types ) - */ - dbmsType2OrientType.put("binary", OType.BINARY); - dbmsType2OrientType.put("binary varying", OType.BINARY); - dbmsType2OrientType.put("blob", OType.BINARY); - dbmsType2OrientType.put("varbinary", OType.BINARY); - dbmsType2OrientType.put("binary large object", OType.BINARY); - dbmsType2OrientType.put("longvarbinary", OType.BINARY); + /* + * Binary Data Types + * (doc at http://hsqldb.org/doc/guide/guide.html#sgc_binary_types ) + */ + dbmsType2OrientType.put("binary", OType.BINARY); + dbmsType2OrientType.put("binary varying", OType.BINARY); + dbmsType2OrientType.put("blob", OType.BINARY); + dbmsType2OrientType.put("varbinary", OType.BINARY); + dbmsType2OrientType.put("binary large object", OType.BINARY); + dbmsType2OrientType.put("longvarbinary", OType.BINARY); - /* - * User Defined Types (Object data types and object views) - */ - // TODO! in EMBEDDED + /* + * User Defined Types (Object data types and object views) + */ + // TODO! in EMBEDDED - return dbmsType2OrientType; - } + return dbmsType2OrientType; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/handler/MySQLDataTypeHandler.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/handler/MySQLDataTypeHandler.java index 2290b701..90e723f2 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/handler/MySQLDataTypeHandler.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/handler/MySQLDataTypeHandler.java @@ -25,122 +25,121 @@ import java.util.Map; /** - * Handler that executes type conversions from MySQL DBMS to the OrientDB types. - * No Geospatial implemented. + * Handler that executes type conversions from MySQL DBMS to the OrientDB types. No Geospatial + * implemented. * * @author Gabriele Ponzi */ - public class MySQLDataTypeHandler extends DBMSDataTypeHandler { - public MySQLDataTypeHandler() { - this.dbmsType2OrientType = this.fillTypesMap(); - super.jsonImplemented = true; - super.geospatialImplemented = false; - } - - private Map fillTypesMap() { - Map dbmsType2OrientType = new HashMap(); - - /* - * Numeric Types - * (doc at http://dev.mysql.com/doc/refman/5.7/en/numeric-types.html ) - */ - dbmsType2OrientType.put("tinyint", OType.SHORT); - dbmsType2OrientType.put("smallint", OType.SHORT); - dbmsType2OrientType.put("mediumint", OType.INTEGER); - dbmsType2OrientType.put("int", OType.INTEGER); - dbmsType2OrientType.put("integer", OType.INTEGER); - dbmsType2OrientType.put("bigint", OType.LONG); - dbmsType2OrientType.put("decimal", OType.DECIMAL); - dbmsType2OrientType.put("dec", OType.DECIMAL); - dbmsType2OrientType.put("fixed", OType.DECIMAL); - dbmsType2OrientType.put("numeric", OType.DECIMAL); - dbmsType2OrientType.put("real", OType.FLOAT); - dbmsType2OrientType.put("float", OType.FLOAT); - dbmsType2OrientType.put("double", OType.DOUBLE); - dbmsType2OrientType.put("double precision", OType.DOUBLE); - - /* - * Bit String Types - * (doc at http://dev.mysql.com/doc/refman/5.7/en/numeric-types.html ) - */ - dbmsType2OrientType.put("bit", OType.STRING); - - /* - * Date/Time Types - * (doc at http://dev.mysql.com/doc/refman/5.7/en/date-and-time-types.html ) - */ - dbmsType2OrientType.put("date", OType.DATE); - dbmsType2OrientType.put("datetime", OType.DATETIME); - dbmsType2OrientType.put("timestamp", OType.DATETIME); - dbmsType2OrientType.put("time", OType.STRING); - dbmsType2OrientType.put("year", OType.STRING); - - /* - * Character Types - * (doc at http://dev.mysql.com/doc/refman/5.7/en/string-types.html ) - */ - dbmsType2OrientType.put("char", OType.STRING); - dbmsType2OrientType.put("varchar", OType.STRING); - dbmsType2OrientType.put("binary", OType.STRING); - dbmsType2OrientType.put("varbinary", OType.STRING); - dbmsType2OrientType.put("tinytext", OType.STRING); - dbmsType2OrientType.put("text", OType.STRING); - dbmsType2OrientType.put("mediumtext", OType.STRING); - dbmsType2OrientType.put("longtext", OType.STRING); - - /* - * Binary Data Types - * (doc at http://dev.mysql.com/doc/refman/5.7/en/binary-varbinary.html - * http://dev.mysql.com/doc/refman/5.7/en/blob.html ) - */ - dbmsType2OrientType.put("binary", OType.BINARY); - dbmsType2OrientType.put("varbinary", OType.BINARY); - dbmsType2OrientType.put("tinyblob", OType.BINARY); - dbmsType2OrientType.put("blob", OType.BINARY); - dbmsType2OrientType.put("mediumblob", OType.BINARY); - dbmsType2OrientType.put("longblob", OType.BINARY); - - /* - * JSON Type - * (doc at http://dev.mysql.com/doc/refman/5.7/en/json.html ) - */ - dbmsType2OrientType.put("json", OType.EMBEDDED); - - /* - * ENUM Types - * (doc at http://dev.mysql.com/doc/refman/5.7/en/enum.html ) - */ - // TODO !!! - - /* - * SET Types - * (doc at http://dev.mysql.com/doc/refman/5.7/en/set.html ) - */ - // TODO !!! - - /* - * Geometric Types - * (doc at http://www.postgresql.org/docs/9.3/static/datatype-geometric.html ) - */ - dbmsType2OrientType.put("geometry", OType.STRING); - dbmsType2OrientType.put("point", OType.STRING); - dbmsType2OrientType.put("linestring", OType.STRING); - dbmsType2OrientType.put("line", OType.STRING); - dbmsType2OrientType.put("linearRing", OType.STRING); - dbmsType2OrientType.put("polygon", OType.STRING); - dbmsType2OrientType.put("geometrycollection", OType.STRING); - dbmsType2OrientType.put("multipoint", OType.STRING); - dbmsType2OrientType.put("multilinestring", OType.STRING); - dbmsType2OrientType.put("multipolygon", OType.STRING); - - /* - * Using Data Types from Other Database Engines - * (doc at http://dev.mysql.com/doc/refman/5.7/en/other-vendor-data-types.html ) - */ - // TODO - - return dbmsType2OrientType; - } + public MySQLDataTypeHandler() { + this.dbmsType2OrientType = this.fillTypesMap(); + super.jsonImplemented = true; + super.geospatialImplemented = false; + } + + private Map fillTypesMap() { + Map dbmsType2OrientType = new HashMap(); + + /* + * Numeric Types + * (doc at http://dev.mysql.com/doc/refman/5.7/en/numeric-types.html ) + */ + dbmsType2OrientType.put("tinyint", OType.SHORT); + dbmsType2OrientType.put("smallint", OType.SHORT); + dbmsType2OrientType.put("mediumint", OType.INTEGER); + dbmsType2OrientType.put("int", OType.INTEGER); + dbmsType2OrientType.put("integer", OType.INTEGER); + dbmsType2OrientType.put("bigint", OType.LONG); + dbmsType2OrientType.put("decimal", OType.DECIMAL); + dbmsType2OrientType.put("dec", OType.DECIMAL); + dbmsType2OrientType.put("fixed", OType.DECIMAL); + dbmsType2OrientType.put("numeric", OType.DECIMAL); + dbmsType2OrientType.put("real", OType.FLOAT); + dbmsType2OrientType.put("float", OType.FLOAT); + dbmsType2OrientType.put("double", OType.DOUBLE); + dbmsType2OrientType.put("double precision", OType.DOUBLE); + + /* + * Bit String Types + * (doc at http://dev.mysql.com/doc/refman/5.7/en/numeric-types.html ) + */ + dbmsType2OrientType.put("bit", OType.STRING); + + /* + * Date/Time Types + * (doc at http://dev.mysql.com/doc/refman/5.7/en/date-and-time-types.html ) + */ + dbmsType2OrientType.put("date", OType.DATE); + dbmsType2OrientType.put("datetime", OType.DATETIME); + dbmsType2OrientType.put("timestamp", OType.DATETIME); + dbmsType2OrientType.put("time", OType.STRING); + dbmsType2OrientType.put("year", OType.STRING); + + /* + * Character Types + * (doc at http://dev.mysql.com/doc/refman/5.7/en/string-types.html ) + */ + dbmsType2OrientType.put("char", OType.STRING); + dbmsType2OrientType.put("varchar", OType.STRING); + dbmsType2OrientType.put("binary", OType.STRING); + dbmsType2OrientType.put("varbinary", OType.STRING); + dbmsType2OrientType.put("tinytext", OType.STRING); + dbmsType2OrientType.put("text", OType.STRING); + dbmsType2OrientType.put("mediumtext", OType.STRING); + dbmsType2OrientType.put("longtext", OType.STRING); + + /* + * Binary Data Types + * (doc at http://dev.mysql.com/doc/refman/5.7/en/binary-varbinary.html + * http://dev.mysql.com/doc/refman/5.7/en/blob.html ) + */ + dbmsType2OrientType.put("binary", OType.BINARY); + dbmsType2OrientType.put("varbinary", OType.BINARY); + dbmsType2OrientType.put("tinyblob", OType.BINARY); + dbmsType2OrientType.put("blob", OType.BINARY); + dbmsType2OrientType.put("mediumblob", OType.BINARY); + dbmsType2OrientType.put("longblob", OType.BINARY); + + /* + * JSON Type + * (doc at http://dev.mysql.com/doc/refman/5.7/en/json.html ) + */ + dbmsType2OrientType.put("json", OType.EMBEDDED); + + /* + * ENUM Types + * (doc at http://dev.mysql.com/doc/refman/5.7/en/enum.html ) + */ + // TODO !!! + + /* + * SET Types + * (doc at http://dev.mysql.com/doc/refman/5.7/en/set.html ) + */ + // TODO !!! + + /* + * Geometric Types + * (doc at http://www.postgresql.org/docs/9.3/static/datatype-geometric.html ) + */ + dbmsType2OrientType.put("geometry", OType.STRING); + dbmsType2OrientType.put("point", OType.STRING); + dbmsType2OrientType.put("linestring", OType.STRING); + dbmsType2OrientType.put("line", OType.STRING); + dbmsType2OrientType.put("linearRing", OType.STRING); + dbmsType2OrientType.put("polygon", OType.STRING); + dbmsType2OrientType.put("geometrycollection", OType.STRING); + dbmsType2OrientType.put("multipoint", OType.STRING); + dbmsType2OrientType.put("multilinestring", OType.STRING); + dbmsType2OrientType.put("multipolygon", OType.STRING); + + /* + * Using Data Types from Other Database Engines + * (doc at http://dev.mysql.com/doc/refman/5.7/en/other-vendor-data-types.html ) + */ + // TODO + + return dbmsType2OrientType; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/handler/OracleDataTypeHandler.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/handler/OracleDataTypeHandler.java index 10fc9ba5..1aede57e 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/handler/OracleDataTypeHandler.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/handler/OracleDataTypeHandler.java @@ -25,105 +25,104 @@ import java.util.Map; /** - * Handler that executes type conversions from Oracle DBMS to the OrientDB types. - * No Geospatial implemented. + * Handler that executes type conversions from Oracle DBMS to the OrientDB types. No Geospatial + * implemented. * * @author Gabriele Ponzi */ - public class OracleDataTypeHandler extends DBMSDataTypeHandler { - public OracleDataTypeHandler() { - this.dbmsType2OrientType = this.fillTypesMap(); - super.jsonImplemented = false; - super.geospatialImplemented = false; - } - - private Map fillTypesMap() { - Map dbmsType2OrientType = new HashMap(); - - /* - * Character Types - * (doc at http://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT213 ) - */ - dbmsType2OrientType.put("char", OType.STRING); - dbmsType2OrientType.put("varchar", OType.STRING); - dbmsType2OrientType.put("varchar2", OType.STRING); - dbmsType2OrientType.put("nvarchar", OType.STRING); - dbmsType2OrientType.put("nvarchar2", OType.STRING); - dbmsType2OrientType.put("clob", OType.STRING); - dbmsType2OrientType.put("nclob", OType.STRING); - dbmsType2OrientType.put("long", OType.STRING); - - /* - * Numeric Types - * (doc at http://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT313 ) - */ - dbmsType2OrientType.put("number", OType.DOUBLE); - dbmsType2OrientType.put("numeric", OType.DECIMAL); - dbmsType2OrientType.put("float", OType.FLOAT); - dbmsType2OrientType.put("binary_float", OType.FLOAT); - dbmsType2OrientType.put("double", OType.DOUBLE); - dbmsType2OrientType.put("binary_double", OType.DOUBLE); - - /* - * Date/Time Types - * (doc at http://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT413 ) - */ - dbmsType2OrientType.put("date", OType.DATE); - dbmsType2OrientType.put("datetime", OType.DATETIME); - dbmsType2OrientType.put("timestamp", OType.DATETIME); - dbmsType2OrientType.put("timestamp with time zone", OType.DATETIME); - dbmsType2OrientType.put("timestamp with local time zone", OType.DATETIME); - - /* - * Binary Data Types - * (doc at http://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT613 ) - */ - dbmsType2OrientType.put("blob", OType.BINARY); - dbmsType2OrientType.put("bfile", OType.BINARY); - dbmsType2OrientType.put("raw", OType.BINARY); - dbmsType2OrientType.put("long raw", OType.BINARY); - - /* - * JSON Type - * (doc at https://docs.oracle.com/database/121/ADXDB/json.htm#GUID-E6CC0DCF-3D72-41EF-ACA4-B3BF54EE3CA0__CACHFFCE) - * - * Unlike XML data, which is stored using SQL data type XMLType, JSON data is stored in Oracle Database using SQL data types VARCHAR2, CLOB, and BLOB. - * Oracle recommends that you always use an is_json check constraint to ensure that column values are valid JSON instances - */ - - /* - * ROWID and UROWID Data Types - * (doc at http://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT713 ) - */ - dbmsType2OrientType.put("rowid", OType.STRING); - dbmsType2OrientType.put("urowid", OType.STRING); - - /* - * ANSI, DB2, and SQL/DS Datatypes - * (doc at http://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT813) - */ - // TODO !!! - - /* - * XML Type - * (doc at http://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT913 ) - */ - dbmsType2OrientType.put("xmltype", OType.STRING); - - /* - * URI Type - * (doc at http://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT1856 ) - */ - dbmsType2OrientType.put("uritype", OType.STRING); - - /* - * User Defined Types (Object data types and object views) - * (doc at http://www.postgresql.org/docs/9.3/static/rowtypes.html) - */ - // TODO! in EMBEDDED - - return dbmsType2OrientType; - } + public OracleDataTypeHandler() { + this.dbmsType2OrientType = this.fillTypesMap(); + super.jsonImplemented = false; + super.geospatialImplemented = false; + } + + private Map fillTypesMap() { + Map dbmsType2OrientType = new HashMap(); + + /* + * Character Types + * (doc at http://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT213 ) + */ + dbmsType2OrientType.put("char", OType.STRING); + dbmsType2OrientType.put("varchar", OType.STRING); + dbmsType2OrientType.put("varchar2", OType.STRING); + dbmsType2OrientType.put("nvarchar", OType.STRING); + dbmsType2OrientType.put("nvarchar2", OType.STRING); + dbmsType2OrientType.put("clob", OType.STRING); + dbmsType2OrientType.put("nclob", OType.STRING); + dbmsType2OrientType.put("long", OType.STRING); + + /* + * Numeric Types + * (doc at http://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT313 ) + */ + dbmsType2OrientType.put("number", OType.DOUBLE); + dbmsType2OrientType.put("numeric", OType.DECIMAL); + dbmsType2OrientType.put("float", OType.FLOAT); + dbmsType2OrientType.put("binary_float", OType.FLOAT); + dbmsType2OrientType.put("double", OType.DOUBLE); + dbmsType2OrientType.put("binary_double", OType.DOUBLE); + + /* + * Date/Time Types + * (doc at http://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT413 ) + */ + dbmsType2OrientType.put("date", OType.DATE); + dbmsType2OrientType.put("datetime", OType.DATETIME); + dbmsType2OrientType.put("timestamp", OType.DATETIME); + dbmsType2OrientType.put("timestamp with time zone", OType.DATETIME); + dbmsType2OrientType.put("timestamp with local time zone", OType.DATETIME); + + /* + * Binary Data Types + * (doc at http://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT613 ) + */ + dbmsType2OrientType.put("blob", OType.BINARY); + dbmsType2OrientType.put("bfile", OType.BINARY); + dbmsType2OrientType.put("raw", OType.BINARY); + dbmsType2OrientType.put("long raw", OType.BINARY); + + /* + * JSON Type + * (doc at https://docs.oracle.com/database/121/ADXDB/json.htm#GUID-E6CC0DCF-3D72-41EF-ACA4-B3BF54EE3CA0__CACHFFCE) + * + * Unlike XML data, which is stored using SQL data type XMLType, JSON data is stored in Oracle Database using SQL data types VARCHAR2, CLOB, and BLOB. + * Oracle recommends that you always use an is_json check constraint to ensure that column values are valid JSON instances + */ + + /* + * ROWID and UROWID Data Types + * (doc at http://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT713 ) + */ + dbmsType2OrientType.put("rowid", OType.STRING); + dbmsType2OrientType.put("urowid", OType.STRING); + + /* + * ANSI, DB2, and SQL/DS Datatypes + * (doc at http://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT813) + */ + // TODO !!! + + /* + * XML Type + * (doc at http://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT913 ) + */ + dbmsType2OrientType.put("xmltype", OType.STRING); + + /* + * URI Type + * (doc at http://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT1856 ) + */ + dbmsType2OrientType.put("uritype", OType.STRING); + + /* + * User Defined Types (Object data types and object views) + * (doc at http://www.postgresql.org/docs/9.3/static/rowtypes.html) + */ + // TODO! in EMBEDDED + + return dbmsType2OrientType; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/handler/PostgreSQLDataTypeHandler.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/handler/PostgreSQLDataTypeHandler.java index 85471f56..dcb842b1 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/handler/PostgreSQLDataTypeHandler.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/handler/PostgreSQLDataTypeHandler.java @@ -27,182 +27,181 @@ import java.util.Map; /** - * Handler that executes type conversions from PostgreSQL DBMS to the OrientDB types. - * Geospatial implemented (PostGis). + * Handler that executes type conversions from PostgreSQL DBMS to the OrientDB types. Geospatial + * implemented (PostGis). * * @author Gabriele Ponzi */ - public class PostgreSQLDataTypeHandler extends DBMSDataTypeHandler { - private List geospatialTypes; - - public PostgreSQLDataTypeHandler() { - this.dbmsType2OrientType = this.fillTypesMap(); - this.geospatialTypes = this.fillGeospatialList(); - super.jsonImplemented = true; - super.geospatialImplemented = false; - } - - private Map fillTypesMap() { - Map dbmsType2OrientType = new HashMap(); - - /* - * Numeric Types - * (doc at http://www.postgresql.org/docs/9.6/static/datatype-numeric.html ) - */ - dbmsType2OrientType.put("smallint", OType.SHORT); - dbmsType2OrientType.put("int2", OType.SHORT); - dbmsType2OrientType.put("integer", OType.INTEGER); - dbmsType2OrientType.put("int", OType.INTEGER); - dbmsType2OrientType.put("int4", OType.INTEGER); - dbmsType2OrientType.put("bigint", OType.LONG); - dbmsType2OrientType.put("int8", OType.LONG); - dbmsType2OrientType.put("decimal", OType.DECIMAL); - dbmsType2OrientType.put("numeric", OType.DECIMAL); - dbmsType2OrientType.put("real", OType.FLOAT); - dbmsType2OrientType.put("float4", OType.FLOAT); - dbmsType2OrientType.put("double precision", OType.DOUBLE); - dbmsType2OrientType.put("float8", OType.DOUBLE); - dbmsType2OrientType.put("smallserial", OType.SHORT); - dbmsType2OrientType.put("serial2", OType.SHORT); - dbmsType2OrientType.put("serial", OType.INTEGER); - dbmsType2OrientType.put("serial4", OType.INTEGER); - dbmsType2OrientType.put("bigserial", OType.LONG); - dbmsType2OrientType.put("serial8", OType.LONG); - - /* - * Monetary Types - * (doc at http://www.postgresql.org/docs/9.6/static/datatype-money.html ) - */ - dbmsType2OrientType.put("money", OType.DOUBLE); - - /* - * Character Types - * (doc at http://www.postgresql.org/docs/9.6/static/datatype-character.html ) - */ - dbmsType2OrientType.put("character varying", OType.STRING); - dbmsType2OrientType.put("varchar", OType.STRING); - dbmsType2OrientType.put("character", OType.STRING); - dbmsType2OrientType.put("char", OType.STRING); - dbmsType2OrientType.put("text", OType.STRING); - - /* - * Binary Data Types - * (doc at http://www.postgresql.org/docs/9.6/static/datatype-binary.html ) - */ - dbmsType2OrientType.put("bytea", OType.BINARY); - - /* - * Date/Time Types - * (doc at http://www.postgresql.org/docs/9.6/static/datatype-datetime.html ) - */ - dbmsType2OrientType.put("timestamp", OType.DATETIME); - dbmsType2OrientType.put("date", OType.DATE); - dbmsType2OrientType.put("time", OType.STRING); - dbmsType2OrientType.put("interval", OType.STRING); - - /* - * Boolean Type - * (doc at http://www.postgresql.org/docs/9.6/static/datatype-boolean.html ) - */ - dbmsType2OrientType.put("boolean", OType.BOOLEAN); - dbmsType2OrientType.put("bool", OType.BOOLEAN); - - /* - * Enumerated Types - * (doc at http://www.postgresql.org/docs/9.6/static/datatype-enum.html ) - */ - //TODO?! - - /* - * Geometric Types - * (doc at http://www.postgresql.org/docs/9.6/static/datatype-geometric.html ) - */ - dbmsType2OrientType.put("point", OType.STRING); - dbmsType2OrientType.put("line", OType.STRING); - dbmsType2OrientType.put("lseg", OType.STRING); - dbmsType2OrientType.put("box", OType.STRING); - dbmsType2OrientType.put("path", OType.STRING); - dbmsType2OrientType.put("polygon", OType.STRING); - dbmsType2OrientType.put("circle", OType.STRING); - // Postgis - dbmsType2OrientType.put("box2d", OType.EMBEDDED); - dbmsType2OrientType.put("box3d", OType.EMBEDDED); - dbmsType2OrientType.put("geometry", OType.EMBEDDED); - dbmsType2OrientType.put("geometry_dump", OType.EMBEDDED); - dbmsType2OrientType.put("geography", OType.EMBEDDED); - - /* - * Network Address Types - * (doc at http://www.postgresql.org/docs/9.6/static/datatype-net-types.html ) - */ - dbmsType2OrientType.put("cidr", OType.STRING); - dbmsType2OrientType.put("inet", OType.STRING); - dbmsType2OrientType.put("macaddr", OType.STRING); - - /* - * Bit String Types - * (doc at http://www.postgresql.org/docs/9.6/static/datatype-bit.html ) - */ - dbmsType2OrientType.put("bit", OType.STRING); - dbmsType2OrientType.put("bit varying", OType.STRING); - dbmsType2OrientType.put("varbit", OType.STRING); - - /* - * Text Search Types - * (doc at http://www.postgresql.org/docs/9.6/static/datatype-textsearch.html ) - */ - //TODO - - /* - * UUID Type - * (doc at http://www.postgresql.org/docs/9.6/static/datatype-uuid.html ) - */ - dbmsType2OrientType.put("uuid", OType.STRING); - - /* - * XML Type - * (doc at http://www.postgresql.org/docs/9.6/static/datatype-xml.html ) - */ - dbmsType2OrientType.put("xml", OType.STRING); - - /* - * JSON Type - * (doc at http://www.postgresql.org/docs/9.6/static/datatype-json.html ) - */ - dbmsType2OrientType.put("json", OType.EMBEDDED); - dbmsType2OrientType.put("jsonb", OType.EMBEDDED); - - /* - * Composite Types - * (doc at http://www.postgresql.org/docs/9.6/static/rowtypes.html ) - */ - // TODO! in EMBEDDED - - /* - * Range Types - * (doc at http://www.postgresql.org/docs/9.6/static/rangetypes.html ) - */ - dbmsType2OrientType.put("int4range", OType.STRING); - dbmsType2OrientType.put("int8range", OType.STRING); - dbmsType2OrientType.put("numrange", OType.STRING); - dbmsType2OrientType.put("tsrange", OType.STRING); - dbmsType2OrientType.put("tstzrange", OType.STRING); - dbmsType2OrientType.put("daterange", OType.STRING); - - return dbmsType2OrientType; - } - - private List fillGeospatialList() { - List geospatialTypes = new ArrayList(); - - geospatialTypes.add("box2d"); - geospatialTypes.add("box3d"); - geospatialTypes.add("geometry"); - geospatialTypes.add("geometry_dump"); - geospatialTypes.add("geography"); - - return geospatialTypes; - } + private List geospatialTypes; + + public PostgreSQLDataTypeHandler() { + this.dbmsType2OrientType = this.fillTypesMap(); + this.geospatialTypes = this.fillGeospatialList(); + super.jsonImplemented = true; + super.geospatialImplemented = false; + } + + private Map fillTypesMap() { + Map dbmsType2OrientType = new HashMap(); + + /* + * Numeric Types + * (doc at http://www.postgresql.org/docs/9.6/static/datatype-numeric.html ) + */ + dbmsType2OrientType.put("smallint", OType.SHORT); + dbmsType2OrientType.put("int2", OType.SHORT); + dbmsType2OrientType.put("integer", OType.INTEGER); + dbmsType2OrientType.put("int", OType.INTEGER); + dbmsType2OrientType.put("int4", OType.INTEGER); + dbmsType2OrientType.put("bigint", OType.LONG); + dbmsType2OrientType.put("int8", OType.LONG); + dbmsType2OrientType.put("decimal", OType.DECIMAL); + dbmsType2OrientType.put("numeric", OType.DECIMAL); + dbmsType2OrientType.put("real", OType.FLOAT); + dbmsType2OrientType.put("float4", OType.FLOAT); + dbmsType2OrientType.put("double precision", OType.DOUBLE); + dbmsType2OrientType.put("float8", OType.DOUBLE); + dbmsType2OrientType.put("smallserial", OType.SHORT); + dbmsType2OrientType.put("serial2", OType.SHORT); + dbmsType2OrientType.put("serial", OType.INTEGER); + dbmsType2OrientType.put("serial4", OType.INTEGER); + dbmsType2OrientType.put("bigserial", OType.LONG); + dbmsType2OrientType.put("serial8", OType.LONG); + + /* + * Monetary Types + * (doc at http://www.postgresql.org/docs/9.6/static/datatype-money.html ) + */ + dbmsType2OrientType.put("money", OType.DOUBLE); + + /* + * Character Types + * (doc at http://www.postgresql.org/docs/9.6/static/datatype-character.html ) + */ + dbmsType2OrientType.put("character varying", OType.STRING); + dbmsType2OrientType.put("varchar", OType.STRING); + dbmsType2OrientType.put("character", OType.STRING); + dbmsType2OrientType.put("char", OType.STRING); + dbmsType2OrientType.put("text", OType.STRING); + + /* + * Binary Data Types + * (doc at http://www.postgresql.org/docs/9.6/static/datatype-binary.html ) + */ + dbmsType2OrientType.put("bytea", OType.BINARY); + + /* + * Date/Time Types + * (doc at http://www.postgresql.org/docs/9.6/static/datatype-datetime.html ) + */ + dbmsType2OrientType.put("timestamp", OType.DATETIME); + dbmsType2OrientType.put("date", OType.DATE); + dbmsType2OrientType.put("time", OType.STRING); + dbmsType2OrientType.put("interval", OType.STRING); + + /* + * Boolean Type + * (doc at http://www.postgresql.org/docs/9.6/static/datatype-boolean.html ) + */ + dbmsType2OrientType.put("boolean", OType.BOOLEAN); + dbmsType2OrientType.put("bool", OType.BOOLEAN); + + /* + * Enumerated Types + * (doc at http://www.postgresql.org/docs/9.6/static/datatype-enum.html ) + */ + // TODO?! + + /* + * Geometric Types + * (doc at http://www.postgresql.org/docs/9.6/static/datatype-geometric.html ) + */ + dbmsType2OrientType.put("point", OType.STRING); + dbmsType2OrientType.put("line", OType.STRING); + dbmsType2OrientType.put("lseg", OType.STRING); + dbmsType2OrientType.put("box", OType.STRING); + dbmsType2OrientType.put("path", OType.STRING); + dbmsType2OrientType.put("polygon", OType.STRING); + dbmsType2OrientType.put("circle", OType.STRING); + // Postgis + dbmsType2OrientType.put("box2d", OType.EMBEDDED); + dbmsType2OrientType.put("box3d", OType.EMBEDDED); + dbmsType2OrientType.put("geometry", OType.EMBEDDED); + dbmsType2OrientType.put("geometry_dump", OType.EMBEDDED); + dbmsType2OrientType.put("geography", OType.EMBEDDED); + + /* + * Network Address Types + * (doc at http://www.postgresql.org/docs/9.6/static/datatype-net-types.html ) + */ + dbmsType2OrientType.put("cidr", OType.STRING); + dbmsType2OrientType.put("inet", OType.STRING); + dbmsType2OrientType.put("macaddr", OType.STRING); + + /* + * Bit String Types + * (doc at http://www.postgresql.org/docs/9.6/static/datatype-bit.html ) + */ + dbmsType2OrientType.put("bit", OType.STRING); + dbmsType2OrientType.put("bit varying", OType.STRING); + dbmsType2OrientType.put("varbit", OType.STRING); + + /* + * Text Search Types + * (doc at http://www.postgresql.org/docs/9.6/static/datatype-textsearch.html ) + */ + // TODO + + /* + * UUID Type + * (doc at http://www.postgresql.org/docs/9.6/static/datatype-uuid.html ) + */ + dbmsType2OrientType.put("uuid", OType.STRING); + + /* + * XML Type + * (doc at http://www.postgresql.org/docs/9.6/static/datatype-xml.html ) + */ + dbmsType2OrientType.put("xml", OType.STRING); + + /* + * JSON Type + * (doc at http://www.postgresql.org/docs/9.6/static/datatype-json.html ) + */ + dbmsType2OrientType.put("json", OType.EMBEDDED); + dbmsType2OrientType.put("jsonb", OType.EMBEDDED); + + /* + * Composite Types + * (doc at http://www.postgresql.org/docs/9.6/static/rowtypes.html ) + */ + // TODO! in EMBEDDED + + /* + * Range Types + * (doc at http://www.postgresql.org/docs/9.6/static/rangetypes.html ) + */ + dbmsType2OrientType.put("int4range", OType.STRING); + dbmsType2OrientType.put("int8range", OType.STRING); + dbmsType2OrientType.put("numrange", OType.STRING); + dbmsType2OrientType.put("tsrange", OType.STRING); + dbmsType2OrientType.put("tstzrange", OType.STRING); + dbmsType2OrientType.put("daterange", OType.STRING); + + return dbmsType2OrientType; + } + + private List fillGeospatialList() { + List geospatialTypes = new ArrayList(); + + geospatialTypes.add("box2d"); + geospatialTypes.add("box3d"); + geospatialTypes.add("geometry"); + geospatialTypes.add("geometry_dump"); + geospatialTypes.add("geography"); + + return geospatialTypes; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/handler/SQLServerDataTypeHandler.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/handler/SQLServerDataTypeHandler.java index 2c6beb06..90a3ab56 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/handler/SQLServerDataTypeHandler.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/handler/SQLServerDataTypeHandler.java @@ -25,91 +25,90 @@ import java.util.Map; /** - * Handler that executes type conversions from SQLServer DBMS to the OrientDB types. - * No Geospatial implemented. + * Handler that executes type conversions from SQLServer DBMS to the OrientDB types. No Geospatial + * implemented. * * @author Gabriele Ponzi */ - public class SQLServerDataTypeHandler extends DBMSDataTypeHandler { - public SQLServerDataTypeHandler() { - this.dbmsType2OrientType = this.fillTypesMap(); - super.jsonImplemented = false; - super.geospatialImplemented = false; - } + public SQLServerDataTypeHandler() { + this.dbmsType2OrientType = this.fillTypesMap(); + super.jsonImplemented = false; + super.geospatialImplemented = false; + } - private Map fillTypesMap() { - Map dbmsType2OrientType = new HashMap(); + private Map fillTypesMap() { + Map dbmsType2OrientType = new HashMap(); - /* - * Character Types - * (doc at https://msdn.microsoft.com/en-us/library/ms176089.aspx, https://msdn.microsoft.com/en-us/library/ms187993.aspx, - * https://msdn.microsoft.com/en-us/library/ms186939.aspx ) - */ - dbmsType2OrientType.put("char", OType.STRING); - dbmsType2OrientType.put("character", OType.STRING); - dbmsType2OrientType.put("varchar", OType.STRING); - dbmsType2OrientType.put("char varying", OType.STRING); - dbmsType2OrientType.put("character varying", OType.STRING); - dbmsType2OrientType.put("text", OType.STRING); - dbmsType2OrientType.put("ntext", OType.STRING); - dbmsType2OrientType.put("nchar", OType.STRING); - dbmsType2OrientType.put("national char", OType.STRING); - dbmsType2OrientType.put("national character", OType.STRING); - dbmsType2OrientType.put("nvarchar", OType.STRING); - dbmsType2OrientType.put("national char varying", OType.STRING); - dbmsType2OrientType.put("national character varying", OType.STRING); + /* + * Character Types + * (doc at https://msdn.microsoft.com/en-us/library/ms176089.aspx, https://msdn.microsoft.com/en-us/library/ms187993.aspx, + * https://msdn.microsoft.com/en-us/library/ms186939.aspx ) + */ + dbmsType2OrientType.put("char", OType.STRING); + dbmsType2OrientType.put("character", OType.STRING); + dbmsType2OrientType.put("varchar", OType.STRING); + dbmsType2OrientType.put("char varying", OType.STRING); + dbmsType2OrientType.put("character varying", OType.STRING); + dbmsType2OrientType.put("text", OType.STRING); + dbmsType2OrientType.put("ntext", OType.STRING); + dbmsType2OrientType.put("nchar", OType.STRING); + dbmsType2OrientType.put("national char", OType.STRING); + dbmsType2OrientType.put("national character", OType.STRING); + dbmsType2OrientType.put("nvarchar", OType.STRING); + dbmsType2OrientType.put("national char varying", OType.STRING); + dbmsType2OrientType.put("national character varying", OType.STRING); - /* - * Numeric Types - * (doc at https://msdn.microsoft.com/en-us/library/ms187745.aspx, - * https://msdn.microsoft.com/en-us/library/ms187746.aspx, https://msdn.microsoft.com/en-us/library/ms173773.aspx ) - */ - dbmsType2OrientType.put("smallint", OType.SHORT); - dbmsType2OrientType.put("int", OType.INTEGER); - dbmsType2OrientType.put("bigint", OType.LONG); - dbmsType2OrientType.put("tinyint", OType.SHORT); - dbmsType2OrientType.put("decimal", OType.DECIMAL); - dbmsType2OrientType.put("dec", OType.DECIMAL); - dbmsType2OrientType.put("numeric", OType.DECIMAL); - dbmsType2OrientType.put("real", OType.FLOAT); - dbmsType2OrientType.put("float", OType.FLOAT); + /* + * Numeric Types + * (doc at https://msdn.microsoft.com/en-us/library/ms187745.aspx, + * https://msdn.microsoft.com/en-us/library/ms187746.aspx, https://msdn.microsoft.com/en-us/library/ms173773.aspx ) + */ + dbmsType2OrientType.put("smallint", OType.SHORT); + dbmsType2OrientType.put("int", OType.INTEGER); + dbmsType2OrientType.put("bigint", OType.LONG); + dbmsType2OrientType.put("tinyint", OType.SHORT); + dbmsType2OrientType.put("decimal", OType.DECIMAL); + dbmsType2OrientType.put("dec", OType.DECIMAL); + dbmsType2OrientType.put("numeric", OType.DECIMAL); + dbmsType2OrientType.put("real", OType.FLOAT); + dbmsType2OrientType.put("float", OType.FLOAT); - /* - * Monetary Types - * (doc at https://msdn.microsoft.com/en-us/library/ms179882.aspx ) - */ - dbmsType2OrientType.put("money", OType.DOUBLE); - dbmsType2OrientType.put("smallmoney", OType.FLOAT); + /* + * Monetary Types + * (doc at https://msdn.microsoft.com/en-us/library/ms179882.aspx ) + */ + dbmsType2OrientType.put("money", OType.DOUBLE); + dbmsType2OrientType.put("smallmoney", OType.FLOAT); - /* - * Bit String Types - * (doc at https://msdn.microsoft.com/en-us/library/ms177603.aspx ) - */ - dbmsType2OrientType.put("bit", OType.STRING); + /* + * Bit String Types + * (doc at https://msdn.microsoft.com/en-us/library/ms177603.aspx ) + */ + dbmsType2OrientType.put("bit", OType.STRING); - /* - * Date/Time Types - * (doc at https://msdn.microsoft.com/en-us/library/bb630352.aspx, https://msdn.microsoft.com/en-us/library/bb677243.aspx, https://msdn.microsoft.com/en-us/library/ms182418.aspx, - * https://msdn.microsoft.com/en-us/library/ms187819.aspx, https://msdn.microsoft.com/en-us/library/bb677335.aspx, https://msdn.microsoft.com/en-us/library/bb630289.aspx ) - */ - dbmsType2OrientType.put("date", OType.DATE); - dbmsType2OrientType.put("time", OType.STRING); - dbmsType2OrientType.put("smalldatetime", OType.DATETIME); - dbmsType2OrientType.put("datetime", OType.DATETIME); - dbmsType2OrientType.put("datetime2", OType.DATETIME); - dbmsType2OrientType.put("datetimeoffset", OType.DATETIME); + /* + * Date/Time Types + * (doc at https://msdn.microsoft.com/en-us/library/bb630352.aspx, https://msdn.microsoft.com/en-us/library/bb677243.aspx, https://msdn.microsoft.com/en-us/library/ms182418.aspx, + * https://msdn.microsoft.com/en-us/library/ms187819.aspx, https://msdn.microsoft.com/en-us/library/bb677335.aspx, https://msdn.microsoft.com/en-us/library/bb630289.aspx ) + */ + dbmsType2OrientType.put("date", OType.DATE); + dbmsType2OrientType.put("time", OType.STRING); + dbmsType2OrientType.put("smalldatetime", OType.DATETIME); + dbmsType2OrientType.put("datetime", OType.DATETIME); + dbmsType2OrientType.put("datetime2", OType.DATETIME); + dbmsType2OrientType.put("datetimeoffset", OType.DATETIME); - /* - * Binary Data Types - * (doc at https://msdn.microsoft.com/en-us/library/ms188362.aspx, https://msdn.microsoft.com/en-us/library/ms187993.aspx ) - */ - dbmsType2OrientType.put("binary", OType.BINARY); - dbmsType2OrientType.put("varbinary", OType.BINARY); - dbmsType2OrientType.put("binary varying", OType.BINARY); - dbmsType2OrientType.put("image", OType.BINARY); + /* + * Binary Data Types + * (doc at https://msdn.microsoft.com/en-us/library/ms188362.aspx, https://msdn.microsoft.com/en-us/library/ms187993.aspx ) + */ + dbmsType2OrientType.put("binary", OType.BINARY); + dbmsType2OrientType.put("varbinary", OType.BINARY); + dbmsType2OrientType.put("binary varying", OType.BINARY); + dbmsType2OrientType.put("image", OType.BINARY); - return dbmsType2OrientType; - } + return dbmsType2OrientType; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/util/DBSourceConnection.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/util/DBSourceConnection.java index a50d1389..3bcb7851 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/util/DBSourceConnection.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/util/DBSourceConnection.java @@ -23,14 +23,12 @@ import com.arcadeanalytics.provider.DataSourceInfo; import com.arcadeanalytics.provider.rdbms.exception.RDBMSProviderRuntimeException; import com.fasterxml.jackson.databind.ObjectMapper; - import java.sql.Connection; import java.sql.DriverManager; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Properties; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,59 +37,62 @@ * * @author Gabriele Ponzi */ - public class DBSourceConnection { - private static final Logger log = LoggerFactory.getLogger(DBSourceConnection.class); + private static final Logger log = LoggerFactory.getLogger(DBSourceConnection.class); - private static Map type2template = new HashMap() { + private static Map type2template = + new HashMap() { { - put("RDBMS_HSQL", "jdbc:hsqldb:{server}:{database}"); - put("RDBMS_DATA_WORLD", "jdbc:data:world:sql:{server}:{database}"); - put("RDBMS_POSTGRESQL", "jdbc:postgresql://{server}:{port}/{database}"); - put("RDBMS_MYSQL", "jdbc:mysql://{server}:{port}/{database}?nullNamePatternMatchesAll=true&autoReconnect=true&useSSL=false"); - put("RDBMS_MSSQLSERVER", "jdbc:sqlserver://{server}:{port};databaseName={database}"); - put("RDBMS_ORACLE", "jdbc:oracle:thin:@{server}:{port}:{database}"); + put("RDBMS_HSQL", "jdbc:hsqldb:{server}:{database}"); + put("RDBMS_DATA_WORLD", "jdbc:data:world:sql:{server}:{database}"); + put("RDBMS_POSTGRESQL", "jdbc:postgresql://{server}:{port}/{database}"); + put( + "RDBMS_MYSQL", + "jdbc:mysql://{server}:{port}/{database}?nullNamePatternMatchesAll=true&autoReconnect=true&useSSL=false"); + put("RDBMS_MSSQLSERVER", "jdbc:sqlserver://{server}:{port};databaseName={database}"); + put("RDBMS_ORACLE", "jdbc:oracle:thin:@{server}:{port}:{database}"); } - }; + }; - /** - * Gets connection according to all the source database info passed as parameter. - * - * @param datasource the ds - * @return a connection - */ - public static Connection getConnection(DataSourceInfo datasource) { - String uri = createConnectionUrl(datasource); - log.debug("getting connection for:: {} ", uri); + /** + * Gets connection according to all the source database info passed as parameter. + * + * @param datasource the ds + * @return a connection + */ + public static Connection getConnection(DataSourceInfo datasource) { + String uri = createConnectionUrl(datasource); + log.debug("getting connection for:: {} ", uri); - Properties props = new Properties(); - props.setProperty("user", datasource.getUsername()); - props.setProperty("password", datasource.getPassword()); + Properties props = new Properties(); + props.setProperty("user", datasource.getUsername()); + props.setProperty("password", datasource.getPassword()); - try { - Map connectionAdditionalProperties = new ObjectMapper() - .readValue(Optional.ofNullable(datasource.getConnectionProperties()) - .orElse("{}"), HashMap.class); + try { + Map connectionAdditionalProperties = + new ObjectMapper() + .readValue( + Optional.ofNullable(datasource.getConnectionProperties()).orElse("{}"), + HashMap.class); - if (connectionAdditionalProperties.size() > 0) { - for (String connectionProp : connectionAdditionalProperties.keySet()) { - props.setProperty(connectionProp, connectionAdditionalProperties.get(connectionProp)); - } - } - - Connection connection = DriverManager.getConnection(uri, props); - return connection; - } catch (Exception e) { - throw new RDBMSProviderRuntimeException(e); + if (!connectionAdditionalProperties.isEmpty()) { + for (String connectionProp : connectionAdditionalProperties.keySet()) { + props.setProperty(connectionProp, connectionAdditionalProperties.get(connectionProp)); } - } + } - public static String createConnectionUrl(DataSourceInfo datasource) { - return type2template - .get(datasource.getType()) - .replace("{server}", datasource.getServer()) - .replace("{port}", String.valueOf(datasource.getPort())) - .replace("{database}", datasource.getDatabase()); + return DriverManager.getConnection(uri, props); + } catch (Exception e) { + throw new RDBMSProviderRuntimeException(e); } + } + + public static String createConnectionUrl(DataSourceInfo datasource) { + return type2template + .get(datasource.getType()) + .replace("{server}", datasource.getServer()) + .replace("{port}", String.valueOf(datasource.getPort())) + .replace("{database}", datasource.getDatabase()); + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/util/QueryResult.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/util/QueryResult.java index 2e7a0ea5..e53340e4 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/util/QueryResult.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/util/QueryResult.java @@ -32,75 +32,76 @@ * * @author Gabriele Ponzi */ - public class QueryResult { - private final Logger log = LoggerFactory.getLogger(QueryResult.class); - private final Connection dbConnection; - private final Statement statement; - private final ResultSet result; - private final String originalQuery; + private final Logger log = LoggerFactory.getLogger(QueryResult.class); + private final Connection dbConnection; + private final Statement statement; + private final ResultSet result; + private final String originalQuery; - public QueryResult(Connection connection, Statement statement, ResultSet result, String originalQuery) { - this.dbConnection = connection; - this.statement = statement; - this.result = result; - this.originalQuery = originalQuery; - } + public QueryResult( + Connection connection, Statement statement, ResultSet result, String originalQuery) { + this.dbConnection = connection; + this.statement = statement; + this.result = result; + this.originalQuery = originalQuery; + } - public Connection getDbConnection() { - return this.dbConnection; - } + public Connection getDbConnection() { + return this.dbConnection; + } - public Statement getStatement() { - return this.statement; - } + public Statement getStatement() { + return this.statement; + } - public ResultSet getResult() { - return result; - } + public ResultSet getResult() { + return result; + } - public String getOriginalQuery() { - return this.originalQuery; - } + public String getOriginalQuery() { + return this.originalQuery; + } - public void close() { - try { - statement.close(); - result.close(); - } catch (SQLException e) { - log.error("", e); - } + public void close() { + try { + statement.close(); + result.close(); + } catch (SQLException e) { + log.error("", e); } + } - public boolean isConnectionClosed() { - try { - return dbConnection.isClosed(); - } catch (Exception e) { - log.error("", e); - } - return false; + public boolean isConnectionClosed() { + try { + return dbConnection.isClosed(); + } catch (Exception e) { + log.error("", e); } + return false; + } - public boolean isStatementClosed() { - try { - return statement.isClosed(); - } catch (Exception e) { - log.error("", e); - } - return false; + public boolean isStatementClosed() { + try { + return statement.isClosed(); + } catch (Exception e) { + log.error("", e); } + return false; + } - public boolean isResultSetClosed() { - try { - return result.isClosed(); - } catch (Exception e) { - log.error("", e); - } - return false; + public boolean isResultSetClosed() { + try { + return result.isClosed(); + } catch (Exception e) { + log.error("", e); } + return false; + } - public boolean isAllClosed() { - if (isConnectionClosed() && isStatementClosed() && isResultSetClosed()) return true; else return false; - } + public boolean isAllClosed() { + if (isConnectionClosed() && isStatementClosed() && isResultSetClosed()) return true; + else return false; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/util/RelationshipQueryResult.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/util/RelationshipQueryResult.java index b5b00fac..c3fff83e 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/util/RelationshipQueryResult.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/persistence/util/RelationshipQueryResult.java @@ -25,22 +25,28 @@ import java.sql.Statement; /** - * Encapsulates the query results with the correspondent statement and connection as the super class Query Result. - * This class is used to collect all the info about the query performed to count the navigable connections of each record. + * Encapsulates the query results with the correspondent statement and connection as the super class + * Query Result. This class is used to collect all the info about the query performed to count the + * navigable connections of each record. * * @author Gabriele Ponzi */ - public class RelationshipQueryResult extends QueryResult { - private String relationshipName; // usually corresponds to the name of the correspondent edge class + private String + relationshipName; // usually corresponds to the name of the correspondent edge class - public RelationshipQueryResult(Connection connection, Statement statement, ResultSet result, String originalQuery, String relationshipName) { - super(connection, statement, result, originalQuery); - this.relationshipName = relationshipName; - } + public RelationshipQueryResult( + Connection connection, + Statement statement, + ResultSet result, + String originalQuery, + String relationshipName) { + super(connection, statement, result, originalQuery); + this.relationshipName = relationshipName; + } - public String getRelationshipName() { - return this.relationshipName; - } + public String getRelationshipName() { + return this.relationshipName; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/strategy/WorkflowStrategy.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/strategy/WorkflowStrategy.java index aa6c748b..8d114297 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/strategy/WorkflowStrategy.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/strategy/WorkflowStrategy.java @@ -31,19 +31,17 @@ * * @author Gabriele Ponzi */ - public interface WorkflowStrategy { - void executeStrategy( - DataSourceInfo dataSource, - String outOrientGraphUri, - String chosenMapper, - String xmlPath, - String nameResolverConvention, - List includedTables, - List excludedTables, - ODocument migrationConfig, - String executionStrategy, - DBQueryEngine queryEngine, - Statistics statistics - ); + void executeStrategy( + DataSourceInfo dataSource, + String outOrientGraphUri, + String chosenMapper, + String xmlPath, + String nameResolverConvention, + List includedTables, + List excludedTables, + ODocument migrationConfig, + String executionStrategy, + DBQueryEngine queryEngine, + Statistics statistics); } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/strategy/rdbms/AbstractDBMSModelBuildingStrategy.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/strategy/rdbms/AbstractDBMSModelBuildingStrategy.java index 4649749c..20711d93 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/strategy/rdbms/AbstractDBMSModelBuildingStrategy.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/strategy/rdbms/AbstractDBMSModelBuildingStrategy.java @@ -39,72 +39,71 @@ /** * @author Gabriele Ponzi */ - public abstract class AbstractDBMSModelBuildingStrategy implements WorkflowStrategy { - private final Logger log = LoggerFactory.getLogger(AbstractDBMSModelBuildingStrategy.class); + private final Logger log = LoggerFactory.getLogger(AbstractDBMSModelBuildingStrategy.class); - protected ER2GraphMapper mapper; + protected ER2GraphMapper mapper; - public AbstractDBMSModelBuildingStrategy() {} + public AbstractDBMSModelBuildingStrategy() {} - @Override - public void executeStrategy( - DataSourceInfo dataSource, - String outOrientGraphUri, - String chosenMapper, - String xmlPath, - String nameResolverConvention, - List includedTables, - List excludedTables, - ODocument migrationConfigDoc, - String executionStrategy, - DBQueryEngine queryEngine, - Statistics statistics - ) { - Date globalStart = new Date(); + @Override + public void executeStrategy( + DataSourceInfo dataSource, + String outOrientGraphUri, + String chosenMapper, + String xmlPath, + String nameResolverConvention, + List includedTables, + List excludedTables, + ODocument migrationConfigDoc, + String executionStrategy, + DBQueryEngine queryEngine, + Statistics statistics) { + Date globalStart = new Date(); - DataTypeHandlerFactory dataTypeHandlerFactory = new DataTypeHandlerFactory(); - DBMSDataTypeHandler handler = (DBMSDataTypeHandler) dataTypeHandlerFactory.buildDataTypeHandler(dataSource.getType()); + DataTypeHandlerFactory dataTypeHandlerFactory = new DataTypeHandlerFactory(); + DBMSDataTypeHandler handler = + (DBMSDataTypeHandler) dataTypeHandlerFactory.buildDataTypeHandler(dataSource.getType()); - /* - * Step 1,2 - */ + /* + * Step 1,2 + */ - NameResolverFactory nameResolverFactory = new NameResolverFactory(); - NameResolver nameResolver = nameResolverFactory.buildNameResolver(nameResolverConvention); + NameResolverFactory nameResolverFactory = new NameResolverFactory(); + NameResolver nameResolver = nameResolverFactory.buildNameResolver(nameResolverConvention); - this.mapper = - this.createSchemaMapper( - dataSource, - outOrientGraphUri, - chosenMapper, - xmlPath, - nameResolver, - handler, - includedTables, - excludedTables, - executionStrategy, - queryEngine, - statistics - ); + this.mapper = + this.createSchemaMapper( + dataSource, + outOrientGraphUri, + chosenMapper, + xmlPath, + nameResolver, + handler, + includedTables, + excludedTables, + executionStrategy, + queryEngine, + statistics); - Date globalEnd = new Date(); + Date globalEnd = new Date(); - log.info("Graph model building complete in {}", FunctionsHandler.getHMSFormat(globalStart, globalEnd)); - } + log.info( + "Graph model building complete in {}", + FunctionsHandler.getHMSFormat(globalStart, globalEnd)); + } - public abstract ER2GraphMapper createSchemaMapper( - DataSourceInfo dataSource, - String outOrientGraphUri, - String chosenMapper, - String xmlPath, - NameResolver nameResolver, - DBMSDataTypeHandler handler, - List includedTables, - List excludedTables, - String executionStrategy, - DBQueryEngine queryEngine, - Statistics statistics - ); + public abstract ER2GraphMapper createSchemaMapper( + DataSourceInfo dataSource, + String outOrientGraphUri, + String chosenMapper, + String xmlPath, + NameResolver nameResolver, + DBMSDataTypeHandler handler, + List includedTables, + List excludedTables, + String executionStrategy, + DBQueryEngine queryEngine, + Statistics statistics); } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/strategy/rdbms/DBMSModelBuildingAggregationStrategy.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/strategy/rdbms/DBMSModelBuildingAggregationStrategy.java index 3d79ce0c..31ebe490 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/strategy/rdbms/DBMSModelBuildingAggregationStrategy.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/strategy/rdbms/DBMSModelBuildingAggregationStrategy.java @@ -33,26 +33,26 @@ /** * @author Gabriele Ponzi */ - public class DBMSModelBuildingAggregationStrategy extends AbstractDBMSModelBuildingStrategy { - private static final Logger log = LoggerFactory.getLogger(DBMSModelBuildingAggregationStrategy.class); + private static final Logger log = + LoggerFactory.getLogger(DBMSModelBuildingAggregationStrategy.class); - @Override - public ER2GraphMapper createSchemaMapper( - DataSourceInfo dataSource, - String outOrientGraphUri, - String chosenMapper, - String xmlPath, - NameResolver nameResolver, - DBMSDataTypeHandler handler, - List includedTables, - List excludedTables, - String executionStrategy, - DBQueryEngine queryEngine, - Statistics statistics - ) { - ER2GraphMapper mapper = new ER2GraphMapper( + @Override + public ER2GraphMapper createSchemaMapper( + DataSourceInfo dataSource, + String outOrientGraphUri, + String chosenMapper, + String xmlPath, + NameResolver nameResolver, + DBMSDataTypeHandler handler, + List includedTables, + List excludedTables, + String executionStrategy, + DBQueryEngine queryEngine, + Statistics statistics) { + ER2GraphMapper mapper = + new ER2GraphMapper( dataSource, includedTables, excludedTables, @@ -60,21 +60,20 @@ public ER2GraphMapper createSchemaMapper( handler, executionStrategy, nameResolver, - statistics - ); + statistics); - // Step 1: DataBase schema building - mapper.buildSourceDatabaseSchema(); - log.debug("{}", mapper.getDataBaseSchema().toString()); + // Step 1: DataBase schema building + mapper.buildSourceDatabaseSchema(); + log.debug("{}", mapper.getDataBaseSchema().toString()); - // Step 2: Graph model building - mapper.buildGraphModel(nameResolver); - log.debug("{}", mapper.getGraphModel().toString()); + // Step 2: Graph model building + mapper.buildGraphModel(nameResolver); + log.debug("{}", mapper.getGraphModel().toString()); - // Step 3: Aggregation - mapper.performAggregations(); - log.debug("'Junction-Entity' aggregation complete:: {}", mapper.getGraphModel().toString()); + // Step 3: Aggregation + mapper.performAggregations(); + log.debug("'Junction-Entity' aggregation complete:: {}", mapper.getGraphModel().toString()); - return mapper; - } + return mapper; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/strategy/rdbms/DBMSSimpleModelBuildingStrategy.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/strategy/rdbms/DBMSSimpleModelBuildingStrategy.java index 5a686e09..a4047016 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/strategy/rdbms/DBMSSimpleModelBuildingStrategy.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/strategy/rdbms/DBMSSimpleModelBuildingStrategy.java @@ -33,28 +33,27 @@ /** * @author Gabriele Ponzi */ - public class DBMSSimpleModelBuildingStrategy extends AbstractDBMSModelBuildingStrategy { - private static final Logger log = LoggerFactory.getLogger(DBMSSimpleModelBuildingStrategy.class); + private static final Logger log = LoggerFactory.getLogger(DBMSSimpleModelBuildingStrategy.class); - public DBMSSimpleModelBuildingStrategy() {} + public DBMSSimpleModelBuildingStrategy() {} - @Override - public ER2GraphMapper createSchemaMapper( - DataSourceInfo dataSource, - String outOrientGraphUri, - String chosenMapper, - String xmlPath, - NameResolver nameResolver, - DBMSDataTypeHandler handler, - List includedTables, - List excludedTables, - String executionStrategy, - DBQueryEngine queryEngine, - Statistics statistics - ) { - ER2GraphMapper mapper = new ER2GraphMapper( + @Override + public ER2GraphMapper createSchemaMapper( + DataSourceInfo dataSource, + String outOrientGraphUri, + String chosenMapper, + String xmlPath, + NameResolver nameResolver, + DBMSDataTypeHandler handler, + List includedTables, + List excludedTables, + String executionStrategy, + DBQueryEngine queryEngine, + Statistics statistics) { + ER2GraphMapper mapper = + new ER2GraphMapper( dataSource, includedTables, excludedTables, @@ -62,17 +61,16 @@ public ER2GraphMapper createSchemaMapper( handler, executionStrategy, nameResolver, - statistics - ); + statistics); - // Step 1: DataBase schema building - mapper.buildSourceDatabaseSchema(); - log.debug("{}", mapper.getDataBaseSchema().toString()); + // Step 1: DataBase schema building + mapper.buildSourceDatabaseSchema(); + log.debug("{}", mapper.getDataBaseSchema().toString()); - // Step 2: Graph model building - mapper.buildGraphModel(nameResolver); - log.debug("{}", mapper.getGraphModel().toString()); + // Step 2: Graph model building + mapper.buildGraphModel(nameResolver); + log.debug("{}", mapper.getGraphModel().toString()); - return mapper; - } + return mapper; + } } diff --git a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/util/FunctionsHandler.java b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/util/FunctionsHandler.java index 447283a1..73a3a1e0 100644 --- a/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/util/FunctionsHandler.java +++ b/rdbms/src/main/java/com/arcadeanalytics/provider/rdbms/util/FunctionsHandler.java @@ -29,69 +29,75 @@ * * @author Gabriele Ponzi */ - public class FunctionsHandler { - public static String getHMSFormat(Date start, Date end) { - String hmsTime = String.format( + public static String getHMSFormat(Date start, Date end) { + String hmsTime = + String.format( "%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(end.getTime() - start.getTime()), - TimeUnit.MILLISECONDS.toMinutes(end.getTime() - start.getTime()) - - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(end.getTime() - start.getTime())), - TimeUnit.MILLISECONDS.toSeconds(end.getTime() - start.getTime()) - - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(end.getTime() - start.getTime())) - ); + TimeUnit.MILLISECONDS.toMinutes(end.getTime() - start.getTime()) + - TimeUnit.HOURS.toMinutes( + TimeUnit.MILLISECONDS.toHours(end.getTime() - start.getTime())), + TimeUnit.MILLISECONDS.toSeconds(end.getTime() - start.getTime()) + - TimeUnit.MINUTES.toSeconds( + TimeUnit.MILLISECONDS.toMinutes(end.getTime() - start.getTime()))); - return hmsTime; - } + return hmsTime; + } - public static String getHMSFormat(long millis) { - String hmsTime = String.format( + public static String getHMSFormat(long millis) { + String hmsTime = + String.format( "%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis), - TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), - TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)) - ); + TimeUnit.MILLISECONDS.toMinutes(millis) + - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), + TimeUnit.MILLISECONDS.toSeconds(millis) + - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))); - return hmsTime; - } + return hmsTime; + } - public static boolean haveDocumentsSameContent(ODocument d1, ODocument d2) { - /* - * properties check - * (i) number - * (ii) name - * (iii) content (recursive) - */ + public static boolean haveDocumentsSameContent(ODocument d1, ODocument d2) { + /* + * properties check + * (i) number + * (ii) name + * (iii) content (recursive) + */ - // (i) number of properties - if (d1.toMap().keySet().size() != d2.toMap().keySet().size()) { - return false; - } + // (i) number of properties + if (d1.toMap().keySet().size() != d2.toMap().keySet().size()) { + return false; + } - for (String key1 : d1.toMap().keySet()) { - // (ii) name of fields - if (!d2.toMap().keySet().contains(key1)) { - return false; - } else { - //(iii) content (recursive) - Object obj1 = d1.toMap().get(key1); - Object obj2 = d2.toMap().get(key1); + for (String key1 : d1.toMap().keySet()) { + // (ii) name of fields + if (!d2.toMap().keySet().contains(key1)) { + return false; + } else { + // (iii) content (recursive) + Object obj1 = d1.toMap().get(key1); + Object obj2 = d2.toMap().get(key1); - if (obj1 instanceof String && obj2 instanceof String) { // base case: value is a string - if (!obj1.equals(obj2)) { - return false; - } - } else if (obj1 instanceof ODocument && obj2 instanceof ODocument) { // inductive case: two values are documents, recursive comparison - if (!haveDocumentsSameContent(((ODocument) obj1), ((ODocument) obj2))) { - return false; - } - } else { - return false; // different aggregation level --> values not equivalent - } - } + if (obj1 instanceof String && obj2 instanceof String) { // base case: value is a string + if (!obj1.equals(obj2)) { + return false; + } + } else if (obj1 instanceof ODocument + && obj2 + instanceof + ODocument) { // inductive case: two values are documents, recursive comparison + if (!haveDocumentsSameContent(((ODocument) obj1), ((ODocument) obj2))) { + return false; + } + } else { + return false; // different aggregation level --> values not equivalent } - - return true; + } } + + return true; + } } diff --git a/rdbms/src/main/kotlin/com/arcadeanalytics/provider/rdbms/RDBMSMetadataProvider.kt b/rdbms/src/main/kotlin/com/arcadeanalytics/provider/rdbms/RDBMSMetadataProvider.kt index 20a0ee93..d0ca5195 100644 --- a/rdbms/src/main/kotlin/com/arcadeanalytics/provider/rdbms/RDBMSMetadataProvider.kt +++ b/rdbms/src/main/kotlin/com/arcadeanalytics/provider/rdbms/RDBMSMetadataProvider.kt @@ -37,15 +37,15 @@ import com.arcadeanalytics.provider.rdbms.strategy.rdbms.AbstractDBMSModelBuildi import java.sql.ResultSet class RDBMSMetadataProvider : DataSourceMetadataProvider { - - override fun supportedDataSourceTypes(): Set = setOf( - "RDBMS_POSTGRESQL", - "RDBMS_MYSQL", - "RDBMS_MSSQLSERVER", - "RDBMS_HSQL", - "RDBMS_ORACLE", - "RDBMS_DATA_WORLD", - ) + override fun supportedDataSourceTypes(): Set = + setOf( + "RDBMS_POSTGRESQL", + "RDBMS_MYSQL", + "RDBMS_MSSQLSERVER", + "RDBMS_HSQL", + "RDBMS_ORACLE", + "RDBMS_DATA_WORLD", + ) override fun fetchMetadata(dataSource: DataSourceInfo): DataSourceMetadata { val dbQueryEngine: DBQueryEngine = DBQueryEngine(dataSource, 300) @@ -54,16 +54,28 @@ class RDBMSMetadataProvider : DataSourceMetadataProvider { val graphModel = mapper.graphModel - val nodesClasses = graphModel.verticesType - .map { - val props = it.allProperties - .map { prop -> prop.name to TypeProperty(prop.name, prop.orientdbType) } - .toMap() - - var cardinality: Long = 0 - if (dataSource.aggregationEnabled) { - if (!it.isFromJoinTable) { - mapper.vertexType2EVClassMappers.get(it)?.get(0)?.entity?.name?.let { tableName -> + val nodesClasses = + graphModel.verticesType + .map { + val props = + it.allProperties + .map { prop -> prop.name to TypeProperty(prop.name, prop.orientdbType) } + .toMap() + + var cardinality: Long = 0 + if (dataSource.aggregationEnabled) { + if (!it.isFromJoinTable) { + mapper.vertexType2EVClassMappers.get(it)?.get(0)?.entity?.name?.let { tableName -> + val queryResult: QueryResult = dbQueryEngine.countTableRecords(tableName) + val countResult: ResultSet = queryResult.result + if (countResult.next()) { + cardinality = countResult.getLong(1) + } + queryResult.close() + } + } + } else { + mapper.vertexType2EVClassMappers.get(it)?.get(0)?.entity?.name.let { tableName -> val queryResult: QueryResult = dbQueryEngine.countTableRecords(tableName) val countResult: ResultSet = queryResult.result if (countResult.next()) { @@ -72,77 +84,87 @@ class RDBMSMetadataProvider : DataSourceMetadataProvider { queryResult.close() } } - } else { - mapper.vertexType2EVClassMappers.get(it)?.get(0)?.entity?.name.let { tableName -> - val queryResult: QueryResult = dbQueryEngine.countTableRecords(tableName) - val countResult: ResultSet = queryResult.result - if (countResult.next()) { - cardinality = countResult.getLong(1) - } - queryResult.close() - } - } - - TypeClass(it.name, cardinality, props) - }.map { - it.name to it - }.toMap() - - val edgesClasses: EdgesClasses = graphModel.edgesType - .map { edgeType -> - val props = edgeType.allProperties - .map { prop -> prop.name to TypeProperty(prop.name, prop.orientdbType) } - .toMap() - val edgeTypeName: String = edgeType.name - - var cardinality: Long = 0 - - if (dataSource.aggregationEnabled) { - if (edgeType.isAggregatorEdge) { - mapper.getJoinVertexTypeByAggregatorEdgeName(edgeTypeName)?.run { - val joinTable = mapper.getEntityByVertexType(this, 0) // join vertex has always 1-1 mapping with the join table, so I always get the first mapping - val queryResult: QueryResult = dbQueryEngine.countTableRecords(joinTable.name) - val countResult: ResultSet = queryResult.result - if (countResult.next()) { - cardinality += countResult.getLong(1) - } - queryResult.close() - } - } else { - val mappedRelationships = mapper.edgeType2relationships.get(edgeType) - mappedRelationships?.forEach { - if (!it.foreignEntity.isAggregableJoinTable) { // excluding relationships that are aggregated in aggregator edges, then all that have a join table as parent entity - val queryResult: RelationshipQueryResult = dbQueryEngine.computeRelationshipCardinality(it, dataSource, edgeTypeName) + TypeClass(it.name, cardinality, props) + }.map { + it.name to it + }.toMap() + + val edgesClasses: EdgesClasses = + graphModel.edgesType + .map { edgeType -> + val props = + edgeType.allProperties + .map { prop -> prop.name to TypeProperty(prop.name, prop.orientdbType) } + .toMap() + + val edgeTypeName: String = edgeType.name + + var cardinality: Long = 0 + + if (dataSource.aggregationEnabled) { + if (edgeType.isAggregatorEdge) { + mapper.getJoinVertexTypeByAggregatorEdgeName(edgeTypeName)?.run { + val joinTable = + mapper.getEntityByVertexType( + this, + 0, + ) // join vertex has always 1-1 mapping with the join table, so I always get the first mapping + val queryResult: QueryResult = dbQueryEngine.countTableRecords(joinTable.name) val countResult: ResultSet = queryResult.result if (countResult.next()) { cardinality += countResult.getLong(1) } queryResult.close() } + } else { + val mappedRelationships = mapper.edgeType2relationships.get(edgeType) + mappedRelationships?.forEach { + // excluding relationships that are aggregated in aggregator edges, then all that have a join table as parent entity + if (!it.foreignEntity.isAggregableJoinTable) { + val queryResult: RelationshipQueryResult = + dbQueryEngine.computeRelationshipCardinality( + it, + dataSource, + edgeTypeName, + ) + val countResult: ResultSet = queryResult.result + if (countResult.next()) { + cardinality += countResult.getLong(1) + } + queryResult.close() + } + } } - } - } else { - val mappedRelationships = mapper.edgeType2relationships.get(edgeType) - mappedRelationships?.forEach { rel -> - val queryResult: RelationshipQueryResult = dbQueryEngine.computeRelationshipCardinality(rel, dataSource, edgeTypeName) - val countResult: ResultSet = queryResult.result - if (countResult.next()) { - cardinality += countResult.getLong(1) + } else { + val mappedRelationships = mapper.edgeType2relationships.get(edgeType) + mappedRelationships?.forEach { rel -> + val queryResult: RelationshipQueryResult = + dbQueryEngine.computeRelationshipCardinality( + rel, + dataSource, + edgeTypeName, + ) + val countResult: ResultSet = queryResult.result + if (countResult.next()) { + cardinality += countResult.getLong(1) + } + queryResult.close() } - queryResult.close() } - } - TypeClass(edgeType.name, cardinality, props) - }.map { - it.name to it - }.toMap() + TypeClass(edgeType.name, cardinality, props) + }.map { + it.name to it + }.toMap() dbQueryEngine.close() return DataSourceMetadata(nodesClasses, edgesClasses) } - private fun getMapper(dbQueryEngine: DBQueryEngine, dataSource: DataSourceInfo): ER2GraphMapper { + private fun getMapper( + dbQueryEngine: DBQueryEngine, + dataSource: DataSourceInfo, + ): ER2GraphMapper { val statistics = Statistics() val aggregate = dataSource.aggregationEnabled @@ -158,20 +180,21 @@ class RDBMSMetadataProvider : DataSourceMetadataProvider { val strategyFactory = StrategyFactory() - val mapper = (strategyFactory.buildStrategy(chosenStrategy) as AbstractDBMSModelBuildingStrategy) - .createSchemaMapper( - dataSource, - null, - "basicDBMapper", - null, - nameResolver, - handler, - null, - null, - chosenStrategy, - dbQueryEngine, - statistics, - ) + val mapper = + (strategyFactory.buildStrategy(chosenStrategy) as AbstractDBMSModelBuildingStrategy) + .createSchemaMapper( + dataSource, + null, + "basicDBMapper", + null, + nameResolver, + handler, + null, + null, + chosenStrategy, + dbQueryEngine, + statistics, + ) return mapper as ER2GraphMapper } diff --git a/rdbms/src/main/kotlin/com/arcadeanalytics/provider/rdbms/RDBMSTableDataProvider.kt b/rdbms/src/main/kotlin/com/arcadeanalytics/provider/rdbms/RDBMSTableDataProvider.kt index 8a1c57ac..a892c525 100644 --- a/rdbms/src/main/kotlin/com/arcadeanalytics/provider/rdbms/RDBMSTableDataProvider.kt +++ b/rdbms/src/main/kotlin/com/arcadeanalytics/provider/rdbms/RDBMSTableDataProvider.kt @@ -15,8 +15,11 @@ import java.sql.ResultSet import java.sql.ResultSetMetaData class RDBMSTableDataProvider : DataSourceTableDataProvider { - - override fun fetchData(dataSource: DataSourceInfo, query: String, limit: Int): GraphData { + override fun fetchData( + dataSource: DataSourceInfo, + query: String, + limit: Int, + ): GraphData { DBSourceConnection.getConnection(dataSource).use { conn -> conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY).use { stmt -> @@ -66,7 +69,10 @@ class RDBMSTableDataProvider : DataSourceTableDataProvider { } } - private fun mapMetadata(columns: Int, md: ResultSetMetaData): MutableMap { + private fun mapMetadata( + columns: Int, + md: ResultSetMetaData, + ): MutableMap { val nodesProperties = mutableMapOf() for (i in 1..columns) { @@ -78,7 +84,11 @@ class RDBMSTableDataProvider : DataSourceTableDataProvider { return nodesProperties } - private fun mapRows(rs: ResultSet, columns: Int, md: ResultSetMetaData): MutableSet { + private fun mapRows( + rs: ResultSet, + columns: Int, + md: ResultSetMetaData, + ): MutableSet { val cytoNodes = mutableSetOf() var cardinality: Long = 0 while (rs.next()) { @@ -89,31 +99,39 @@ class RDBMSTableDataProvider : DataSourceTableDataProvider { val data = Data(id = cardinality++.toString(), record = record) - val cytoData = CytoData( - classes = TABLE_CLASS, - group = "nodes", - data = data, - ) + val cytoData = + CytoData( + classes = TABLE_CLASS, + group = "nodes", + data = data, + ) cytoNodes.add(cytoData) } return cytoNodes } - override fun fetchData(dataSource: DataSourceInfo, query: String, params: QueryParams, limit: Int): GraphData { + override fun fetchData( + dataSource: DataSourceInfo, + query: String, + params: QueryParams, + limit: Int, + ): GraphData { var filledQuery = query - params.asSequence() + params + .asSequence() .forEach { p -> filledQuery = filledQuery.replace("${p.name.prefixIfAbsent(":")}", p.value) } return fetchData(dataSource, filledQuery, limit) } - override fun supportedDataSourceTypes(): Set = setOf( - "RDBMS_POSTGRESQL", - "RDBMS_MYSQL", - "RDBMS_MSSQLSERVER", - "RDBMS_HSQL", - "RDBMS_ORACLE", - "RDBMS_DATA_WORLD", - ) + override fun supportedDataSourceTypes(): Set = + setOf( + "RDBMS_POSTGRESQL", + "RDBMS_MYSQL", + "RDBMS_MSSQLSERVER", + "RDBMS_HSQL", + "RDBMS_ORACLE", + "RDBMS_DATA_WORLD", + ) } diff --git a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/AbstractRDBMSProviderTest.java b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/AbstractRDBMSProviderTest.java index 0efd7ac0..cc43e087 100644 --- a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/AbstractRDBMSProviderTest.java +++ b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/AbstractRDBMSProviderTest.java @@ -25,38 +25,38 @@ public abstract class AbstractRDBMSProviderTest { - protected RDBMSDataProvider provider; + protected RDBMSDataProvider provider; - @BeforeEach - public abstract void setUp() throws Exception; + @BeforeEach + public abstract void setUp() throws Exception; - @Test - public abstract void fetchDataThroughTableScanTest() throws Exception; + @Test + public abstract void fetchDataThroughTableScanTest() throws Exception; - @Test - public abstract void loadVerticesFromIdsSingleTableTest() throws Exception; + @Test + public abstract void loadVerticesFromIdsSingleTableTest() throws Exception; - @Test - public abstract void loadVerticesFromIdsMultipleTablesTest(); + @Test + public abstract void loadVerticesFromIdsMultipleTablesTest(); - @Test - public abstract void expand1To1RelWithSimpleFKTest() throws Exception; + @Test + public abstract void expand1To1RelWithSimpleFKTest() throws Exception; - @Test - public abstract void expand1ToNRelWithSimpleFKTest(); + @Test + public abstract void expand1ToNRelWithSimpleFKTest(); - @Test - public abstract void expandMultiple1ToNRelWithSimpleFKTest(); + @Test + public abstract void expandMultiple1ToNRelWithSimpleFKTest(); - @Test - public abstract void expand1ToNRelWithJoinTableAndSimpleFKTest(); + @Test + public abstract void expand1ToNRelWithJoinTableAndSimpleFKTest(); - @Test - public abstract void expand1To1RelWithCompositeFKTest(); + @Test + public abstract void expand1To1RelWithCompositeFKTest(); - @Test - public abstract void expand1ToNRelWithCompositeFKTest(); + @Test + public abstract void expand1ToNRelWithCompositeFKTest(); - @Test - public abstract void expand1ToNRelWithJoinTableAndCompositeFKTest(); + @Test + public abstract void expand1ToNRelWithJoinTableAndCompositeFKTest(); } diff --git a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/AbstractRDBMSProviderWithAggregationTest.java b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/AbstractRDBMSProviderWithAggregationTest.java index f9cf7336..8df73c8e 100644 --- a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/AbstractRDBMSProviderWithAggregationTest.java +++ b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/AbstractRDBMSProviderWithAggregationTest.java @@ -25,14 +25,14 @@ public abstract class AbstractRDBMSProviderWithAggregationTest { - protected RDBMSDataProvider provider; + protected RDBMSDataProvider provider; - @BeforeEach - public abstract void setUp() throws Exception; + @BeforeEach + public abstract void setUp() throws Exception; - @Test - public abstract void fetchDataThroughTableScanTest(); + @Test + public abstract void fetchDataThroughTableScanTest(); - @Test - public abstract void expandN2NRelationship(); + @Test + public abstract void expandN2NRelationship(); } diff --git a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/MySQLContainerHolder.java b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/MySQLContainerHolder.java index 86031236..df0c882a 100644 --- a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/MySQLContainerHolder.java +++ b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/MySQLContainerHolder.java @@ -25,15 +25,17 @@ public abstract class MySQLContainerHolder { - public static final MySQLContainer container; + public static final MySQLContainer container; - static { - container = - new MySQLContainer(DockerImageName.parse("arcadeanalytics/mysql-sakila").asCompatibleSubstituteFor("mysql")) - .withUsername("test") - .withPassword("test") - .withDatabaseName("sakila"); + static { + container = + new MySQLContainer( + DockerImageName.parse("arcadeanalytics/mysql-sakila") + .asCompatibleSubstituteFor("mysql")) + .withUsername("test") + .withPassword("test") + .withDatabaseName("sakila"); - container.start(); - } + container.start(); + } } diff --git a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/MysqlSQLDataProviderTest.java b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/MysqlSQLDataProviderTest.java index 53d3a095..004e96e7 100644 --- a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/MysqlSQLDataProviderTest.java +++ b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/MysqlSQLDataProviderTest.java @@ -20,10 +20,8 @@ * #L% */ -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import com.arcadeanalytics.provider.CytoData; import com.arcadeanalytics.provider.DataSourceInfo; @@ -31,9 +29,12 @@ import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; +import java.sql.Timestamp; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; +import java.time.LocalDateTime; +import java.time.ZoneOffset; import java.util.Date; import java.util.Iterator; import java.util.Map; @@ -43,1790 +44,1824 @@ import org.junit.jupiter.api.Test; import org.testcontainers.containers.MySQLContainer; -public class MysqlSQLDataProviderTest extends AbstractRDBMSProviderTest { - - private static final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssX"); - - private DataSourceInfo dataSource = null; - - @BeforeEach - public void setUp() throws Exception { - final MySQLContainer container = MySQLContainerHolder.container; - this.dataSource = - new DataSourceInfo( - 1L, - "RDBMS_MYSQL", - "testDataSource", - "desc", - container.getContainerIpAddress(), - container.getFirstMappedPort(), - container.getDatabaseName(), - container.getUsername(), - container.getPassword(), - false, - "{}", - false, - false, - "", - 22, - "", - false - ); - - provider = new RDBMSDataProvider(); +class MysqlSQLDataProviderTest extends AbstractRDBMSProviderTest { + + private static final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssX"); + + private DataSourceInfo dataSource = null; + + @BeforeEach + public void setUp() throws Exception { + final MySQLContainer container = MySQLContainerHolder.container; + this.dataSource = + new DataSourceInfo( + 1L, + "RDBMS_MYSQL", + "testDataSource", + "desc", + container.getContainerIpAddress(), + container.getFirstMappedPort(), + container.getDatabaseName(), + container.getUsername(), + container.getPassword(), + false, + "{}", + false, + false, + "", + 22, + "", + false); + + provider = new RDBMSDataProvider(); + } + + @Override + @Test + public void fetchDataThroughTableScanTest() throws Exception { + String query = "select * from actor limit 5"; + + GraphData data = provider.fetchData(dataSource, query, 5); + + assertThat(data.getNodesClasses().size()).isEqualTo(1); + assertThat(data.getNodes().size()).isEqualTo(5); + assertThat(data.getEdgesClasses().size()).isEqualTo(0); + assertThat(data.getEdges().size()).isEqualTo(0); + + // Node classes checks + assertThat(data.getNodesClasses().containsKey("actor")).isTrue(); + + Map actorClass = data.getNodesClasses().get("actor"); + assertThat(actorClass.containsKey("actor_id")).isTrue(); + assertThat(actorClass.containsKey("first_name")).isTrue(); + assertThat(actorClass.containsKey("last_name")).isTrue(); + assertThat(actorClass.containsKey("last_update")).isTrue(); + // nodes checks + Iterator it = data.getNodes().iterator(); + CytoData currNodeContent; + Map currRecord; + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(1); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("PENELOPE"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("GUINESS"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + // assertEquals("2006-02-15 05:34:33.0", currRecord.get("last_update").toString()); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 03:34:33-00").toInstant()); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(2); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("NICK"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("WAHLBERG"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + // assertEquals("2006-02-15 05:34:33.0", currRecord.get("last_update").toString()); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 03:34:33-00").toInstant()); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(3); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("ED"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("CHASE"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + // assertEquals("2006-02-15 05:34:33.0", currRecord.get("last_update").toString()); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 03:34:33-00").toInstant()); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(4); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("JENNIFER"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("DAVIS"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + // assertEquals("2006-02-15 05:34:33.0", currRecord.get("last_update").toString()); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 03:34:33-00").toInstant()); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(5); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("JOHNNY"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("LOLLOBRIGIDA"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + // assertEquals("2006-02-15 05:34:33.0", currRecord.get("last_update").toString()); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 03:34:33-00").toInstant()); + } + + @Override + @Test + public void loadVerticesFromIdsMultipleTablesTest() { + /* + * Fetching the first 5 vertices from the actor table and the first 2 vertices from the store table by cyto-ids + * cyto-id from is x_y where: + * - x is refers to the source table (actor is the first table in the source db schema) + * - y is the external key, then the pk value of the source record + */ + + String[] ids = {"1_1", "1_2", "1_3", "1_4", "1_5", "16_1", "16_2"}; + + GraphData data = provider.load(dataSource, ids); + + assertThat(data.getNodesClasses().size()).isEqualTo(2); + assertThat(data.getNodes().size()).isEqualTo(7); + assertThat(data.getEdgesClasses().size()).isEqualTo(0); + assertThat(data.getEdges().size()).isEqualTo(0); + + // Node classes checks + assertThat(data.getNodesClasses().containsKey("actor")).isTrue(); + assertThat(data.getNodesClasses().containsKey("store")).isTrue(); + + Map actorClass = data.getNodesClasses().get("actor"); + assertThat(actorClass.containsKey("actor_id")).isTrue(); + assertThat(actorClass.containsKey("first_name")).isTrue(); + assertThat(actorClass.containsKey("last_name")).isTrue(); + assertThat(actorClass.containsKey("last_update")).isTrue(); + Map storeClass = data.getNodesClasses().get("store"); + assertThat(storeClass.containsKey("store_id")).isTrue(); + assertThat(storeClass.containsKey("manager_staff_id")).isTrue(); + assertThat(storeClass.containsKey("address_id")).isTrue(); + assertThat(storeClass.containsKey("last_update")).isTrue(); + + // nodes checks + Iterator it = data.getNodes().iterator(); + CytoData currNodeContent; + Map currRecord; + + try { + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(1); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("PENELOPE"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("GUINESS"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 03:34:33-00").toInstant()); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(2); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("NICK"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("WAHLBERG"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 03:34:33-00").toInstant()); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(3); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("ED"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("CHASE"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 03:34:33-00").toInstant()); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(4); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("JENNIFER"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("DAVIS"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 03:34:33-00").toInstant()); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(5); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("JOHNNY"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("LOLLOBRIGIDA"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 03:34:33-00").toInstant()); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("store_id")).isTrue(); + assertThat(currRecord.get("store_id")).isEqualTo(1); + assertThat(currRecord.containsKey("manager_staff_id")).isTrue(); + assertThat(currRecord.get("manager_staff_id")).isEqualTo(1); + assertThat(currRecord.containsKey("address_id")).isTrue(); + assertThat(currRecord.get("address_id")).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 03:57:12-00").toInstant()); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("store_id")).isTrue(); + assertThat(currRecord.get("store_id")).isEqualTo(2); + assertThat(currRecord.containsKey("manager_staff_id")).isTrue(); + assertThat(currRecord.get("manager_staff_id")).isEqualTo(2); + assertThat(currRecord.containsKey("address_id")).isTrue(); + assertThat(currRecord.get("address_id")).isEqualTo(2); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 03:57:12-00").toInstant()); + } catch (ParseException e) { + e.printStackTrace(); + fail(""); } - - @Override - @Test - public void fetchDataThroughTableScanTest() throws Exception { - String query = "select * from actor limit 5"; - - GraphData data = provider.fetchData(dataSource, query, 5); - - assertEquals(data.getNodesClasses().size(), 1); - assertEquals(data.getNodes().size(), 5); - assertEquals(data.getEdgesClasses().size(), 0); - assertEquals(data.getEdges().size(), 0); - - // Node classes checks - assertTrue(data.getNodesClasses().containsKey("actor")); - - Map actorClass = data.getNodesClasses().get("actor"); - assertTrue(actorClass.containsKey("actor_id")); - assertTrue(actorClass.containsKey("first_name")); - assertTrue(actorClass.containsKey("last_name")); - assertTrue(actorClass.containsKey("last_update")); - // nodes checks - Iterator it = data.getNodes().iterator(); - CytoData currNodeContent; - Map currRecord; - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(1, currRecord.get("actor_id")); - assertTrue(currRecord.containsKey("first_name")); - assertEquals("PENELOPE", currRecord.get("first_name")); - assertTrue(currRecord.containsKey("last_name")); - assertEquals("GUINESS", currRecord.get("last_name")); - assertTrue(currRecord.containsKey("last_update")); - // assertEquals("2006-02-15 05:34:33.0", currRecord.get("last_update").toString()); - assertEquals(df.parse("2006-02-15 04:34:33-00").toInstant(), ((Date) currRecord.get("last_update")).toInstant()); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 2); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "NICK"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "WAHLBERG"); - assertTrue(currRecord.containsKey("last_update")); - // assertEquals("2006-02-15 05:34:33.0", currRecord.get("last_update").toString()); - assertEquals(df.parse("2006-02-15 04:34:33-00").toInstant(), ((Date) currRecord.get("last_update")).toInstant()); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(3, currRecord.get("actor_id")); - assertTrue(currRecord.containsKey("first_name")); - assertEquals("ED", currRecord.get("first_name")); - assertTrue(currRecord.containsKey("last_name")); - assertEquals("CHASE", currRecord.get("last_name")); - assertTrue(currRecord.containsKey("last_update")); - // assertEquals("2006-02-15 05:34:33.0", currRecord.get("last_update").toString()); - assertEquals(df.parse("2006-02-15 04:34:33-00").toInstant(), ((Date) currRecord.get("last_update")).toInstant()); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(4, currRecord.get("actor_id")); - assertTrue(currRecord.containsKey("first_name")); - assertEquals("JENNIFER", currRecord.get("first_name")); - assertTrue(currRecord.containsKey("last_name")); - assertEquals("DAVIS", currRecord.get("last_name")); - assertTrue(currRecord.containsKey("last_update")); - // assertEquals("2006-02-15 05:34:33.0", currRecord.get("last_update").toString()); - assertEquals(df.parse("2006-02-15 04:34:33-00").toInstant(), ((Date) currRecord.get("last_update")).toInstant()); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(5, currRecord.get("actor_id")); - assertTrue(currRecord.containsKey("first_name")); - assertEquals("JOHNNY", currRecord.get("first_name")); - assertTrue(currRecord.containsKey("last_name")); - assertEquals("LOLLOBRIGIDA", currRecord.get("last_name")); - assertTrue(currRecord.containsKey("last_update")); - // assertEquals("2006-02-15 05:34:33.0", currRecord.get("last_update").toString()); - assertEquals(df.parse("2006-02-15 04:34:33-00").toInstant(), ((Date) currRecord.get("last_update")).toInstant()); + } + + @Override + @Test + public void loadVerticesFromIdsSingleTableTest() throws Exception { + /* + * Fetching the first 5 vertices from the actor table by cyto-ids + * cyto-id from is x_y where: + * - x is refers to the source table (actor is the first table in the source db schema) + * - y is the external key, then the pk value of the source record + */ + + String[] actorIds = {"1_1", "1_2", "1_3", "1_4", "1_5"}; + + GraphData data = provider.load(dataSource, actorIds); + + assertThat(data.getNodesClasses().size()).isEqualTo(1); + assertThat(data.getNodes().size()).isEqualTo(5); + assertThat(data.getEdgesClasses().size()).isEqualTo(0); + assertThat(data.getEdges().size()).isEqualTo(0); + + // Node classes checks + assertThat(data.getNodesClasses().containsKey("actor")).isTrue(); + + Map actorClass = data.getNodesClasses().get("actor"); + assertThat(actorClass.containsKey("actor_id")).isTrue(); + assertThat(actorClass.containsKey("first_name")).isTrue(); + assertThat(actorClass.containsKey("last_name")).isTrue(); + assertThat(actorClass.containsKey("last_update")).isTrue(); + + // nodes checks + Iterator it = data.getNodes().iterator(); + CytoData currNodeContent; + Map currRecord; + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(1); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("PENELOPE"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("GUINESS"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 03:34:33-00").toInstant()); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(2); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("NICK"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("WAHLBERG"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 03:34:33-00").toInstant()); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(3); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("ED"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("CHASE"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 03:34:33-00").toInstant()); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(4); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("JENNIFER"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("DAVIS"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 03:34:33-00").toInstant()); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(5); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("JOHNNY"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("LOLLOBRIGIDA"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 03:34:33-00").toInstant()); + + /* + * Fetching 2 vertices from the store table by cyto-ids + * cyto-id from is x_y where: + * - x is refers to the source table (actor is the first table in the source db schema) + * - y is the external key, then the pk value of the source record + */ + + String[] storeIds = {"16_1", "16_2"}; + data = provider.load(dataSource, storeIds); + + assertThat(data.getNodesClasses().size()).isEqualTo(1); + assertThat(data.getNodes().size()).isEqualTo(2); + assertThat(data.getEdgesClasses().size()).isEqualTo(0); + assertThat(data.getEdges().size()).isEqualTo(0); + + // Node classes checks + assertThat(data.getNodesClasses().containsKey("store")).isTrue(); + + Map storeClass = data.getNodesClasses().get("store"); + assertThat(storeClass.containsKey("store_id")).isTrue(); + assertThat(storeClass.containsKey("manager_staff_id")).isTrue(); + assertThat(storeClass.containsKey("address_id")).isTrue(); + assertThat(storeClass.containsKey("last_update")).isTrue(); + + // nodes checks + it = data.getNodes().iterator(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("store_id")).isTrue(); + assertThat(currRecord.get("store_id")).isEqualTo(1); + assertThat(currRecord.containsKey("manager_staff_id")).isTrue(); + assertThat(currRecord.get("manager_staff_id")).isEqualTo(1); + assertThat(currRecord.containsKey("address_id")).isTrue(); + assertThat(currRecord.get("address_id")).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 03:57:12-00").toInstant()); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("store_id")).isTrue(); + assertThat(currRecord.get("store_id")).isEqualTo(2); + assertThat(currRecord.containsKey("manager_staff_id")).isTrue(); + assertThat(currRecord.get("manager_staff_id")).isEqualTo(2); + assertThat(currRecord.containsKey("address_id")).isTrue(); + assertThat(currRecord.get("address_id")).isEqualTo(2); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 03:57:12-00").toInstant()); + } + + @Override + @Test + public void expand1To1RelWithSimpleFKTest() throws Exception { + // 1-1 Relationship: distribution_country -[has_distribution_language]-> language + + // adding schema info + Connection connection = null; + Statement st = null; + + try { + connection = + DriverManager.getConnection( + MySQLContainerHolder.container.getJdbcUrl(), + MySQLContainerHolder.container.getUsername(), + MySQLContainerHolder.container.getPassword()); + + String distributioCountryTableBuilding = + "create table distribution_country (distribution_country_id integer not null, name" + + " varchar(256) not null, distribution_language tinyint unsigned, primary key" + + " (distribution_country_id), foreign key (distribution_language) references" + + " language(language_id)) ENGINE=INNODB"; + st = connection.createStatement(); + st.execute(distributioCountryTableBuilding); + + // populating the new table + String distributionCountryFilling = + "insert into distribution_country (distribution_country_id,name,distribution_language)" + + " values (1,'USA',1),(2,'Italy',2),(3,'Japan',3),(4,'China',4),(5,'France',5)," + + "(6,'Germany',6)"; + st.execute(distributionCountryFilling); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } finally { + try { + connection.close(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } } - @Override - @Test - public void loadVerticesFromIdsMultipleTablesTest() { - /* - * Fetching the first 5 vertices from the actor table and the first 2 vertices from the store table by cyto-ids - * cyto-id from is x_y where: - * - x is refers to the source table (actor is the first table in the source db schema) - * - y is the external key, then the pk value of the source record - */ - - String[] ids = { "1_1", "1_2", "1_3", "1_4", "1_5", "16_1", "16_2" }; - - GraphData data = provider.load(dataSource, ids); - - assertEquals(data.getNodesClasses().size(), 2); - assertEquals(data.getNodes().size(), 7); - assertEquals(data.getEdgesClasses().size(), 0); - assertEquals(data.getEdges().size(), 0); - - // Node classes checks - assertTrue(data.getNodesClasses().containsKey("actor")); - assertTrue(data.getNodesClasses().containsKey("store")); - - Map actorClass = data.getNodesClasses().get("actor"); - assertTrue(actorClass.containsKey("actor_id")); - assertTrue(actorClass.containsKey("first_name")); - assertTrue(actorClass.containsKey("last_name")); - assertTrue(actorClass.containsKey("last_update")); - Map storeClass = data.getNodesClasses().get("store"); - assertTrue(storeClass.containsKey("store_id")); - assertTrue(storeClass.containsKey("manager_staff_id")); - assertTrue(storeClass.containsKey("address_id")); - assertTrue(storeClass.containsKey("last_update")); - - // nodes checks - Iterator it = data.getNodes().iterator(); - CytoData currNodeContent; - Map currRecord; - - try { - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(1, currRecord.get("actor_id")); - assertTrue(currRecord.containsKey("first_name")); - assertEquals("PENELOPE", currRecord.get("first_name")); - assertTrue(currRecord.containsKey("last_name")); - assertEquals("GUINESS", currRecord.get("last_name")); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(df.parse("2006-02-15 04:34:33-00").toInstant(), ((Date) currRecord.get("last_update")).toInstant()); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(2, currRecord.get("actor_id")); - assertTrue(currRecord.containsKey("first_name")); - assertEquals("NICK", currRecord.get("first_name")); - assertTrue(currRecord.containsKey("last_name")); - assertEquals("WAHLBERG", currRecord.get("last_name")); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(df.parse("2006-02-15 04:34:33-00").toInstant(), ((Date) currRecord.get("last_update")).toInstant()); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(3, currRecord.get("actor_id")); - assertTrue(currRecord.containsKey("first_name")); - assertEquals("ED", currRecord.get("first_name")); - assertTrue(currRecord.containsKey("last_name")); - assertEquals("CHASE", currRecord.get("last_name")); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(df.parse("2006-02-15 04:34:33-00").toInstant(), ((Date) currRecord.get("last_update")).toInstant()); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(4, currRecord.get("actor_id")); - assertTrue(currRecord.containsKey("first_name")); - assertEquals("JENNIFER", currRecord.get("first_name")); - assertTrue(currRecord.containsKey("last_name")); - assertEquals("DAVIS", currRecord.get("last_name")); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(df.parse("2006-02-15 04:34:33-00").toInstant(), ((Date) currRecord.get("last_update")).toInstant()); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(5, currRecord.get("actor_id")); - assertTrue(currRecord.containsKey("first_name")); - assertEquals("JOHNNY", currRecord.get("first_name")); - assertTrue(currRecord.containsKey("last_name")); - assertEquals("LOLLOBRIGIDA", currRecord.get("last_name")); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(df.parse("2006-02-15 04:34:33-00").toInstant(), ((Date) currRecord.get("last_update")).toInstant()); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("store_id")); - assertEquals(1, currRecord.get("store_id")); - assertTrue(currRecord.containsKey("manager_staff_id")); - assertEquals(1, currRecord.get("manager_staff_id")); - assertTrue(currRecord.containsKey("address_id")); - assertEquals(1, currRecord.get("address_id")); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(df.parse("2006-02-15 04:57:12-00").toInstant(), ((Date) currRecord.get("last_update")).toInstant()); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("store_id")); - assertEquals(2, currRecord.get("store_id")); - assertTrue(currRecord.containsKey("manager_staff_id")); - assertEquals(2, currRecord.get("manager_staff_id")); - assertTrue(currRecord.containsKey("address_id")); - assertEquals(2, currRecord.get("address_id")); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(df.parse("2006-02-15 04:57:12-00").toInstant(), ((Date) currRecord.get("last_update")).toInstant()); - } catch (ParseException e) { - e.printStackTrace(); - fail(); - } + String[] rootIds = {"7_1", "7_2", "7_3", "7_4", "7_5", "7_6"}; + GraphData data = provider.expand(dataSource, rootIds, "out", "has_distribution_language", 300); + + assertThat(data.getNodesClasses().size()).isEqualTo(1); + assertThat(data.getNodes().size()).isEqualTo(6); + assertThat(data.getEdgesClasses().size()).isEqualTo(1); + assertThat(data.getEdges().size()).isEqualTo(6); + + // Node classes checks + assertThat(data.getNodesClasses().containsKey("language")).isTrue(); + + Map languageClass = data.getNodesClasses().get("language"); + assertThat(languageClass.containsKey("language_id")).isTrue(); + assertThat(languageClass.containsKey("name")).isTrue(); + assertThat(languageClass.containsKey("last_update")).isTrue(); + + // nodes checks + Iterator it = data.getNodes().iterator(); + CytoData currNodeContent; + Map currRecord; + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("language_id")).isTrue(); + assertThat(currRecord.get("language_id")).isEqualTo(1); + assertThat(currRecord.containsKey("name")).isTrue(); + assertThat(((String) currRecord.get("name")).trim()).isEqualTo("English"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 04:02:19-00").toInstant()); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("language_id")).isTrue(); + assertThat(currRecord.get("language_id")).isEqualTo(2); + assertThat(currRecord.containsKey("name")).isTrue(); + assertThat(((String) currRecord.get("name")).trim()).isEqualTo("Italian"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 04:02:19-00").toInstant()); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("language_id")).isTrue(); + assertThat(currRecord.get("language_id")).isEqualTo(3); + assertThat(currRecord.containsKey("name")).isTrue(); + assertThat(((String) currRecord.get("name")).trim()).isEqualTo("Japanese"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 04:02:19-00").toInstant()); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("language_id")).isTrue(); + assertThat(currRecord.get("language_id")).isEqualTo(4); + assertThat(currRecord.containsKey("name")).isTrue(); + assertThat(((String) currRecord.get("name")).trim()).isEqualTo("Mandarin"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 04:02:19-00").toInstant()); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("language_id")).isTrue(); + assertThat(currRecord.get("language_id")).isEqualTo(5); + assertThat(currRecord.containsKey("name")).isTrue(); + assertThat(((String) currRecord.get("name")).trim()).isEqualTo("French"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 04:02:19-00").toInstant()); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("language_id")).isTrue(); + assertThat(currRecord.get("language_id")).isEqualTo(6); + assertThat(currRecord.containsKey("name")).isTrue(); + assertThat(((String) currRecord.get("name")).trim()).isEqualTo("German"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 04:02:19-00").toInstant()); + + // edges checks + it = data.getEdges().iterator(); + CytoData currEdgeContent; + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_distribution_language"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("7_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("13_1"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("71_131"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_distribution_language"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("7_2"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("13_2"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("72_132"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_distribution_language"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("7_3"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("13_3"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("73_133"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_distribution_language"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("7_4"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("13_4"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("74_134"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_distribution_language"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("7_5"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("13_5"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("75_135"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_distribution_language"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("7_6"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("13_6"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("76_136"); + + // 1-1 Relationship: language <-[has_distribution_language]- distribution_country + + rootIds[0] = "13_1"; + rootIds[1] = "13_2"; + rootIds[2] = "13_3"; + rootIds[3] = "13_4"; + rootIds[4] = "13_5"; + rootIds[5] = "13_6"; + data = provider.expand(dataSource, rootIds, "in", "has_distribution_language", 300); + + assertThat(data.getNodesClasses().size()).isEqualTo(1); + assertThat(data.getNodes().size()).isEqualTo(6); + assertThat(data.getEdgesClasses().size()).isEqualTo(1); + assertThat(data.getEdges().size()).isEqualTo(6); + + // Node classes checks + assertThat(data.getNodesClasses().containsKey("distribution_country")).isTrue(); + + Map distributionCountryClass = + data.getNodesClasses().get("distribution_country"); + assertThat(distributionCountryClass.containsKey("distribution_country_id")).isTrue(); + assertThat(distributionCountryClass.containsKey("name")).isTrue(); + assertThat(distributionCountryClass.containsKey("distribution_language")).isTrue(); + + it = data.getNodes().iterator(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("distribution_country_id")).isTrue(); + assertThat(currRecord.get("distribution_country_id")).isEqualTo(1); + assertThat(currRecord.containsKey("name")).isTrue(); + assertThat(((String) currRecord.get("name"))).isEqualTo("USA"); + assertThat(currRecord.containsKey("distribution_language")).isTrue(); + assertThat(currRecord.get("distribution_language")).isEqualTo(1); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("distribution_country_id")).isTrue(); + assertThat(currRecord.get("distribution_country_id")).isEqualTo(2); + assertThat(currRecord.containsKey("name")).isTrue(); + assertThat(((String) currRecord.get("name"))).isEqualTo("Italy"); + assertThat(currRecord.containsKey("distribution_language")).isTrue(); + assertThat(currRecord.get("distribution_language")).isEqualTo(2); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("distribution_country_id")).isTrue(); + assertThat(currRecord.get("distribution_country_id")).isEqualTo(3); + assertThat(currRecord.containsKey("name")).isTrue(); + assertThat(((String) currRecord.get("name"))).isEqualTo("Japan"); + assertThat(currRecord.containsKey("distribution_language")).isTrue(); + assertThat(currRecord.get("distribution_language")).isEqualTo(3); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("distribution_country_id")).isTrue(); + assertThat(currRecord.get("distribution_country_id")).isEqualTo(4); + assertThat(currRecord.containsKey("name")).isTrue(); + assertThat(((String) currRecord.get("name"))).isEqualTo("China"); + assertThat(currRecord.containsKey("distribution_language")).isTrue(); + assertThat(currRecord.get("distribution_language")).isEqualTo(4); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("distribution_country_id")).isTrue(); + assertThat(currRecord.get("distribution_country_id")).isEqualTo(5); + assertThat(currRecord.containsKey("name")).isTrue(); + assertThat(((String) currRecord.get("name"))).isEqualTo("France"); + assertThat(currRecord.containsKey("distribution_language")).isTrue(); + assertThat(currRecord.get("distribution_language")).isEqualTo(5); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("distribution_country_id")).isTrue(); + assertThat(currRecord.get("distribution_country_id")).isEqualTo(6); + assertThat(currRecord.containsKey("name")).isTrue(); + assertThat(((String) currRecord.get("name"))).isEqualTo("Germany"); + assertThat(currRecord.containsKey("distribution_language")).isTrue(); + assertThat(currRecord.get("distribution_language")).isEqualTo(6); + + // edges checks + it = data.getEdges().iterator(); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_distribution_language"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("7_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("13_1"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("71_131"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_distribution_language"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("7_2"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("13_2"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("72_132"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_distribution_language"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("7_3"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("13_3"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("73_133"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_distribution_language"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("7_4"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("13_4"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("74_134"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_distribution_language"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("7_5"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("13_5"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("75_135"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_distribution_language"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("7_6"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("13_6"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("76_136"); + + // dropping the new added table + try { + connection = + DriverManager.getConnection( + MySQLContainerHolder.container.getJdbcUrl(), + MySQLContainerHolder.container.getUsername(), + MySQLContainerHolder.container.getPassword()); + + String deleteDistributionCountryTable = "drop table distribution_country"; + st = connection.createStatement(); + st.execute(deleteDistributionCountryTable); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } finally { + try { + connection.close(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } } - - @Override - @Test - public void loadVerticesFromIdsSingleTableTest() throws Exception { - /* - * Fetching the first 5 vertices from the actor table by cyto-ids - * cyto-id from is x_y where: - * - x is refers to the source table (actor is the first table in the source db schema) - * - y is the external key, then the pk value of the source record - */ - - String[] actorIds = { "1_1", "1_2", "1_3", "1_4", "1_5" }; - - GraphData data = provider.load(dataSource, actorIds); - - assertEquals(data.getNodesClasses().size(), 1); - assertEquals(data.getNodes().size(), 5); - assertEquals(data.getEdgesClasses().size(), 0); - assertEquals(data.getEdges().size(), 0); - - // Node classes checks - assertTrue(data.getNodesClasses().containsKey("actor")); - - Map actorClass = data.getNodesClasses().get("actor"); - assertTrue(actorClass.containsKey("actor_id")); - assertTrue(actorClass.containsKey("first_name")); - assertTrue(actorClass.containsKey("last_name")); - assertTrue(actorClass.containsKey("last_update")); - - // nodes checks - Iterator it = data.getNodes().iterator(); - CytoData currNodeContent; - Map currRecord; - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 1); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "PENELOPE"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "GUINESS"); - assertTrue(currRecord.containsKey("last_update")); - - assertEquals(df.parse("2006-02-15 04:34:33-00").toInstant(), ((Date) currRecord.get("last_update")).toInstant()); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 2); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "NICK"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "WAHLBERG"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(df.parse("2006-02-15 04:34:33-00").toInstant(), ((Date) currRecord.get("last_update")).toInstant()); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 3); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "ED"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "CHASE"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(df.parse("2006-02-15 04:34:33-00").toInstant(), ((Date) currRecord.get("last_update")).toInstant()); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 4); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "JENNIFER"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "DAVIS"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(df.parse("2006-02-15 04:34:33-00").toInstant(), ((Date) currRecord.get("last_update")).toInstant()); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 5); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "JOHNNY"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "LOLLOBRIGIDA"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(df.parse("2006-02-15 04:34:33-00").toInstant(), ((Date) currRecord.get("last_update")).toInstant()); - - /* - * Fetching 2 vertices from the store table by cyto-ids - * cyto-id from is x_y where: - * - x is refers to the source table (actor is the first table in the source db schema) - * - y is the external key, then the pk value of the source record - */ - - String[] storeIds = { "16_1", "16_2" }; - data = provider.load(dataSource, storeIds); - - assertEquals(data.getNodesClasses().size(), 1); - assertEquals(data.getNodes().size(), 2); - assertEquals(data.getEdgesClasses().size(), 0); - assertEquals(data.getEdges().size(), 0); - - // Node classes checks - assertTrue(data.getNodesClasses().containsKey("store")); - - Map storeClass = data.getNodesClasses().get("store"); - assertTrue(storeClass.containsKey("store_id")); - assertTrue(storeClass.containsKey("manager_staff_id")); - assertTrue(storeClass.containsKey("address_id")); - assertTrue(storeClass.containsKey("last_update")); - - // nodes checks - it = data.getNodes().iterator(); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("store_id")); - assertEquals(currRecord.get("store_id"), 1); - assertTrue(currRecord.containsKey("manager_staff_id")); - assertEquals(currRecord.get("manager_staff_id"), 1); - assertTrue(currRecord.containsKey("address_id")); - assertEquals(currRecord.get("address_id"), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(((Date) currRecord.get("last_update")).toInstant(), df.parse("2006-02-15 04:57:12-00").toInstant()); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("store_id")); - assertEquals(currRecord.get("store_id"), 2); - assertTrue(currRecord.containsKey("manager_staff_id")); - assertEquals(currRecord.get("manager_staff_id"), 2); - assertTrue(currRecord.containsKey("address_id")); - assertEquals(currRecord.get("address_id"), 2); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(((Date) currRecord.get("last_update")).toInstant(), df.parse("2006-02-15 04:57:12-00").toInstant()); + } + + @Override + @Test + public void expand1ToNRelWithSimpleFKTest() { + // 1-N Relationship: city -[has_country]-> country + + String[] rootIds = {"4_1"}; + GraphData data = provider.expand(dataSource, rootIds, "out", "has_country", 300); + + assertThat(data.getNodesClasses().size()).isEqualTo(1); + assertThat(data.getNodes().size()).isEqualTo(1); + assertThat(data.getEdgesClasses().size()).isEqualTo(1); + assertThat(data.getEdges().size()).isEqualTo(1); + + // Node classes checks + assertThat(data.getNodesClasses().containsKey("country")).isTrue(); + + Map customerClass = data.getNodesClasses().get("country"); + assertThat(customerClass.containsKey("country_id")).isTrue(); + assertThat(customerClass.containsKey("country")).isTrue(); + assertThat(customerClass.containsKey("last_update")).isTrue(); + + // nodes checks + Iterator it = data.getNodes().iterator(); + CytoData currNodeContent; + Map currRecord; + + try { + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("country_id")).isTrue(); + assertThat(currRecord.get("country_id")).isEqualTo(87); + assertThat(currRecord.containsKey("country")).isTrue(); + assertThat(currRecord.get("country")).isEqualTo("Spain"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 03:44:00-00").toInstant()); + } catch (ParseException e) { + e.printStackTrace(); + fail(""); } - @Override - @Test - public void expand1To1RelWithSimpleFKTest() throws Exception { - // 1-1 Relationship: distribution_country -[has_distribution_language]-> language - - // adding schema info - Connection connection = null; - Statement st = null; - - try { - connection = - DriverManager.getConnection( - MySQLContainerHolder.container.getJdbcUrl(), - MySQLContainerHolder.container.getUsername(), - MySQLContainerHolder.container.getPassword() - ); - - String distributioCountryTableBuilding = - "create table distribution_country (distribution_country_id integer not null," + - " name varchar(256) not null, distribution_language tinyint unsigned, primary key (distribution_country_id)," + - " foreign key (distribution_language) references language(language_id)) ENGINE=INNODB"; - st = connection.createStatement(); - st.execute(distributioCountryTableBuilding); - - // populating the new table - String distributionCountryFilling = - "insert into distribution_country (distribution_country_id,name,distribution_language) values " + - "(1,'USA',1)," + - "(2,'Italy',2)," + - "(3,'Japan',3)," + - "(4,'China',4)," + - "(5,'France',5)," + - "(6,'Germany',6)"; - st.execute(distributionCountryFilling); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } finally { - try { - connection.close(); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } - } - - String[] rootIds = { "7_1", "7_2", "7_3", "7_4", "7_5", "7_6" }; - GraphData data = provider.expand(dataSource, rootIds, "out", "has_distribution_language", 300); - - assertEquals(data.getNodesClasses().size(), 1); - assertEquals(data.getNodes().size(), 6); - assertEquals(data.getEdgesClasses().size(), 1); - assertEquals(data.getEdges().size(), 6); - - // Node classes checks - assertTrue(data.getNodesClasses().containsKey("language")); - - Map languageClass = data.getNodesClasses().get("language"); - assertTrue(languageClass.containsKey("language_id")); - assertTrue(languageClass.containsKey("name")); - assertTrue(languageClass.containsKey("last_update")); - - // nodes checks - Iterator it = data.getNodes().iterator(); - CytoData currNodeContent; - Map currRecord; - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("language_id")); - assertEquals(currRecord.get("language_id"), 1); - assertTrue(currRecord.containsKey("name")); - assertEquals(((String) currRecord.get("name")).trim(), "English"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(((Date) currRecord.get("last_update")).toInstant(), df.parse("2006-02-15 05:02:19-00").toInstant()); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("language_id")); - assertEquals(currRecord.get("language_id"), 2); - assertTrue(currRecord.containsKey("name")); - assertEquals(((String) currRecord.get("name")).trim(), "Italian"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(((Date) currRecord.get("last_update")).toInstant(), df.parse("2006-02-15 05:02:19-00").toInstant()); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("language_id")); - assertEquals(currRecord.get("language_id"), 3); - assertTrue(currRecord.containsKey("name")); - assertEquals(((String) currRecord.get("name")).trim(), "Japanese"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(((Date) currRecord.get("last_update")).toInstant(), df.parse("2006-02-15 05:02:19-00").toInstant()); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("language_id")); - assertEquals(currRecord.get("language_id"), 4); - assertTrue(currRecord.containsKey("name")); - assertEquals(((String) currRecord.get("name")).trim(), "Mandarin"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(((Date) currRecord.get("last_update")).toInstant(), df.parse("2006-02-15 05:02:19-00").toInstant()); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("language_id")); - assertEquals(currRecord.get("language_id"), 5); - assertTrue(currRecord.containsKey("name")); - assertEquals(((String) currRecord.get("name")).trim(), "French"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(((Date) currRecord.get("last_update")).toInstant(), df.parse("2006-02-15 05:02:19-00").toInstant()); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("language_id")); - assertEquals(currRecord.get("language_id"), 6); - assertTrue(currRecord.containsKey("name")); - assertEquals(((String) currRecord.get("name")).trim(), "German"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(((Date) currRecord.get("last_update")).toInstant(), df.parse("2006-02-15 05:02:19-00").toInstant()); - - // edges checks - it = data.getEdges().iterator(); - CytoData currEdgeContent; - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_distribution_language"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "7_1"); - assertEquals(currEdgeContent.getData().getTarget(), "13_1"); - assertEquals(currEdgeContent.getData().getId(), "71_131"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_distribution_language"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "7_2"); - assertEquals(currEdgeContent.getData().getTarget(), "13_2"); - assertEquals(currEdgeContent.getData().getId(), "72_132"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_distribution_language"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "7_3"); - assertEquals(currEdgeContent.getData().getTarget(), "13_3"); - assertEquals(currEdgeContent.getData().getId(), "73_133"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_distribution_language"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "7_4"); - assertEquals(currEdgeContent.getData().getTarget(), "13_4"); - assertEquals(currEdgeContent.getData().getId(), "74_134"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_distribution_language"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "7_5"); - assertEquals(currEdgeContent.getData().getTarget(), "13_5"); - assertEquals(currEdgeContent.getData().getId(), "75_135"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_distribution_language"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "7_6"); - assertEquals(currEdgeContent.getData().getTarget(), "13_6"); - assertEquals(currEdgeContent.getData().getId(), "76_136"); - - // 1-1 Relationship: language <-[has_distribution_language]- distribution_country - - rootIds[0] = "13_1"; - rootIds[1] = "13_2"; - rootIds[2] = "13_3"; - rootIds[3] = "13_4"; - rootIds[4] = "13_5"; - rootIds[5] = "13_6"; - data = provider.expand(dataSource, rootIds, "in", "has_distribution_language", 300); - - assertEquals(data.getNodesClasses().size(), 1); - assertEquals(data.getNodes().size(), 6); - assertEquals(data.getEdgesClasses().size(), 1); - assertEquals(data.getEdges().size(), 6); - - // Node classes checks - assertTrue(data.getNodesClasses().containsKey("distribution_country")); - - Map distributionCountryClass = data.getNodesClasses().get("distribution_country"); - assertTrue(distributionCountryClass.containsKey("distribution_country_id")); - assertTrue(distributionCountryClass.containsKey("name")); - assertTrue(distributionCountryClass.containsKey("distribution_language")); - - it = data.getNodes().iterator(); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("distribution_country_id")); - assertEquals(currRecord.get("distribution_country_id"), 1); - assertTrue(currRecord.containsKey("name")); - assertEquals(((String) currRecord.get("name")), "USA"); - assertTrue(currRecord.containsKey("distribution_language")); - assertEquals(currRecord.get("distribution_language"), 1); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("distribution_country_id")); - assertEquals(currRecord.get("distribution_country_id"), 2); - assertTrue(currRecord.containsKey("name")); - assertEquals(((String) currRecord.get("name")), "Italy"); - assertTrue(currRecord.containsKey("distribution_language")); - assertEquals(currRecord.get("distribution_language"), 2); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("distribution_country_id")); - assertEquals(currRecord.get("distribution_country_id"), 3); - assertTrue(currRecord.containsKey("name")); - assertEquals(((String) currRecord.get("name")), "Japan"); - assertTrue(currRecord.containsKey("distribution_language")); - assertEquals(currRecord.get("distribution_language"), 3); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("distribution_country_id")); - assertEquals(currRecord.get("distribution_country_id"), 4); - assertTrue(currRecord.containsKey("name")); - assertEquals(((String) currRecord.get("name")), "China"); - assertTrue(currRecord.containsKey("distribution_language")); - assertEquals(currRecord.get("distribution_language"), 4); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("distribution_country_id")); - assertEquals(currRecord.get("distribution_country_id"), 5); - assertTrue(currRecord.containsKey("name")); - assertEquals(((String) currRecord.get("name")), "France"); - assertTrue(currRecord.containsKey("distribution_language")); - assertEquals(currRecord.get("distribution_language"), 5); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("distribution_country_id")); - assertEquals(currRecord.get("distribution_country_id"), 6); - assertTrue(currRecord.containsKey("name")); - assertEquals(((String) currRecord.get("name")), "Germany"); - assertTrue(currRecord.containsKey("distribution_language")); - assertEquals(currRecord.get("distribution_language"), 6); - - // edges checks - it = data.getEdges().iterator(); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_distribution_language"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "7_1"); - assertEquals(currEdgeContent.getData().getTarget(), "13_1"); - assertEquals(currEdgeContent.getData().getId(), "71_131"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_distribution_language"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "7_2"); - assertEquals(currEdgeContent.getData().getTarget(), "13_2"); - assertEquals(currEdgeContent.getData().getId(), "72_132"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_distribution_language"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "7_3"); - assertEquals(currEdgeContent.getData().getTarget(), "13_3"); - assertEquals(currEdgeContent.getData().getId(), "73_133"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_distribution_language"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "7_4"); - assertEquals(currEdgeContent.getData().getTarget(), "13_4"); - assertEquals(currEdgeContent.getData().getId(), "74_134"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_distribution_language"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "7_5"); - assertEquals(currEdgeContent.getData().getTarget(), "13_5"); - assertEquals(currEdgeContent.getData().getId(), "75_135"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_distribution_language"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "7_6"); - assertEquals(currEdgeContent.getData().getTarget(), "13_6"); - assertEquals(currEdgeContent.getData().getId(), "76_136"); - - // dropping the new added table - try { - connection = - DriverManager.getConnection( - MySQLContainerHolder.container.getJdbcUrl(), - MySQLContainerHolder.container.getUsername(), - MySQLContainerHolder.container.getPassword() - ); - - String deleteDistributionCountryTable = "drop table distribution_country"; - st = connection.createStatement(); - st.execute(deleteDistributionCountryTable); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } finally { - try { - connection.close(); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } - } + // edges checks + it = data.getEdges().iterator(); + CytoData currEdgeContent; + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + + assertThat(currEdgeContent.getClasses()).isEqualTo("has_country"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("4_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("5_87"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("41_587"); + + // 1-N Relationship: city <-[has_country]- country + + rootIds[0] = "5_87"; + data = provider.expand(dataSource, rootIds, "in", "has_country", 300); + + assertThat(data.getNodesClasses().size()).isEqualTo(1); + assertThat(data.getNodes().size()).isEqualTo(5); + assertThat(data.getEdgesClasses().size()).isEqualTo(1); + assertThat(data.getEdges().size()).isEqualTo(5); + + // nodes checks + it = data.getNodes().iterator(); + + try { + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("city_id")).isTrue(); + assertThat(currRecord.get("city_id")).isEqualTo(1); + assertThat(currRecord.containsKey("city")).isTrue(); + assertThat(currRecord.get("city")).isEqualTo("A Corua (La Corua)"); + assertThat(currRecord.containsKey("country_id")).isTrue(); + assertThat(currRecord.get("country_id")).isEqualTo(87); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 03:45:25-00").toInstant()); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("city_id")).isTrue(); + assertThat(currRecord.get("city_id")).isEqualTo(146); + assertThat(currRecord.containsKey("city")).isTrue(); + assertThat(currRecord.get("city")).isEqualTo("Donostia-San Sebastin"); + assertThat(currRecord.containsKey("country_id")).isTrue(); + assertThat(currRecord.get("country_id")).isEqualTo(87); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 03:45:25-00").toInstant()); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("city_id")).isTrue(); + assertThat(currRecord.get("city_id")).isEqualTo(181); + assertThat(currRecord.containsKey("city")).isTrue(); + assertThat(currRecord.get("city")).isEqualTo("Gijn"); + assertThat(currRecord.containsKey("country_id")).isTrue(); + assertThat(currRecord.get("country_id")).isEqualTo(87); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 03:45:25-00").toInstant()); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("city_id")).isTrue(); + assertThat(currRecord.get("city_id")).isEqualTo(388); + assertThat(currRecord.containsKey("city")).isTrue(); + assertThat(currRecord.get("city")).isEqualTo("Ourense (Orense)"); + assertThat(currRecord.containsKey("country_id")).isTrue(); + assertThat(currRecord.get("country_id")).isEqualTo(87); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 03:45:25-00").toInstant()); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("city_id")).isTrue(); + assertThat(currRecord.get("city_id")).isEqualTo(459); + assertThat(currRecord.containsKey("city")).isTrue(); + assertThat(currRecord.get("city")).isEqualTo("Santiago de Compostela"); + assertThat(currRecord.containsKey("country_id")).isTrue(); + assertThat(currRecord.get("country_id")).isEqualTo(87); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 03:45:25-00").toInstant()); + } catch (ParseException e) { + e.printStackTrace(); + fail(""); } - @Override - @Test - public void expand1ToNRelWithSimpleFKTest() { - // 1-N Relationship: city -[has_country]-> country - - String[] rootIds = { "4_1" }; - GraphData data = provider.expand(dataSource, rootIds, "out", "has_country", 300); - - assertEquals(data.getNodesClasses().size(), 1); - assertEquals(data.getNodes().size(), 1); - assertEquals(data.getEdgesClasses().size(), 1); - assertEquals(data.getEdges().size(), 1); - - // Node classes checks - assertTrue(data.getNodesClasses().containsKey("country")); - - Map customerClass = data.getNodesClasses().get("country"); - assertTrue(customerClass.containsKey("country_id")); - assertTrue(customerClass.containsKey("country")); - assertTrue(customerClass.containsKey("last_update")); - - // nodes checks - Iterator it = data.getNodes().iterator(); - CytoData currNodeContent; - Map currRecord; - - try { - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("country_id")); - assertEquals(currRecord.get("country_id"), 87); - assertTrue(currRecord.containsKey("country")); - assertEquals(currRecord.get("country"), "Spain"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(((Date) currRecord.get("last_update")).toInstant(), df.parse("2006-02-15 04:44:00-00").toInstant()); - } catch (ParseException e) { - e.printStackTrace(); - fail(); - } - - // edges checks - it = data.getEdges().iterator(); - CytoData currEdgeContent; - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - - assertEquals(currEdgeContent.getClasses(), "has_country"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "4_1"); - assertEquals(currEdgeContent.getData().getTarget(), "5_87"); - assertEquals(currEdgeContent.getData().getId(), "41_587"); - - // 1-N Relationship: city <-[has_country]- country - - rootIds[0] = "5_87"; - data = provider.expand(dataSource, rootIds, "in", "has_country", 300); - - assertEquals(data.getNodesClasses().size(), 1); - assertEquals(data.getNodes().size(), 5); - assertEquals(data.getEdgesClasses().size(), 1); - assertEquals(data.getEdges().size(), 5); - - // nodes checks - it = data.getNodes().iterator(); - - try { - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("city_id")); - assertEquals(currRecord.get("city_id"), 1); - assertTrue(currRecord.containsKey("city")); - assertEquals(currRecord.get("city"), "A Corua (La Corua)"); - assertTrue(currRecord.containsKey("country_id")); - assertEquals(currRecord.get("country_id"), 87); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(((Date) currRecord.get("last_update")).toInstant(), df.parse("2006-02-15 04:45:25-00").toInstant()); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("city_id")); - assertEquals(currRecord.get("city_id"), 146); - assertTrue(currRecord.containsKey("city")); - assertEquals(currRecord.get("city"), "Donostia-San Sebastin"); - assertTrue(currRecord.containsKey("country_id")); - assertEquals(currRecord.get("country_id"), 87); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(((Date) currRecord.get("last_update")).toInstant(), df.parse("2006-02-15 04:45:25-00").toInstant()); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("city_id")); - assertEquals(currRecord.get("city_id"), 181); - assertTrue(currRecord.containsKey("city")); - assertEquals(currRecord.get("city"), "Gijn"); - assertTrue(currRecord.containsKey("country_id")); - assertEquals(currRecord.get("country_id"), 87); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(((Date) currRecord.get("last_update")).toInstant(), df.parse("2006-02-15 04:45:25-00").toInstant()); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("city_id")); - assertEquals(currRecord.get("city_id"), 388); - assertTrue(currRecord.containsKey("city")); - assertEquals(currRecord.get("city"), "Ourense (Orense)"); - assertTrue(currRecord.containsKey("country_id")); - assertEquals(currRecord.get("country_id"), 87); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(((Date) currRecord.get("last_update")).toInstant(), df.parse("2006-02-15 04:45:25-00").toInstant()); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("city_id")); - assertEquals(currRecord.get("city_id"), 459); - assertTrue(currRecord.containsKey("city")); - assertEquals(currRecord.get("city"), "Santiago de Compostela"); - assertTrue(currRecord.containsKey("country_id")); - assertEquals(currRecord.get("country_id"), 87); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(((Date) currRecord.get("last_update")).toInstant(), df.parse("2006-02-15 04:45:25-00").toInstant()); - } catch (ParseException e) { - e.printStackTrace(); - fail(); - } - - // edges checks - it = data.getEdges().iterator(); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_country"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "4_1"); - assertEquals(currEdgeContent.getData().getTarget(), "5_87"); - assertEquals(currEdgeContent.getData().getId(), "41_587"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_country"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "4_146"); - assertEquals(currEdgeContent.getData().getTarget(), "5_87"); - assertEquals(currEdgeContent.getData().getId(), "4146_587"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_country"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "4_181"); - assertEquals(currEdgeContent.getData().getTarget(), "5_87"); - assertEquals(currEdgeContent.getData().getId(), "4181_587"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_country"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "4_388"); - assertEquals(currEdgeContent.getData().getTarget(), "5_87"); - assertEquals(currEdgeContent.getData().getId(), "4388_587"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_country"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "4_459"); - assertEquals(currEdgeContent.getData().getTarget(), "5_87"); - assertEquals(currEdgeContent.getData().getId(), "4459_587"); + // edges checks + it = data.getEdges().iterator(); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_country"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("4_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("5_87"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("41_587"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_country"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("4_146"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("5_87"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("4146_587"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_country"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("4_181"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("5_87"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("4181_587"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_country"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("4_388"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("5_87"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("4388_587"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_country"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("4_459"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("5_87"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("4459_587"); + } + + @Override + @Test + public void expandMultiple1ToNRelWithSimpleFKTest() { + // 1-N Relationship: rental -[has_customer]-> customer + + String[] rootIds = {"14_1"}; + GraphData data = provider.expand(dataSource, rootIds, "out", "has_customer", 300); + + assertThat(data.getNodesClasses().size()).isEqualTo(1); + assertThat(data.getNodes().size()).isEqualTo(1); + assertThat(data.getEdgesClasses().size()).isEqualTo(1); + assertThat(data.getEdges().size()).isEqualTo(1); + + // Node classes checks + assertThat(data.getNodesClasses().containsKey("customer")).isTrue(); + + Map customerClass = data.getNodesClasses().get("customer"); + assertThat(customerClass.containsKey("customer_id")).isTrue(); + assertThat(customerClass.containsKey("store_id")).isTrue(); + assertThat(customerClass.containsKey("first_name")).isTrue(); + assertThat(customerClass.containsKey("last_name")).isTrue(); + assertThat(customerClass.containsKey("email")).isTrue(); + assertThat(customerClass.containsKey("address_id")).isTrue(); + assertThat(customerClass.containsKey("create_date")).isTrue(); + assertThat(customerClass.containsKey("last_update")).isTrue(); + assertThat(customerClass.containsKey("active")).isTrue(); + + // nodes checks + Iterator it = data.getNodes().iterator(); + CytoData currNodeContent; + Map currRecord; + + try { + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("customer_id")).isTrue(); + assertThat(currRecord.get("customer_id")).isEqualTo(130); + assertThat(currRecord.containsKey("store_id")).isTrue(); + assertThat(currRecord.get("store_id")).isEqualTo(1); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("CHARLOTTE"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("HUNTER"); + assertThat(currRecord.containsKey("email")).isTrue(); + assertThat(currRecord.get("email")).isEqualTo("CHARLOTTE.HUNTER@sakilacustomer.org"); + assertThat(currRecord.containsKey("address_id")).isTrue(); + assertThat(currRecord.get("address_id")).isEqualTo(134); + assertThat(currRecord.containsKey("create_date")).isTrue(); + assertThat(((LocalDateTime) currRecord.get("create_date")).toInstant(ZoneOffset.UTC)) + .isEqualTo(df.parse("2006-02-14 22:04:36-00").toInstant()); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(((Timestamp) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 03:57:20-00").toInstant()); + assertThat(currRecord.containsKey("active")).isTrue(); + assertThat(currRecord.get("active")).isEqualTo(true); + } catch (ParseException e) { + fail(""); } - @Override - @Test - public void expandMultiple1ToNRelWithSimpleFKTest() { - // 1-N Relationship: rental -[has_customer]-> customer - - String[] rootIds = { "14_1" }; - GraphData data = provider.expand(dataSource, rootIds, "out", "has_customer", 300); - - assertEquals(data.getNodesClasses().size(), 1); - assertEquals(data.getNodes().size(), 1); - assertEquals(data.getEdgesClasses().size(), 1); - assertEquals(data.getEdges().size(), 1); - - // Node classes checks - assertTrue(data.getNodesClasses().containsKey("customer")); - - Map customerClass = data.getNodesClasses().get("customer"); - assertTrue(customerClass.containsKey("customer_id")); - assertTrue(customerClass.containsKey("store_id")); - assertTrue(customerClass.containsKey("first_name")); - assertTrue(customerClass.containsKey("last_name")); - assertTrue(customerClass.containsKey("email")); - assertTrue(customerClass.containsKey("address_id")); - assertTrue(customerClass.containsKey("create_date")); - assertTrue(customerClass.containsKey("last_update")); - assertTrue(customerClass.containsKey("active")); - - // nodes checks - Iterator it = data.getNodes().iterator(); - CytoData currNodeContent; - Map currRecord; - - try { - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("customer_id")); - assertEquals(currRecord.get("customer_id"), 130); - assertTrue(currRecord.containsKey("store_id")); - assertEquals(currRecord.get("store_id"), 1); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "CHARLOTTE"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "HUNTER"); - assertTrue(currRecord.containsKey("email")); - assertEquals(currRecord.get("email"), "CHARLOTTE.HUNTER@sakilacustomer.org"); - assertTrue(currRecord.containsKey("address_id")); - assertEquals(currRecord.get("address_id"), 134); - assertTrue(currRecord.containsKey("create_date")); - assertEquals(((Date) currRecord.get("create_date")).toInstant(), df.parse("2006-02-14 22:04:36-00").toInstant()); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(((Date) currRecord.get("last_update")).toInstant(), df.parse("2006-02-15 04:57:20-00").toInstant()); - assertTrue(currRecord.containsKey("active")); - assertEquals(currRecord.get("active"), true); - } catch (ParseException e) { - e.printStackTrace(); - fail(); - } - - // edges checks - it = data.getEdges().iterator(); - CytoData currEdgeContent; - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - - assertEquals(currEdgeContent.getClasses(), "has_customer"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "14_1"); - assertEquals(currEdgeContent.getData().getTarget(), "6_130"); - assertEquals(currEdgeContent.getData().getId(), "141_6130"); - - // 1-N Relationship: customer <-[has_customer]- rental - - rootIds[0] = "6_130"; - data = provider.expand(dataSource, rootIds, "in", "has_customer", 300); - - assertEquals(data.getNodesClasses().size(), 2); - assertEquals(data.getNodes().size(), 48); - assertEquals(data.getEdgesClasses().size(), 1); - assertEquals(data.getEdges().size(), 48); - - // Node classes checks - assertTrue(data.getNodesClasses().containsKey("rental")); - assertTrue(data.getNodesClasses().containsKey("payment")); // has_customer represents also the relationship: Payment -> Customer - - // nodes checks - Set rentalNodes = data.getNodes().stream().filter(rentalNode -> rentalNode.getClasses().equals("rental")).collect(Collectors.toSet()); - Set paymentNodes = data.getNodes().stream().filter(rentalNode -> rentalNode.getClasses().equals("payment")).collect(Collectors.toSet()); - - assertEquals(rentalNodes.size(), 24); - assertEquals(paymentNodes.size(), 24); + // edges checks + it = data.getEdges().iterator(); + CytoData currEdgeContent; + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + + assertThat(currEdgeContent.getClasses()).isEqualTo("has_customer"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("14_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("6_130"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("141_6130"); + + // 1-N Relationship: customer <-[has_customer]- rental + + rootIds[0] = "6_130"; + data = provider.expand(dataSource, rootIds, "in", "has_customer", 300); + + assertThat(data.getNodesClasses().size()).isEqualTo(2); + assertThat(data.getNodes().size()).isEqualTo(48); + assertThat(data.getEdgesClasses().size()).isEqualTo(1); + assertThat(data.getEdges().size()).isEqualTo(48); + + // Node classes checks + assertThat(data.getNodesClasses().containsKey("rental")).isTrue(); + assertThat(data.getNodesClasses().containsKey("payment")) + .isTrue(); // has_customer represents also the relationship: Payment -> Customer + + // nodes checks + Set rentalNodes = + data.getNodes().stream() + .filter(rentalNode -> rentalNode.getClasses().equals("rental")) + .collect(Collectors.toSet()); + Set paymentNodes = + data.getNodes().stream() + .filter(rentalNode -> rentalNode.getClasses().equals("payment")) + .collect(Collectors.toSet()); + + assertThat(rentalNodes.size()).isEqualTo(24); + assertThat(paymentNodes.size()).isEqualTo(24); + } + + @Override + @Test + public void expand1ToNRelWithJoinTableAndSimpleFKTest() { + /** Get movies by actor */ + + // expanding 1-N relationship: actor <-[has_actor]- film_actor + String[] rootIds = {"1_1"}; + GraphData data = provider.expand(dataSource, rootIds, "in", "has_actor", 300); + + assertThat(data.getNodesClasses().size()).isEqualTo(1); + assertThat(data.getNodes().size()).isEqualTo(19); + assertThat(data.getEdgesClasses().size()).isEqualTo(1); + assertThat(data.getEdges().size()).isEqualTo(19); + + // Node classes checks + assertThat(data.getNodesClasses().containsKey("film_actor")).isTrue(); + + Map filmActorClass = data.getNodesClasses().get("film_actor"); + assertThat(filmActorClass.containsKey("film_id")).isTrue(); + assertThat(filmActorClass.containsKey("actor_id")).isTrue(); + assertThat(filmActorClass.containsKey("last_update")).isTrue(); + + String[] joinRecordRoots = new String[19]; + int i = 0; + for (CytoData currentData : data.getNodes()) { + joinRecordRoots[i] = "8_1_" + currentData.getData().getRecord().get("film_id").toString(); + i++; } - @Override - @Test - public void expand1ToNRelWithJoinTableAndSimpleFKTest() { - /** - * Get movies by actor - */ - - // expanding 1-N relationship: actor <-[has_actor]- film_actor - String[] rootIds = { "1_1" }; - GraphData data = provider.expand(dataSource, rootIds, "in", "has_actor", 300); - - assertEquals(data.getNodesClasses().size(), 1); - assertEquals(data.getNodes().size(), 19); - assertEquals(data.getEdgesClasses().size(), 1); - assertEquals(data.getEdges().size(), 19); - - // Node classes checks - assertTrue(data.getNodesClasses().containsKey("film_actor")); - - Map filmActorClass = data.getNodesClasses().get("film_actor"); - assertTrue(filmActorClass.containsKey("film_id")); - assertTrue(filmActorClass.containsKey("actor_id")); - assertTrue(filmActorClass.containsKey("last_update")); - - String[] joinRecordRoots = new String[19]; - int i = 0; - for (CytoData currentData : data.getNodes()) { - joinRecordRoots[i] = "8_1_" + currentData.getData().getRecord().get("film_id").toString(); - i++; - } - - // expanding 1-N relationship: film_actor -[has_film] -> film - - data = provider.expand(dataSource, joinRecordRoots, "out", "has_film", 300); - - assertEquals(data.getNodesClasses().size(), 1); - assertEquals(data.getNodes().size(), 19); - assertEquals(data.getEdgesClasses().size(), 1); - assertEquals(data.getEdges().size(), 19); - - // Node classes checks - assertTrue(data.getNodesClasses().containsKey("film")); - - Map filmClass = data.getNodesClasses().get("film"); - assertTrue(filmClass.containsKey("film_id")); - assertTrue(filmClass.containsKey("title")); - assertTrue(filmClass.containsKey("description")); - assertTrue(filmClass.containsKey("release_year")); - assertTrue(filmClass.containsKey("language_id")); - assertTrue(filmClass.containsKey("original_language_id")); - assertTrue(filmClass.containsKey("rental_duration")); - assertTrue(filmClass.containsKey("rental_rate")); - assertTrue(filmClass.containsKey("length")); - assertTrue(filmClass.containsKey("replacement_cost")); - assertTrue(filmClass.containsKey("rating")); - assertTrue(filmClass.containsKey("last_update")); - assertTrue(filmClass.containsKey("special_features")); - - // nodes checks - Iterator it = data.getNodes().iterator(); - CytoData currNodeContent; - Map currRecord; - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 1); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "ACADEMY DINOSAUR"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 23); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "ANACONDA CONFESSIONS"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 25); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "ANGELS LIFE"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 106); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "BULWORTH COMMANDMENTS"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 140); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "CHEAPER CLYDE"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 166); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "COLOR PHILADELPHIA"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 277); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "ELEPHANT TROJAN"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 361); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "GLEAMING JAWBREAKER"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 438); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "HUMAN GRAFFITI"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 499); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "KING EVOLUTION"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 506); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "LADY STAGE"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 509); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "LANGUAGE COWBOY"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 605); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "MULHOLLAND BEAST"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 635); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "OKLAHOMA JUMANJI"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 749); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "RULES HUMAN"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 832); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "SPLASH GUMP"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 939); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "VERTIGO NORTHWEST"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 970); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "WESTWARD SEABISCUIT"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 980); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "WIZARD COLDBLOODED"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - // edges checks - it = data.getEdges().iterator(); - CytoData currEdgeContent; - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_1"); - assertEquals(currEdgeContent.getData().getId(), "811_71"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_23"); - assertEquals(currEdgeContent.getData().getTarget(), "7_23"); - assertEquals(currEdgeContent.getData().getId(), "8123_723"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_25"); - assertEquals(currEdgeContent.getData().getTarget(), "7_25"); - assertEquals(currEdgeContent.getData().getId(), "8125_725"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_106"); - assertEquals(currEdgeContent.getData().getTarget(), "7_106"); - assertEquals(currEdgeContent.getData().getId(), "81106_7106"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_140"); - assertEquals(currEdgeContent.getData().getTarget(), "7_140"); - assertEquals(currEdgeContent.getData().getId(), "81140_7140"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_166"); - assertEquals(currEdgeContent.getData().getTarget(), "7_166"); - assertEquals(currEdgeContent.getData().getId(), "81166_7166"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_277"); - assertEquals(currEdgeContent.getData().getTarget(), "7_277"); - assertEquals(currEdgeContent.getData().getId(), "81277_7277"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_361"); - assertEquals(currEdgeContent.getData().getTarget(), "7_361"); - assertEquals(currEdgeContent.getData().getId(), "81361_7361"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_438"); - assertEquals(currEdgeContent.getData().getTarget(), "7_438"); - assertEquals(currEdgeContent.getData().getId(), "81438_7438"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_499"); - assertEquals(currEdgeContent.getData().getTarget(), "7_499"); - assertEquals(currEdgeContent.getData().getId(), "81499_7499"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_506"); - assertEquals(currEdgeContent.getData().getTarget(), "7_506"); - assertEquals(currEdgeContent.getData().getId(), "81506_7506"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_509"); - assertEquals(currEdgeContent.getData().getTarget(), "7_509"); - assertEquals(currEdgeContent.getData().getId(), "81509_7509"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_605"); - assertEquals(currEdgeContent.getData().getTarget(), "7_605"); - assertEquals(currEdgeContent.getData().getId(), "81605_7605"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_635"); - assertEquals(currEdgeContent.getData().getTarget(), "7_635"); - assertEquals(currEdgeContent.getData().getId(), "81635_7635"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_749"); - assertEquals(currEdgeContent.getData().getTarget(), "7_749"); - assertEquals(currEdgeContent.getData().getId(), "81749_7749"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_832"); - assertEquals(currEdgeContent.getData().getTarget(), "7_832"); - assertEquals(currEdgeContent.getData().getId(), "81832_7832"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_939"); - assertEquals(currEdgeContent.getData().getTarget(), "7_939"); - assertEquals(currEdgeContent.getData().getId(), "81939_7939"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_970"); - assertEquals(currEdgeContent.getData().getTarget(), "7_970"); - assertEquals(currEdgeContent.getData().getId(), "81970_7970"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_980"); - assertEquals(currEdgeContent.getData().getTarget(), "7_980"); - assertEquals(currEdgeContent.getData().getId(), "81980_7980"); - - /** - * Get actors by movie - */ - - // expanding 1-N relationship: film <-[has_film]- film_actor - - rootIds[0] = "7_2"; - data = provider.expand(dataSource, rootIds, "in", "has_film", 300); - - assertEquals(data.getNodesClasses().size(), 3); - assertEquals(data.getNodes().size(), 8); - assertEquals(data.getEdgesClasses().size(), 1); - assertEquals(data.getEdges().size(), 8); - - // Node classes checks - assertTrue(data.getNodesClasses().containsKey("film_actor")); - assertTrue(data.getNodesClasses().containsKey("film_category")); // has_film represents also the relationship: film_category -> film - assertTrue(data.getNodesClasses().containsKey("inventory")); // has_film represents also the relationship: inventory -> film - - filmActorClass = data.getNodesClasses().get("film_actor"); - assertTrue(filmActorClass.containsKey("film_id")); - assertTrue(filmActorClass.containsKey("actor_id")); - assertTrue(filmActorClass.containsKey("last_update")); - filmActorClass = data.getNodesClasses().get("film_category"); - assertTrue(filmActorClass.containsKey("film_id")); - assertTrue(filmActorClass.containsKey("category_id")); - assertTrue(filmActorClass.containsKey("last_update")); - Map inventoryClass = data.getNodesClasses().get("inventory"); - assertTrue(inventoryClass.containsKey("inventory_id")); - assertTrue(inventoryClass.containsKey("film_id")); - assertTrue(inventoryClass.containsKey("store_id")); - assertTrue(inventoryClass.containsKey("last_update")); - - Set filmActorNodes = data - .getNodes() - .stream() + // expanding 1-N relationship: film_actor -[has_film] -> film + + data = provider.expand(dataSource, joinRecordRoots, "out", "has_film", 300); + + assertThat(data.getNodesClasses().size()).isEqualTo(1); + assertThat(data.getNodes().size()).isEqualTo(19); + assertThat(data.getEdgesClasses().size()).isEqualTo(1); + assertThat(data.getEdges().size()).isEqualTo(19); + + // Node classes checks + assertThat(data.getNodesClasses().containsKey("film")).isTrue(); + + Map filmClass = data.getNodesClasses().get("film"); + assertThat(filmClass.containsKey("film_id")).isTrue(); + assertThat(filmClass.containsKey("title")).isTrue(); + assertThat(filmClass.containsKey("description")).isTrue(); + assertThat(filmClass.containsKey("release_year")).isTrue(); + assertThat(filmClass.containsKey("language_id")).isTrue(); + assertThat(filmClass.containsKey("original_language_id")).isTrue(); + assertThat(filmClass.containsKey("rental_duration")).isTrue(); + assertThat(filmClass.containsKey("rental_rate")).isTrue(); + assertThat(filmClass.containsKey("length")).isTrue(); + assertThat(filmClass.containsKey("replacement_cost")).isTrue(); + assertThat(filmClass.containsKey("rating")).isTrue(); + assertThat(filmClass.containsKey("last_update")).isTrue(); + assertThat(filmClass.containsKey("special_features")).isTrue(); + + // nodes checks + Iterator it = data.getNodes().iterator(); + CytoData currNodeContent; + Map currRecord; + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(1); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("ACADEMY DINOSAUR"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(23); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("ANACONDA CONFESSIONS"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(25); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("ANGELS LIFE"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(106); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("BULWORTH COMMANDMENTS"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(140); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("CHEAPER CLYDE"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(166); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("COLOR PHILADELPHIA"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(277); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("ELEPHANT TROJAN"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(361); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("GLEAMING JAWBREAKER"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(438); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("HUMAN GRAFFITI"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(499); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("KING EVOLUTION"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(506); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("LADY STAGE"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(509); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("LANGUAGE COWBOY"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(605); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("MULHOLLAND BEAST"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(635); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("OKLAHOMA JUMANJI"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(749); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("RULES HUMAN"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(832); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("SPLASH GUMP"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(939); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("VERTIGO NORTHWEST"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(970); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("WESTWARD SEABISCUIT"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(980); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("WIZARD COLDBLOODED"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + // edges checks + it = data.getEdges().iterator(); + CytoData currEdgeContent; + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_1"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("811_71"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_23"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_23"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8123_723"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_25"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_25"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8125_725"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_106"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_106"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81106_7106"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_140"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_140"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81140_7140"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_166"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_166"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81166_7166"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_277"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_277"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81277_7277"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_361"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_361"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81361_7361"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_438"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_438"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81438_7438"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_499"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_499"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81499_7499"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_506"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_506"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81506_7506"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_509"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_509"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81509_7509"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_605"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_605"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81605_7605"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_635"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_635"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81635_7635"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_749"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_749"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81749_7749"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_832"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_832"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81832_7832"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_939"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_939"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81939_7939"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_970"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_970"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81970_7970"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_980"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_980"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81980_7980"); + + /** Get actors by movie */ + + // expanding 1-N relationship: film <-[has_film]- film_actor + + rootIds[0] = "7_2"; + data = provider.expand(dataSource, rootIds, "in", "has_film", 300); + + assertThat(data.getNodesClasses().size()).isEqualTo(3); + assertThat(data.getNodes().size()).isEqualTo(8); + assertThat(data.getEdgesClasses().size()).isEqualTo(1); + assertThat(data.getEdges().size()).isEqualTo(8); + + // Node classes checks + assertThat(data.getNodesClasses().containsKey("film_actor")).isTrue(); + assertThat(data.getNodesClasses().containsKey("film_category")) + .isTrue(); // has_film represents also the relationship: film_category -> film + assertThat(data.getNodesClasses().containsKey("inventory")) + .isTrue(); // has_film represents also the relationship: inventory -> film + + filmActorClass = data.getNodesClasses().get("film_actor"); + assertThat(filmActorClass.containsKey("film_id")).isTrue(); + assertThat(filmActorClass.containsKey("actor_id")).isTrue(); + assertThat(filmActorClass.containsKey("last_update")).isTrue(); + filmActorClass = data.getNodesClasses().get("film_category"); + assertThat(filmActorClass.containsKey("film_id")).isTrue(); + assertThat(filmActorClass.containsKey("category_id")).isTrue(); + assertThat(filmActorClass.containsKey("last_update")).isTrue(); + Map inventoryClass = data.getNodesClasses().get("inventory"); + assertThat(inventoryClass.containsKey("inventory_id")).isTrue(); + assertThat(inventoryClass.containsKey("film_id")).isTrue(); + assertThat(inventoryClass.containsKey("store_id")).isTrue(); + assertThat(inventoryClass.containsKey("last_update")).isTrue(); + + Set filmActorNodes = + data.getNodes().stream() .filter(filmActorNode -> filmActorNode.getClasses().equals("film_actor")) .collect(Collectors.toSet()); - Set filmCategoryNodes = data - .getNodes() - .stream() + Set filmCategoryNodes = + data.getNodes().stream() .filter(filmCategoryNode -> filmCategoryNode.getClasses().equals("film_category")) .collect(Collectors.toSet()); - Set inventoryNodes = data - .getNodes() - .stream() + Set inventoryNodes = + data.getNodes().stream() .filter(inventoryNode -> inventoryNode.getClasses().equals("inventory")) .collect(Collectors.toSet()); - assertEquals(filmActorNodes.size(), 4); - assertEquals(filmCategoryNodes.size(), 1); - assertEquals(inventoryNodes.size(), 3); - - joinRecordRoots = new String[4]; - i = 0; - for (CytoData currentData : filmActorNodes) { - joinRecordRoots[i] = "8_" + currentData.getData().getRecord().get("actor_id").toString() + "_2"; - i++; - } - - // expanding 1-N relationship: film_actor -[has_actor]-> actor - - data = provider.expand(dataSource, joinRecordRoots, "out", "has_actor", 300); - - assertEquals(data.getNodesClasses().size(), 1); - assertEquals(data.getNodes().size(), 4); - assertEquals(data.getEdgesClasses().size(), 1); - assertEquals(data.getEdges().size(), 4); - - // Node classes checks - assertTrue(data.getNodesClasses().containsKey("actor")); - - Map actorClass = data.getNodesClasses().get("actor"); - assertTrue(actorClass.containsKey("actor_id")); - assertTrue(actorClass.containsKey("first_name")); - assertTrue(actorClass.containsKey("last_name")); - assertTrue(actorClass.containsKey("last_update")); - - // nodes checks - it = data.getNodes().iterator(); - - try { - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 19); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "BOB"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "FAWCETT"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(((Date) currRecord.get("last_update")).toInstant(), df.parse("2006-02-15 04:34:33-00").toInstant()); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 85); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "MINNIE"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "ZELLWEGER"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(((Date) currRecord.get("last_update")).toInstant(), df.parse("2006-02-15 04:34:33-00").toInstant()); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 90); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "SEAN"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "GUINESS"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(((Date) currRecord.get("last_update")).toInstant(), df.parse("2006-02-15 04:34:33-00").toInstant()); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 160); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "CHRIS"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "DEPP"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(((Date) currRecord.get("last_update")).toInstant(), df.parse("2006-02-15 04:34:33-00").toInstant()); - } catch (ParseException e) { - e.printStackTrace(); - fail(); - } - - // edges checks - it = data.getEdges().iterator(); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_19_2"); - assertEquals(currEdgeContent.getData().getTarget(), "1_19"); - assertEquals(currEdgeContent.getData().getId(), "8192_119"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_85_2"); - assertEquals(currEdgeContent.getData().getTarget(), "1_85"); - assertEquals(currEdgeContent.getData().getId(), "8852_185"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_90_2"); - assertEquals(currEdgeContent.getData().getTarget(), "1_90"); - assertEquals(currEdgeContent.getData().getId(), "8902_190"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_160_2"); - assertEquals(currEdgeContent.getData().getTarget(), "1_160"); - assertEquals(currEdgeContent.getData().getId(), "81602_1160"); - } + assertThat(filmActorNodes.size()).isEqualTo(4); + assertThat(filmCategoryNodes.size()).isEqualTo(1); + assertThat(inventoryNodes.size()).isEqualTo(3); - @Override - @Test - public void expand1To1RelWithCompositeFKTest() {} + joinRecordRoots = new String[4]; + i = 0; + for (CytoData currentData : filmActorNodes) { + joinRecordRoots[i] = + "8_" + currentData.getData().getRecord().get("actor_id").toString() + "_2"; + i++; + } - @Override - @Test - public void expand1ToNRelWithCompositeFKTest() {} + // expanding 1-N relationship: film_actor -[has_actor]-> actor + + data = provider.expand(dataSource, joinRecordRoots, "out", "has_actor", 300); + + assertThat(data.getNodesClasses().size()).isEqualTo(1); + assertThat(data.getNodes().size()).isEqualTo(4); + assertThat(data.getEdgesClasses().size()).isEqualTo(1); + assertThat(data.getEdges().size()).isEqualTo(4); + + // Node classes checks + assertThat(data.getNodesClasses().containsKey("actor")).isTrue(); + + Map actorClass = data.getNodesClasses().get("actor"); + assertThat(actorClass.containsKey("actor_id")).isTrue(); + assertThat(actorClass.containsKey("first_name")).isTrue(); + assertThat(actorClass.containsKey("last_name")).isTrue(); + assertThat(actorClass.containsKey("last_update")).isTrue(); + + // nodes checks + it = data.getNodes().iterator(); + + try { + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(19); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("BOB"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("FAWCETT"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(((Timestamp) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 03:34:33-00").toInstant()); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(85); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("MINNIE"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("ZELLWEGER"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 03:34:33-00").toInstant()); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(90); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("SEAN"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("GUINESS"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 03:34:33-00").toInstant()); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(160); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("CHRIS"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("DEPP"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(((Date) currRecord.get("last_update")).toInstant()) + .isEqualTo(df.parse("2006-02-15 03:34:33-00").toInstant()); + } catch (ParseException e) { + e.printStackTrace(); + fail(""); + } - @Override - @Test - public void expand1ToNRelWithJoinTableAndCompositeFKTest() {} + // edges checks + it = data.getEdges().iterator(); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_19_2"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("1_19"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8192_119"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_85_2"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("1_85"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8852_185"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_90_2"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("1_90"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8902_190"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_160_2"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("1_160"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81602_1160"); + } + + @Override + @Test + public void expand1To1RelWithCompositeFKTest() {} + + @Override + @Test + public void expand1ToNRelWithCompositeFKTest() {} + + @Override + @Test + public void expand1ToNRelWithJoinTableAndCompositeFKTest() {} } diff --git a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/MysqlSQLDataProviderWithAggregationTest.java b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/MysqlSQLDataProviderWithAggregationTest.java index 9f3c5fa9..a4c07ec1 100644 --- a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/MysqlSQLDataProviderWithAggregationTest.java +++ b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/MysqlSQLDataProviderWithAggregationTest.java @@ -20,10 +20,8 @@ * #L% */ -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import com.arcadeanalytics.provider.CytoData; import com.arcadeanalytics.provider.DataSourceInfo; @@ -34,655 +32,652 @@ import org.junit.jupiter.api.Test; import org.testcontainers.containers.MySQLContainer; -public class MysqlSQLDataProviderWithAggregationTest extends AbstractRDBMSProviderWithAggregationTest { - - private DataSourceInfo dataSource = null; - - @BeforeEach - public void setUp() { - final MySQLContainer container = MySQLContainerHolder.container; - this.dataSource = - new DataSourceInfo( - 1L, - "RDBMS_MYSQL", - "testDataSource", - "desc", - container.getContainerIpAddress(), - container.getFirstMappedPort(), - container.getDatabaseName(), - container.getUsername(), - container.getPassword(), - true, - "{}", - false, - false, - "", - 22, - "", - false - ); - - provider = new RDBMSDataProvider(); - } - - @Override - @Test - public void fetchDataThroughTableScanTest() { - try { - provider.fetchData(dataSource, "select * from film_actor limit 5", 5); - fail(); - } catch (Exception e) { - String message = e.getMessage(); - assertTrue(message.contains("Wrong query content: the requested table was aggregated into")); - } - } - - @Override - public void expandN2NRelationship() { - /** - * Get movies by actor - */ - - // expanding 1-N relationship: actor -[film_actor]-> film - String[] rootIds = { "1_1" }; - GraphData data = provider.expand(dataSource, rootIds, "out", "film_actor", 300); - - assertEquals(data.getNodesClasses().size(), 1); - assertEquals(data.getNodes().size(), 19); - assertEquals(data.getEdgesClasses().size(), 1); - assertEquals(data.getEdges().size(), 19); - - // Node classes checks - assertTrue(data.getNodesClasses().containsKey("film")); - - Map filmClass = data.getNodesClasses().get("film"); - assertTrue(filmClass.containsKey("film_id")); - assertTrue(filmClass.containsKey("title")); - assertTrue(filmClass.containsKey("description")); - assertTrue(filmClass.containsKey("release_year")); - assertTrue(filmClass.containsKey("language_id")); - assertTrue(filmClass.containsKey("original_language_id")); - assertTrue(filmClass.containsKey("rental_duration")); - assertTrue(filmClass.containsKey("rental_rate")); - assertTrue(filmClass.containsKey("length")); - assertTrue(filmClass.containsKey("replacement_cost")); - assertTrue(filmClass.containsKey("rating")); - assertTrue(filmClass.containsKey("last_update")); - assertTrue(filmClass.containsKey("special_features")); - - // nodes checks - Iterator it = data.getNodes().iterator(); - CytoData currNodeContent; - Map currRecord; - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 1); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "ACADEMY DINOSAUR"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 23); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "ANACONDA CONFESSIONS"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 25); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "ANGELS LIFE"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 106); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "BULWORTH COMMANDMENTS"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 140); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "CHEAPER CLYDE"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 166); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "COLOR PHILADELPHIA"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 277); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "ELEPHANT TROJAN"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 361); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "GLEAMING JAWBREAKER"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 438); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "HUMAN GRAFFITI"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 499); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "KING EVOLUTION"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 506); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "LADY STAGE"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 509); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "LANGUAGE COWBOY"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 605); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "MULHOLLAND BEAST"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 635); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "OKLAHOMA JUMANJI"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 749); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "RULES HUMAN"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 832); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "SPLASH GUMP"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 939); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "VERTIGO NORTHWEST"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 970); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "WESTWARD SEABISCUIT"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 980); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "WIZARD COLDBLOODED"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - // edges checks - it = data.getEdges().iterator(); - CytoData currEdgeContent; - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_1"); - assertEquals(currEdgeContent.getData().getId(), "8_1_1"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_23"); - assertEquals(currEdgeContent.getData().getId(), "8_1_23"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_25"); - assertEquals(currEdgeContent.getData().getId(), "8_1_25"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_106"); - assertEquals(currEdgeContent.getData().getId(), "8_1_106"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_140"); - assertEquals(currEdgeContent.getData().getId(), "8_1_140"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_166"); - assertEquals(currEdgeContent.getData().getId(), "8_1_166"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_277"); - assertEquals(currEdgeContent.getData().getId(), "8_1_277"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_361"); - assertEquals(currEdgeContent.getData().getId(), "8_1_361"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_438"); - assertEquals(currEdgeContent.getData().getId(), "8_1_438"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_499"); - assertEquals(currEdgeContent.getData().getId(), "8_1_499"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_506"); - assertEquals(currEdgeContent.getData().getId(), "8_1_506"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_509"); - assertEquals(currEdgeContent.getData().getId(), "8_1_509"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_605"); - assertEquals(currEdgeContent.getData().getId(), "8_1_605"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_635"); - assertEquals(currEdgeContent.getData().getId(), "8_1_635"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_749"); - assertEquals(currEdgeContent.getData().getId(), "8_1_749"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_832"); - assertEquals(currEdgeContent.getData().getId(), "8_1_832"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_939"); - assertEquals(currEdgeContent.getData().getId(), "8_1_939"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_970"); - assertEquals(currEdgeContent.getData().getId(), "8_1_970"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_980"); - assertEquals(currEdgeContent.getData().getId(), "8_1_980"); - - /** - * Get actors by movie - */ - - // expanding 1-N relationship: film <-[has_film]- actor - - rootIds[0] = "7_2"; - data = provider.expand(dataSource, rootIds, "in", "film_actor", 300); - - assertEquals(data.getNodesClasses().size(), 1); - assertEquals(data.getNodes().size(), 4); - assertEquals(data.getEdgesClasses().size(), 1); - assertEquals(data.getEdges().size(), 4); - - // Node classes checks - assertTrue(data.getNodesClasses().containsKey("actor")); - - Map actorClass = data.getNodesClasses().get("actor"); - assertTrue(actorClass.containsKey("actor_id")); - assertTrue(actorClass.containsKey("first_name")); - assertTrue(actorClass.containsKey("last_name")); - assertTrue(actorClass.containsKey("last_update")); - - // nodes checks - it = data.getNodes().iterator(); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 19); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "BOB"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "FAWCETT"); - assertTrue(currRecord.containsKey("last_update")); - // assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 85); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "MINNIE"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "ZELLWEGER"); - assertTrue(currRecord.containsKey("last_update")); - // assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 90); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "SEAN"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "GUINESS"); - assertTrue(currRecord.containsKey("last_update")); - // assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 160); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "CHRIS"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "DEPP"); - assertTrue(currRecord.containsKey("last_update")); - // assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); - - // edges checks - it = data.getEdges().iterator(); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_19"); - assertEquals(currEdgeContent.getData().getTarget(), "7_2"); - assertEquals(currEdgeContent.getData().getId(), "8_19_2"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_85"); - assertEquals(currEdgeContent.getData().getTarget(), "7_2"); - assertEquals(currEdgeContent.getData().getId(), "8_85_2"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_90"); - assertEquals(currEdgeContent.getData().getTarget(), "7_2"); - assertEquals(currEdgeContent.getData().getId(), "8_90_2"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_160"); - assertEquals(currEdgeContent.getData().getTarget(), "7_2"); - assertEquals(currEdgeContent.getData().getId(), "8_160_2"); +class MysqlSQLDataProviderWithAggregationTest extends AbstractRDBMSProviderWithAggregationTest { + + private DataSourceInfo dataSource = null; + + @BeforeEach + public void setUp() { + final MySQLContainer container = MySQLContainerHolder.container; + this.dataSource = + new DataSourceInfo( + 1L, + "RDBMS_MYSQL", + "testDataSource", + "desc", + container.getContainerIpAddress(), + container.getFirstMappedPort(), + container.getDatabaseName(), + container.getUsername(), + container.getPassword(), + true, + "{}", + false, + false, + "", + 22, + "", + false); + + provider = new RDBMSDataProvider(); + } + + @Override + @Test + public void fetchDataThroughTableScanTest() { + try { + provider.fetchData(dataSource, "select * from film_actor limit 5", 5); + fail(""); + } catch (Exception e) { + String message = e.getMessage(); + assertThat(message.contains("Wrong query content: the requested table was aggregated into")) + .isTrue(); } + } + + @Override + @Test + public void expandN2NRelationship() { + /** Get movies by actor */ + + // expanding 1-N relationship: actor -[film_actor]-> film + String[] rootIds = {"1_1"}; + GraphData data = provider.expand(dataSource, rootIds, "out", "film_actor", 300); + + assertThat(data.getNodesClasses().size()).isEqualTo(1); + assertThat(data.getNodes().size()).isEqualTo(19); + assertThat(data.getEdgesClasses().size()).isEqualTo(1); + assertThat(data.getEdges().size()).isEqualTo(19); + + // Node classes checks + assertThat(data.getNodesClasses().containsKey("film")).isTrue(); + + Map filmClass = data.getNodesClasses().get("film"); + assertThat(filmClass.containsKey("film_id")).isTrue(); + assertThat(filmClass.containsKey("title")).isTrue(); + assertThat(filmClass.containsKey("description")).isTrue(); + assertThat(filmClass.containsKey("release_year")).isTrue(); + assertThat(filmClass.containsKey("language_id")).isTrue(); + assertThat(filmClass.containsKey("original_language_id")).isTrue(); + assertThat(filmClass.containsKey("rental_duration")).isTrue(); + assertThat(filmClass.containsKey("rental_rate")).isTrue(); + assertThat(filmClass.containsKey("length")).isTrue(); + assertThat(filmClass.containsKey("replacement_cost")).isTrue(); + assertThat(filmClass.containsKey("rating")).isTrue(); + assertThat(filmClass.containsKey("last_update")).isTrue(); + assertThat(filmClass.containsKey("special_features")).isTrue(); + + // nodes checks + Iterator it = data.getNodes().iterator(); + CytoData currNodeContent; + Map currRecord; + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(1); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("ACADEMY DINOSAUR"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(23); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("ANACONDA CONFESSIONS"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(25); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("ANGELS LIFE"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(106); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("BULWORTH COMMANDMENTS"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(140); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("CHEAPER CLYDE"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(166); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("COLOR PHILADELPHIA"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(277); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("ELEPHANT TROJAN"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(361); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("GLEAMING JAWBREAKER"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(438); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("HUMAN GRAFFITI"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(499); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("KING EVOLUTION"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(506); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("LADY STAGE"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(509); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("LANGUAGE COWBOY"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(605); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("MULHOLLAND BEAST"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(635); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("OKLAHOMA JUMANJI"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(749); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("RULES HUMAN"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(832); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("SPLASH GUMP"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(939); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("VERTIGO NORTHWEST"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(970); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("WESTWARD SEABISCUIT"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(980); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("WIZARD COLDBLOODED"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + // edges checks + it = data.getEdges().iterator(); + CytoData currEdgeContent; + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_1"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_1"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_23"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_23"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_25"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_25"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_106"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_106"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_140"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_140"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_166"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_166"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_277"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_277"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_361"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_361"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_438"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_438"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_499"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_499"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_506"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_506"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_509"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_509"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_605"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_605"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_635"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_635"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_749"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_749"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_832"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_832"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_939"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_939"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_970"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_970"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_980"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_980"); + + /** Get actors by movie */ + + // expanding 1-N relationship: film <-[has_film]- actor + + rootIds[0] = "7_2"; + data = provider.expand(dataSource, rootIds, "in", "film_actor", 300); + + assertThat(data.getNodesClasses().size()).isEqualTo(1); + assertThat(data.getNodes().size()).isEqualTo(4); + assertThat(data.getEdgesClasses().size()).isEqualTo(1); + assertThat(data.getEdges().size()).isEqualTo(4); + + // Node classes checks + assertThat(data.getNodesClasses().containsKey("actor")).isTrue(); + + Map actorClass = data.getNodesClasses().get("actor"); + assertThat(actorClass.containsKey("actor_id")).isTrue(); + assertThat(actorClass.containsKey("first_name")).isTrue(); + assertThat(actorClass.containsKey("last_name")).isTrue(); + assertThat(actorClass.containsKey("last_update")).isTrue(); + + // nodes checks + it = data.getNodes().iterator(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(19); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("BOB"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("FAWCETT"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + // assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(85); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("MINNIE"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("ZELLWEGER"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + // assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(90); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("SEAN"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("GUINESS"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + // assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(160); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("CHRIS"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("DEPP"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + // assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); + + // edges checks + it = data.getEdges().iterator(); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_19"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_2"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_19_2"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_85"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_2"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_85_2"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_90"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_2"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_90_2"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_160"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_2"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_160_2"); + } } diff --git a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/PostgreSQLContainerHolder.java b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/PostgreSQLContainerHolder.java index c733e926..cc4232a2 100644 --- a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/PostgreSQLContainerHolder.java +++ b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/PostgreSQLContainerHolder.java @@ -25,15 +25,17 @@ public abstract class PostgreSQLContainerHolder { - public static final PostgreSQLContainer container; + public static final PostgreSQLContainer container; - static { - container = - new PostgreSQLContainer(DockerImageName.parse("arcadeanalytics/postgres-dvdrental").asCompatibleSubstituteFor("postgres")) - .withUsername("postgres") - .withPassword("postgres"); - container.start(); + static { + container = + new PostgreSQLContainer( + DockerImageName.parse("arcadeanalytics/postgres-dvdrental") + .asCompatibleSubstituteFor("postgres")) + .withUsername("postgres") + .withPassword("postgres"); + container.start(); - container.withDatabaseName("dvdrental"); - } + container.withDatabaseName("dvdrental"); + } } diff --git a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/PostgreSQLDataProviderTest.java b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/PostgreSQLDataProviderTest.java index 5c143ec5..24739963 100644 --- a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/PostgreSQLDataProviderTest.java +++ b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/PostgreSQLDataProviderTest.java @@ -20,10 +20,8 @@ * #L% */ -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import com.arcadeanalytics.provider.CytoData; import com.arcadeanalytics.provider.DataSourceInfo; @@ -39,1743 +37,1747 @@ import org.junit.jupiter.api.Test; import org.testcontainers.containers.PostgreSQLContainer; -public class PostgreSQLDataProviderTest extends AbstractRDBMSProviderTest { - - private DataSourceInfo dataSource; - - @BeforeEach - public void setUp() throws Exception { - final PostgreSQLContainer container = PostgreSQLContainerHolder.container; - String dbUrl = container.getJdbcUrl(); - this.dataSource = - new DataSourceInfo( - 1L, - "RDBMS_POSTGRESQL", - "testDataSource", - "desc", - container.getContainerIpAddress(), - container.getFirstMappedPort(), - container.getDatabaseName(), - "postgres", - "postgres", - false, - "{}", - false, - false, - "", - 22, - "", - false - ); - - provider = new RDBMSDataProvider(); +class PostgreSQLDataProviderTest extends AbstractRDBMSProviderTest { + + private DataSourceInfo dataSource; + + @BeforeEach + public void setUp() throws Exception { + final PostgreSQLContainer container = PostgreSQLContainerHolder.container; + String dbUrl = container.getJdbcUrl(); + this.dataSource = + new DataSourceInfo( + 1L, + "RDBMS_POSTGRESQL", + "testDataSource", + "desc", + container.getContainerIpAddress(), + container.getFirstMappedPort(), + container.getDatabaseName(), + "postgres", + "postgres", + false, + "{}", + false, + false, + "", + 22, + "", + false); + + provider = new RDBMSDataProvider(); + } + + @Override + @Test + public void fetchDataThroughTableScanTest() { + GraphData data = provider.fetchData(dataSource, "select * from actor limit 5", 5); + + assertThat(data.getNodesClasses().size()).isEqualTo(1); + assertThat(data.getNodes().size()).isEqualTo(5); + assertThat(data.getEdgesClasses().size()).isEqualTo(0); + assertThat(data.getEdges().size()).isEqualTo(0); + + // Node classes checks + assertThat(data.getNodesClasses().containsKey("actor")).isTrue(); + + Map actorClass = data.getNodesClasses().get("actor"); + assertThat(actorClass.containsKey("actor_id")).isTrue(); + assertThat(actorClass.containsKey("first_name")).isTrue(); + assertThat(actorClass.containsKey("last_name")).isTrue(); + assertThat(actorClass.containsKey("last_update")).isTrue(); + + // nodes checks + Iterator it = data.getNodes().iterator(); + CytoData currNodeContent; + Map currRecord; + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(1); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("Penelope"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("Guiness"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2013-05-26 14:47:57.62"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(2); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("Nick"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("Wahlberg"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2013-05-26 14:47:57.62"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(3); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("Ed"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("Chase"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2013-05-26 14:47:57.62"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(4); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("Jennifer"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("Davis"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2013-05-26 14:47:57.62"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(5); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("Johnny"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("Lollobrigida"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2013-05-26 14:47:57.62"); + } + + @Override + @Test + public void loadVerticesFromIdsMultipleTablesTest() { + /* + * Fetching the first 5 vertices from the actor table and the first 2 vertices from the store table by cyto-ids + * cyto-id from is x_y where: + * - x is refers to the source table (actor is the first table in the source db schema) + * - y is the external key, then the pk value of the source record + */ + + String[] ids = {"1_1", "1_2", "1_3", "1_4", "1_5", "15_1", "15_2"}; + + GraphData data = provider.load(dataSource, ids); + + assertThat(data.getNodesClasses().size()).isEqualTo(2); + assertThat(data.getNodes().size()).isEqualTo(7); + assertThat(data.getEdgesClasses().size()).isEqualTo(0); + assertThat(data.getEdges().size()).isEqualTo(0); + + // Node classes checks + assertThat(data.getNodesClasses().containsKey("actor")).isTrue(); + assertThat(data.getNodesClasses().containsKey("store")).isTrue(); + + Map actorClass = data.getNodesClasses().get("actor"); + assertThat(actorClass.containsKey("actor_id")).isTrue(); + assertThat(actorClass.containsKey("first_name")).isTrue(); + assertThat(actorClass.containsKey("last_name")).isTrue(); + assertThat(actorClass.containsKey("last_update")).isTrue(); + Map storeClass = data.getNodesClasses().get("store"); + assertThat(storeClass.containsKey("store_id")).isTrue(); + assertThat(storeClass.containsKey("manager_staff_id")).isTrue(); + assertThat(storeClass.containsKey("address_id")).isTrue(); + assertThat(storeClass.containsKey("last_update")).isTrue(); + + // nodes checks + Iterator it = data.getNodes().iterator(); + CytoData currNodeContent; + Map currRecord; + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(1); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("Penelope"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("Guiness"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2013-05-26 14:47:57.62"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(2); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("Nick"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("Wahlberg"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2013-05-26 14:47:57.62"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(3); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("Ed"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("Chase"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2013-05-26 14:47:57.62"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(4); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("Jennifer"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("Davis"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2013-05-26 14:47:57.62"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(5); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("Johnny"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("Lollobrigida"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2013-05-26 14:47:57.62"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("store_id")).isTrue(); + assertThat(currRecord.get("store_id")).isEqualTo(1); + assertThat(currRecord.containsKey("manager_staff_id")).isTrue(); + assertThat(currRecord.get("manager_staff_id")).isEqualTo(1); + assertThat(currRecord.containsKey("address_id")).isTrue(); + assertThat(currRecord.get("address_id")).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2006-02-15 09:57:12.0"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("store_id")).isTrue(); + assertThat(currRecord.get("store_id")).isEqualTo(2); + assertThat(currRecord.containsKey("manager_staff_id")).isTrue(); + assertThat(currRecord.get("manager_staff_id")).isEqualTo(2); + assertThat(currRecord.containsKey("address_id")).isTrue(); + assertThat(currRecord.get("address_id")).isEqualTo(2); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2006-02-15 09:57:12.0"); + } + + @Override + @Test + public void loadVerticesFromIdsSingleTableTest() { + /* + * Fetching the first 5 vertices from the actor table by cyto-ids + * cyto-id from is x_y where: + * - x is refers to the source table (actor is the first table in the source db schema) + * - y is the external key, then the pk value of the source record + */ + + String[] actorIds = {"1_1", "1_2", "1_3", "1_4", "1_5"}; + + GraphData data = provider.load(dataSource, actorIds); + + assertThat(data.getNodesClasses().size()).isEqualTo(1); + assertThat(data.getNodes().size()).isEqualTo(5); + assertThat(data.getEdgesClasses().size()).isEqualTo(0); + assertThat(data.getEdges().size()).isEqualTo(0); + + // Node classes checks + assertThat(data.getNodesClasses().containsKey("actor")).isTrue(); + + Map actorClass = data.getNodesClasses().get("actor"); + assertThat(actorClass.containsKey("actor_id")).isTrue(); + assertThat(actorClass.containsKey("first_name")).isTrue(); + assertThat(actorClass.containsKey("last_name")).isTrue(); + assertThat(actorClass.containsKey("last_update")).isTrue(); + + // nodes checks + Iterator it = data.getNodes().iterator(); + CytoData currNodeContent; + Map currRecord; + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(1); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("Penelope"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("Guiness"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2013-05-26 14:47:57.62"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(2); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("Nick"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("Wahlberg"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2013-05-26 14:47:57.62"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(3); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("Ed"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("Chase"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2013-05-26 14:47:57.62"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(4); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("Jennifer"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("Davis"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2013-05-26 14:47:57.62"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(5); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("Johnny"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("Lollobrigida"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2013-05-26 14:47:57.62"); + + /* + * Fetching 2 vertices from the store table by cyto-ids + * cyto-id from is x_y where: + * - x is refers to the source table (actor is the first table in the source db schema) + * - y is the external key, then the pk value of the source record + */ + + String[] storeIds = {"15_1", "15_2"}; + data = provider.load(dataSource, storeIds); + + assertThat(data.getNodesClasses().size()).isEqualTo(1); + assertThat(data.getNodes().size()).isEqualTo(2); + assertThat(data.getEdgesClasses().size()).isEqualTo(0); + assertThat(data.getEdges().size()).isEqualTo(0); + + // Node classes checks + assertThat(data.getNodesClasses().containsKey("store")).isTrue(); + + Map storeClass = data.getNodesClasses().get("store"); + assertThat(storeClass.containsKey("store_id")).isTrue(); + assertThat(storeClass.containsKey("manager_staff_id")).isTrue(); + assertThat(storeClass.containsKey("address_id")).isTrue(); + assertThat(storeClass.containsKey("last_update")).isTrue(); + + // nodes checks + it = data.getNodes().iterator(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("store_id")).isTrue(); + assertThat(currRecord.get("store_id")).isEqualTo(1); + assertThat(currRecord.containsKey("manager_staff_id")).isTrue(); + assertThat(currRecord.get("manager_staff_id")).isEqualTo(1); + assertThat(currRecord.containsKey("address_id")).isTrue(); + assertThat(currRecord.get("address_id")).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2006-02-15 09:57:12.0"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("store_id")).isTrue(); + assertThat(currRecord.get("store_id")).isEqualTo(2); + assertThat(currRecord.containsKey("manager_staff_id")).isTrue(); + assertThat(currRecord.get("manager_staff_id")).isEqualTo(2); + assertThat(currRecord.containsKey("address_id")).isTrue(); + assertThat(currRecord.get("address_id")).isEqualTo(2); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2006-02-15 09:57:12.0"); + } + + @Override + @Test + public void expand1To1RelWithSimpleFKTest() { + // 1-1 Relationship: distribution_country -[has_distribution_language]-> language + + // adding schema info + Connection connection = null; + Statement st = null; + + try { + connection = + DriverManager.getConnection( + PostgreSQLContainerHolder.container.getJdbcUrl(), "postgres", "postgres"); + + String distributioCountryTableBuilding = + "create table distribution_country (distribution_country_id integer not null, name" + + " varchar(256) not null, distribution_language integer not null, primary key" + + " (distribution_country_id), foreign key (distribution_language) references" + + " language(language_id))"; + st = connection.createStatement(); + st.execute(distributioCountryTableBuilding); + + // populating the new table + String distributionCountryFilling = + "insert into distribution_country (distribution_country_id,name,distribution_language)" + + " values (1,'USA',1),(2,'Italy',2),(3,'Japan',3),(4,'China',4),(5,'France',5)," + + "(6,'Germany',6)"; + st.execute(distributionCountryFilling); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } finally { + try { + connection.close(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } } - @Override - @Test - public void fetchDataThroughTableScanTest() { - GraphData data = provider.fetchData(dataSource, "select * from actor limit 5", 5); - - assertEquals(data.getNodesClasses().size(), 1); - assertEquals(data.getNodes().size(), 5); - assertEquals(data.getEdgesClasses().size(), 0); - assertEquals(data.getEdges().size(), 0); - - // Node classes checks - assertTrue(data.getNodesClasses().containsKey("actor")); - - Map actorClass = data.getNodesClasses().get("actor"); - assertTrue(actorClass.containsKey("actor_id")); - assertTrue(actorClass.containsKey("first_name")); - assertTrue(actorClass.containsKey("last_name")); - assertTrue(actorClass.containsKey("last_update")); - - // nodes checks - Iterator it = data.getNodes().iterator(); - CytoData currNodeContent; - Map currRecord; - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 1); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "Penelope"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "Guiness"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 2); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "Nick"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "Wahlberg"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 3); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "Ed"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "Chase"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 4); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "Jennifer"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "Davis"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 5); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "Johnny"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "Lollobrigida"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); + String[] rootIds = {"7_1", "7_2", "7_3", "7_4", "7_5", "7_6"}; + GraphData data = provider.expand(dataSource, rootIds, "out", "has_distribution_language", 300); + + assertThat(data.getNodesClasses().size()).isEqualTo(1); + assertThat(data.getNodes().size()).isEqualTo(6); + assertThat(data.getEdgesClasses().size()).isEqualTo(1); + assertThat(data.getEdges().size()).isEqualTo(6); + + // Node classes checks + assertThat(data.getNodesClasses().containsKey("language")).isTrue(); + + Map languageClass = data.getNodesClasses().get("language"); + assertThat(languageClass.containsKey("language_id")).isTrue(); + assertThat(languageClass.containsKey("name")).isTrue(); + assertThat(languageClass.containsKey("last_update")).isTrue(); + + // nodes checks + Iterator it = data.getNodes().iterator(); + CytoData currNodeContent; + Map currRecord; + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("language_id")).isTrue(); + assertThat(currRecord.get("language_id")).isEqualTo(1); + assertThat(currRecord.containsKey("name")).isTrue(); + assertThat(((String) currRecord.get("name")).trim()).isEqualTo("English"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2006-02-15 10:02:19.0"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("language_id")).isTrue(); + assertThat(currRecord.get("language_id")).isEqualTo(2); + assertThat(currRecord.containsKey("name")).isTrue(); + assertThat(((String) currRecord.get("name")).trim()).isEqualTo("Italian"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2006-02-15 10:02:19.0"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("language_id")).isTrue(); + assertThat(currRecord.get("language_id")).isEqualTo(3); + assertThat(currRecord.containsKey("name")).isTrue(); + assertThat(((String) currRecord.get("name")).trim()).isEqualTo("Japanese"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2006-02-15 10:02:19.0"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("language_id")).isTrue(); + assertThat(currRecord.get("language_id")).isEqualTo(4); + assertThat(currRecord.containsKey("name")).isTrue(); + assertThat(((String) currRecord.get("name")).trim()).isEqualTo("Mandarin"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2006-02-15 10:02:19.0"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("language_id")).isTrue(); + assertThat(currRecord.get("language_id")).isEqualTo(5); + assertThat(currRecord.containsKey("name")).isTrue(); + assertThat(((String) currRecord.get("name")).trim()).isEqualTo("French"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2006-02-15 10:02:19.0"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("language_id")).isTrue(); + assertThat(currRecord.get("language_id")).isEqualTo(6); + assertThat(currRecord.containsKey("name")).isTrue(); + assertThat(((String) currRecord.get("name")).trim()).isEqualTo("German"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2006-02-15 10:02:19.0"); + + // edges checks + it = data.getEdges().iterator(); + CytoData currEdgeContent; + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_distribution_language"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("7_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("12_1"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("71_121"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_distribution_language"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("7_2"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("12_2"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("72_122"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_distribution_language"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("7_3"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("12_3"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("73_123"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_distribution_language"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("7_4"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("12_4"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("74_124"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_distribution_language"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("7_5"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("12_5"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("75_125"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_distribution_language"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("7_6"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("12_6"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("76_126"); + + // 1-1 Relationship: language <-[has_distribution_language]- distribution_country + + rootIds[0] = "12_1"; + rootIds[1] = "12_2"; + rootIds[2] = "12_3"; + rootIds[3] = "12_4"; + rootIds[4] = "12_5"; + rootIds[5] = "12_6"; + data = provider.expand(dataSource, rootIds, "in", "has_distribution_language", 300); + + assertThat(data.getNodesClasses().size()).isEqualTo(1); + assertThat(data.getNodes().size()).isEqualTo(6); + assertThat(data.getEdgesClasses().size()).isEqualTo(1); + assertThat(data.getEdges().size()).isEqualTo(6); + + // Node classes checks + assertThat(data.getNodesClasses().containsKey("distribution_country")).isTrue(); + + Map distributionCountryClass = + data.getNodesClasses().get("distribution_country"); + assertThat(distributionCountryClass.containsKey("distribution_country_id")).isTrue(); + assertThat(distributionCountryClass.containsKey("name")).isTrue(); + assertThat(distributionCountryClass.containsKey("distribution_language")).isTrue(); + + it = data.getNodes().iterator(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("distribution_country_id")).isTrue(); + assertThat(currRecord.get("distribution_country_id")).isEqualTo(1); + assertThat(currRecord.containsKey("name")).isTrue(); + assertThat(((String) currRecord.get("name"))).isEqualTo("USA"); + assertThat(currRecord.containsKey("distribution_language")).isTrue(); + assertThat(currRecord.get("distribution_language")).isEqualTo(1); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("distribution_country_id")).isTrue(); + assertThat(currRecord.get("distribution_country_id")).isEqualTo(2); + assertThat(currRecord.containsKey("name")).isTrue(); + assertThat(((String) currRecord.get("name"))).isEqualTo("Italy"); + assertThat(currRecord.containsKey("distribution_language")).isTrue(); + assertThat(currRecord.get("distribution_language")).isEqualTo(2); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("distribution_country_id")).isTrue(); + assertThat(currRecord.get("distribution_country_id")).isEqualTo(3); + assertThat(currRecord.containsKey("name")).isTrue(); + assertThat(((String) currRecord.get("name"))).isEqualTo("Japan"); + assertThat(currRecord.containsKey("distribution_language")).isTrue(); + assertThat(currRecord.get("distribution_language")).isEqualTo(3); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("distribution_country_id")).isTrue(); + assertThat(currRecord.get("distribution_country_id")).isEqualTo(4); + assertThat(currRecord.containsKey("name")).isTrue(); + assertThat(((String) currRecord.get("name"))).isEqualTo("China"); + assertThat(currRecord.containsKey("distribution_language")).isTrue(); + assertThat(currRecord.get("distribution_language")).isEqualTo(4); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("distribution_country_id")).isTrue(); + assertThat(currRecord.get("distribution_country_id")).isEqualTo(5); + assertThat(currRecord.containsKey("name")).isTrue(); + assertThat(((String) currRecord.get("name"))).isEqualTo("France"); + assertThat(currRecord.containsKey("distribution_language")).isTrue(); + assertThat(currRecord.get("distribution_language")).isEqualTo(5); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("distribution_country_id")).isTrue(); + assertThat(currRecord.get("distribution_country_id")).isEqualTo(6); + assertThat(currRecord.containsKey("name")).isTrue(); + assertThat(((String) currRecord.get("name"))).isEqualTo("Germany"); + assertThat(currRecord.containsKey("distribution_language")).isTrue(); + assertThat(currRecord.get("distribution_language")).isEqualTo(6); + + // edges checks + it = data.getEdges().iterator(); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_distribution_language"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("7_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("12_1"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("71_121"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_distribution_language"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("7_2"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("12_2"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("72_122"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_distribution_language"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("7_3"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("12_3"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("73_123"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_distribution_language"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("7_4"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("12_4"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("74_124"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_distribution_language"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("7_5"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("12_5"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("75_125"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_distribution_language"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("7_6"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("12_6"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("76_126"); + + // dropping the new added table + try { + connection = + DriverManager.getConnection( + PostgreSQLContainerHolder.container.getJdbcUrl(), "postgres", "postgres"); + + String deleteDistributionCountryTable = "drop table distribution_country"; + st = connection.createStatement(); + st.execute(deleteDistributionCountryTable); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } finally { + try { + connection.close(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } } + } + + @Override + @Test + public void expand1ToNRelWithSimpleFKTest() { + // 1-N Relationship: city -[has_country]-> country + + String[] rootIds = {"4_1"}; + GraphData data = provider.expand(dataSource, rootIds, "out", "has_country", 300); + + assertThat(data.getNodesClasses().size()).isEqualTo(1); + assertThat(data.getNodes().size()).isEqualTo(1); + assertThat(data.getEdgesClasses().size()).isEqualTo(1); + assertThat(data.getEdges().size()).isEqualTo(1); + + // Node classes checks + assertThat(data.getNodesClasses().containsKey("country")).isTrue(); + + Map customerClass = data.getNodesClasses().get("country"); + assertThat(customerClass.containsKey("country_id")).isTrue(); + assertThat(customerClass.containsKey("country")).isTrue(); + assertThat(customerClass.containsKey("last_update")).isTrue(); + + // nodes checks + Iterator it = data.getNodes().iterator(); + CytoData currNodeContent; + Map currRecord; + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("country_id")).isTrue(); + assertThat(currRecord.get("country_id")).isEqualTo(87); + assertThat(currRecord.containsKey("country")).isTrue(); + assertThat(currRecord.get("country")).isEqualTo("Spain"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2006-02-15 09:44:00.0"); + + // edges checks + it = data.getEdges().iterator(); + CytoData currEdgeContent; + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + + assertThat(currEdgeContent.getClasses()).isEqualTo("has_country"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("4_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("5_87"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("41_587"); + + // 1-N Relationship: city <-[has_country]- country + + rootIds[0] = "5_87"; + data = provider.expand(dataSource, rootIds, "in", "has_country", 300); + + assertThat(data.getNodesClasses().size()).isEqualTo(1); + assertThat(data.getNodes().size()).isEqualTo(5); + assertThat(data.getEdgesClasses().size()).isEqualTo(1); + assertThat(data.getEdges().size()).isEqualTo(5); + + // nodes checks + it = data.getNodes().iterator(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("city_id")).isTrue(); + assertThat(currRecord.get("city_id")).isEqualTo(1); + assertThat(currRecord.containsKey("city")).isTrue(); + assertThat(currRecord.get("city")).isEqualTo("A Corua (La Corua)"); + assertThat(currRecord.containsKey("country_id")).isTrue(); + assertThat(currRecord.get("country_id")).isEqualTo(87); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2006-02-15 09:45:25.0"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("city_id")).isTrue(); + assertThat(currRecord.get("city_id")).isEqualTo(146); + assertThat(currRecord.containsKey("city")).isTrue(); + assertThat(currRecord.get("city")).isEqualTo("Donostia-San Sebastin"); + assertThat(currRecord.containsKey("country_id")).isTrue(); + assertThat(currRecord.get("country_id")).isEqualTo(87); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2006-02-15 09:45:25.0"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("city_id")).isTrue(); + assertThat(currRecord.get("city_id")).isEqualTo(181); + assertThat(currRecord.containsKey("city")).isTrue(); + assertThat(currRecord.get("city")).isEqualTo("Gijn"); + assertThat(currRecord.containsKey("country_id")).isTrue(); + assertThat(currRecord.get("country_id")).isEqualTo(87); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2006-02-15 09:45:25.0"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("city_id")).isTrue(); + assertThat(currRecord.get("city_id")).isEqualTo(388); + assertThat(currRecord.containsKey("city")).isTrue(); + assertThat(currRecord.get("city")).isEqualTo("Ourense (Orense)"); + assertThat(currRecord.containsKey("country_id")).isTrue(); + assertThat(currRecord.get("country_id")).isEqualTo(87); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2006-02-15 09:45:25.0"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("city_id")).isTrue(); + assertThat(currRecord.get("city_id")).isEqualTo(459); + assertThat(currRecord.containsKey("city")).isTrue(); + assertThat(currRecord.get("city")).isEqualTo("Santiago de Compostela"); + assertThat(currRecord.containsKey("country_id")).isTrue(); + assertThat(currRecord.get("country_id")).isEqualTo(87); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2006-02-15 09:45:25.0"); + + // edges checks + it = data.getEdges().iterator(); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_country"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("4_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("5_87"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("41_587"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_country"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("4_146"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("5_87"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("4146_587"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_country"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("4_181"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("5_87"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("4181_587"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_country"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("4_388"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("5_87"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("4388_587"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_country"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("4_459"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("5_87"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("4459_587"); + } + + @Override + @Test + public void expandMultiple1ToNRelWithSimpleFKTest() { + // 1-N Relationship: rental -[has_customer]-> customer + + String[] rootIds = {"13_1"}; + GraphData data = provider.expand(dataSource, rootIds, "out", "has_customer", 300); + + assertThat(data.getNodesClasses().size()).isEqualTo(1); + assertThat(data.getNodes().size()).isEqualTo(1); + assertThat(data.getEdgesClasses().size()).isEqualTo(1); + assertThat(data.getEdges().size()).isEqualTo(1); + + // Node classes checks + assertThat(data.getNodesClasses().containsKey("customer")).isTrue(); + + Map customerClass = data.getNodesClasses().get("customer"); + assertThat(customerClass.containsKey("customer_id")).isTrue(); + assertThat(customerClass.containsKey("store_id")).isTrue(); + assertThat(customerClass.containsKey("first_name")).isTrue(); + assertThat(customerClass.containsKey("last_name")).isTrue(); + assertThat(customerClass.containsKey("email")).isTrue(); + assertThat(customerClass.containsKey("address_id")).isTrue(); + assertThat(customerClass.containsKey("create_date")).isTrue(); + assertThat(customerClass.containsKey("last_update")).isTrue(); + assertThat(customerClass.containsKey("active")).isTrue(); + + // nodes checks + Iterator it = data.getNodes().iterator(); + CytoData currNodeContent; + Map currRecord; + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("customer_id")).isTrue(); + assertThat(currRecord.get("customer_id")).isEqualTo(130); + assertThat(currRecord.containsKey("store_id")).isTrue(); + assertThat(currRecord.get("store_id")).isEqualTo(1); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("Charlotte"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("Hunter"); + assertThat(currRecord.containsKey("email")).isTrue(); + assertThat(currRecord.get("email")).isEqualTo("charlotte.hunter@sakilacustomer.org"); + assertThat(currRecord.containsKey("address_id")).isTrue(); + assertThat(currRecord.get("address_id")).isEqualTo(134); + assertThat(currRecord.containsKey("activebool")).isTrue(); + assertThat(currRecord.get("activebool")).isEqualTo(true); + assertThat(currRecord.containsKey("create_date")).isTrue(); + assertThat(currRecord.get("create_date").toString()).isEqualTo("2006-02-14"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2013-05-26 14:49:45.738"); + assertThat(currRecord.containsKey("active")).isTrue(); + assertThat(currRecord.get("active")).isEqualTo(1); + + // edges checks + it = data.getEdges().iterator(); + CytoData currEdgeContent; + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + + assertThat(currEdgeContent.getClasses()).isEqualTo("has_customer"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("13_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("6_130"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("131_6130"); + + // 1-N Relationship: customer <-[has_customer]- rental + + rootIds[0] = "6_130"; + data = provider.expand(dataSource, rootIds, "in", "has_customer", 300); + + assertThat(data.getNodesClasses().size()).isEqualTo(2); + assertThat(data.getNodes().size()).isEqualTo(46); + assertThat(data.getEdgesClasses().size()).isEqualTo(1); + assertThat(data.getEdges().size()).isEqualTo(46); + + // Node classes checks + assertThat(data.getNodesClasses().containsKey("rental")).isTrue(); + assertThat(data.getNodesClasses().containsKey("payment")) + .isTrue(); // has_customer represents also the relationship: Payment -> Customer + + // nodes checks + Set rentalNodes = + data.getNodes().stream() + .filter(rentalNode -> rentalNode.getClasses().equals("rental")) + .collect(Collectors.toSet()); + Set paymentNodes = + data.getNodes().stream() + .filter(rentalNode -> rentalNode.getClasses().equals("payment")) + .collect(Collectors.toSet()); - @Override - @Test - public void loadVerticesFromIdsMultipleTablesTest() { - /* - * Fetching the first 5 vertices from the actor table and the first 2 vertices from the store table by cyto-ids - * cyto-id from is x_y where: - * - x is refers to the source table (actor is the first table in the source db schema) - * - y is the external key, then the pk value of the source record - */ - - String[] ids = { "1_1", "1_2", "1_3", "1_4", "1_5", "15_1", "15_2" }; - - GraphData data = provider.load(dataSource, ids); - - assertEquals(data.getNodesClasses().size(), 2); - assertEquals(data.getNodes().size(), 7); - assertEquals(data.getEdgesClasses().size(), 0); - assertEquals(data.getEdges().size(), 0); - - // Node classes checks - assertTrue(data.getNodesClasses().containsKey("actor")); - assertTrue(data.getNodesClasses().containsKey("store")); - - Map actorClass = data.getNodesClasses().get("actor"); - assertTrue(actorClass.containsKey("actor_id")); - assertTrue(actorClass.containsKey("first_name")); - assertTrue(actorClass.containsKey("last_name")); - assertTrue(actorClass.containsKey("last_update")); - Map storeClass = data.getNodesClasses().get("store"); - assertTrue(storeClass.containsKey("store_id")); - assertTrue(storeClass.containsKey("manager_staff_id")); - assertTrue(storeClass.containsKey("address_id")); - assertTrue(storeClass.containsKey("last_update")); - - // nodes checks - Iterator it = data.getNodes().iterator(); - CytoData currNodeContent; - Map currRecord; - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 1); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "Penelope"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "Guiness"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 2); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "Nick"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "Wahlberg"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 3); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "Ed"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "Chase"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 4); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "Jennifer"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "Davis"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 5); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "Johnny"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "Lollobrigida"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("store_id")); - assertEquals(currRecord.get("store_id"), 1); - assertTrue(currRecord.containsKey("manager_staff_id")); - assertEquals(currRecord.get("manager_staff_id"), 1); - assertTrue(currRecord.containsKey("address_id")); - assertEquals(currRecord.get("address_id"), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2006-02-15 09:57:12.0"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("store_id")); - assertEquals(currRecord.get("store_id"), 2); - assertTrue(currRecord.containsKey("manager_staff_id")); - assertEquals(currRecord.get("manager_staff_id"), 2); - assertTrue(currRecord.containsKey("address_id")); - assertEquals(currRecord.get("address_id"), 2); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2006-02-15 09:57:12.0"); - } + assertThat(rentalNodes.size()).isEqualTo(24); + assertThat(paymentNodes.size()).isEqualTo(22); + } - @Override - @Test - public void loadVerticesFromIdsSingleTableTest() { - /* - * Fetching the first 5 vertices from the actor table by cyto-ids - * cyto-id from is x_y where: - * - x is refers to the source table (actor is the first table in the source db schema) - * - y is the external key, then the pk value of the source record - */ - - String[] actorIds = { "1_1", "1_2", "1_3", "1_4", "1_5" }; - - GraphData data = provider.load(dataSource, actorIds); - - assertEquals(data.getNodesClasses().size(), 1); - assertEquals(data.getNodes().size(), 5); - assertEquals(data.getEdgesClasses().size(), 0); - assertEquals(data.getEdges().size(), 0); - - // Node classes checks - assertTrue(data.getNodesClasses().containsKey("actor")); - - Map actorClass = data.getNodesClasses().get("actor"); - assertTrue(actorClass.containsKey("actor_id")); - assertTrue(actorClass.containsKey("first_name")); - assertTrue(actorClass.containsKey("last_name")); - assertTrue(actorClass.containsKey("last_update")); - - // nodes checks - Iterator it = data.getNodes().iterator(); - CytoData currNodeContent; - Map currRecord; - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 1); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "Penelope"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "Guiness"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 2); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "Nick"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "Wahlberg"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 3); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "Ed"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "Chase"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 4); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "Jennifer"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "Davis"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 5); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "Johnny"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "Lollobrigida"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); - - /* - * Fetching 2 vertices from the store table by cyto-ids - * cyto-id from is x_y where: - * - x is refers to the source table (actor is the first table in the source db schema) - * - y is the external key, then the pk value of the source record - */ - - String[] storeIds = { "15_1", "15_2" }; - data = provider.load(dataSource, storeIds); - - assertEquals(data.getNodesClasses().size(), 1); - assertEquals(data.getNodes().size(), 2); - assertEquals(data.getEdgesClasses().size(), 0); - assertEquals(data.getEdges().size(), 0); - - // Node classes checks - assertTrue(data.getNodesClasses().containsKey("store")); - - Map storeClass = data.getNodesClasses().get("store"); - assertTrue(storeClass.containsKey("store_id")); - assertTrue(storeClass.containsKey("manager_staff_id")); - assertTrue(storeClass.containsKey("address_id")); - assertTrue(storeClass.containsKey("last_update")); - - // nodes checks - it = data.getNodes().iterator(); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("store_id")); - assertEquals(currRecord.get("store_id"), 1); - assertTrue(currRecord.containsKey("manager_staff_id")); - assertEquals(currRecord.get("manager_staff_id"), 1); - assertTrue(currRecord.containsKey("address_id")); - assertEquals(currRecord.get("address_id"), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2006-02-15 09:57:12.0"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("store_id")); - assertEquals(currRecord.get("store_id"), 2); - assertTrue(currRecord.containsKey("manager_staff_id")); - assertEquals(currRecord.get("manager_staff_id"), 2); - assertTrue(currRecord.containsKey("address_id")); - assertEquals(currRecord.get("address_id"), 2); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2006-02-15 09:57:12.0"); - } + @Override + @Test + public void expand1ToNRelWithJoinTableAndSimpleFKTest() { + /** Get movies by actor */ - @Override - @Test - public void expand1To1RelWithSimpleFKTest() { - // 1-1 Relationship: distribution_country -[has_distribution_language]-> language - - // adding schema info - Connection connection = null; - Statement st = null; - - try { - connection = DriverManager.getConnection(PostgreSQLContainerHolder.container.getJdbcUrl(), "postgres", "postgres"); - - String distributioCountryTableBuilding = - "create table distribution_country (distribution_country_id integer not null," + - " name varchar(256) not null, distribution_language integer not null, primary key (distribution_country_id), " + - "foreign key (distribution_language) references language(language_id))"; - st = connection.createStatement(); - st.execute(distributioCountryTableBuilding); - - // populating the new table - String distributionCountryFilling = - "insert into distribution_country (distribution_country_id,name,distribution_language) values " + - "(1,'USA',1)," + - "(2,'Italy',2)," + - "(3,'Japan',3)," + - "(4,'China',4)," + - "(5,'France',5)," + - "(6,'Germany',6)"; - st.execute(distributionCountryFilling); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } finally { - try { - connection.close(); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } - } - - String[] rootIds = { "7_1", "7_2", "7_3", "7_4", "7_5", "7_6" }; - GraphData data = provider.expand(dataSource, rootIds, "out", "has_distribution_language", 300); - - assertEquals(data.getNodesClasses().size(), 1); - assertEquals(data.getNodes().size(), 6); - assertEquals(data.getEdgesClasses().size(), 1); - assertEquals(data.getEdges().size(), 6); - - // Node classes checks - assertTrue(data.getNodesClasses().containsKey("language")); - - Map languageClass = data.getNodesClasses().get("language"); - assertTrue(languageClass.containsKey("language_id")); - assertTrue(languageClass.containsKey("name")); - assertTrue(languageClass.containsKey("last_update")); - - // nodes checks - Iterator it = data.getNodes().iterator(); - CytoData currNodeContent; - Map currRecord; - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("language_id")); - assertEquals(currRecord.get("language_id"), 1); - assertTrue(currRecord.containsKey("name")); - assertEquals(((String) currRecord.get("name")).trim(), "English"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2006-02-15 10:02:19.0"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("language_id")); - assertEquals(currRecord.get("language_id"), 2); - assertTrue(currRecord.containsKey("name")); - assertEquals(((String) currRecord.get("name")).trim(), "Italian"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2006-02-15 10:02:19.0"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("language_id")); - assertEquals(currRecord.get("language_id"), 3); - assertTrue(currRecord.containsKey("name")); - assertEquals(((String) currRecord.get("name")).trim(), "Japanese"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2006-02-15 10:02:19.0"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("language_id")); - assertEquals(currRecord.get("language_id"), 4); - assertTrue(currRecord.containsKey("name")); - assertEquals(((String) currRecord.get("name")).trim(), "Mandarin"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2006-02-15 10:02:19.0"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("language_id")); - assertEquals(currRecord.get("language_id"), 5); - assertTrue(currRecord.containsKey("name")); - assertEquals(((String) currRecord.get("name")).trim(), "French"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2006-02-15 10:02:19.0"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("language_id")); - assertEquals(currRecord.get("language_id"), 6); - assertTrue(currRecord.containsKey("name")); - assertEquals(((String) currRecord.get("name")).trim(), "German"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2006-02-15 10:02:19.0"); - - // edges checks - it = data.getEdges().iterator(); - CytoData currEdgeContent; - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_distribution_language"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "7_1"); - assertEquals(currEdgeContent.getData().getTarget(), "12_1"); - assertEquals(currEdgeContent.getData().getId(), "71_121"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_distribution_language"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "7_2"); - assertEquals(currEdgeContent.getData().getTarget(), "12_2"); - assertEquals(currEdgeContent.getData().getId(), "72_122"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_distribution_language"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "7_3"); - assertEquals(currEdgeContent.getData().getTarget(), "12_3"); - assertEquals(currEdgeContent.getData().getId(), "73_123"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_distribution_language"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "7_4"); - assertEquals(currEdgeContent.getData().getTarget(), "12_4"); - assertEquals(currEdgeContent.getData().getId(), "74_124"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_distribution_language"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "7_5"); - assertEquals(currEdgeContent.getData().getTarget(), "12_5"); - assertEquals(currEdgeContent.getData().getId(), "75_125"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_distribution_language"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "7_6"); - assertEquals(currEdgeContent.getData().getTarget(), "12_6"); - assertEquals(currEdgeContent.getData().getId(), "76_126"); - - // 1-1 Relationship: language <-[has_distribution_language]- distribution_country - - rootIds[0] = "12_1"; - rootIds[1] = "12_2"; - rootIds[2] = "12_3"; - rootIds[3] = "12_4"; - rootIds[4] = "12_5"; - rootIds[5] = "12_6"; - data = provider.expand(dataSource, rootIds, "in", "has_distribution_language", 300); - - assertEquals(data.getNodesClasses().size(), 1); - assertEquals(data.getNodes().size(), 6); - assertEquals(data.getEdgesClasses().size(), 1); - assertEquals(data.getEdges().size(), 6); - - // Node classes checks - assertTrue(data.getNodesClasses().containsKey("distribution_country")); - - Map distributionCountryClass = data.getNodesClasses().get("distribution_country"); - assertTrue(distributionCountryClass.containsKey("distribution_country_id")); - assertTrue(distributionCountryClass.containsKey("name")); - assertTrue(distributionCountryClass.containsKey("distribution_language")); - - it = data.getNodes().iterator(); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("distribution_country_id")); - assertEquals(currRecord.get("distribution_country_id"), 1); - assertTrue(currRecord.containsKey("name")); - assertEquals(((String) currRecord.get("name")), "USA"); - assertTrue(currRecord.containsKey("distribution_language")); - assertEquals(currRecord.get("distribution_language"), 1); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("distribution_country_id")); - assertEquals(currRecord.get("distribution_country_id"), 2); - assertTrue(currRecord.containsKey("name")); - assertEquals(((String) currRecord.get("name")), "Italy"); - assertTrue(currRecord.containsKey("distribution_language")); - assertEquals(currRecord.get("distribution_language"), 2); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("distribution_country_id")); - assertEquals(currRecord.get("distribution_country_id"), 3); - assertTrue(currRecord.containsKey("name")); - assertEquals(((String) currRecord.get("name")), "Japan"); - assertTrue(currRecord.containsKey("distribution_language")); - assertEquals(currRecord.get("distribution_language"), 3); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("distribution_country_id")); - assertEquals(currRecord.get("distribution_country_id"), 4); - assertTrue(currRecord.containsKey("name")); - assertEquals(((String) currRecord.get("name")), "China"); - assertTrue(currRecord.containsKey("distribution_language")); - assertEquals(currRecord.get("distribution_language"), 4); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("distribution_country_id")); - assertEquals(currRecord.get("distribution_country_id"), 5); - assertTrue(currRecord.containsKey("name")); - assertEquals(((String) currRecord.get("name")), "France"); - assertTrue(currRecord.containsKey("distribution_language")); - assertEquals(currRecord.get("distribution_language"), 5); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("distribution_country_id")); - assertEquals(currRecord.get("distribution_country_id"), 6); - assertTrue(currRecord.containsKey("name")); - assertEquals(((String) currRecord.get("name")), "Germany"); - assertTrue(currRecord.containsKey("distribution_language")); - assertEquals(currRecord.get("distribution_language"), 6); - - // edges checks - it = data.getEdges().iterator(); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_distribution_language"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "7_1"); - assertEquals(currEdgeContent.getData().getTarget(), "12_1"); - assertEquals(currEdgeContent.getData().getId(), "71_121"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_distribution_language"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "7_2"); - assertEquals(currEdgeContent.getData().getTarget(), "12_2"); - assertEquals(currEdgeContent.getData().getId(), "72_122"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_distribution_language"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "7_3"); - assertEquals(currEdgeContent.getData().getTarget(), "12_3"); - assertEquals(currEdgeContent.getData().getId(), "73_123"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_distribution_language"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "7_4"); - assertEquals(currEdgeContent.getData().getTarget(), "12_4"); - assertEquals(currEdgeContent.getData().getId(), "74_124"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_distribution_language"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "7_5"); - assertEquals(currEdgeContent.getData().getTarget(), "12_5"); - assertEquals(currEdgeContent.getData().getId(), "75_125"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_distribution_language"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "7_6"); - assertEquals(currEdgeContent.getData().getTarget(), "12_6"); - assertEquals(currEdgeContent.getData().getId(), "76_126"); - - // dropping the new added table - try { - connection = DriverManager.getConnection(PostgreSQLContainerHolder.container.getJdbcUrl(), "postgres", "postgres"); - - String deleteDistributionCountryTable = "drop table distribution_country"; - st = connection.createStatement(); - st.execute(deleteDistributionCountryTable); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } finally { - try { - connection.close(); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } - } - } + // expanding 1-N relationship: actor <-[has_actor]- film_actor + String[] rootIds = {"1_1"}; + GraphData data = provider.expand(dataSource, rootIds, "in", "has_actor", 300); - @Override - @Test - public void expand1ToNRelWithSimpleFKTest() { - // 1-N Relationship: city -[has_country]-> country - - String[] rootIds = { "4_1" }; - GraphData data = provider.expand(dataSource, rootIds, "out", "has_country", 300); - - assertEquals(data.getNodesClasses().size(), 1); - assertEquals(data.getNodes().size(), 1); - assertEquals(data.getEdgesClasses().size(), 1); - assertEquals(data.getEdges().size(), 1); - - // Node classes checks - assertTrue(data.getNodesClasses().containsKey("country")); - - Map customerClass = data.getNodesClasses().get("country"); - assertTrue(customerClass.containsKey("country_id")); - assertTrue(customerClass.containsKey("country")); - assertTrue(customerClass.containsKey("last_update")); - - // nodes checks - Iterator it = data.getNodes().iterator(); - CytoData currNodeContent; - Map currRecord; - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("country_id")); - assertEquals(currRecord.get("country_id"), 87); - assertTrue(currRecord.containsKey("country")); - assertEquals(currRecord.get("country"), "Spain"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2006-02-15 09:44:00.0"); - - // edges checks - it = data.getEdges().iterator(); - CytoData currEdgeContent; - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - - assertEquals(currEdgeContent.getClasses(), "has_country"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "4_1"); - assertEquals(currEdgeContent.getData().getTarget(), "5_87"); - assertEquals(currEdgeContent.getData().getId(), "41_587"); - - // 1-N Relationship: city <-[has_country]- country - - rootIds[0] = "5_87"; - data = provider.expand(dataSource, rootIds, "in", "has_country", 300); - - assertEquals(data.getNodesClasses().size(), 1); - assertEquals(data.getNodes().size(), 5); - assertEquals(data.getEdgesClasses().size(), 1); - assertEquals(data.getEdges().size(), 5); - - // nodes checks - it = data.getNodes().iterator(); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("city_id")); - assertEquals(currRecord.get("city_id"), 1); - assertTrue(currRecord.containsKey("city")); - assertEquals(currRecord.get("city"), "A Corua (La Corua)"); - assertTrue(currRecord.containsKey("country_id")); - assertEquals(currRecord.get("country_id"), 87); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2006-02-15 09:45:25.0"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("city_id")); - assertEquals(currRecord.get("city_id"), 146); - assertTrue(currRecord.containsKey("city")); - assertEquals(currRecord.get("city"), "Donostia-San Sebastin"); - assertTrue(currRecord.containsKey("country_id")); - assertEquals(currRecord.get("country_id"), 87); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2006-02-15 09:45:25.0"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("city_id")); - assertEquals(currRecord.get("city_id"), 181); - assertTrue(currRecord.containsKey("city")); - assertEquals(currRecord.get("city"), "Gijn"); - assertTrue(currRecord.containsKey("country_id")); - assertEquals(currRecord.get("country_id"), 87); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2006-02-15 09:45:25.0"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("city_id")); - assertEquals(currRecord.get("city_id"), 388); - assertTrue(currRecord.containsKey("city")); - assertEquals(currRecord.get("city"), "Ourense (Orense)"); - assertTrue(currRecord.containsKey("country_id")); - assertEquals(currRecord.get("country_id"), 87); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2006-02-15 09:45:25.0"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("city_id")); - assertEquals(currRecord.get("city_id"), 459); - assertTrue(currRecord.containsKey("city")); - assertEquals(currRecord.get("city"), "Santiago de Compostela"); - assertTrue(currRecord.containsKey("country_id")); - assertEquals(currRecord.get("country_id"), 87); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2006-02-15 09:45:25.0"); - - // edges checks - it = data.getEdges().iterator(); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_country"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "4_1"); - assertEquals(currEdgeContent.getData().getTarget(), "5_87"); - assertEquals(currEdgeContent.getData().getId(), "41_587"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_country"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "4_146"); - assertEquals(currEdgeContent.getData().getTarget(), "5_87"); - assertEquals(currEdgeContent.getData().getId(), "4146_587"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_country"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "4_181"); - assertEquals(currEdgeContent.getData().getTarget(), "5_87"); - assertEquals(currEdgeContent.getData().getId(), "4181_587"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_country"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "4_388"); - assertEquals(currEdgeContent.getData().getTarget(), "5_87"); - assertEquals(currEdgeContent.getData().getId(), "4388_587"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_country"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "4_459"); - assertEquals(currEdgeContent.getData().getTarget(), "5_87"); - assertEquals(currEdgeContent.getData().getId(), "4459_587"); - } + assertThat(data.getNodesClasses().size()).isEqualTo(1); + assertThat(data.getNodes().size()).isEqualTo(19); + assertThat(data.getEdgesClasses().size()).isEqualTo(1); + assertThat(data.getEdges().size()).isEqualTo(19); - @Override - @Test - public void expandMultiple1ToNRelWithSimpleFKTest() { - // 1-N Relationship: rental -[has_customer]-> customer - - String[] rootIds = { "13_1" }; - GraphData data = provider.expand(dataSource, rootIds, "out", "has_customer", 300); - - assertEquals(data.getNodesClasses().size(), 1); - assertEquals(data.getNodes().size(), 1); - assertEquals(data.getEdgesClasses().size(), 1); - assertEquals(data.getEdges().size(), 1); - - // Node classes checks - assertTrue(data.getNodesClasses().containsKey("customer")); - - Map customerClass = data.getNodesClasses().get("customer"); - assertTrue(customerClass.containsKey("customer_id")); - assertTrue(customerClass.containsKey("store_id")); - assertTrue(customerClass.containsKey("first_name")); - assertTrue(customerClass.containsKey("last_name")); - assertTrue(customerClass.containsKey("email")); - assertTrue(customerClass.containsKey("address_id")); - assertTrue(customerClass.containsKey("create_date")); - assertTrue(customerClass.containsKey("last_update")); - assertTrue(customerClass.containsKey("active")); - - // nodes checks - Iterator it = data.getNodes().iterator(); - CytoData currNodeContent; - Map currRecord; - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("customer_id")); - assertEquals(currRecord.get("customer_id"), 130); - assertTrue(currRecord.containsKey("store_id")); - assertEquals(currRecord.get("store_id"), 1); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "Charlotte"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "Hunter"); - assertTrue(currRecord.containsKey("email")); - assertEquals(currRecord.get("email"), "charlotte.hunter@sakilacustomer.org"); - assertTrue(currRecord.containsKey("address_id")); - assertEquals(currRecord.get("address_id"), 134); - assertTrue(currRecord.containsKey("activebool")); - assertEquals(currRecord.get("activebool"), true); - assertTrue(currRecord.containsKey("create_date")); - assertEquals(currRecord.get("create_date").toString(), "2006-02-14"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:49:45.738"); - assertTrue(currRecord.containsKey("active")); - assertEquals(currRecord.get("active"), 1); - - // edges checks - it = data.getEdges().iterator(); - CytoData currEdgeContent; - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - - assertEquals(currEdgeContent.getClasses(), "has_customer"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "13_1"); - assertEquals(currEdgeContent.getData().getTarget(), "6_130"); - assertEquals(currEdgeContent.getData().getId(), "131_6130"); - - // 1-N Relationship: customer <-[has_customer]- rental - - rootIds[0] = "6_130"; - data = provider.expand(dataSource, rootIds, "in", "has_customer", 300); - - assertEquals(data.getNodesClasses().size(), 2); - assertEquals(data.getNodes().size(), 46); - assertEquals(data.getEdgesClasses().size(), 1); - assertEquals(data.getEdges().size(), 46); - - // Node classes checks - assertTrue(data.getNodesClasses().containsKey("rental")); - assertTrue(data.getNodesClasses().containsKey("payment")); // has_customer represents also the relationship: Payment -> Customer - - // nodes checks - Set rentalNodes = data.getNodes().stream().filter(rentalNode -> rentalNode.getClasses().equals("rental")).collect(Collectors.toSet()); - Set paymentNodes = data.getNodes().stream().filter(rentalNode -> rentalNode.getClasses().equals("payment")).collect(Collectors.toSet()); - - assertEquals(rentalNodes.size(), 24); - assertEquals(paymentNodes.size(), 22); + // Node classes checks + assertThat(data.getNodesClasses().containsKey("film_actor")).isTrue(); + + Map filmActorClass = data.getNodesClasses().get("film_actor"); + assertThat(filmActorClass.containsKey("last_update")).isTrue(); + + String[] joinRecordRoots = new String[19]; + int i = 0; + for (CytoData currentData : data.getNodes()) { + joinRecordRoots[i] = "8_1_" + currentData.getData().getRecord().get("film_id").toString(); + i++; } - @Override - @Test - public void expand1ToNRelWithJoinTableAndSimpleFKTest() { - /** - * Get movies by actor - */ - - // expanding 1-N relationship: actor <-[has_actor]- film_actor - String[] rootIds = { "1_1" }; - GraphData data = provider.expand(dataSource, rootIds, "in", "has_actor", 300); - - assertEquals(data.getNodesClasses().size(), 1); - assertEquals(data.getNodes().size(), 19); - assertEquals(data.getEdgesClasses().size(), 1); - assertEquals(data.getEdges().size(), 19); - - // Node classes checks - assertTrue(data.getNodesClasses().containsKey("film_actor")); - - Map filmActorClass = data.getNodesClasses().get("film_actor"); - assertTrue(filmActorClass.containsKey("last_update")); - - String[] joinRecordRoots = new String[19]; - int i = 0; - for (CytoData currentData : data.getNodes()) { - joinRecordRoots[i] = "8_1_" + currentData.getData().getRecord().get("film_id").toString(); - i++; - } - - // expanding 1-N relationship: film_actor -[has_film] -> film - - data = provider.expand(dataSource, joinRecordRoots, "out", "has_film", 300); - - assertEquals(data.getNodesClasses().size(), 1); - assertEquals(data.getNodes().size(), 19); - assertEquals(data.getEdgesClasses().size(), 1); - assertEquals(data.getEdges().size(), 19); - - // Node classes checks - assertTrue(data.getNodesClasses().containsKey("film")); - - Map filmClass = data.getNodesClasses().get("film"); - assertTrue(filmClass.containsKey("film_id")); - assertTrue(filmClass.containsKey("title")); - assertTrue(filmClass.containsKey("description")); - assertTrue(filmClass.containsKey("release_year")); - assertTrue(filmClass.containsKey("language_id")); - assertTrue(filmClass.containsKey("rental_duration")); - assertTrue(filmClass.containsKey("rental_rate")); - assertTrue(filmClass.containsKey("length")); - assertTrue(filmClass.containsKey("replacement_cost")); - assertTrue(filmClass.containsKey("rating")); - assertTrue(filmClass.containsKey("last_update")); - assertTrue(filmClass.containsKey("special_features")); - assertTrue(filmClass.containsKey("fulltext")); - - // nodes checks - Iterator it = data.getNodes().iterator(); - CytoData currNodeContent; - Map currRecord; - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 1); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Academy Dinosaur"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 23); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Anaconda Confessions"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 25); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Angels Life"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 106); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Bulworth Commandments"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 140); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Cheaper Clyde"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 166); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Color Philadelphia"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 277); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Elephant Trojan"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 361); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Gleaming Jawbreaker"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 438); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Human Graffiti"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 499); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "King Evolution"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 506); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Lady Stage"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 509); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Language Cowboy"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 605); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Mulholland Beast"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 635); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Oklahoma Jumanji"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 749); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Rules Human"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 832); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Splash Gump"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 939); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Vertigo Northwest"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 970); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Westward Seabiscuit"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 980); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Wizard Coldblooded"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - // edges checks - it = data.getEdges().iterator(); - CytoData currEdgeContent; - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_1"); - assertEquals(currEdgeContent.getData().getId(), "811_71"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_23"); - assertEquals(currEdgeContent.getData().getTarget(), "7_23"); - assertEquals(currEdgeContent.getData().getId(), "8123_723"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_25"); - assertEquals(currEdgeContent.getData().getTarget(), "7_25"); - assertEquals(currEdgeContent.getData().getId(), "8125_725"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_106"); - assertEquals(currEdgeContent.getData().getTarget(), "7_106"); - assertEquals(currEdgeContent.getData().getId(), "81106_7106"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_140"); - assertEquals(currEdgeContent.getData().getTarget(), "7_140"); - assertEquals(currEdgeContent.getData().getId(), "81140_7140"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_166"); - assertEquals(currEdgeContent.getData().getTarget(), "7_166"); - assertEquals(currEdgeContent.getData().getId(), "81166_7166"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_277"); - assertEquals(currEdgeContent.getData().getTarget(), "7_277"); - assertEquals(currEdgeContent.getData().getId(), "81277_7277"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_361"); - assertEquals(currEdgeContent.getData().getTarget(), "7_361"); - assertEquals(currEdgeContent.getData().getId(), "81361_7361"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_438"); - assertEquals(currEdgeContent.getData().getTarget(), "7_438"); - assertEquals(currEdgeContent.getData().getId(), "81438_7438"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_499"); - assertEquals(currEdgeContent.getData().getTarget(), "7_499"); - assertEquals(currEdgeContent.getData().getId(), "81499_7499"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_506"); - assertEquals(currEdgeContent.getData().getTarget(), "7_506"); - assertEquals(currEdgeContent.getData().getId(), "81506_7506"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_509"); - assertEquals(currEdgeContent.getData().getTarget(), "7_509"); - assertEquals(currEdgeContent.getData().getId(), "81509_7509"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_605"); - assertEquals(currEdgeContent.getData().getTarget(), "7_605"); - assertEquals(currEdgeContent.getData().getId(), "81605_7605"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_635"); - assertEquals(currEdgeContent.getData().getTarget(), "7_635"); - assertEquals(currEdgeContent.getData().getId(), "81635_7635"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_749"); - assertEquals(currEdgeContent.getData().getTarget(), "7_749"); - assertEquals(currEdgeContent.getData().getId(), "81749_7749"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_832"); - assertEquals(currEdgeContent.getData().getTarget(), "7_832"); - assertEquals(currEdgeContent.getData().getId(), "81832_7832"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_939"); - assertEquals(currEdgeContent.getData().getTarget(), "7_939"); - assertEquals(currEdgeContent.getData().getId(), "81939_7939"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_970"); - assertEquals(currEdgeContent.getData().getTarget(), "7_970"); - assertEquals(currEdgeContent.getData().getId(), "81970_7970"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_film"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_1_980"); - assertEquals(currEdgeContent.getData().getTarget(), "7_980"); - assertEquals(currEdgeContent.getData().getId(), "81980_7980"); - - /** - * Get actors by movie - */ - - // expanding 1-N relationship: film <-[has_film]- film_actor - - rootIds[0] = "7_2"; - data = provider.expand(dataSource, rootIds, "in", "has_film", 300); - - assertEquals(data.getNodesClasses().size(), 3); - assertEquals(data.getNodes().size(), 8); - assertEquals(data.getEdgesClasses().size(), 1); - assertEquals(data.getEdges().size(), 8); - - // Node classes checks - assertTrue(data.getNodesClasses().containsKey("film_actor")); - assertTrue(data.getNodesClasses().containsKey("film_category")); // has_film represents also the relationship: film_category -> film - assertTrue(data.getNodesClasses().containsKey("inventory")); // has_film represents also the relationship: inventory -> film - - filmActorClass = data.getNodesClasses().get("film_actor"); - assertTrue(filmActorClass.containsKey("last_update")); - filmActorClass = data.getNodesClasses().get("film_category"); - assertTrue(filmActorClass.containsKey("last_update")); - filmActorClass = data.getNodesClasses().get("inventory"); - assertTrue(filmActorClass.containsKey("inventory_id")); - assertTrue(filmActorClass.containsKey("film_id")); - assertTrue(filmActorClass.containsKey("store_id")); - assertTrue(filmActorClass.containsKey("last_update")); - - Set filmActorNodes = data - .getNodes() - .stream() + // expanding 1-N relationship: film_actor -[has_film] -> film + + data = provider.expand(dataSource, joinRecordRoots, "out", "has_film", 300); + + assertThat(data.getNodesClasses().size()).isEqualTo(1); + assertThat(data.getNodes().size()).isEqualTo(19); + assertThat(data.getEdgesClasses().size()).isEqualTo(1); + assertThat(data.getEdges().size()).isEqualTo(19); + + // Node classes checks + assertThat(data.getNodesClasses().containsKey("film")).isTrue(); + + Map filmClass = data.getNodesClasses().get("film"); + assertThat(filmClass.containsKey("film_id")).isTrue(); + assertThat(filmClass.containsKey("title")).isTrue(); + assertThat(filmClass.containsKey("description")).isTrue(); + assertThat(filmClass.containsKey("release_year")).isTrue(); + assertThat(filmClass.containsKey("language_id")).isTrue(); + assertThat(filmClass.containsKey("rental_duration")).isTrue(); + assertThat(filmClass.containsKey("rental_rate")).isTrue(); + assertThat(filmClass.containsKey("length")).isTrue(); + assertThat(filmClass.containsKey("replacement_cost")).isTrue(); + assertThat(filmClass.containsKey("rating")).isTrue(); + assertThat(filmClass.containsKey("last_update")).isTrue(); + assertThat(filmClass.containsKey("special_features")).isTrue(); + assertThat(filmClass.containsKey("fulltext")).isTrue(); + + // nodes checks + Iterator it = data.getNodes().iterator(); + CytoData currNodeContent; + Map currRecord; + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(1); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Academy Dinosaur"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(23); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Anaconda Confessions"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(25); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Angels Life"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(106); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Bulworth Commandments"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(140); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Cheaper Clyde"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(166); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Color Philadelphia"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(277); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Elephant Trojan"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(361); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Gleaming Jawbreaker"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(438); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Human Graffiti"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(499); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("King Evolution"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(506); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Lady Stage"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(509); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Language Cowboy"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(605); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Mulholland Beast"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(635); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Oklahoma Jumanji"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(749); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Rules Human"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(832); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Splash Gump"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(939); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Vertigo Northwest"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(970); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Westward Seabiscuit"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(980); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Wizard Coldblooded"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + // edges checks + it = data.getEdges().iterator(); + CytoData currEdgeContent; + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_1"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("811_71"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_23"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_23"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8123_723"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_25"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_25"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8125_725"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_106"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_106"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81106_7106"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_140"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_140"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81140_7140"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_166"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_166"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81166_7166"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_277"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_277"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81277_7277"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_361"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_361"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81361_7361"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_438"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_438"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81438_7438"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_499"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_499"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81499_7499"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_506"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_506"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81506_7506"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_509"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_509"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81509_7509"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_605"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_605"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81605_7605"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_635"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_635"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81635_7635"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_749"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_749"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81749_7749"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_832"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_832"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81832_7832"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_939"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_939"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81939_7939"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_970"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_970"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81970_7970"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_film"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_1_980"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_980"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81980_7980"); + + /** Get actors by movie */ + + // expanding 1-N relationship: film <-[has_film]- film_actor + + rootIds[0] = "7_2"; + data = provider.expand(dataSource, rootIds, "in", "has_film", 300); + + assertThat(data.getNodesClasses().size()).isEqualTo(3); + assertThat(data.getNodes().size()).isEqualTo(8); + assertThat(data.getEdgesClasses().size()).isEqualTo(1); + assertThat(data.getEdges().size()).isEqualTo(8); + + // Node classes checks + assertThat(data.getNodesClasses().containsKey("film_actor")).isTrue(); + assertThat(data.getNodesClasses().containsKey("film_category")) + .isTrue(); // has_film represents also the relationship: film_category -> film + assertThat(data.getNodesClasses().containsKey("inventory")) + .isTrue(); // has_film represents also the relationship: inventory -> film + + filmActorClass = data.getNodesClasses().get("film_actor"); + assertThat(filmActorClass.containsKey("last_update")).isTrue(); + filmActorClass = data.getNodesClasses().get("film_category"); + assertThat(filmActorClass.containsKey("last_update")).isTrue(); + filmActorClass = data.getNodesClasses().get("inventory"); + assertThat(filmActorClass.containsKey("inventory_id")).isTrue(); + assertThat(filmActorClass.containsKey("film_id")).isTrue(); + assertThat(filmActorClass.containsKey("store_id")).isTrue(); + assertThat(filmActorClass.containsKey("last_update")).isTrue(); + + Set filmActorNodes = + data.getNodes().stream() .filter(filmActorNode -> filmActorNode.getClasses().equals("film_actor")) .collect(Collectors.toSet()); - Set filmCategoryNodes = data - .getNodes() - .stream() + Set filmCategoryNodes = + data.getNodes().stream() .filter(filmCategoryNode -> filmCategoryNode.getClasses().equals("film_category")) .collect(Collectors.toSet()); - Set inventoryNodes = data - .getNodes() - .stream() + Set inventoryNodes = + data.getNodes().stream() .filter(inventoryNode -> inventoryNode.getClasses().equals("inventory")) .collect(Collectors.toSet()); - assertEquals(filmActorNodes.size(), 4); - assertEquals(filmCategoryNodes.size(), 1); - assertEquals(inventoryNodes.size(), 3); - - joinRecordRoots = new String[4]; - i = 0; - for (CytoData currentData : filmActorNodes) { - joinRecordRoots[i] = "8_" + currentData.getData().getRecord().get("actor_id").toString() + "_2"; - i++; - } - - // expanding 1-N relationship: film_actor -[has_actor]-> actor - - data = provider.expand(dataSource, joinRecordRoots, "out", "has_actor", 300); - - assertEquals(data.getNodesClasses().size(), 1); - assertEquals(data.getNodes().size(), 4); - assertEquals(data.getEdgesClasses().size(), 1); - assertEquals(data.getEdges().size(), 4); - - // Node classes checks - assertTrue(data.getNodesClasses().containsKey("actor")); - - Map actorClass = data.getNodesClasses().get("actor"); - assertTrue(actorClass.containsKey("actor_id")); - assertTrue(actorClass.containsKey("first_name")); - assertTrue(actorClass.containsKey("last_name")); - assertTrue(actorClass.containsKey("last_update")); - - // nodes checks - it = data.getNodes().iterator(); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 19); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "Bob"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "Fawcett"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 85); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "Minnie"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "Zellweger"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 90); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "Sean"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "Guiness"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 160); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "Chris"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "Depp"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); - - // edges checks - it = data.getEdges().iterator(); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_19_2"); - assertEquals(currEdgeContent.getData().getTarget(), "1_19"); - assertEquals(currEdgeContent.getData().getId(), "8192_119"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_85_2"); - assertEquals(currEdgeContent.getData().getTarget(), "1_85"); - assertEquals(currEdgeContent.getData().getId(), "8852_185"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_90_2"); - assertEquals(currEdgeContent.getData().getTarget(), "1_90"); - assertEquals(currEdgeContent.getData().getId(), "8902_190"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 0); - assertEquals(currEdgeContent.getClasses(), "has_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "8_160_2"); - assertEquals(currEdgeContent.getData().getTarget(), "1_160"); - assertEquals(currEdgeContent.getData().getId(), "81602_1160"); - } + assertThat(filmActorNodes.size()).isEqualTo(4); + assertThat(filmCategoryNodes.size()).isEqualTo(1); + assertThat(inventoryNodes.size()).isEqualTo(3); - @Override - @Test - public void expand1To1RelWithCompositeFKTest() {} - - @Override - @Test - public void expand1ToNRelWithCompositeFKTest() {} + joinRecordRoots = new String[4]; + i = 0; + for (CytoData currentData : filmActorNodes) { + joinRecordRoots[i] = + "8_" + currentData.getData().getRecord().get("actor_id").toString() + "_2"; + i++; + } - @Override - @Test - public void expand1ToNRelWithJoinTableAndCompositeFKTest() {} + // expanding 1-N relationship: film_actor -[has_actor]-> actor + + data = provider.expand(dataSource, joinRecordRoots, "out", "has_actor", 300); + + assertThat(data.getNodesClasses().size()).isEqualTo(1); + assertThat(data.getNodes().size()).isEqualTo(4); + assertThat(data.getEdgesClasses().size()).isEqualTo(1); + assertThat(data.getEdges().size()).isEqualTo(4); + + // Node classes checks + assertThat(data.getNodesClasses().containsKey("actor")).isTrue(); + + Map actorClass = data.getNodesClasses().get("actor"); + assertThat(actorClass.containsKey("actor_id")).isTrue(); + assertThat(actorClass.containsKey("first_name")).isTrue(); + assertThat(actorClass.containsKey("last_name")).isTrue(); + assertThat(actorClass.containsKey("last_update")).isTrue(); + + // nodes checks + it = data.getNodes().iterator(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(19); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("Bob"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("Fawcett"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2013-05-26 14:47:57.62"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(85); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("Minnie"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("Zellweger"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2013-05-26 14:47:57.62"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(90); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("Sean"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("Guiness"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2013-05-26 14:47:57.62"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(160); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("Chris"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("Depp"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2013-05-26 14:47:57.62"); + + // edges checks + it = data.getEdges().iterator(); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_19_2"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("1_19"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8192_119"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_85_2"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("1_85"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8852_185"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_90_2"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("1_90"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8902_190"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(0); + assertThat(currEdgeContent.getClasses()).isEqualTo("has_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("8_160_2"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("1_160"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("81602_1160"); + } + + @Override + @Test + public void expand1To1RelWithCompositeFKTest() {} + + @Override + @Test + public void expand1ToNRelWithCompositeFKTest() {} + + @Override + @Test + public void expand1ToNRelWithJoinTableAndCompositeFKTest() {} } diff --git a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/PostgreSQLDataProviderWithAggregationTest.java b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/PostgreSQLDataProviderWithAggregationTest.java index d41fa77b..f9125c28 100644 --- a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/PostgreSQLDataProviderWithAggregationTest.java +++ b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/dataprovider/PostgreSQLDataProviderWithAggregationTest.java @@ -20,10 +20,8 @@ * #L% */ -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import com.arcadeanalytics.provider.CytoData; import com.arcadeanalytics.provider.DataSourceInfo; @@ -34,657 +32,653 @@ import org.junit.jupiter.api.Test; import org.testcontainers.containers.PostgreSQLContainer; -public class PostgreSQLDataProviderWithAggregationTest extends AbstractRDBMSProviderWithAggregationTest { - - private DataSourceInfo dataSource; - - @BeforeEach - public void setUp() { - final PostgreSQLContainer container = PostgreSQLContainerHolder.container; - - this.dataSource = - new DataSourceInfo( - 1L, - "RDBMS_POSTGRESQL", - "testDataSource", - "desc", - container.getContainerIpAddress(), - container.getFirstMappedPort(), - container.getDatabaseName(), - container.getUsername(), - container.getPassword(), - true, - "{}", - false, - false, - "", - 22, - "", - false - ); - - provider = new RDBMSDataProvider(); - } - - @Override - @Test - public void fetchDataThroughTableScanTest() { - try { - provider.fetchData(dataSource, "select * from film_actor limit 5", 5); - fail(); - } catch (Exception e) { - String message = e.getMessage(); - assertTrue(message.contains("Wrong query content: the requested table was aggregated into")); - } - } - - @Override - @Test - public void expandN2NRelationship() { - /** - * Get movies by actor - */ - - // expanding 1-N relationship: actor -[film_actor]-> film - String[] rootIds = { "1_1" }; - GraphData data = provider.expand(dataSource, rootIds, "out", "film_actor", 300); - - assertEquals(data.getNodesClasses().size(), 1); - assertEquals(data.getNodes().size(), 19); - assertEquals(data.getEdgesClasses().size(), 1); - assertEquals(data.getEdges().size(), 19); - - // Node classes checks - assertTrue(data.getNodesClasses().containsKey("film")); - - Map filmClass = data.getNodesClasses().get("film"); - assertTrue(filmClass.containsKey("film_id")); - assertTrue(filmClass.containsKey("title")); - assertTrue(filmClass.containsKey("description")); - assertTrue(filmClass.containsKey("release_year")); - assertTrue(filmClass.containsKey("language_id")); - assertTrue(filmClass.containsKey("rental_duration")); - assertTrue(filmClass.containsKey("rental_rate")); - assertTrue(filmClass.containsKey("length")); - assertTrue(filmClass.containsKey("replacement_cost")); - assertTrue(filmClass.containsKey("rating")); - assertTrue(filmClass.containsKey("last_update")); - assertTrue(filmClass.containsKey("special_features")); - assertTrue(filmClass.containsKey("fulltext")); - - // nodes checks - Iterator it = data.getNodes().iterator(); - CytoData currNodeContent; - Map currRecord; - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 1); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Academy Dinosaur"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 23); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Anaconda Confessions"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 25); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Angels Life"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 106); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Bulworth Commandments"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 140); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Cheaper Clyde"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 166); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Color Philadelphia"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 277); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Elephant Trojan"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 361); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Gleaming Jawbreaker"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 438); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Human Graffiti"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 499); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "King Evolution"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 506); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Lady Stage"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 509); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Language Cowboy"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 605); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Mulholland Beast"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 635); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Oklahoma Jumanji"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 749); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Rules Human"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 832); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Splash Gump"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 939); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Vertigo Northwest"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 970); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Westward Seabiscuit"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("film_id")); - assertEquals(currRecord.get("film_id"), 980); - assertTrue(currRecord.containsKey("title")); - assertEquals(currRecord.get("title"), "Wizard Coldblooded"); - assertTrue(currRecord.containsKey("description")); - assertNotNull(currRecord.get("description")); - - // edges checks - it = data.getEdges().iterator(); - CytoData currEdgeContent; - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_1"); - assertEquals(currEdgeContent.getData().getId(), "8_1_1"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_23"); - assertEquals(currEdgeContent.getData().getId(), "8_1_23"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_25"); - assertEquals(currEdgeContent.getData().getId(), "8_1_25"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_106"); - assertEquals(currEdgeContent.getData().getId(), "8_1_106"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_140"); - assertEquals(currEdgeContent.getData().getId(), "8_1_140"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_166"); - assertEquals(currEdgeContent.getData().getId(), "8_1_166"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_277"); - assertEquals(currEdgeContent.getData().getId(), "8_1_277"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_361"); - assertEquals(currEdgeContent.getData().getId(), "8_1_361"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_438"); - assertEquals(currEdgeContent.getData().getId(), "8_1_438"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_499"); - assertEquals(currEdgeContent.getData().getId(), "8_1_499"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_506"); - assertEquals(currEdgeContent.getData().getId(), "8_1_506"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_509"); - assertEquals(currEdgeContent.getData().getId(), "8_1_509"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_605"); - assertEquals(currEdgeContent.getData().getId(), "8_1_605"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_635"); - assertEquals(currEdgeContent.getData().getId(), "8_1_635"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_749"); - assertEquals(currEdgeContent.getData().getId(), "8_1_749"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_832"); - assertEquals(currEdgeContent.getData().getId(), "8_1_832"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_939"); - assertEquals(currEdgeContent.getData().getId(), "8_1_939"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_970"); - assertEquals(currEdgeContent.getData().getId(), "8_1_970"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_1"); - assertEquals(currEdgeContent.getData().getTarget(), "7_980"); - assertEquals(currEdgeContent.getData().getId(), "8_1_980"); - - /** - * Get actors by movie - */ - - // expanding 1-N relationship: film <-[has_film]- actor - - rootIds[0] = "7_2"; - data = provider.expand(dataSource, rootIds, "in", "film_actor", 300); - - assertEquals(data.getNodesClasses().size(), 1); - assertEquals(data.getNodes().size(), 4); - assertEquals(data.getEdgesClasses().size(), 1); - assertEquals(data.getEdges().size(), 4); - - // Node classes checks - assertTrue(data.getNodesClasses().containsKey("actor")); - - Map actorClass = data.getNodesClasses().get("actor"); - assertTrue(actorClass.containsKey("actor_id")); - assertTrue(actorClass.containsKey("first_name")); - assertTrue(actorClass.containsKey("last_name")); - assertTrue(actorClass.containsKey("last_update")); - - // nodes checks - it = data.getNodes().iterator(); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 19); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "Bob"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "Fawcett"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 85); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "Minnie"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "Zellweger"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 90); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "Sean"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "Guiness"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); - - currNodeContent = it.next(); - assertNotNull(currNodeContent.getData()); - assertNotNull(currNodeContent.getData().getRecord()); - currRecord = currNodeContent.getData().getRecord(); - assertTrue(currRecord.containsKey("actor_id")); - assertEquals(currRecord.get("actor_id"), 160); - assertTrue(currRecord.containsKey("first_name")); - assertEquals(currRecord.get("first_name"), "Chris"); - assertTrue(currRecord.containsKey("last_name")); - assertEquals(currRecord.get("last_name"), "Depp"); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currRecord.get("last_update").toString(), "2013-05-26 14:47:57.62"); - - // edges checks - it = data.getEdges().iterator(); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_19"); - assertEquals(currEdgeContent.getData().getTarget(), "7_2"); - assertEquals(currEdgeContent.getData().getId(), "8_19_2"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_85"); - assertEquals(currEdgeContent.getData().getTarget(), "7_2"); - assertEquals(currEdgeContent.getData().getId(), "8_85_2"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_90"); - assertEquals(currEdgeContent.getData().getTarget(), "7_2"); - assertEquals(currEdgeContent.getData().getId(), "8_90_2"); - - currEdgeContent = it.next(); - assertNotNull(currEdgeContent.getData()); - assertNotNull(currEdgeContent.getData().getRecord()); - currRecord = currEdgeContent.getData().getRecord(); - assertEquals(currRecord.size(), 1); - assertTrue(currRecord.containsKey("last_update")); - assertEquals(currEdgeContent.getClasses(), "film_actor"); - assertEquals(currEdgeContent.getGroup(), "edges"); - assertEquals(currEdgeContent.getData().getSource(), "1_160"); - assertEquals(currEdgeContent.getData().getTarget(), "7_2"); - assertEquals(currEdgeContent.getData().getId(), "8_160_2"); +class PostgreSQLDataProviderWithAggregationTest extends AbstractRDBMSProviderWithAggregationTest { + + private DataSourceInfo dataSource; + + @BeforeEach + public void setUp() { + final PostgreSQLContainer container = PostgreSQLContainerHolder.container; + + this.dataSource = + new DataSourceInfo( + 1L, + "RDBMS_POSTGRESQL", + "testDataSource", + "desc", + container.getContainerIpAddress(), + container.getFirstMappedPort(), + container.getDatabaseName(), + container.getUsername(), + container.getPassword(), + true, + "{}", + false, + false, + "", + 22, + "", + false); + + provider = new RDBMSDataProvider(); + } + + @Override + @Test + public void fetchDataThroughTableScanTest() { + try { + provider.fetchData(dataSource, "select * from film_actor limit 5", 5); + fail(""); + } catch (Exception e) { + String message = e.getMessage(); + assertThat(message.contains("Wrong query content: the requested table was aggregated into")) + .isTrue(); } + } + + @Override + @Test + public void expandN2NRelationship() { + /** Get movies by actor */ + + // expanding 1-N relationship: actor -[film_actor]-> film + String[] rootIds = {"1_1"}; + GraphData data = provider.expand(dataSource, rootIds, "out", "film_actor", 300); + + assertThat(data.getNodesClasses().size()).isEqualTo(1); + assertThat(data.getNodes().size()).isEqualTo(19); + assertThat(data.getEdgesClasses().size()).isEqualTo(1); + assertThat(data.getEdges().size()).isEqualTo(19); + + // Node classes checks + assertThat(data.getNodesClasses().containsKey("film")).isTrue(); + + Map filmClass = data.getNodesClasses().get("film"); + assertThat(filmClass.containsKey("film_id")).isTrue(); + assertThat(filmClass.containsKey("title")).isTrue(); + assertThat(filmClass.containsKey("description")).isTrue(); + assertThat(filmClass.containsKey("release_year")).isTrue(); + assertThat(filmClass.containsKey("language_id")).isTrue(); + assertThat(filmClass.containsKey("rental_duration")).isTrue(); + assertThat(filmClass.containsKey("rental_rate")).isTrue(); + assertThat(filmClass.containsKey("length")).isTrue(); + assertThat(filmClass.containsKey("replacement_cost")).isTrue(); + assertThat(filmClass.containsKey("rating")).isTrue(); + assertThat(filmClass.containsKey("last_update")).isTrue(); + assertThat(filmClass.containsKey("special_features")).isTrue(); + assertThat(filmClass.containsKey("fulltext")).isTrue(); + + // nodes checks + Iterator it = data.getNodes().iterator(); + CytoData currNodeContent; + Map currRecord; + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(1); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Academy Dinosaur"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(23); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Anaconda Confessions"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(25); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Angels Life"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(106); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Bulworth Commandments"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(140); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Cheaper Clyde"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(166); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Color Philadelphia"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(277); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Elephant Trojan"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(361); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Gleaming Jawbreaker"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(438); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Human Graffiti"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(499); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("King Evolution"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(506); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Lady Stage"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(509); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Language Cowboy"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(605); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Mulholland Beast"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(635); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Oklahoma Jumanji"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(749); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Rules Human"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(832); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Splash Gump"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(939); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Vertigo Northwest"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(970); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Westward Seabiscuit"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("film_id")).isTrue(); + assertThat(currRecord.get("film_id")).isEqualTo(980); + assertThat(currRecord.containsKey("title")).isTrue(); + assertThat(currRecord.get("title")).isEqualTo("Wizard Coldblooded"); + assertThat(currRecord.containsKey("description")).isTrue(); + assertThat(currRecord.get("description")).isNotNull(); + + // edges checks + it = data.getEdges().iterator(); + CytoData currEdgeContent; + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_1"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_1"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_23"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_23"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_25"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_25"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_106"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_106"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_140"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_140"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_166"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_166"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_277"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_277"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_361"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_361"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_438"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_438"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_499"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_499"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_506"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_506"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_509"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_509"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_605"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_605"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_635"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_635"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_749"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_749"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_832"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_832"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_939"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_939"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_970"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_970"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_1"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_980"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_1_980"); + + /** Get actors by movie */ + + // expanding 1-N relationship: film <-[has_film]- actor + + rootIds[0] = "7_2"; + data = provider.expand(dataSource, rootIds, "in", "film_actor", 300); + + assertThat(data.getNodesClasses().size()).isEqualTo(1); + assertThat(data.getNodes().size()).isEqualTo(4); + assertThat(data.getEdgesClasses().size()).isEqualTo(1); + assertThat(data.getEdges().size()).isEqualTo(4); + + // Node classes checks + assertThat(data.getNodesClasses().containsKey("actor")).isTrue(); + + Map actorClass = data.getNodesClasses().get("actor"); + assertThat(actorClass.containsKey("actor_id")).isTrue(); + assertThat(actorClass.containsKey("first_name")).isTrue(); + assertThat(actorClass.containsKey("last_name")).isTrue(); + assertThat(actorClass.containsKey("last_update")).isTrue(); + + // nodes checks + it = data.getNodes().iterator(); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(19); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("Bob"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("Fawcett"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2013-05-26 14:47:57.62"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(85); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("Minnie"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("Zellweger"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2013-05-26 14:47:57.62"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(90); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("Sean"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("Guiness"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2013-05-26 14:47:57.62"); + + currNodeContent = it.next(); + assertThat(currNodeContent.getData()).isNotNull(); + assertThat(currNodeContent.getData().getRecord()).isNotNull(); + currRecord = currNodeContent.getData().getRecord(); + assertThat(currRecord.containsKey("actor_id")).isTrue(); + assertThat(currRecord.get("actor_id")).isEqualTo(160); + assertThat(currRecord.containsKey("first_name")).isTrue(); + assertThat(currRecord.get("first_name")).isEqualTo("Chris"); + assertThat(currRecord.containsKey("last_name")).isTrue(); + assertThat(currRecord.get("last_name")).isEqualTo("Depp"); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currRecord.get("last_update").toString()).isEqualTo("2013-05-26 14:47:57.62"); + + // edges checks + it = data.getEdges().iterator(); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_19"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_2"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_19_2"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_85"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_2"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_85_2"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_90"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_2"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_90_2"); + + currEdgeContent = it.next(); + assertThat(currEdgeContent.getData()).isNotNull(); + assertThat(currEdgeContent.getData().getRecord()).isNotNull(); + currRecord = currEdgeContent.getData().getRecord(); + assertThat(currRecord.size()).isEqualTo(1); + assertThat(currRecord.containsKey("last_update")).isTrue(); + assertThat(currEdgeContent.getClasses()).isEqualTo("film_actor"); + assertThat(currEdgeContent.getGroup()).isEqualTo("edges"); + assertThat(currEdgeContent.getData().getSource()).isEqualTo("1_160"); + assertThat(currEdgeContent.getData().getTarget()).isEqualTo("7_2"); + assertThat(currEdgeContent.getData().getId()).isEqualTo("8_160_2"); + } } diff --git a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/filter/FilterTableMappingTest.java b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/filter/FilterTableMappingTest.java index 4f33e37c..d970ef90 100644 --- a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/filter/FilterTableMappingTest.java +++ b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/filter/FilterTableMappingTest.java @@ -40,12 +40,8 @@ * #L% */ -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.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import com.arcadeanalytics.provider.DataSourceInfo; import com.arcadeanalytics.provider.rdbms.context.Statistics; @@ -75,3847 +71,5091 @@ /** * @author Gabriele Ponzi */ - -public class FilterTableMappingTest { - - private static final String XML_TABLE_PER_CLASS = "src/test/resources/provider/rdbms/inheritance/hibernate/tablePerClassHierarchyImportTest.xml"; - private static final String XML_TABLE_PER_SUBCLASS1 = "src/test/resources/provider/rdbms/inheritance/hibernate/tablePerSubclassImportTest1.xml"; - private static final String XML_TABLE_PER_SUBCLASS2 = "src/test/resources/provider/rdbms/inheritance/hibernate/tablePerSubclassImportTest2.xml"; - private static final String XML_TABLE_PER_CONCRETE_CLASS = "src/test/resources/provider/rdbms/inheritance/hibernate/tablePerConcreteClassImportTest.xml"; - private ER2GraphMapper mapper; - private DBQueryEngine dbQueryEngine; - private String driver = "org.hsqldb.jdbc.JDBCDriver"; - private String jurl = "jdbc:hsqldb:mem:mydb"; - private String username = "SA"; - private String password = ""; - private SourceDatabaseInfo sourceDBInfo; - private DataSourceInfo dataSource; - private String executionStrategy; - private NameResolver nameResolver; - private DBMSDataTypeHandler dataTypeHandler; - private Statistics statistics; - - @BeforeEach - public void init() { - this.dataSource = - new DataSourceInfo( - 1L, - "RDBMS_HSQL", - "testDataSource", - "desc", - "mem", - 1234, - "mydb", - username, - password, - false, - "{}", - false, - false, - "", - 22, - "", - false - ); - - dbQueryEngine = new DBQueryEngine(dataSource, 300); - executionStrategy = "not_specified"; - nameResolver = new JavaConventionNameResolver(); - dataTypeHandler = new HSQLDBDataTypeHandler(); - statistics = new Statistics(); - } - - @Test - /* - * Filtering out a table through include-tables (without inheritance). - */public void filterOutThroughIncludeWithNoInheritance() { - Connection connection = null; - Statement st = null; - - try { - Class.forName(this.driver); - connection = DriverManager.getConnection(this.jurl, this.username, this.password); - - String countryTableBuilding = "create memory table COUNTRY(ID varchar(256) not null, NAME varchar(256), CONTINENT varchar(256), primary key (ID))"; - st = connection.createStatement(); - st.execute(countryTableBuilding); - - String residenceTableBuilding = - "create memory table RESIDENCE(ID varchar(256) not null, CITY varchar(256), COUNTRY varchar(256), " + - "primary key (ID), foreign key (COUNTRY) references COUNTRY(ID))"; - st.execute(residenceTableBuilding); - - String managerTableBuilding = "create memory table MANAGER(ID varchar(256) not null, NAME varchar(256), PROJECT varchar(256), primary key (ID))"; - st.execute(managerTableBuilding); - - String employeeTableBuilding = - "create memory table EMPLOYEE (ID varchar(256) not null," + - " NAME varchar(256), SALARY decimal(10,2), RESIDENCE varchar(256), MANAGER varchar(256), " + - "primary key (ID), foreign key (RESIDENCE) references RESIDENCE(ID), foreign key (MANAGER) references MANAGER(ID))"; - st.execute(employeeTableBuilding); - - // Records Inserting - - String countryFilling = "insert into COUNTRY (ID,NAME,CONTINENT) values (" + "('C001','Italy','Europe'))"; - st.execute(countryFilling); - - String residenceFilling = "insert into RESIDENCE (ID,CITY,COUNTRY) values (" + "('R001','Rome','C001')," + "('R002','Milan','C001'))"; - st.execute(residenceFilling); - - String managerFilling = "insert into MANAGER (ID,NAME,PROJECT) values (" + "('M001','Bill Right','New World'))"; - st.execute(managerFilling); - - String employeeFilling = - "insert into EMPLOYEE (ID,NAME,SALARY,RESIDENCE,MANAGER) values (" + - "('E001','John Black',1500.00,'R001',null)," + - "('E002','Andrew Brown','1000.00','R001','M001')," + - "('E003','Jack Johnson',2000.00,'R002',null))"; - st.execute(employeeFilling); - - List includedTables = new ArrayList(); - includedTables.add("COUNTRY"); - includedTables.add("MANAGER"); - includedTables.add("EMPLOYEE"); - - this.mapper = new ER2GraphMapper(dataSource, includedTables, null, dbQueryEngine, dataTypeHandler, executionStrategy, nameResolver, statistics); - mapper.buildSourceDatabaseSchema(); - mapper.buildGraphModel(new JavaConventionNameResolver()); - - /* - * Testing context information - */ - - assertEquals(3, statistics.totalNumberOfEntities); - assertEquals(3, statistics.builtEntities); - assertEquals(1, statistics.totalNumberOfRelationships); - assertEquals(1, statistics.builtRelationships); - - assertEquals(3, statistics.totalNumberOfModelVertices); - assertEquals(3, statistics.builtModelVertexTypes); - assertEquals(1, statistics.totalNumberOfModelEdges); - assertEquals(1, statistics.builtModelEdgeTypes); - - /* - * Testing built source db schema - */ - - Entity employeeEntity = mapper.getDataBaseSchema().getEntityByName("EMPLOYEE"); - Entity countryEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("COUNTRY"); - Entity managerEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("MANAGER"); - Entity residenceEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("RESIDENCE"); - - // entities check - assertEquals(3, mapper.getDataBaseSchema().getEntities().size()); - assertEquals(1, mapper.getDataBaseSchema().getCanonicalRelationships().size()); - assertNotNull(employeeEntity); - assertNotNull(countryEntity); - assertNotNull(managerEntity); - assertNull(residenceEntity); - - // attributes check - assertEquals(5, employeeEntity.getAttributes().size()); - - assertNotNull(employeeEntity.getAttributeByName("ID")); - assertEquals("ID", employeeEntity.getAttributeByName("ID").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("ID").getDataType()); - assertEquals(1, employeeEntity.getAttributeByName("ID").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(employeeEntity.getAttributeByName("NAME")); - assertEquals("NAME", employeeEntity.getAttributeByName("NAME").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("NAME").getDataType()); - assertEquals(2, employeeEntity.getAttributeByName("NAME").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(employeeEntity.getAttributeByName("SALARY")); - assertEquals("SALARY", employeeEntity.getAttributeByName("SALARY").getName()); - assertEquals("DECIMAL", employeeEntity.getAttributeByName("SALARY").getDataType()); - assertEquals(3, employeeEntity.getAttributeByName("SALARY").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("SALARY").getBelongingEntity().getName()); - - assertNotNull(employeeEntity.getAttributeByName("RESIDENCE")); - assertEquals("RESIDENCE", employeeEntity.getAttributeByName("RESIDENCE").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("RESIDENCE").getDataType()); - assertEquals(4, employeeEntity.getAttributeByName("RESIDENCE").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("RESIDENCE").getBelongingEntity().getName()); - - assertNotNull(employeeEntity.getAttributeByName("MANAGER")); - assertEquals("MANAGER", employeeEntity.getAttributeByName("MANAGER").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("MANAGER").getDataType()); - assertEquals(5, employeeEntity.getAttributeByName("MANAGER").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("MANAGER").getBelongingEntity().getName()); - - assertEquals(3, countryEntity.getAttributes().size()); - - assertNotNull(countryEntity.getAttributeByName("ID")); - assertEquals("ID", countryEntity.getAttributeByName("ID").getName()); - assertEquals("VARCHAR", countryEntity.getAttributeByName("ID").getDataType()); - assertEquals(1, countryEntity.getAttributeByName("ID").getOrdinalPosition()); - assertEquals("COUNTRY", countryEntity.getAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(countryEntity.getAttributeByName("NAME")); - assertEquals("NAME", countryEntity.getAttributeByName("NAME").getName()); - assertEquals("VARCHAR", countryEntity.getAttributeByName("NAME").getDataType()); - assertEquals(2, countryEntity.getAttributeByName("NAME").getOrdinalPosition()); - assertEquals("COUNTRY", countryEntity.getAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(countryEntity.getAttributeByName("CONTINENT")); - assertEquals("CONTINENT", countryEntity.getAttributeByName("CONTINENT").getName()); - assertEquals("VARCHAR", countryEntity.getAttributeByName("CONTINENT").getDataType()); - assertEquals(3, countryEntity.getAttributeByName("CONTINENT").getOrdinalPosition()); - assertEquals("COUNTRY", countryEntity.getAttributeByName("CONTINENT").getBelongingEntity().getName()); - - assertEquals(3, managerEntity.getAttributes().size()); - - assertNotNull(managerEntity.getAttributeByName("ID")); - assertEquals("ID", managerEntity.getAttributeByName("ID").getName()); - assertEquals("VARCHAR", managerEntity.getAttributeByName("ID").getDataType()); - assertEquals(1, managerEntity.getAttributeByName("ID").getOrdinalPosition()); - assertEquals("MANAGER", managerEntity.getAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(managerEntity.getAttributeByName("NAME")); - assertEquals("NAME", managerEntity.getAttributeByName("NAME").getName()); - assertEquals("VARCHAR", managerEntity.getAttributeByName("NAME").getDataType()); - assertEquals(2, managerEntity.getAttributeByName("NAME").getOrdinalPosition()); - assertEquals("MANAGER", managerEntity.getAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(managerEntity.getAttributeByName("PROJECT")); - assertEquals("PROJECT", managerEntity.getAttributeByName("PROJECT").getName()); - assertEquals("VARCHAR", managerEntity.getAttributeByName("PROJECT").getDataType()); - assertEquals(3, managerEntity.getAttributeByName("PROJECT").getOrdinalPosition()); - assertEquals("MANAGER", managerEntity.getAttributeByName("PROJECT").getBelongingEntity().getName()); - - // relationship, primary and foreign key check - assertEquals(1, employeeEntity.getOutCanonicalRelationships().size()); - assertEquals(0, managerEntity.getOutCanonicalRelationships().size()); - assertEquals(0, countryEntity.getOutCanonicalRelationships().size()); - assertEquals(0, employeeEntity.getInCanonicalRelationships().size()); - assertEquals(1, managerEntity.getInCanonicalRelationships().size()); - assertEquals(0, countryEntity.getOutCanonicalRelationships().size()); - assertEquals(1, employeeEntity.getForeignKeys().size()); - - Iterator itEmp = employeeEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship currentEmpRel = itEmp.next(); - assertEquals("MANAGER", currentEmpRel.getParentEntity().getName()); - assertEquals("EMPLOYEE", currentEmpRel.getForeignEntity().getName()); - assertEquals(managerEntity.getPrimaryKey(), currentEmpRel.getPrimaryKey()); - assertEquals(employeeEntity.getForeignKeys().get(0), currentEmpRel.getForeignKey()); - assertFalse(itEmp.hasNext()); - - Iterator itManager = managerEntity.getInCanonicalRelationships().iterator(); - CanonicalRelationship currentManRel = itManager.next(); - assertEquals(currentEmpRel, currentManRel); - - /* - * Testing built graph model - */ - - VertexType employeeVertexType = mapper.getGraphModel().getVertexTypeByName("Employee"); - VertexType countryVertexType = mapper.getGraphModel().getVertexTypeByName("Country"); - VertexType managerVertexType = mapper.getGraphModel().getVertexTypeByName("Manager"); - VertexType residenceVertexType = mapper.getGraphModel().getVertexTypeByName("Residence"); - - // vertices check - assertEquals(3, mapper.getGraphModel().getVerticesType().size()); - assertNotNull(employeeVertexType); - assertNotNull(countryVertexType); - assertNotNull(managerVertexType); - assertNull(residenceVertexType); - - // properties check - assertEquals(5, employeeVertexType.getProperties().size()); - - assertNotNull(employeeVertexType.getPropertyByName("id")); - assertEquals("id", employeeVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, employeeVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, employeeVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(employeeVertexType.getPropertyByName("name")); - assertEquals("name", employeeVertexType.getPropertyByName("name").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("name").getOriginalType()); - assertEquals(2, employeeVertexType.getPropertyByName("name").getOrdinalPosition()); - assertEquals(false, employeeVertexType.getPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(employeeVertexType.getPropertyByName("salary")); - assertEquals("salary", employeeVertexType.getPropertyByName("salary").getName()); - assertEquals("DECIMAL", employeeVertexType.getPropertyByName("salary").getOriginalType()); - assertEquals(3, employeeVertexType.getPropertyByName("salary").getOrdinalPosition()); - assertEquals(false, employeeVertexType.getPropertyByName("salary").isFromPrimaryKey()); - - assertNotNull(employeeVertexType.getPropertyByName("residence")); - assertEquals("residence", employeeVertexType.getPropertyByName("residence").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("residence").getOriginalType()); - assertEquals(4, employeeVertexType.getPropertyByName("residence").getOrdinalPosition()); - assertEquals(false, employeeVertexType.getPropertyByName("residence").isFromPrimaryKey()); - - assertNotNull(employeeVertexType.getPropertyByName("manager")); - assertEquals("manager", employeeVertexType.getPropertyByName("manager").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("manager").getOriginalType()); - assertEquals(5, employeeVertexType.getPropertyByName("manager").getOrdinalPosition()); - assertEquals(false, employeeVertexType.getPropertyByName("manager").isFromPrimaryKey()); - - assertEquals(3, countryVertexType.getProperties().size()); - - assertNotNull(countryVertexType.getPropertyByName("id")); - assertEquals("id", countryVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", countryVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, countryVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, countryVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(countryVertexType.getPropertyByName("name")); - assertEquals("name", countryVertexType.getPropertyByName("name").getName()); - assertEquals("VARCHAR", countryVertexType.getPropertyByName("name").getOriginalType()); - assertEquals(2, countryVertexType.getPropertyByName("name").getOrdinalPosition()); - assertEquals(false, countryVertexType.getPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(countryVertexType.getPropertyByName("continent")); - assertEquals("continent", countryVertexType.getPropertyByName("continent").getName()); - assertEquals("VARCHAR", countryVertexType.getPropertyByName("continent").getOriginalType()); - assertEquals(3, countryVertexType.getPropertyByName("continent").getOrdinalPosition()); - assertEquals(false, countryVertexType.getPropertyByName("continent").isFromPrimaryKey()); - - assertEquals(3, managerVertexType.getProperties().size()); - - assertNotNull(managerVertexType.getPropertyByName("id")); - assertEquals("id", managerVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", managerVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, managerVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, managerVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(managerVertexType.getPropertyByName("name")); - assertEquals("name", managerVertexType.getPropertyByName("name").getName()); - assertEquals("VARCHAR", managerVertexType.getPropertyByName("name").getOriginalType()); - assertEquals(2, managerVertexType.getPropertyByName("name").getOrdinalPosition()); - assertEquals(false, managerVertexType.getPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(managerVertexType.getPropertyByName("project")); - assertEquals("project", managerVertexType.getPropertyByName("project").getName()); - assertEquals("VARCHAR", managerVertexType.getPropertyByName("project").getOriginalType()); - assertEquals(3, managerVertexType.getPropertyByName("project").getOrdinalPosition()); - assertEquals(false, managerVertexType.getPropertyByName("project").isFromPrimaryKey()); - - // edges check - - assertEquals(1, mapper.getRelationship2edgeType().size()); - - assertEquals(1, mapper.getGraphModel().getEdgesType().size()); - assertEquals("HasManager", mapper.getGraphModel().getEdgesType().get(0).getName()); - - assertEquals(1, employeeVertexType.getOutEdgesType().size()); - assertEquals("HasManager", employeeVertexType.getOutEdgesType().get(0).getName()); - - /* - * Rules check - */ - - // Classes Mapping - - assertEquals(3, mapper.getVertexType2EVClassMappers().size()); - assertEquals(3, mapper.getEntity2EVClassMappers().size()); - - assertEquals(1, mapper.getEVClassMappersByVertex(employeeVertexType).size()); - EVClassMapper employeeClassMapper = mapper.getEVClassMappersByVertex(employeeVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(employeeEntity).size()); - assertEquals(employeeClassMapper, mapper.getEVClassMappersByEntity(employeeEntity).get(0)); - assertEquals(employeeClassMapper.getEntity(), employeeEntity); - assertEquals(employeeClassMapper.getVertexType(), employeeVertexType); - - assertEquals(5, employeeClassMapper.getAttribute2property().size()); - assertEquals(5, employeeClassMapper.getProperty2attribute().size()); - assertEquals("id", employeeClassMapper.getAttribute2property().get("ID")); - assertEquals("name", employeeClassMapper.getAttribute2property().get("NAME")); - assertEquals("salary", employeeClassMapper.getAttribute2property().get("SALARY")); - assertEquals("residence", employeeClassMapper.getAttribute2property().get("RESIDENCE")); - assertEquals("manager", employeeClassMapper.getAttribute2property().get("MANAGER")); - assertEquals("ID", employeeClassMapper.getProperty2attribute().get("id")); - assertEquals("NAME", employeeClassMapper.getProperty2attribute().get("name")); - assertEquals("SALARY", employeeClassMapper.getProperty2attribute().get("salary")); - assertEquals("RESIDENCE", employeeClassMapper.getProperty2attribute().get("residence")); - assertEquals("MANAGER", employeeClassMapper.getProperty2attribute().get("manager")); - - assertEquals(1, mapper.getEVClassMappersByVertex(countryVertexType).size()); - EVClassMapper countryClassMapper = mapper.getEVClassMappersByVertex(countryVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(countryEntity).size()); - assertEquals(countryClassMapper, mapper.getEVClassMappersByEntity(countryEntity).get(0)); - assertEquals(countryClassMapper.getEntity(), countryEntity); - assertEquals(countryClassMapper.getVertexType(), countryVertexType); - - assertEquals(3, countryClassMapper.getAttribute2property().size()); - assertEquals(3, countryClassMapper.getProperty2attribute().size()); - assertEquals("id", countryClassMapper.getAttribute2property().get("ID")); - assertEquals("name", countryClassMapper.getAttribute2property().get("NAME")); - assertEquals("continent", countryClassMapper.getAttribute2property().get("CONTINENT")); - assertEquals("ID", countryClassMapper.getProperty2attribute().get("id")); - assertEquals("NAME", countryClassMapper.getProperty2attribute().get("name")); - assertEquals("CONTINENT", countryClassMapper.getProperty2attribute().get("continent")); - - assertEquals(1, mapper.getEVClassMappersByVertex(managerVertexType).size()); - EVClassMapper managerClassMapper = mapper.getEVClassMappersByVertex(managerVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(managerEntity).size()); - assertEquals(managerClassMapper, mapper.getEVClassMappersByEntity(managerEntity).get(0)); - assertEquals(managerClassMapper.getEntity(), managerEntity); - assertEquals(managerClassMapper.getVertexType(), managerVertexType); - - assertEquals(3, managerClassMapper.getAttribute2property().size()); - assertEquals(3, managerClassMapper.getProperty2attribute().size()); - assertEquals("id", managerClassMapper.getAttribute2property().get("ID")); - assertEquals("name", managerClassMapper.getAttribute2property().get("NAME")); - assertEquals("project", managerClassMapper.getAttribute2property().get("PROJECT")); - assertEquals("ID", managerClassMapper.getProperty2attribute().get("id")); - assertEquals("NAME", managerClassMapper.getProperty2attribute().get("name")); - assertEquals("PROJECT", managerClassMapper.getProperty2attribute().get("project")); - - // Relationships-Edges Mapping - - Iterator it = employeeEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship hasManagerRelationship = it.next(); - assertFalse(it.hasNext()); - - EdgeType hasManagerEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasManager"); - - assertEquals(1, mapper.getRelationship2edgeType().size()); - assertEquals(hasManagerEdgeType, mapper.getRelationship2edgeType().get(hasManagerRelationship)); - - assertEquals(1, mapper.getEdgeType2relationships().size()); - assertEquals(1, mapper.getEdgeType2relationships().get(hasManagerEdgeType).size()); - assertTrue(mapper.getEdgeType2relationships().get(hasManagerEdgeType).contains(hasManagerRelationship)); - - // JoinVertexes-AggregatorEdges Mapping - - assertEquals(0, mapper.getJoinVertex2aggregatorEdges().size()); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } finally { - try { - // Dropping Source DB Schema and OrientGraph - String dbDropping = "drop schema public cascade"; - st.execute(dbDropping); - connection.close(); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } - } +class FilterTableMappingTest { + + private static final String XML_TABLE_PER_CLASS = + "src/test/resources/provider/rdbms/inheritance/hibernate/tablePerClassHierarchyImportTest.xml"; + private static final String XML_TABLE_PER_SUBCLASS1 = + "src/test/resources/provider/rdbms/inheritance/hibernate/tablePerSubclassImportTest1.xml"; + private static final String XML_TABLE_PER_SUBCLASS2 = + "src/test/resources/provider/rdbms/inheritance/hibernate/tablePerSubclassImportTest2.xml"; + private static final String XML_TABLE_PER_CONCRETE_CLASS = + "src/test/resources/provider/rdbms/inheritance/hibernate/tablePerConcreteClassImportTest.xml"; + private ER2GraphMapper mapper; + private DBQueryEngine dbQueryEngine; + private String driver = "org.hsqldb.jdbc.JDBCDriver"; + private String jurl = "jdbc:hsqldb:mem:mydb"; + private String username = "SA"; + private String password = ""; + private SourceDatabaseInfo sourceDBInfo; + private DataSourceInfo dataSource; + private String executionStrategy; + private NameResolver nameResolver; + private DBMSDataTypeHandler dataTypeHandler; + private Statistics statistics; + + @BeforeEach + void init() { + this.dataSource = + new DataSourceInfo( + 1L, + "RDBMS_HSQL", + "testDataSource", + "desc", + "mem", + 1234, + "mydb", + username, + password, + false, + "{}", + false, + false, + "", + 22, + "", + false); + + dbQueryEngine = new DBQueryEngine(dataSource, 300); + executionStrategy = "not_specified"; + nameResolver = new JavaConventionNameResolver(); + dataTypeHandler = new HSQLDBDataTypeHandler(); + statistics = new Statistics(); + } + + /* + * Filtering out a table through include-tables (without inheritance). + */ @Test + void filterOutThroughIncludeWithNoInheritance() { + Connection connection = null; + Statement st = null; + + try { + Class.forName(this.driver); + connection = DriverManager.getConnection(this.jurl, this.username, this.password); + + String countryTableBuilding = + "create memory table COUNTRY(ID varchar(256) not null, NAME varchar(256), CONTINENT" + + " varchar(256), primary key (ID))"; + st = connection.createStatement(); + st.execute(countryTableBuilding); + + String residenceTableBuilding = + "create memory table RESIDENCE(ID varchar(256) not null, CITY varchar(256), COUNTRY" + + " varchar(256), primary key (ID), foreign key (COUNTRY) references COUNTRY(ID))"; + st.execute(residenceTableBuilding); + + String managerTableBuilding = + "create memory table MANAGER(ID varchar(256) not null, NAME varchar(256), PROJECT" + + " varchar(256), primary key (ID))"; + st.execute(managerTableBuilding); + + String employeeTableBuilding = + "create memory table EMPLOYEE (ID varchar(256) not null, NAME varchar(256), SALARY" + + " decimal(10,2), RESIDENCE varchar(256), MANAGER varchar(256), primary key (ID)," + + " foreign key (RESIDENCE) references RESIDENCE(ID), foreign key (MANAGER)" + + " references MANAGER(ID))"; + st.execute(employeeTableBuilding); + + // Records Inserting + + String countryFilling = + "insert into COUNTRY (ID,NAME,CONTINENT) values (" + "('C001','Italy','Europe'))"; + st.execute(countryFilling); + + String residenceFilling = + "insert into RESIDENCE (ID,CITY,COUNTRY) values (" + + "('R001','Rome','C001')," + + "('R002','Milan','C001'))"; + st.execute(residenceFilling); + + String managerFilling = + "insert into MANAGER (ID,NAME,PROJECT) values (" + "('M001','Bill Right','New World'))"; + st.execute(managerFilling); + + String employeeFilling = + "insert into EMPLOYEE (ID,NAME,SALARY,RESIDENCE,MANAGER) values (" + + "('E001','John Black',1500.00,'R001',null)," + + "('E002','Andrew Brown','1000.00','R001','M001')," + + "('E003','Jack Johnson',2000.00,'R002',null))"; + st.execute(employeeFilling); + + List includedTables = new ArrayList(); + includedTables.add("COUNTRY"); + includedTables.add("MANAGER"); + includedTables.add("EMPLOYEE"); + + this.mapper = + new ER2GraphMapper( + dataSource, + includedTables, + null, + dbQueryEngine, + dataTypeHandler, + executionStrategy, + nameResolver, + statistics); + mapper.buildSourceDatabaseSchema(); + mapper.buildGraphModel(new JavaConventionNameResolver()); + + /* + * Testing context information + */ + + assertThat(statistics.totalNumberOfEntities).isEqualTo(3); + assertThat(statistics.builtEntities).isEqualTo(3); + assertThat(statistics.totalNumberOfRelationships).isEqualTo(1); + assertThat(statistics.builtRelationships).isEqualTo(1); + + assertThat(statistics.totalNumberOfModelVertices).isEqualTo(3); + assertThat(statistics.builtModelVertexTypes).isEqualTo(3); + assertThat(statistics.totalNumberOfModelEdges).isEqualTo(1); + assertThat(statistics.builtModelEdgeTypes).isEqualTo(1); + + /* + * Testing built source db schema + */ + + Entity employeeEntity = mapper.getDataBaseSchema().getEntityByName("EMPLOYEE"); + Entity countryEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("COUNTRY"); + Entity managerEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("MANAGER"); + Entity residenceEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("RESIDENCE"); + + // entities check + assertThat(mapper.getDataBaseSchema().getEntities().size()).isEqualTo(3); + assertThat(mapper.getDataBaseSchema().getCanonicalRelationships().size()).isEqualTo(1); + assertThat(employeeEntity).isNotNull(); + assertThat(countryEntity).isNotNull(); + assertThat(managerEntity).isNotNull(); + assertThat(residenceEntity).isNull(); + + // attributes check + assertThat(employeeEntity.getAttributes().size()).isEqualTo(5); + + assertThat(employeeEntity.getAttributeByName("ID")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(employeeEntity.getAttributeByName("ID").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("ID").getOrdinalPosition()).isEqualTo(1); + assertThat(employeeEntity.getAttributeByName("ID").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(employeeEntity.getAttributeByName("NAME")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("NAME").getName()).isEqualTo("NAME"); + assertThat(employeeEntity.getAttributeByName("NAME").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("NAME").getOrdinalPosition()).isEqualTo(2); + assertThat(employeeEntity.getAttributeByName("NAME").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(employeeEntity.getAttributeByName("SALARY")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("SALARY").getName()).isEqualTo("SALARY"); + assertThat(employeeEntity.getAttributeByName("SALARY").getDataType()).isEqualTo("DECIMAL"); + assertThat(employeeEntity.getAttributeByName("SALARY").getOrdinalPosition()).isEqualTo(3); + assertThat(employeeEntity.getAttributeByName("SALARY").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(employeeEntity.getAttributeByName("RESIDENCE")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getName()).isEqualTo("RESIDENCE"); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getOrdinalPosition()).isEqualTo(4); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(employeeEntity.getAttributeByName("MANAGER")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("MANAGER").getName()).isEqualTo("MANAGER"); + assertThat(employeeEntity.getAttributeByName("MANAGER").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("MANAGER").getOrdinalPosition()).isEqualTo(5); + assertThat(employeeEntity.getAttributeByName("MANAGER").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(countryEntity.getAttributes().size()).isEqualTo(3); + + assertThat(countryEntity.getAttributeByName("ID")).isNotNull(); + assertThat(countryEntity.getAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(countryEntity.getAttributeByName("ID").getDataType()).isEqualTo("VARCHAR"); + assertThat(countryEntity.getAttributeByName("ID").getOrdinalPosition()).isEqualTo(1); + assertThat(countryEntity.getAttributeByName("ID").getBelongingEntity().getName()) + .isEqualTo("COUNTRY"); + + assertThat(countryEntity.getAttributeByName("NAME")).isNotNull(); + assertThat(countryEntity.getAttributeByName("NAME").getName()).isEqualTo("NAME"); + assertThat(countryEntity.getAttributeByName("NAME").getDataType()).isEqualTo("VARCHAR"); + assertThat(countryEntity.getAttributeByName("NAME").getOrdinalPosition()).isEqualTo(2); + assertThat(countryEntity.getAttributeByName("NAME").getBelongingEntity().getName()) + .isEqualTo("COUNTRY"); + + assertThat(countryEntity.getAttributeByName("CONTINENT")).isNotNull(); + assertThat(countryEntity.getAttributeByName("CONTINENT").getName()).isEqualTo("CONTINENT"); + assertThat(countryEntity.getAttributeByName("CONTINENT").getDataType()).isEqualTo("VARCHAR"); + assertThat(countryEntity.getAttributeByName("CONTINENT").getOrdinalPosition()).isEqualTo(3); + assertThat(countryEntity.getAttributeByName("CONTINENT").getBelongingEntity().getName()) + .isEqualTo("COUNTRY"); + + assertThat(managerEntity.getAttributes().size()).isEqualTo(3); + + assertThat(managerEntity.getAttributeByName("ID")).isNotNull(); + assertThat(managerEntity.getAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(managerEntity.getAttributeByName("ID").getDataType()).isEqualTo("VARCHAR"); + assertThat(managerEntity.getAttributeByName("ID").getOrdinalPosition()).isEqualTo(1); + assertThat(managerEntity.getAttributeByName("ID").getBelongingEntity().getName()) + .isEqualTo("MANAGER"); + + assertThat(managerEntity.getAttributeByName("NAME")).isNotNull(); + assertThat(managerEntity.getAttributeByName("NAME").getName()).isEqualTo("NAME"); + assertThat(managerEntity.getAttributeByName("NAME").getDataType()).isEqualTo("VARCHAR"); + assertThat(managerEntity.getAttributeByName("NAME").getOrdinalPosition()).isEqualTo(2); + assertThat(managerEntity.getAttributeByName("NAME").getBelongingEntity().getName()) + .isEqualTo("MANAGER"); + + assertThat(managerEntity.getAttributeByName("PROJECT")).isNotNull(); + assertThat(managerEntity.getAttributeByName("PROJECT").getName()).isEqualTo("PROJECT"); + assertThat(managerEntity.getAttributeByName("PROJECT").getDataType()).isEqualTo("VARCHAR"); + assertThat(managerEntity.getAttributeByName("PROJECT").getOrdinalPosition()).isEqualTo(3); + assertThat(managerEntity.getAttributeByName("PROJECT").getBelongingEntity().getName()) + .isEqualTo("MANAGER"); + + // relationship, primary and foreign key check + assertThat(employeeEntity.getOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(managerEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(countryEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(employeeEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(managerEntity.getInCanonicalRelationships().size()).isEqualTo(1); + assertThat(countryEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(employeeEntity.getForeignKeys().size()).isEqualTo(1); + + Iterator itEmp = + employeeEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship currentEmpRel = itEmp.next(); + assertThat(currentEmpRel.getParentEntity().getName()).isEqualTo("MANAGER"); + assertThat(currentEmpRel.getForeignEntity().getName()).isEqualTo("EMPLOYEE"); + assertThat(currentEmpRel.getPrimaryKey()).isEqualTo(managerEntity.getPrimaryKey()); + assertThat(currentEmpRel.getForeignKey()).isEqualTo(employeeEntity.getForeignKeys().get(0)); + assertThat(itEmp.hasNext()).isFalse(); + + Iterator itManager = + managerEntity.getInCanonicalRelationships().iterator(); + CanonicalRelationship currentManRel = itManager.next(); + assertThat(currentManRel).isEqualTo(currentEmpRel); + + /* + * Testing built graph model + */ + + VertexType employeeVertexType = mapper.getGraphModel().getVertexTypeByName("Employee"); + VertexType countryVertexType = mapper.getGraphModel().getVertexTypeByName("Country"); + VertexType managerVertexType = mapper.getGraphModel().getVertexTypeByName("Manager"); + VertexType residenceVertexType = mapper.getGraphModel().getVertexTypeByName("Residence"); + + // vertices check + assertThat(mapper.getGraphModel().getVerticesType().size()).isEqualTo(3); + assertThat(employeeVertexType).isNotNull(); + assertThat(countryVertexType).isNotNull(); + assertThat(managerVertexType).isNotNull(); + assertThat(residenceVertexType).isNull(); + + // properties check + assertThat(employeeVertexType.getProperties().size()).isEqualTo(5); + + assertThat(employeeVertexType.getPropertyByName("id")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(employeeVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(employeeVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(employeeVertexType.getPropertyByName("name")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("name").getName()).isEqualTo("name"); + assertThat(employeeVertexType.getPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("name").getOrdinalPosition()).isEqualTo(2); + assertThat(employeeVertexType.getPropertyByName("name").isFromPrimaryKey()).isFalse(); + + assertThat(employeeVertexType.getPropertyByName("salary")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("salary").getName()).isEqualTo("salary"); + assertThat(employeeVertexType.getPropertyByName("salary").getOriginalType()) + .isEqualTo("DECIMAL"); + assertThat(employeeVertexType.getPropertyByName("salary").getOrdinalPosition()).isEqualTo(3); + assertThat(employeeVertexType.getPropertyByName("salary").isFromPrimaryKey()).isFalse(); + + assertThat(employeeVertexType.getPropertyByName("residence")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("residence").getName()) + .isEqualTo("residence"); + assertThat(employeeVertexType.getPropertyByName("residence").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("residence").getOrdinalPosition()) + .isEqualTo(4); + assertThat(employeeVertexType.getPropertyByName("residence").isFromPrimaryKey()).isFalse(); + + assertThat(employeeVertexType.getPropertyByName("manager")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("manager").getName()).isEqualTo("manager"); + assertThat(employeeVertexType.getPropertyByName("manager").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("manager").getOrdinalPosition()).isEqualTo(5); + assertThat(employeeVertexType.getPropertyByName("manager").isFromPrimaryKey()).isFalse(); + + assertThat(countryVertexType.getProperties().size()).isEqualTo(3); + + assertThat(countryVertexType.getPropertyByName("id")).isNotNull(); + assertThat(countryVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(countryVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(countryVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(countryVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(countryVertexType.getPropertyByName("name")).isNotNull(); + assertThat(countryVertexType.getPropertyByName("name").getName()).isEqualTo("name"); + assertThat(countryVertexType.getPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(countryVertexType.getPropertyByName("name").getOrdinalPosition()).isEqualTo(2); + assertThat(countryVertexType.getPropertyByName("name").isFromPrimaryKey()).isFalse(); + + assertThat(countryVertexType.getPropertyByName("continent")).isNotNull(); + assertThat(countryVertexType.getPropertyByName("continent").getName()).isEqualTo("continent"); + assertThat(countryVertexType.getPropertyByName("continent").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(countryVertexType.getPropertyByName("continent").getOrdinalPosition()) + .isEqualTo(3); + assertThat(countryVertexType.getPropertyByName("continent").isFromPrimaryKey()).isFalse(); + + assertThat(managerVertexType.getProperties().size()).isEqualTo(3); + + assertThat(managerVertexType.getPropertyByName("id")).isNotNull(); + assertThat(managerVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(managerVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(managerVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(managerVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(managerVertexType.getPropertyByName("name")).isNotNull(); + assertThat(managerVertexType.getPropertyByName("name").getName()).isEqualTo("name"); + assertThat(managerVertexType.getPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(managerVertexType.getPropertyByName("name").getOrdinalPosition()).isEqualTo(2); + assertThat(managerVertexType.getPropertyByName("name").isFromPrimaryKey()).isFalse(); + + assertThat(managerVertexType.getPropertyByName("project")).isNotNull(); + assertThat(managerVertexType.getPropertyByName("project").getName()).isEqualTo("project"); + assertThat(managerVertexType.getPropertyByName("project").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(managerVertexType.getPropertyByName("project").getOrdinalPosition()).isEqualTo(3); + assertThat(managerVertexType.getPropertyByName("project").isFromPrimaryKey()).isFalse(); + + // edges check + + assertThat(mapper.getRelationship2edgeType().size()).isEqualTo(1); + + assertThat(mapper.getGraphModel().getEdgesType().size()).isEqualTo(1); + assertThat(mapper.getGraphModel().getEdgesType().get(0).getName()).isEqualTo("HasManager"); + + assertThat(employeeVertexType.getOutEdgesType().size()).isEqualTo(1); + assertThat(employeeVertexType.getOutEdgesType().get(0).getName()).isEqualTo("HasManager"); + + /* + * Rules check + */ + + // Classes Mapping + + assertThat(mapper.getVertexType2EVClassMappers().size()).isEqualTo(3); + assertThat(mapper.getEntity2EVClassMappers().size()).isEqualTo(3); + + assertThat(mapper.getEVClassMappersByVertex(employeeVertexType).size()).isEqualTo(1); + EVClassMapper employeeClassMapper = + mapper.getEVClassMappersByVertex(employeeVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(employeeEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(employeeEntity).get(0)) + .isEqualTo(employeeClassMapper); + assertThat(employeeEntity).isEqualTo(employeeClassMapper.getEntity()); + assertThat(employeeVertexType).isEqualTo(employeeClassMapper.getVertexType()); + + assertThat(employeeClassMapper.getAttribute2property().size()).isEqualTo(5); + assertThat(employeeClassMapper.getProperty2attribute().size()).isEqualTo(5); + assertThat(employeeClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(employeeClassMapper.getAttribute2property().get("NAME")).isEqualTo("name"); + assertThat(employeeClassMapper.getAttribute2property().get("SALARY")).isEqualTo("salary"); + assertThat(employeeClassMapper.getAttribute2property().get("RESIDENCE")) + .isEqualTo("residence"); + assertThat(employeeClassMapper.getAttribute2property().get("MANAGER")).isEqualTo("manager"); + assertThat(employeeClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(employeeClassMapper.getProperty2attribute().get("name")).isEqualTo("NAME"); + assertThat(employeeClassMapper.getProperty2attribute().get("salary")).isEqualTo("SALARY"); + assertThat(employeeClassMapper.getProperty2attribute().get("residence")) + .isEqualTo("RESIDENCE"); + assertThat(employeeClassMapper.getProperty2attribute().get("manager")).isEqualTo("MANAGER"); + + assertThat(mapper.getEVClassMappersByVertex(countryVertexType).size()).isEqualTo(1); + EVClassMapper countryClassMapper = mapper.getEVClassMappersByVertex(countryVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(countryEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(countryEntity).get(0)) + .isEqualTo(countryClassMapper); + assertThat(countryEntity).isEqualTo(countryClassMapper.getEntity()); + assertThat(countryVertexType).isEqualTo(countryClassMapper.getVertexType()); + + assertThat(countryClassMapper.getAttribute2property().size()).isEqualTo(3); + assertThat(countryClassMapper.getProperty2attribute().size()).isEqualTo(3); + assertThat(countryClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(countryClassMapper.getAttribute2property().get("NAME")).isEqualTo("name"); + assertThat(countryClassMapper.getAttribute2property().get("CONTINENT")) + .isEqualTo("continent"); + assertThat(countryClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(countryClassMapper.getProperty2attribute().get("name")).isEqualTo("NAME"); + assertThat(countryClassMapper.getProperty2attribute().get("continent")) + .isEqualTo("CONTINENT"); + + assertThat(mapper.getEVClassMappersByVertex(managerVertexType).size()).isEqualTo(1); + EVClassMapper managerClassMapper = mapper.getEVClassMappersByVertex(managerVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(managerEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(managerEntity).get(0)) + .isEqualTo(managerClassMapper); + assertThat(managerEntity).isEqualTo(managerClassMapper.getEntity()); + assertThat(managerVertexType).isEqualTo(managerClassMapper.getVertexType()); + + assertThat(managerClassMapper.getAttribute2property().size()).isEqualTo(3); + assertThat(managerClassMapper.getProperty2attribute().size()).isEqualTo(3); + assertThat(managerClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(managerClassMapper.getAttribute2property().get("NAME")).isEqualTo("name"); + assertThat(managerClassMapper.getAttribute2property().get("PROJECT")).isEqualTo("project"); + assertThat(managerClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(managerClassMapper.getProperty2attribute().get("name")).isEqualTo("NAME"); + assertThat(managerClassMapper.getProperty2attribute().get("project")).isEqualTo("PROJECT"); + + // Relationships-Edges Mapping + + Iterator it = employeeEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship hasManagerRelationship = it.next(); + assertThat(it.hasNext()).isFalse(); + + EdgeType hasManagerEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasManager"); + + assertThat(mapper.getRelationship2edgeType().size()).isEqualTo(1); + assertThat(mapper.getRelationship2edgeType().get(hasManagerRelationship)) + .isEqualTo(hasManagerEdgeType); + + assertThat(mapper.getEdgeType2relationships().size()).isEqualTo(1); + assertThat(mapper.getEdgeType2relationships().get(hasManagerEdgeType).size()).isEqualTo(1); + assertThat( + mapper + .getEdgeType2relationships() + .get(hasManagerEdgeType) + .contains(hasManagerRelationship)) + .isTrue(); + + // JoinVertexes-AggregatorEdges Mapping + + assertThat(mapper.getJoinVertex2aggregatorEdges().size()).isEqualTo(0); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } finally { + try { + // Dropping Source DB Schema and OrientGraph + String dbDropping = "drop schema public cascade"; + st.execute(dbDropping); + connection.close(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } } - - @Test - /* - * Filtering out a table through exclude-tables (without inheritance). - */public void filterOutThroughExcludeWithNoInheritance() { - Connection connection = null; - Statement st = null; - - try { - Class.forName(this.driver); - connection = DriverManager.getConnection(this.jurl, this.username, this.password); - - String countryTableBuilding = "create memory table COUNTRY(ID varchar(256) not null, NAME varchar(256), CONTINENT varchar(256), primary key (ID))"; - st = connection.createStatement(); - st.execute(countryTableBuilding); - - String residenceTableBuilding = - "create memory table RESIDENCE(ID varchar(256) not null, CITY varchar(256), COUNTRY varchar(256), " + - "primary key (ID), foreign key (COUNTRY) references COUNTRY(ID))"; - st.execute(residenceTableBuilding); - - String managerTableBuilding = "create memory table MANAGER(ID varchar(256) not null, NAME varchar(256), PROJECT varchar(256), primary key (ID))"; - st.execute(managerTableBuilding); - - String employeeTableBuilding = - "create memory table EMPLOYEE (ID varchar(256) not null," + - " NAME varchar(256), SALARY decimal(10,2), RESIDENCE varchar(256), MANAGER varchar(256), " + - "primary key (id), foreign key (RESIDENCE) references RESIDENCE(ID), foreign key (MANAGER) references MANAGER(ID))"; - st.execute(employeeTableBuilding); - - // Records Inserting - - String countryFilling = "insert into COUNTRY (ID,NAME,CONTINENT) values (" + "('C001','Italy','Europe'))"; - st.execute(countryFilling); - - String residenceFilling = "insert into RESIDENCE (ID,CITY,COUNTRY) values (" + "('R001','Rome','C001')," + "('R002','Milan','C001'))"; - st.execute(residenceFilling); - - String managerFilling = "insert into MANAGER (ID,NAME,PROJECT) values (" + "('M001','Bill Right','New World'))"; - st.execute(managerFilling); - - String employeeFilling = - "insert into EMPLOYEE (ID,NAME,SALARY,RESIDENCE,MANAGER) values (" + - "('E001','John Black',1500.00,'R001',null)," + - "('E002','Andrew Brown','1000.00','R001','M001')," + - "('E003','Jack Johnson',2000.00,'R002',null))"; - st.execute(employeeFilling); - - List excludedTables = new ArrayList(); - excludedTables.add("RESIDENCE"); - - this.mapper = new ER2GraphMapper(dataSource, null, excludedTables, dbQueryEngine, dataTypeHandler, executionStrategy, nameResolver, statistics); - - mapper.buildSourceDatabaseSchema(); - mapper.buildGraphModel(new JavaConventionNameResolver()); - - /* - * Testing context information - */ - - assertEquals(3, statistics.totalNumberOfEntities); - assertEquals(3, statistics.builtEntities); - assertEquals(1, statistics.totalNumberOfRelationships); - assertEquals(1, statistics.builtRelationships); - - assertEquals(3, statistics.totalNumberOfModelVertices); - assertEquals(3, statistics.builtModelVertexTypes); - assertEquals(1, statistics.totalNumberOfModelEdges); - assertEquals(1, statistics.builtModelEdgeTypes); - - /* - * Testing built source db schema - */ - - Entity employeeEntity = mapper.getDataBaseSchema().getEntityByName("EMPLOYEE"); - Entity countryEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("COUNTRY"); - Entity managerEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("MANAGER"); - Entity residenceEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("RESIDENCE"); - - // entities check - assertEquals(3, mapper.getDataBaseSchema().getEntities().size()); - assertEquals(1, mapper.getDataBaseSchema().getCanonicalRelationships().size()); - assertNotNull(employeeEntity); - assertNotNull(countryEntity); - assertNotNull(managerEntity); - assertNull(residenceEntity); - - // attributes check - assertEquals(5, employeeEntity.getAttributes().size()); - - assertNotNull(employeeEntity.getAttributeByName("ID")); - assertEquals("ID", employeeEntity.getAttributeByName("ID").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("ID").getDataType()); - assertEquals(1, employeeEntity.getAttributeByName("ID").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(employeeEntity.getAttributeByName("NAME")); - assertEquals("NAME", employeeEntity.getAttributeByName("NAME").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("NAME").getDataType()); - assertEquals(2, employeeEntity.getAttributeByName("NAME").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(employeeEntity.getAttributeByName("SALARY")); - assertEquals("SALARY", employeeEntity.getAttributeByName("SALARY").getName()); - assertEquals("DECIMAL", employeeEntity.getAttributeByName("SALARY").getDataType()); - assertEquals(3, employeeEntity.getAttributeByName("SALARY").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("SALARY").getBelongingEntity().getName()); - - assertNotNull(employeeEntity.getAttributeByName("RESIDENCE")); - assertEquals("RESIDENCE", employeeEntity.getAttributeByName("RESIDENCE").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("RESIDENCE").getDataType()); - assertEquals(4, employeeEntity.getAttributeByName("RESIDENCE").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("RESIDENCE").getBelongingEntity().getName()); - - assertNotNull(employeeEntity.getAttributeByName("MANAGER")); - assertEquals("MANAGER", employeeEntity.getAttributeByName("MANAGER").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("MANAGER").getDataType()); - assertEquals(5, employeeEntity.getAttributeByName("MANAGER").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("MANAGER").getBelongingEntity().getName()); - - assertEquals(3, countryEntity.getAttributes().size()); - - assertNotNull(countryEntity.getAttributeByName("ID")); - assertEquals("ID", countryEntity.getAttributeByName("ID").getName()); - assertEquals("VARCHAR", countryEntity.getAttributeByName("ID").getDataType()); - assertEquals(1, countryEntity.getAttributeByName("ID").getOrdinalPosition()); - assertEquals("COUNTRY", countryEntity.getAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(countryEntity.getAttributeByName("NAME")); - assertEquals("NAME", countryEntity.getAttributeByName("NAME").getName()); - assertEquals("VARCHAR", countryEntity.getAttributeByName("NAME").getDataType()); - assertEquals(2, countryEntity.getAttributeByName("NAME").getOrdinalPosition()); - assertEquals("COUNTRY", countryEntity.getAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(countryEntity.getAttributeByName("CONTINENT")); - assertEquals("CONTINENT", countryEntity.getAttributeByName("CONTINENT").getName()); - assertEquals("VARCHAR", countryEntity.getAttributeByName("CONTINENT").getDataType()); - assertEquals(3, countryEntity.getAttributeByName("CONTINENT").getOrdinalPosition()); - assertEquals("COUNTRY", countryEntity.getAttributeByName("CONTINENT").getBelongingEntity().getName()); - - assertEquals(3, managerEntity.getAttributes().size()); - - assertNotNull(managerEntity.getAttributeByName("ID")); - assertEquals("ID", managerEntity.getAttributeByName("ID").getName()); - assertEquals("VARCHAR", managerEntity.getAttributeByName("ID").getDataType()); - assertEquals(1, managerEntity.getAttributeByName("ID").getOrdinalPosition()); - assertEquals("MANAGER", managerEntity.getAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(managerEntity.getAttributeByName("NAME")); - assertEquals("NAME", managerEntity.getAttributeByName("NAME").getName()); - assertEquals("VARCHAR", managerEntity.getAttributeByName("NAME").getDataType()); - assertEquals(2, managerEntity.getAttributeByName("NAME").getOrdinalPosition()); - assertEquals("MANAGER", managerEntity.getAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(managerEntity.getAttributeByName("PROJECT")); - assertEquals("PROJECT", managerEntity.getAttributeByName("PROJECT").getName()); - assertEquals("VARCHAR", managerEntity.getAttributeByName("PROJECT").getDataType()); - assertEquals(3, managerEntity.getAttributeByName("PROJECT").getOrdinalPosition()); - assertEquals("MANAGER", managerEntity.getAttributeByName("PROJECT").getBelongingEntity().getName()); - - // relationship, primary and foreign key check - assertEquals(1, employeeEntity.getOutCanonicalRelationships().size()); - assertEquals(0, managerEntity.getOutCanonicalRelationships().size()); - assertEquals(0, employeeEntity.getInCanonicalRelationships().size()); - assertEquals(1, managerEntity.getInCanonicalRelationships().size()); - assertEquals(1, employeeEntity.getForeignKeys().size()); - - Iterator itEmp = employeeEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship currentEmpRel = itEmp.next(); - assertEquals("MANAGER", currentEmpRel.getParentEntity().getName()); - assertEquals("EMPLOYEE", currentEmpRel.getForeignEntity().getName()); - assertEquals(managerEntity.getPrimaryKey(), currentEmpRel.getPrimaryKey()); - assertEquals(employeeEntity.getForeignKeys().get(0), currentEmpRel.getForeignKey()); - assertFalse(itEmp.hasNext()); - - Iterator itManager = managerEntity.getInCanonicalRelationships().iterator(); - CanonicalRelationship currentManRel = itManager.next(); - assertEquals(currentEmpRel, currentManRel); - - /* - * Testing built graph model - */ - - VertexType employeeVertexType = mapper.getGraphModel().getVertexTypeByName("Employee"); - VertexType countryVertexType = mapper.getGraphModel().getVertexTypeByName("Country"); - VertexType managerVertexType = mapper.getGraphModel().getVertexTypeByName("Manager"); - VertexType residenceVertexType = mapper.getGraphModel().getVertexTypeByName("Residence"); - - // vertices check - assertEquals(3, mapper.getGraphModel().getVerticesType().size()); - assertNotNull(employeeVertexType); - assertNotNull(countryVertexType); - assertNotNull(managerVertexType); - assertNull(residenceVertexType); - - // properties check - assertEquals(5, employeeVertexType.getProperties().size()); - - assertNotNull(employeeVertexType.getPropertyByName("id")); - assertEquals("id", employeeVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, employeeVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, employeeVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(employeeVertexType.getPropertyByName("name")); - assertEquals("name", employeeVertexType.getPropertyByName("name").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("name").getOriginalType()); - assertEquals(2, employeeVertexType.getPropertyByName("name").getOrdinalPosition()); - assertEquals(false, employeeVertexType.getPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(employeeVertexType.getPropertyByName("salary")); - assertEquals("salary", employeeVertexType.getPropertyByName("salary").getName()); - assertEquals("DECIMAL", employeeVertexType.getPropertyByName("salary").getOriginalType()); - assertEquals(3, employeeVertexType.getPropertyByName("salary").getOrdinalPosition()); - assertEquals(false, employeeVertexType.getPropertyByName("salary").isFromPrimaryKey()); - - assertNotNull(employeeVertexType.getPropertyByName("residence")); - assertEquals("residence", employeeVertexType.getPropertyByName("residence").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("residence").getOriginalType()); - assertEquals(4, employeeVertexType.getPropertyByName("residence").getOrdinalPosition()); - assertEquals(false, employeeVertexType.getPropertyByName("residence").isFromPrimaryKey()); - - assertNotNull(employeeVertexType.getPropertyByName("manager")); - assertEquals("manager", employeeVertexType.getPropertyByName("manager").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("manager").getOriginalType()); - assertEquals(5, employeeVertexType.getPropertyByName("manager").getOrdinalPosition()); - assertEquals(false, employeeVertexType.getPropertyByName("manager").isFromPrimaryKey()); - - assertEquals(3, countryVertexType.getProperties().size()); - - assertNotNull(countryVertexType.getPropertyByName("id")); - assertEquals("id", countryVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", countryVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, countryVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, countryVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(countryVertexType.getPropertyByName("name")); - assertEquals("name", countryVertexType.getPropertyByName("name").getName()); - assertEquals("VARCHAR", countryVertexType.getPropertyByName("name").getOriginalType()); - assertEquals(2, countryVertexType.getPropertyByName("name").getOrdinalPosition()); - assertEquals(false, countryVertexType.getPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(countryVertexType.getPropertyByName("continent")); - assertEquals("continent", countryVertexType.getPropertyByName("continent").getName()); - assertEquals("VARCHAR", countryVertexType.getPropertyByName("continent").getOriginalType()); - assertEquals(3, countryVertexType.getPropertyByName("continent").getOrdinalPosition()); - assertEquals(false, countryVertexType.getPropertyByName("continent").isFromPrimaryKey()); - - assertEquals(3, managerVertexType.getProperties().size()); - - assertNotNull(managerVertexType.getPropertyByName("id")); - assertEquals("id", managerVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", managerVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, managerVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, managerVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(managerVertexType.getPropertyByName("name")); - assertEquals("name", managerVertexType.getPropertyByName("name").getName()); - assertEquals("VARCHAR", managerVertexType.getPropertyByName("name").getOriginalType()); - assertEquals(2, managerVertexType.getPropertyByName("name").getOrdinalPosition()); - assertEquals(false, managerVertexType.getPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(managerVertexType.getPropertyByName("project")); - assertEquals("project", managerVertexType.getPropertyByName("project").getName()); - assertEquals("VARCHAR", managerVertexType.getPropertyByName("project").getOriginalType()); - assertEquals(3, managerVertexType.getPropertyByName("project").getOrdinalPosition()); - assertEquals(false, managerVertexType.getPropertyByName("project").isFromPrimaryKey()); - - // edges check - - assertEquals(1, mapper.getRelationship2edgeType().size()); - - assertEquals(1, mapper.getGraphModel().getEdgesType().size()); - assertEquals("HasManager", mapper.getGraphModel().getEdgesType().get(0).getName()); - - assertEquals(1, employeeVertexType.getOutEdgesType().size()); - assertEquals("HasManager", employeeVertexType.getOutEdgesType().get(0).getName()); - - /* - * Rules check - */ - - // Classes Mapping - - assertEquals(3, mapper.getVertexType2EVClassMappers().size()); - assertEquals(3, mapper.getEntity2EVClassMappers().size()); - - assertEquals(1, mapper.getEVClassMappersByVertex(employeeVertexType).size()); - EVClassMapper employeeClassMapper = mapper.getEVClassMappersByVertex(employeeVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(employeeEntity).size()); - assertEquals(employeeClassMapper, mapper.getEVClassMappersByEntity(employeeEntity).get(0)); - assertEquals(employeeClassMapper.getEntity(), employeeEntity); - assertEquals(employeeClassMapper.getVertexType(), employeeVertexType); - - assertEquals(5, employeeClassMapper.getAttribute2property().size()); - assertEquals(5, employeeClassMapper.getProperty2attribute().size()); - assertEquals("id", employeeClassMapper.getAttribute2property().get("ID")); - assertEquals("name", employeeClassMapper.getAttribute2property().get("NAME")); - assertEquals("salary", employeeClassMapper.getAttribute2property().get("SALARY")); - assertEquals("residence", employeeClassMapper.getAttribute2property().get("RESIDENCE")); - assertEquals("manager", employeeClassMapper.getAttribute2property().get("MANAGER")); - assertEquals("ID", employeeClassMapper.getProperty2attribute().get("id")); - assertEquals("NAME", employeeClassMapper.getProperty2attribute().get("name")); - assertEquals("SALARY", employeeClassMapper.getProperty2attribute().get("salary")); - assertEquals("RESIDENCE", employeeClassMapper.getProperty2attribute().get("residence")); - assertEquals("MANAGER", employeeClassMapper.getProperty2attribute().get("manager")); - - assertEquals(1, mapper.getEVClassMappersByVertex(countryVertexType).size()); - EVClassMapper countryClassMapper = mapper.getEVClassMappersByVertex(countryVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(countryEntity).size()); - assertEquals(countryClassMapper, mapper.getEVClassMappersByEntity(countryEntity).get(0)); - assertEquals(countryClassMapper.getEntity(), countryEntity); - assertEquals(countryClassMapper.getVertexType(), countryVertexType); - - assertEquals(3, countryClassMapper.getAttribute2property().size()); - assertEquals(3, countryClassMapper.getProperty2attribute().size()); - assertEquals("id", countryClassMapper.getAttribute2property().get("ID")); - assertEquals("name", countryClassMapper.getAttribute2property().get("NAME")); - assertEquals("continent", countryClassMapper.getAttribute2property().get("CONTINENT")); - assertEquals("ID", countryClassMapper.getProperty2attribute().get("id")); - assertEquals("NAME", countryClassMapper.getProperty2attribute().get("name")); - assertEquals("CONTINENT", countryClassMapper.getProperty2attribute().get("continent")); - - assertEquals(1, mapper.getEVClassMappersByVertex(managerVertexType).size()); - EVClassMapper managerClassMapper = mapper.getEVClassMappersByVertex(managerVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(managerEntity).size()); - assertEquals(managerClassMapper, mapper.getEVClassMappersByEntity(managerEntity).get(0)); - assertEquals(managerClassMapper.getEntity(), managerEntity); - assertEquals(managerClassMapper.getVertexType(), managerVertexType); - - assertEquals(3, managerClassMapper.getAttribute2property().size()); - assertEquals(3, managerClassMapper.getProperty2attribute().size()); - assertEquals("id", managerClassMapper.getAttribute2property().get("ID")); - assertEquals("name", managerClassMapper.getAttribute2property().get("NAME")); - assertEquals("project", managerClassMapper.getAttribute2property().get("PROJECT")); - assertEquals("ID", managerClassMapper.getProperty2attribute().get("id")); - assertEquals("NAME", managerClassMapper.getProperty2attribute().get("name")); - assertEquals("PROJECT", managerClassMapper.getProperty2attribute().get("project")); - - // Relationships-Edges Mapping - - Iterator it = employeeEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship hasManagerRelationship = it.next(); - assertFalse(it.hasNext()); - - EdgeType hasManagerEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasManager"); - - assertEquals(1, mapper.getRelationship2edgeType().size()); - assertEquals(hasManagerEdgeType, mapper.getRelationship2edgeType().get(hasManagerRelationship)); - - assertEquals(1, mapper.getEdgeType2relationships().size()); - assertEquals(1, mapper.getEdgeType2relationships().get(hasManagerEdgeType).size()); - assertTrue(mapper.getEdgeType2relationships().get(hasManagerEdgeType).contains(hasManagerRelationship)); - - // JoinVertexes-AggregatorEdges Mapping - - assertEquals(0, mapper.getJoinVertex2aggregatorEdges().size()); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } finally { - try { - // Dropping Source DB Schema and OrientGraph - String dbDropping = "drop schema public cascade"; - st.execute(dbDropping); - connection.close(); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } - } + } + + /* + * Filtering out a table through exclude-tables (without inheritance). + */ @Test + void filterOutThroughExcludeWithNoInheritance() { + Connection connection = null; + Statement st = null; + + try { + Class.forName(this.driver); + connection = DriverManager.getConnection(this.jurl, this.username, this.password); + + String countryTableBuilding = + "create memory table COUNTRY(ID varchar(256) not null, NAME varchar(256), CONTINENT" + + " varchar(256), primary key (ID))"; + st = connection.createStatement(); + st.execute(countryTableBuilding); + + String residenceTableBuilding = + "create memory table RESIDENCE(ID varchar(256) not null, CITY varchar(256), COUNTRY" + + " varchar(256), primary key (ID), foreign key (COUNTRY) references COUNTRY(ID))"; + st.execute(residenceTableBuilding); + + String managerTableBuilding = + "create memory table MANAGER(ID varchar(256) not null, NAME varchar(256), PROJECT" + + " varchar(256), primary key (ID))"; + st.execute(managerTableBuilding); + + String employeeTableBuilding = + "create memory table EMPLOYEE (ID varchar(256) not null, NAME varchar(256), SALARY" + + " decimal(10,2), RESIDENCE varchar(256), MANAGER varchar(256), primary key (id)," + + " foreign key (RESIDENCE) references RESIDENCE(ID), foreign key (MANAGER)" + + " references MANAGER(ID))"; + st.execute(employeeTableBuilding); + + // Records Inserting + + String countryFilling = + "insert into COUNTRY (ID,NAME,CONTINENT) values (" + "('C001','Italy','Europe'))"; + st.execute(countryFilling); + + String residenceFilling = + "insert into RESIDENCE (ID,CITY,COUNTRY) values (" + + "('R001','Rome','C001')," + + "('R002','Milan','C001'))"; + st.execute(residenceFilling); + + String managerFilling = + "insert into MANAGER (ID,NAME,PROJECT) values (" + "('M001','Bill Right','New World'))"; + st.execute(managerFilling); + + String employeeFilling = + "insert into EMPLOYEE (ID,NAME,SALARY,RESIDENCE,MANAGER) values (" + + "('E001','John Black',1500.00,'R001',null)," + + "('E002','Andrew Brown','1000.00','R001','M001')," + + "('E003','Jack Johnson',2000.00,'R002',null))"; + st.execute(employeeFilling); + + List excludedTables = new ArrayList(); + excludedTables.add("RESIDENCE"); + + this.mapper = + new ER2GraphMapper( + dataSource, + null, + excludedTables, + dbQueryEngine, + dataTypeHandler, + executionStrategy, + nameResolver, + statistics); + + mapper.buildSourceDatabaseSchema(); + mapper.buildGraphModel(new JavaConventionNameResolver()); + + /* + * Testing context information + */ + + assertThat(statistics.totalNumberOfEntities).isEqualTo(3); + assertThat(statistics.builtEntities).isEqualTo(3); + assertThat(statistics.totalNumberOfRelationships).isEqualTo(1); + assertThat(statistics.builtRelationships).isEqualTo(1); + + assertThat(statistics.totalNumberOfModelVertices).isEqualTo(3); + assertThat(statistics.builtModelVertexTypes).isEqualTo(3); + assertThat(statistics.totalNumberOfModelEdges).isEqualTo(1); + assertThat(statistics.builtModelEdgeTypes).isEqualTo(1); + + /* + * Testing built source db schema + */ + + Entity employeeEntity = mapper.getDataBaseSchema().getEntityByName("EMPLOYEE"); + Entity countryEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("COUNTRY"); + Entity managerEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("MANAGER"); + Entity residenceEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("RESIDENCE"); + + // entities check + assertThat(mapper.getDataBaseSchema().getEntities().size()).isEqualTo(3); + assertThat(mapper.getDataBaseSchema().getCanonicalRelationships().size()).isEqualTo(1); + assertThat(employeeEntity).isNotNull(); + assertThat(countryEntity).isNotNull(); + assertThat(managerEntity).isNotNull(); + assertThat(residenceEntity).isNull(); + + // attributes check + assertThat(employeeEntity.getAttributes().size()).isEqualTo(5); + + assertThat(employeeEntity.getAttributeByName("ID")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(employeeEntity.getAttributeByName("ID").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("ID").getOrdinalPosition()).isEqualTo(1); + assertThat(employeeEntity.getAttributeByName("ID").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(employeeEntity.getAttributeByName("NAME")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("NAME").getName()).isEqualTo("NAME"); + assertThat(employeeEntity.getAttributeByName("NAME").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("NAME").getOrdinalPosition()).isEqualTo(2); + assertThat(employeeEntity.getAttributeByName("NAME").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(employeeEntity.getAttributeByName("SALARY")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("SALARY").getName()).isEqualTo("SALARY"); + assertThat(employeeEntity.getAttributeByName("SALARY").getDataType()).isEqualTo("DECIMAL"); + assertThat(employeeEntity.getAttributeByName("SALARY").getOrdinalPosition()).isEqualTo(3); + assertThat(employeeEntity.getAttributeByName("SALARY").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(employeeEntity.getAttributeByName("RESIDENCE")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getName()).isEqualTo("RESIDENCE"); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getOrdinalPosition()).isEqualTo(4); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(employeeEntity.getAttributeByName("MANAGER")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("MANAGER").getName()).isEqualTo("MANAGER"); + assertThat(employeeEntity.getAttributeByName("MANAGER").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("MANAGER").getOrdinalPosition()).isEqualTo(5); + assertThat(employeeEntity.getAttributeByName("MANAGER").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(countryEntity.getAttributes().size()).isEqualTo(3); + + assertThat(countryEntity.getAttributeByName("ID")).isNotNull(); + assertThat(countryEntity.getAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(countryEntity.getAttributeByName("ID").getDataType()).isEqualTo("VARCHAR"); + assertThat(countryEntity.getAttributeByName("ID").getOrdinalPosition()).isEqualTo(1); + assertThat(countryEntity.getAttributeByName("ID").getBelongingEntity().getName()) + .isEqualTo("COUNTRY"); + + assertThat(countryEntity.getAttributeByName("NAME")).isNotNull(); + assertThat(countryEntity.getAttributeByName("NAME").getName()).isEqualTo("NAME"); + assertThat(countryEntity.getAttributeByName("NAME").getDataType()).isEqualTo("VARCHAR"); + assertThat(countryEntity.getAttributeByName("NAME").getOrdinalPosition()).isEqualTo(2); + assertThat(countryEntity.getAttributeByName("NAME").getBelongingEntity().getName()) + .isEqualTo("COUNTRY"); + + assertThat(countryEntity.getAttributeByName("CONTINENT")).isNotNull(); + assertThat(countryEntity.getAttributeByName("CONTINENT").getName()).isEqualTo("CONTINENT"); + assertThat(countryEntity.getAttributeByName("CONTINENT").getDataType()).isEqualTo("VARCHAR"); + assertThat(countryEntity.getAttributeByName("CONTINENT").getOrdinalPosition()).isEqualTo(3); + assertThat(countryEntity.getAttributeByName("CONTINENT").getBelongingEntity().getName()) + .isEqualTo("COUNTRY"); + + assertThat(managerEntity.getAttributes().size()).isEqualTo(3); + + assertThat(managerEntity.getAttributeByName("ID")).isNotNull(); + assertThat(managerEntity.getAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(managerEntity.getAttributeByName("ID").getDataType()).isEqualTo("VARCHAR"); + assertThat(managerEntity.getAttributeByName("ID").getOrdinalPosition()).isEqualTo(1); + assertThat(managerEntity.getAttributeByName("ID").getBelongingEntity().getName()) + .isEqualTo("MANAGER"); + + assertThat(managerEntity.getAttributeByName("NAME")).isNotNull(); + assertThat(managerEntity.getAttributeByName("NAME").getName()).isEqualTo("NAME"); + assertThat(managerEntity.getAttributeByName("NAME").getDataType()).isEqualTo("VARCHAR"); + assertThat(managerEntity.getAttributeByName("NAME").getOrdinalPosition()).isEqualTo(2); + assertThat(managerEntity.getAttributeByName("NAME").getBelongingEntity().getName()) + .isEqualTo("MANAGER"); + + assertThat(managerEntity.getAttributeByName("PROJECT")).isNotNull(); + assertThat(managerEntity.getAttributeByName("PROJECT").getName()).isEqualTo("PROJECT"); + assertThat(managerEntity.getAttributeByName("PROJECT").getDataType()).isEqualTo("VARCHAR"); + assertThat(managerEntity.getAttributeByName("PROJECT").getOrdinalPosition()).isEqualTo(3); + assertThat(managerEntity.getAttributeByName("PROJECT").getBelongingEntity().getName()) + .isEqualTo("MANAGER"); + + // relationship, primary and foreign key check + assertThat(employeeEntity.getOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(managerEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(employeeEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(managerEntity.getInCanonicalRelationships().size()).isEqualTo(1); + assertThat(employeeEntity.getForeignKeys().size()).isEqualTo(1); + + Iterator itEmp = + employeeEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship currentEmpRel = itEmp.next(); + assertThat(currentEmpRel.getParentEntity().getName()).isEqualTo("MANAGER"); + assertThat(currentEmpRel.getForeignEntity().getName()).isEqualTo("EMPLOYEE"); + assertThat(currentEmpRel.getPrimaryKey()).isEqualTo(managerEntity.getPrimaryKey()); + assertThat(currentEmpRel.getForeignKey()).isEqualTo(employeeEntity.getForeignKeys().get(0)); + assertThat(itEmp.hasNext()).isFalse(); + + Iterator itManager = + managerEntity.getInCanonicalRelationships().iterator(); + CanonicalRelationship currentManRel = itManager.next(); + assertThat(currentManRel).isEqualTo(currentEmpRel); + + /* + * Testing built graph model + */ + + VertexType employeeVertexType = mapper.getGraphModel().getVertexTypeByName("Employee"); + VertexType countryVertexType = mapper.getGraphModel().getVertexTypeByName("Country"); + VertexType managerVertexType = mapper.getGraphModel().getVertexTypeByName("Manager"); + VertexType residenceVertexType = mapper.getGraphModel().getVertexTypeByName("Residence"); + + // vertices check + assertThat(mapper.getGraphModel().getVerticesType().size()).isEqualTo(3); + assertThat(employeeVertexType).isNotNull(); + assertThat(countryVertexType).isNotNull(); + assertThat(managerVertexType).isNotNull(); + assertThat(residenceVertexType).isNull(); + + // properties check + assertThat(employeeVertexType.getProperties().size()).isEqualTo(5); + + assertThat(employeeVertexType.getPropertyByName("id")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(employeeVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(employeeVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(employeeVertexType.getPropertyByName("name")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("name").getName()).isEqualTo("name"); + assertThat(employeeVertexType.getPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("name").getOrdinalPosition()).isEqualTo(2); + assertThat(employeeVertexType.getPropertyByName("name").isFromPrimaryKey()).isFalse(); + + assertThat(employeeVertexType.getPropertyByName("salary")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("salary").getName()).isEqualTo("salary"); + assertThat(employeeVertexType.getPropertyByName("salary").getOriginalType()) + .isEqualTo("DECIMAL"); + assertThat(employeeVertexType.getPropertyByName("salary").getOrdinalPosition()).isEqualTo(3); + assertThat(employeeVertexType.getPropertyByName("salary").isFromPrimaryKey()).isFalse(); + + assertThat(employeeVertexType.getPropertyByName("residence")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("residence").getName()) + .isEqualTo("residence"); + assertThat(employeeVertexType.getPropertyByName("residence").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("residence").getOrdinalPosition()) + .isEqualTo(4); + assertThat(employeeVertexType.getPropertyByName("residence").isFromPrimaryKey()).isFalse(); + + assertThat(employeeVertexType.getPropertyByName("manager")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("manager").getName()).isEqualTo("manager"); + assertThat(employeeVertexType.getPropertyByName("manager").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("manager").getOrdinalPosition()).isEqualTo(5); + assertThat(employeeVertexType.getPropertyByName("manager").isFromPrimaryKey()).isFalse(); + + assertThat(countryVertexType.getProperties().size()).isEqualTo(3); + + assertThat(countryVertexType.getPropertyByName("id")).isNotNull(); + assertThat(countryVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(countryVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(countryVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(countryVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(countryVertexType.getPropertyByName("name")).isNotNull(); + assertThat(countryVertexType.getPropertyByName("name").getName()).isEqualTo("name"); + assertThat(countryVertexType.getPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(countryVertexType.getPropertyByName("name").getOrdinalPosition()).isEqualTo(2); + assertThat(countryVertexType.getPropertyByName("name").isFromPrimaryKey()).isFalse(); + + assertThat(countryVertexType.getPropertyByName("continent")).isNotNull(); + assertThat(countryVertexType.getPropertyByName("continent").getName()).isEqualTo("continent"); + assertThat(countryVertexType.getPropertyByName("continent").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(countryVertexType.getPropertyByName("continent").getOrdinalPosition()) + .isEqualTo(3); + assertThat(countryVertexType.getPropertyByName("continent").isFromPrimaryKey()).isFalse(); + + assertThat(managerVertexType.getProperties().size()).isEqualTo(3); + + assertThat(managerVertexType.getPropertyByName("id")).isNotNull(); + assertThat(managerVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(managerVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(managerVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(managerVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(managerVertexType.getPropertyByName("name")).isNotNull(); + assertThat(managerVertexType.getPropertyByName("name").getName()).isEqualTo("name"); + assertThat(managerVertexType.getPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(managerVertexType.getPropertyByName("name").getOrdinalPosition()).isEqualTo(2); + assertThat(managerVertexType.getPropertyByName("name").isFromPrimaryKey()).isFalse(); + + assertThat(managerVertexType.getPropertyByName("project")).isNotNull(); + assertThat(managerVertexType.getPropertyByName("project").getName()).isEqualTo("project"); + assertThat(managerVertexType.getPropertyByName("project").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(managerVertexType.getPropertyByName("project").getOrdinalPosition()).isEqualTo(3); + assertThat(managerVertexType.getPropertyByName("project").isFromPrimaryKey()).isFalse(); + + // edges check + + assertThat(mapper.getRelationship2edgeType().size()).isEqualTo(1); + + assertThat(mapper.getGraphModel().getEdgesType().size()).isEqualTo(1); + assertThat(mapper.getGraphModel().getEdgesType().get(0).getName()).isEqualTo("HasManager"); + + assertThat(employeeVertexType.getOutEdgesType().size()).isEqualTo(1); + assertThat(employeeVertexType.getOutEdgesType().get(0).getName()).isEqualTo("HasManager"); + + /* + * Rules check + */ + + // Classes Mapping + + assertThat(mapper.getVertexType2EVClassMappers().size()).isEqualTo(3); + assertThat(mapper.getEntity2EVClassMappers().size()).isEqualTo(3); + + assertThat(mapper.getEVClassMappersByVertex(employeeVertexType).size()).isEqualTo(1); + EVClassMapper employeeClassMapper = + mapper.getEVClassMappersByVertex(employeeVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(employeeEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(employeeEntity).get(0)) + .isEqualTo(employeeClassMapper); + assertThat(employeeEntity).isEqualTo(employeeClassMapper.getEntity()); + assertThat(employeeVertexType).isEqualTo(employeeClassMapper.getVertexType()); + + assertThat(employeeClassMapper.getAttribute2property().size()).isEqualTo(5); + assertThat(employeeClassMapper.getProperty2attribute().size()).isEqualTo(5); + assertThat(employeeClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(employeeClassMapper.getAttribute2property().get("NAME")).isEqualTo("name"); + assertThat(employeeClassMapper.getAttribute2property().get("SALARY")).isEqualTo("salary"); + assertThat(employeeClassMapper.getAttribute2property().get("RESIDENCE")) + .isEqualTo("residence"); + assertThat(employeeClassMapper.getAttribute2property().get("MANAGER")).isEqualTo("manager"); + assertThat(employeeClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(employeeClassMapper.getProperty2attribute().get("name")).isEqualTo("NAME"); + assertThat(employeeClassMapper.getProperty2attribute().get("salary")).isEqualTo("SALARY"); + assertThat(employeeClassMapper.getProperty2attribute().get("residence")) + .isEqualTo("RESIDENCE"); + assertThat(employeeClassMapper.getProperty2attribute().get("manager")).isEqualTo("MANAGER"); + + assertThat(mapper.getEVClassMappersByVertex(countryVertexType).size()).isEqualTo(1); + EVClassMapper countryClassMapper = mapper.getEVClassMappersByVertex(countryVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(countryEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(countryEntity).get(0)) + .isEqualTo(countryClassMapper); + assertThat(countryEntity).isEqualTo(countryClassMapper.getEntity()); + assertThat(countryVertexType).isEqualTo(countryClassMapper.getVertexType()); + + assertThat(countryClassMapper.getAttribute2property().size()).isEqualTo(3); + assertThat(countryClassMapper.getProperty2attribute().size()).isEqualTo(3); + assertThat(countryClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(countryClassMapper.getAttribute2property().get("NAME")).isEqualTo("name"); + assertThat(countryClassMapper.getAttribute2property().get("CONTINENT")) + .isEqualTo("continent"); + assertThat(countryClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(countryClassMapper.getProperty2attribute().get("name")).isEqualTo("NAME"); + assertThat(countryClassMapper.getProperty2attribute().get("continent")) + .isEqualTo("CONTINENT"); + + assertThat(mapper.getEVClassMappersByVertex(managerVertexType).size()).isEqualTo(1); + EVClassMapper managerClassMapper = mapper.getEVClassMappersByVertex(managerVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(managerEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(managerEntity).get(0)) + .isEqualTo(managerClassMapper); + assertThat(managerEntity).isEqualTo(managerClassMapper.getEntity()); + assertThat(managerVertexType).isEqualTo(managerClassMapper.getVertexType()); + + assertThat(managerClassMapper.getAttribute2property().size()).isEqualTo(3); + assertThat(managerClassMapper.getProperty2attribute().size()).isEqualTo(3); + assertThat(managerClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(managerClassMapper.getAttribute2property().get("NAME")).isEqualTo("name"); + assertThat(managerClassMapper.getAttribute2property().get("PROJECT")).isEqualTo("project"); + assertThat(managerClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(managerClassMapper.getProperty2attribute().get("name")).isEqualTo("NAME"); + assertThat(managerClassMapper.getProperty2attribute().get("project")).isEqualTo("PROJECT"); + + // Relationships-Edges Mapping + + Iterator it = employeeEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship hasManagerRelationship = it.next(); + assertThat(it.hasNext()).isFalse(); + + EdgeType hasManagerEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasManager"); + + assertThat(mapper.getRelationship2edgeType().size()).isEqualTo(1); + assertThat(mapper.getRelationship2edgeType().get(hasManagerRelationship)) + .isEqualTo(hasManagerEdgeType); + + assertThat(mapper.getEdgeType2relationships().size()).isEqualTo(1); + assertThat(mapper.getEdgeType2relationships().get(hasManagerEdgeType).size()).isEqualTo(1); + assertThat( + mapper + .getEdgeType2relationships() + .get(hasManagerEdgeType) + .contains(hasManagerRelationship)) + .isTrue(); + + // JoinVertexes-AggregatorEdges Mapping + + assertThat(mapper.getJoinVertex2aggregatorEdges().size()).isEqualTo(0); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } finally { + try { + // Dropping Source DB Schema and OrientGraph + String dbDropping = "drop schema public cascade"; + st.execute(dbDropping); + connection.close(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } } - - @Test - /* - * Filtering out a table through include-tables (with Table per Hierarchy inheritance). - */public void filterOutThroughIncludeWithTablePerHierarchyInheritance() { - Connection connection = null; - Statement st = null; - - try { - Class.forName(this.driver); - connection = DriverManager.getConnection(this.jurl, this.username, this.password); - - String countryTableBuilding = "create memory table COUNTRY(ID varchar(256) not null, NAME varchar(256), CONTINENT varchar(256), primary key (ID))"; - st = connection.createStatement(); - st.execute(countryTableBuilding); - - String residenceTableBuilding = - "create memory table RESIDENCE(ID varchar(256) not null, CITY varchar(256), COUNTRY varchar(256), " + - "primary key (ID), foreign key (COUNTRY) references COUNTRY(ID))"; - st.execute(residenceTableBuilding); - - String managerTableBuilding = - "create memory table MANAGER(ID varchar(256) not null, TYPE varchar(256), NAME varchar(256), PROJECT varchar(256), primary key (ID))"; - st.execute(managerTableBuilding); - - String employeeTableBuilding = - "create memory table EMPLOYEE (ID varchar(256) not null," + - " TYPE varchar(256), NAME varchar(256), SALARY decimal(10,2), BONUS decimal(10,0), " + - "PAY_PER_HOUR decimal(10,2), CONTRACT_DURATION varchar(256), RESIDENCE varchar(256), MANAGER varchar(256), " + - "primary key (id), foreign key (RESIDENCE) references RESIDENCE(ID), foreign key (MANAGER) references MANAGER(ID))"; - st.execute(employeeTableBuilding); - - // Records Inserting - - String countryFilling = "insert into country (ID,NAME,CONTINENT) values (" + "('C001','Italy','Europe'))"; - st.execute(countryFilling); - - String residenceFilling = "insert into RESIDENCE (ID,CITY,COUNTRY) values (" + "('R001','Rome','C001')," + "('R002','Milan','C001'))"; - st.execute(residenceFilling); - - String managerFilling = "insert into MANAGER (ID,TYPE,NAME,PROJECT) values (" + "('M001','prj_mgr','Bill Right','New World'))"; - st.execute(managerFilling); - - String employeeFilling = - "insert into EMPLOYEE (ID,TYPE,NAME,SALARY,BONUS,PAY_PER_HOUR,CONTRACT_DURATION,RESIDENCE,MANAGER) values (" + - "('E001','emp','John Black',null,null,null,null,'R001',null)," + - "('E002','reg_emp','Andrew Brown','1000.00','10',null,null,'R001','M001')," + - "('E003','cont_emp','Jack Johnson',null,null,'50.00','6','R002',null))"; - st.execute(employeeFilling); - - List includedTables = new ArrayList(); - includedTables.add("COUNTRY"); - includedTables.add("MANAGER"); - includedTables.add("EMPLOYEE"); - - this.mapper = - new Hibernate2GraphMapper( - dataSource, - FilterTableMappingTest.XML_TABLE_PER_CLASS, - includedTables, - null, - dbQueryEngine, - dataTypeHandler, - executionStrategy, - nameResolver, - statistics - ); - mapper.buildSourceDatabaseSchema(); - mapper.buildGraphModel(new JavaConventionNameResolver()); - - /* - * Testing context information - */ - - assertEquals(3, statistics.totalNumberOfEntities); - assertEquals(3, statistics.builtEntities); - assertEquals(1, statistics.totalNumberOfRelationships); - assertEquals(1, statistics.builtRelationships); - - assertEquals(6, statistics.totalNumberOfModelVertices); - assertEquals(6, statistics.builtModelVertexTypes); - assertEquals(1, statistics.totalNumberOfModelEdges); - assertEquals(1, statistics.builtModelEdgeTypes); - - /* - * Testing built source db schema - */ - - Entity employeeEntity = mapper.getDataBaseSchema().getEntityByName("EMPLOYEE"); - Entity regularEmployeeEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("REGULAR_EMPLOYEE"); - Entity contractEmployeeEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("CONTRACT_EMPLOYEE"); - Entity countryEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("COUNTRY"); - Entity managerEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("MANAGER"); - Entity projectManagerEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("PROJECT_MANAGER"); - Entity residenceEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("RESIDENCE"); - - // entities check - assertEquals(6, mapper.getDataBaseSchema().getEntities().size()); - assertEquals(1, mapper.getDataBaseSchema().getCanonicalRelationships().size()); - assertNotNull(employeeEntity); - assertNotNull(regularEmployeeEntity); - assertNotNull(contractEmployeeEntity); - assertNotNull(countryEntity); - assertNotNull(managerEntity); - assertNull(residenceEntity); - - // attributes check - assertEquals(4, employeeEntity.getAttributes().size()); - - assertNotNull(employeeEntity.getAttributeByName("ID")); - assertEquals("ID", employeeEntity.getAttributeByName("ID").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("ID").getDataType()); - assertEquals(1, employeeEntity.getAttributeByName("ID").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(employeeEntity.getAttributeByName("NAME")); - assertEquals("NAME", employeeEntity.getAttributeByName("NAME").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("NAME").getDataType()); - assertEquals(2, employeeEntity.getAttributeByName("NAME").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(employeeEntity.getAttributeByName("RESIDENCE")); - assertEquals("RESIDENCE", employeeEntity.getAttributeByName("RESIDENCE").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("RESIDENCE").getDataType()); - assertEquals(3, employeeEntity.getAttributeByName("RESIDENCE").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("RESIDENCE").getBelongingEntity().getName()); - - assertNotNull(employeeEntity.getAttributeByName("MANAGER")); - assertEquals("MANAGER", employeeEntity.getAttributeByName("MANAGER").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("MANAGER").getDataType()); - assertEquals(4, employeeEntity.getAttributeByName("MANAGER").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("MANAGER").getBelongingEntity().getName()); - - assertEquals(2, regularEmployeeEntity.getAttributes().size()); - - assertNotNull(regularEmployeeEntity.getAttributeByName("SALARY")); - assertEquals("SALARY", regularEmployeeEntity.getAttributeByName("SALARY").getName()); - assertEquals("DECIMAL", regularEmployeeEntity.getAttributeByName("SALARY").getDataType()); - assertEquals(1, regularEmployeeEntity.getAttributeByName("SALARY").getOrdinalPosition()); - assertEquals("Regular_Employee", regularEmployeeEntity.getAttributeByName("SALARY").getBelongingEntity().getName()); - - assertNotNull(regularEmployeeEntity.getAttributeByName("BONUS")); - assertEquals("BONUS", regularEmployeeEntity.getAttributeByName("BONUS").getName()); - assertEquals("DECIMAL", regularEmployeeEntity.getAttributeByName("BONUS").getDataType()); - assertEquals(2, regularEmployeeEntity.getAttributeByName("BONUS").getOrdinalPosition()); - assertEquals("Regular_Employee", regularEmployeeEntity.getAttributeByName("BONUS").getBelongingEntity().getName()); - - assertEquals(2, contractEmployeeEntity.getAttributes().size()); - - assertNotNull(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR")); - assertEquals("PAY_PER_HOUR", contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getName()); - assertEquals("DECIMAL", contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getDataType()); - assertEquals(1, contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getOrdinalPosition()); - assertEquals("Contract_Employee", contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getBelongingEntity().getName()); - - assertNotNull(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION")); - assertEquals("CONTRACT_DURATION", contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getDataType()); - assertEquals(2, contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getOrdinalPosition()); - assertEquals("Contract_Employee", contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getBelongingEntity().getName()); - - assertEquals(3, countryEntity.getAttributes().size()); - - assertNotNull(countryEntity.getAttributeByName("ID")); - assertEquals("ID", countryEntity.getAttributeByName("ID").getName()); - assertEquals("VARCHAR", countryEntity.getAttributeByName("ID").getDataType()); - assertEquals(1, countryEntity.getAttributeByName("ID").getOrdinalPosition()); - assertEquals("COUNTRY", countryEntity.getAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(countryEntity.getAttributeByName("NAME")); - assertEquals("NAME", countryEntity.getAttributeByName("NAME").getName()); - assertEquals("VARCHAR", countryEntity.getAttributeByName("NAME").getDataType()); - assertEquals(2, countryEntity.getAttributeByName("NAME").getOrdinalPosition()); - assertEquals("COUNTRY", countryEntity.getAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(countryEntity.getAttributeByName("CONTINENT")); - assertEquals("CONTINENT", countryEntity.getAttributeByName("CONTINENT").getName()); - assertEquals("VARCHAR", countryEntity.getAttributeByName("CONTINENT").getDataType()); - assertEquals(3, countryEntity.getAttributeByName("CONTINENT").getOrdinalPosition()); - assertEquals("COUNTRY", countryEntity.getAttributeByName("CONTINENT").getBelongingEntity().getName()); - - assertEquals(2, managerEntity.getAttributes().size()); - - assertNotNull(managerEntity.getAttributeByName("ID")); - assertEquals("ID", managerEntity.getAttributeByName("ID").getName()); - assertEquals("VARCHAR", managerEntity.getAttributeByName("ID").getDataType()); - assertEquals(1, managerEntity.getAttributeByName("ID").getOrdinalPosition()); - assertEquals("MANAGER", managerEntity.getAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(managerEntity.getAttributeByName("NAME")); - assertEquals("NAME", managerEntity.getAttributeByName("NAME").getName()); - assertEquals("VARCHAR", managerEntity.getAttributeByName("NAME").getDataType()); - assertEquals(2, managerEntity.getAttributeByName("NAME").getOrdinalPosition()); - assertEquals("MANAGER", managerEntity.getAttributeByName("NAME").getBelongingEntity().getName()); - - assertEquals(1, projectManagerEntity.getAttributes().size()); - - assertNotNull(projectManagerEntity.getAttributeByName("PROJECT")); - assertEquals("PROJECT", projectManagerEntity.getAttributeByName("PROJECT").getName()); - assertEquals("VARCHAR", projectManagerEntity.getAttributeByName("PROJECT").getDataType()); - assertEquals(1, projectManagerEntity.getAttributeByName("PROJECT").getOrdinalPosition()); - assertEquals("Project_Manager", projectManagerEntity.getAttributeByName("PROJECT").getBelongingEntity().getName()); - - // inherited attributes check - assertEquals(0, employeeEntity.getInheritedAttributes().size()); - - assertEquals(4, regularEmployeeEntity.getInheritedAttributes().size()); - - assertNotNull(regularEmployeeEntity.getInheritedAttributeByName("ID")); - assertEquals("ID", regularEmployeeEntity.getInheritedAttributeByName("ID").getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getInheritedAttributeByName("ID").getDataType()); - assertEquals(1, regularEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()); - assertEquals("EMPLOYEE", regularEmployeeEntity.getInheritedAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(regularEmployeeEntity.getInheritedAttributeByName("NAME")); - assertEquals("NAME", regularEmployeeEntity.getInheritedAttributeByName("NAME").getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()); - assertEquals(2, regularEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()); - assertEquals("EMPLOYEE", regularEmployeeEntity.getInheritedAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE")); - assertEquals("RESIDENCE", regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()); - assertEquals(3, regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()); - assertEquals("EMPLOYEE", regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getBelongingEntity().getName()); - - assertNotNull(regularEmployeeEntity.getInheritedAttributeByName("MANAGER")); - assertEquals("MANAGER", regularEmployeeEntity.getInheritedAttributeByName("MANAGER").getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getInheritedAttributeByName("MANAGER").getDataType()); - assertEquals(4, regularEmployeeEntity.getInheritedAttributeByName("MANAGER").getOrdinalPosition()); - assertEquals("EMPLOYEE", regularEmployeeEntity.getInheritedAttributeByName("MANAGER").getBelongingEntity().getName()); - - assertEquals(4, contractEmployeeEntity.getInheritedAttributes().size()); - - assertNotNull(contractEmployeeEntity.getInheritedAttributeByName("ID")); - assertEquals("ID", contractEmployeeEntity.getInheritedAttributeByName("ID").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getInheritedAttributeByName("ID").getDataType()); - assertEquals(1, contractEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()); - assertEquals("EMPLOYEE", contractEmployeeEntity.getInheritedAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(contractEmployeeEntity.getInheritedAttributeByName("NAME")); - assertEquals("NAME", contractEmployeeEntity.getInheritedAttributeByName("NAME").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()); - assertEquals(2, contractEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()); - assertEquals("EMPLOYEE", contractEmployeeEntity.getInheritedAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE")); - assertEquals("RESIDENCE", contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()); - assertEquals(3, contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()); - assertEquals("EMPLOYEE", contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getBelongingEntity().getName()); - - assertNotNull(contractEmployeeEntity.getInheritedAttributeByName("MANAGER")); - assertEquals("MANAGER", contractEmployeeEntity.getInheritedAttributeByName("MANAGER").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getInheritedAttributeByName("MANAGER").getDataType()); - assertEquals(4, contractEmployeeEntity.getInheritedAttributeByName("MANAGER").getOrdinalPosition()); - assertEquals("EMPLOYEE", contractEmployeeEntity.getInheritedAttributeByName("MANAGER").getBelongingEntity().getName()); - - assertEquals(2, projectManagerEntity.getInheritedAttributes().size()); - - assertNotNull(projectManagerEntity.getInheritedAttributeByName("ID")); - assertEquals("ID", projectManagerEntity.getInheritedAttributeByName("ID").getName()); - assertEquals("VARCHAR", projectManagerEntity.getInheritedAttributeByName("ID").getDataType()); - assertEquals(1, projectManagerEntity.getInheritedAttributeByName("ID").getOrdinalPosition()); - assertEquals("MANAGER", projectManagerEntity.getInheritedAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(projectManagerEntity.getInheritedAttributeByName("NAME")); - assertEquals("NAME", projectManagerEntity.getInheritedAttributeByName("NAME").getName()); - assertEquals("VARCHAR", projectManagerEntity.getInheritedAttributeByName("NAME").getDataType()); - assertEquals(2, projectManagerEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()); - assertEquals("MANAGER", projectManagerEntity.getInheritedAttributeByName("NAME").getBelongingEntity().getName()); - - assertEquals(0, countryEntity.getInheritedAttributes().size()); - assertEquals(0, managerEntity.getInheritedAttributes().size()); - - // primary key check - assertEquals(1, regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()); - assertEquals("ID", regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()); - assertEquals("EMPLOYEE", regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getBelongingEntity().getName()); - - assertEquals(1, contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()); - assertEquals("ID", contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()); - assertEquals("EMPLOYEE", contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getBelongingEntity().getName()); - - assertEquals(1, projectManagerEntity.getPrimaryKey().getInvolvedAttributes().size()); - assertEquals("ID", projectManagerEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()); - assertEquals("VARCHAR", projectManagerEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()); - assertEquals("MANAGER", projectManagerEntity.getPrimaryKey().getInvolvedAttributes().get(0).getBelongingEntity().getName()); - - // relationship, primary and foreign key check - assertEquals(0, regularEmployeeEntity.getOutCanonicalRelationships().size()); - assertEquals(0, contractEmployeeEntity.getOutCanonicalRelationships().size()); - assertEquals(1, employeeEntity.getOutCanonicalRelationships().size()); - assertEquals(0, countryEntity.getOutCanonicalRelationships().size()); - assertEquals(0, managerEntity.getOutCanonicalRelationships().size()); - assertEquals(0, regularEmployeeEntity.getInCanonicalRelationships().size()); - assertEquals(0, contractEmployeeEntity.getInCanonicalRelationships().size()); - assertEquals(0, employeeEntity.getInCanonicalRelationships().size()); - assertEquals(0, countryEntity.getInCanonicalRelationships().size()); - assertEquals(1, managerEntity.getInCanonicalRelationships().size()); - - assertEquals(0, regularEmployeeEntity.getForeignKeys().size()); - assertEquals(0, contractEmployeeEntity.getForeignKeys().size()); - assertEquals(1, employeeEntity.getForeignKeys().size()); - assertEquals(0, countryEntity.getForeignKeys().size()); - assertEquals(0, managerEntity.getForeignKeys().size()); - - Iterator itEmp = employeeEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship currentEmpRel = itEmp.next(); - assertEquals("MANAGER", currentEmpRel.getParentEntity().getName()); - assertEquals("EMPLOYEE", currentEmpRel.getForeignEntity().getName()); - assertEquals(managerEntity.getPrimaryKey(), currentEmpRel.getPrimaryKey()); - assertEquals(employeeEntity.getForeignKeys().get(0), currentEmpRel.getForeignKey()); - assertFalse(itEmp.hasNext()); - - Iterator itManager = managerEntity.getInCanonicalRelationships().iterator(); - CanonicalRelationship currentManRel = itManager.next(); - assertEquals(currentEmpRel, currentManRel); - - // inherited relationships check - assertEquals(1, regularEmployeeEntity.getInheritedOutCanonicalRelationships().size()); - assertEquals(1, contractEmployeeEntity.getInheritedOutCanonicalRelationships().size()); - assertEquals(0, employeeEntity.getInheritedOutCanonicalRelationships().size()); - - Iterator itRegEmp = regularEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); - Iterator itContEmp = contractEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); - CanonicalRelationship currentRegEmpRel = itRegEmp.next(); - CanonicalRelationship currentContEmpRel = itContEmp.next(); - assertEquals("MANAGER", currentRegEmpRel.getParentEntity().getName()); - assertEquals("EMPLOYEE", currentRegEmpRel.getForeignEntity().getName()); - assertEquals("MANAGER", currentContEmpRel.getParentEntity().getName()); - assertEquals("EMPLOYEE", currentContEmpRel.getForeignEntity().getName()); - assertEquals(managerEntity.getPrimaryKey(), currentRegEmpRel.getPrimaryKey()); - assertEquals(1, currentRegEmpRel.getFromColumns().size()); - assertEquals("MANAGER", currentRegEmpRel.getFromColumns().get(0).getName()); - assertEquals(managerEntity.getPrimaryKey(), currentContEmpRel.getPrimaryKey()); - assertEquals(1, currentContEmpRel.getFromColumns().size()); - assertEquals("MANAGER", currentContEmpRel.getFromColumns().get(0).getName()); - assertFalse(itRegEmp.hasNext()); - assertFalse(itContEmp.hasNext()); - - // inheritance check - assertEquals(employeeEntity, regularEmployeeEntity.getParentEntity()); - assertEquals(employeeEntity, contractEmployeeEntity.getParentEntity()); - assertNull(employeeEntity.getParentEntity()); - - assertEquals(1, regularEmployeeEntity.getInheritanceLevel()); - assertEquals(1, contractEmployeeEntity.getInheritanceLevel()); - assertEquals(0, employeeEntity.getInheritanceLevel()); - - // Hierarchical Bag check - assertEquals(2, mapper.getDataBaseSchema().getHierarchicalBags().size()); - - HierarchicalBag hierarchicalBag1 = mapper.getDataBaseSchema().getHierarchicalBags().get(0); - HierarchicalBag hierarchicalBag2 = mapper.getDataBaseSchema().getHierarchicalBags().get(1); - assertEquals("table-per-hierarchy", hierarchicalBag1.getInheritancePattern()); - assertEquals("table-per-hierarchy", hierarchicalBag2.getInheritancePattern()); - - assertEquals(2, hierarchicalBag1.getDepth2entities().size()); - - assertEquals(1, hierarchicalBag1.getDepth2entities().get(0).size()); - Iterator it = hierarchicalBag1.getDepth2entities().get(0).iterator(); - assertEquals("EMPLOYEE", it.next().getName()); - assertTrue(!it.hasNext()); - - assertEquals(2, hierarchicalBag1.getDepth2entities().get(1).size()); - it = hierarchicalBag1.getDepth2entities().get(1).iterator(); - assertEquals("Regular_Employee", it.next().getName()); - assertEquals("Contract_Employee", it.next().getName()); - assertTrue(!it.hasNext()); - - assertEquals(hierarchicalBag1, employeeEntity.getHierarchicalBag()); - assertEquals(hierarchicalBag1, regularEmployeeEntity.getHierarchicalBag()); - assertEquals(hierarchicalBag1, contractEmployeeEntity.getHierarchicalBag()); - - assertNotNull(hierarchicalBag1.getDiscriminatorColumn()); - assertEquals("TYPE", hierarchicalBag1.getDiscriminatorColumn()); - - assertEquals(3, hierarchicalBag1.getEntityName2discriminatorValue().size()); - assertEquals("emp", hierarchicalBag1.getEntityName2discriminatorValue().get("EMPLOYEE")); - assertEquals("reg_emp", hierarchicalBag1.getEntityName2discriminatorValue().get("Regular_Employee")); - assertEquals("cont_emp", hierarchicalBag1.getEntityName2discriminatorValue().get("Contract_Employee")); - - assertEquals(2, hierarchicalBag2.getDepth2entities().size()); - - assertEquals(1, hierarchicalBag2.getDepth2entities().get(0).size()); - it = hierarchicalBag2.getDepth2entities().get(0).iterator(); - assertEquals("MANAGER", it.next().getName()); - assertTrue(!it.hasNext()); - - assertEquals(1, hierarchicalBag2.getDepth2entities().get(1).size()); - it = hierarchicalBag2.getDepth2entities().get(1).iterator(); - assertEquals("Project_Manager", it.next().getName()); - assertTrue(!it.hasNext()); - - assertEquals(hierarchicalBag2, managerEntity.getHierarchicalBag()); - assertEquals(hierarchicalBag2, projectManagerEntity.getHierarchicalBag()); - - assertNotNull(hierarchicalBag2.getDiscriminatorColumn()); - assertEquals("TYPE", hierarchicalBag2.getDiscriminatorColumn()); - - assertEquals(2, hierarchicalBag2.getEntityName2discriminatorValue().size()); - assertEquals("mgr", hierarchicalBag2.getEntityName2discriminatorValue().get("MANAGER")); - assertEquals("prj_mgr", hierarchicalBag2.getEntityName2discriminatorValue().get("Project_Manager")); - - /* - * Testing built graph model - */ - - VertexType employeeVertexType = mapper.getGraphModel().getVertexTypeByName("Employee"); - VertexType regularEmployeeVertexType = mapper.getGraphModel().getVertexTypeByName("RegularEmployee"); - VertexType contractEmployeeVertexType = mapper.getGraphModel().getVertexTypeByName("ContractEmployee"); - VertexType countryVertexType = mapper.getGraphModel().getVertexTypeByName("Country"); - VertexType managerVertexType = mapper.getGraphModel().getVertexTypeByName("Manager"); - VertexType projectManagerVertexType = mapper.getGraphModel().getVertexTypeByName("ProjectManager"); - VertexType residenceVertexType = mapper.getGraphModel().getVertexTypeByName("Residence"); - - // vertices check - assertEquals(6, mapper.getGraphModel().getVerticesType().size()); - assertNotNull(employeeVertexType); - assertNotNull(regularEmployeeVertexType); - assertNotNull(contractEmployeeVertexType); - assertNotNull(countryVertexType); - assertNotNull(managerVertexType); - assertNotNull(projectManagerVertexType); - assertNull(residenceVertexType); - - // properties check - assertEquals(4, employeeVertexType.getProperties().size()); - - assertNotNull(employeeVertexType.getPropertyByName("id")); - assertEquals("id", employeeVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, employeeVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, employeeVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(employeeVertexType.getPropertyByName("name")); - assertEquals("name", employeeVertexType.getPropertyByName("name").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("name").getOriginalType()); - assertEquals(2, employeeVertexType.getPropertyByName("name").getOrdinalPosition()); - assertEquals(false, employeeVertexType.getPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(employeeVertexType.getPropertyByName("residence")); - assertEquals("residence", employeeVertexType.getPropertyByName("residence").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("residence").getOriginalType()); - assertEquals(3, employeeVertexType.getPropertyByName("residence").getOrdinalPosition()); - assertEquals(false, employeeVertexType.getPropertyByName("residence").isFromPrimaryKey()); - - assertNotNull(employeeVertexType.getPropertyByName("manager")); - assertEquals("manager", employeeVertexType.getPropertyByName("manager").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("manager").getOriginalType()); - assertEquals(4, employeeVertexType.getPropertyByName("manager").getOrdinalPosition()); - assertEquals(false, employeeVertexType.getPropertyByName("manager").isFromPrimaryKey()); - - assertEquals(2, regularEmployeeVertexType.getProperties().size()); - - assertNotNull(regularEmployeeVertexType.getPropertyByName("salary")); - assertEquals("salary", regularEmployeeVertexType.getPropertyByName("salary").getName()); - assertEquals("DECIMAL", regularEmployeeVertexType.getPropertyByName("salary").getOriginalType()); - assertEquals(1, regularEmployeeVertexType.getPropertyByName("salary").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getPropertyByName("salary").isFromPrimaryKey()); - - assertNotNull(regularEmployeeVertexType.getPropertyByName("bonus")); - assertEquals("bonus", regularEmployeeVertexType.getPropertyByName("bonus").getName()); - assertEquals("DECIMAL", regularEmployeeVertexType.getPropertyByName("bonus").getOriginalType()); - assertEquals(2, regularEmployeeVertexType.getPropertyByName("bonus").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getPropertyByName("bonus").isFromPrimaryKey()); - - assertEquals(2, contractEmployeeVertexType.getProperties().size()); - - assertNotNull(contractEmployeeVertexType.getPropertyByName("payPerHour")); - assertEquals("payPerHour", contractEmployeeVertexType.getPropertyByName("payPerHour").getName()); - assertEquals("DECIMAL", contractEmployeeVertexType.getPropertyByName("payPerHour").getOriginalType()); - assertEquals(1, contractEmployeeVertexType.getPropertyByName("payPerHour").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getPropertyByName("payPerHour").isFromPrimaryKey()); - - assertNotNull(contractEmployeeVertexType.getPropertyByName("contractDuration")); - assertEquals("contractDuration", contractEmployeeVertexType.getPropertyByName("contractDuration").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getPropertyByName("contractDuration").getOriginalType()); - assertEquals(2, contractEmployeeVertexType.getPropertyByName("contractDuration").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getPropertyByName("contractDuration").isFromPrimaryKey()); - - assertEquals(3, countryVertexType.getProperties().size()); - - assertNotNull(countryVertexType.getPropertyByName("id")); - assertEquals("id", countryVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", countryVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, countryVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, countryVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(countryVertexType.getPropertyByName("name")); - assertEquals("name", countryVertexType.getPropertyByName("name").getName()); - assertEquals("VARCHAR", countryVertexType.getPropertyByName("name").getOriginalType()); - assertEquals(2, countryVertexType.getPropertyByName("name").getOrdinalPosition()); - assertEquals(false, countryVertexType.getPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(countryVertexType.getPropertyByName("continent")); - assertEquals("continent", countryVertexType.getPropertyByName("continent").getName()); - assertEquals("VARCHAR", countryVertexType.getPropertyByName("continent").getOriginalType()); - assertEquals(3, countryVertexType.getPropertyByName("continent").getOrdinalPosition()); - assertEquals(false, countryVertexType.getPropertyByName("continent").isFromPrimaryKey()); - - assertEquals(2, managerVertexType.getProperties().size()); - - assertNotNull(managerVertexType.getPropertyByName("id")); - assertEquals("id", managerVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", managerVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, managerVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, managerVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(managerVertexType.getPropertyByName("name")); - assertEquals("name", managerVertexType.getPropertyByName("name").getName()); - assertEquals("VARCHAR", managerVertexType.getPropertyByName("name").getOriginalType()); - assertEquals(2, managerVertexType.getPropertyByName("name").getOrdinalPosition()); - assertEquals(false, managerVertexType.getPropertyByName("name").isFromPrimaryKey()); - - assertEquals(1, projectManagerVertexType.getProperties().size()); - - assertNotNull(projectManagerVertexType.getPropertyByName("project")); - assertEquals("project", projectManagerVertexType.getPropertyByName("project").getName()); - assertEquals("VARCHAR", projectManagerVertexType.getPropertyByName("project").getOriginalType()); - assertEquals(1, projectManagerVertexType.getPropertyByName("project").getOrdinalPosition()); - assertEquals(false, projectManagerVertexType.getPropertyByName("project").isFromPrimaryKey()); - - // inherited properties check - assertEquals(0, employeeVertexType.getInheritedProperties().size()); - - assertEquals(4, regularEmployeeVertexType.getInheritedProperties().size()); - - assertNotNull(regularEmployeeVertexType.getInheritedPropertyByName("id")); - assertEquals("id", regularEmployeeVertexType.getInheritedPropertyByName("id").getName()); - assertEquals("VARCHAR", regularEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()); - assertEquals(1, regularEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()); - assertEquals(true, regularEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(regularEmployeeVertexType.getInheritedPropertyByName("name")); - assertEquals("name", regularEmployeeVertexType.getInheritedPropertyByName("name").getName()); - assertEquals("VARCHAR", regularEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()); - assertEquals(2, regularEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(regularEmployeeVertexType.getInheritedPropertyByName("residence")); - assertEquals("residence", regularEmployeeVertexType.getInheritedPropertyByName("residence").getName()); - assertEquals("VARCHAR", regularEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()); - assertEquals(3, regularEmployeeVertexType.getInheritedPropertyByName("residence").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()); - - assertNotNull(regularEmployeeVertexType.getInheritedPropertyByName("manager")); - assertEquals("manager", regularEmployeeVertexType.getInheritedPropertyByName("manager").getName()); - assertEquals("VARCHAR", regularEmployeeVertexType.getInheritedPropertyByName("manager").getOriginalType()); - assertEquals(4, regularEmployeeVertexType.getInheritedPropertyByName("manager").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getInheritedPropertyByName("manager").isFromPrimaryKey()); - - assertEquals(4, contractEmployeeVertexType.getInheritedProperties().size()); - - assertNotNull(contractEmployeeVertexType.getInheritedPropertyByName("id")); - assertEquals("id", contractEmployeeVertexType.getInheritedPropertyByName("id").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()); - assertEquals(1, contractEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()); - assertEquals(true, contractEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(contractEmployeeVertexType.getInheritedPropertyByName("name")); - assertEquals("name", contractEmployeeVertexType.getInheritedPropertyByName("name").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()); - assertEquals(2, contractEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(contractEmployeeVertexType.getInheritedPropertyByName("residence")); - assertEquals("residence", contractEmployeeVertexType.getInheritedPropertyByName("residence").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()); - assertEquals(3, contractEmployeeVertexType.getInheritedPropertyByName("residence").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()); - - assertNotNull(contractEmployeeVertexType.getInheritedPropertyByName("manager")); - assertEquals("manager", contractEmployeeVertexType.getInheritedPropertyByName("manager").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getInheritedPropertyByName("manager").getOriginalType()); - assertEquals(4, contractEmployeeVertexType.getInheritedPropertyByName("manager").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getInheritedPropertyByName("manager").isFromPrimaryKey()); - - assertEquals(2, projectManagerVertexType.getInheritedProperties().size()); - - assertNotNull(projectManagerVertexType.getInheritedPropertyByName("id")); - assertEquals("id", projectManagerVertexType.getInheritedPropertyByName("id").getName()); - assertEquals("VARCHAR", projectManagerVertexType.getInheritedPropertyByName("id").getOriginalType()); - assertEquals(1, projectManagerVertexType.getInheritedPropertyByName("id").getOrdinalPosition()); - assertEquals(true, projectManagerVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(projectManagerVertexType.getInheritedPropertyByName("name")); - assertEquals("name", projectManagerVertexType.getInheritedPropertyByName("name").getName()); - assertEquals("VARCHAR", projectManagerVertexType.getInheritedPropertyByName("name").getOriginalType()); - assertEquals(2, projectManagerVertexType.getInheritedPropertyByName("name").getOrdinalPosition()); - assertEquals(false, projectManagerVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()); - - assertEquals(0, countryVertexType.getInheritedProperties().size()); - assertEquals(0, managerVertexType.getInheritedProperties().size()); - - // edges check - - assertEquals(1, mapper.getRelationship2edgeType().size()); - - assertEquals(1, mapper.getGraphModel().getEdgesType().size()); - assertEquals("HasManager", mapper.getGraphModel().getEdgesType().get(0).getName()); - - assertEquals(1, employeeVertexType.getOutEdgesType().size()); - assertEquals("HasManager", employeeVertexType.getOutEdgesType().get(0).getName()); - - assertEquals(1, regularEmployeeVertexType.getOutEdgesType().size()); - assertEquals("HasManager", regularEmployeeVertexType.getOutEdgesType().get(0).getName()); - - assertEquals(1, contractEmployeeVertexType.getOutEdgesType().size()); - assertEquals("HasManager", contractEmployeeVertexType.getOutEdgesType().get(0).getName()); - - /* - * Rules check - */ - - // Classes Mapping - - assertEquals(6, mapper.getVertexType2EVClassMappers().size()); - assertEquals(6, mapper.getEntity2EVClassMappers().size()); - - assertEquals(1, mapper.getEVClassMappersByVertex(employeeVertexType).size()); - EVClassMapper employeeClassMapper = mapper.getEVClassMappersByVertex(employeeVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(employeeEntity).size()); - assertEquals(employeeClassMapper, mapper.getEVClassMappersByEntity(employeeEntity).get(0)); - assertEquals(employeeClassMapper.getEntity(), employeeEntity); - assertEquals(employeeClassMapper.getVertexType(), employeeVertexType); - - assertEquals(4, employeeClassMapper.getAttribute2property().size()); - assertEquals(4, employeeClassMapper.getProperty2attribute().size()); - assertEquals("id", employeeClassMapper.getAttribute2property().get("ID")); - assertEquals("name", employeeClassMapper.getAttribute2property().get("NAME")); - assertEquals("residence", employeeClassMapper.getAttribute2property().get("RESIDENCE")); - assertEquals("manager", employeeClassMapper.getAttribute2property().get("MANAGER")); - assertEquals("ID", employeeClassMapper.getProperty2attribute().get("id")); - assertEquals("NAME", employeeClassMapper.getProperty2attribute().get("name")); - assertEquals("RESIDENCE", employeeClassMapper.getProperty2attribute().get("residence")); - assertEquals("MANAGER", employeeClassMapper.getProperty2attribute().get("manager")); - - assertEquals(1, mapper.getEVClassMappersByVertex(regularEmployeeVertexType).size()); - EVClassMapper regularEmployeeClassMapper = mapper.getEVClassMappersByVertex(regularEmployeeVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(regularEmployeeEntity).size()); - assertEquals(regularEmployeeClassMapper, mapper.getEVClassMappersByEntity(regularEmployeeEntity).get(0)); - assertEquals(regularEmployeeClassMapper.getEntity(), regularEmployeeEntity); - assertEquals(regularEmployeeClassMapper.getVertexType(), regularEmployeeVertexType); - - assertEquals(2, regularEmployeeClassMapper.getAttribute2property().size()); - assertEquals(2, regularEmployeeClassMapper.getProperty2attribute().size()); - assertEquals("salary", regularEmployeeClassMapper.getAttribute2property().get("SALARY")); - assertEquals("bonus", regularEmployeeClassMapper.getAttribute2property().get("BONUS")); - assertEquals("SALARY", regularEmployeeClassMapper.getProperty2attribute().get("salary")); - assertEquals("BONUS", regularEmployeeClassMapper.getProperty2attribute().get("bonus")); - - assertEquals(1, mapper.getEVClassMappersByVertex(contractEmployeeVertexType).size()); - EVClassMapper contractEmployeeClassMapper = mapper.getEVClassMappersByVertex(contractEmployeeVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(contractEmployeeEntity).size()); - assertEquals(contractEmployeeClassMapper, mapper.getEVClassMappersByEntity(contractEmployeeEntity).get(0)); - assertEquals(contractEmployeeClassMapper.getEntity(), contractEmployeeEntity); - assertEquals(contractEmployeeClassMapper.getVertexType(), contractEmployeeVertexType); - - assertEquals(2, contractEmployeeClassMapper.getAttribute2property().size()); - assertEquals(2, contractEmployeeClassMapper.getProperty2attribute().size()); - assertEquals("payPerHour", contractEmployeeClassMapper.getAttribute2property().get("PAY_PER_HOUR")); - assertEquals("contractDuration", contractEmployeeClassMapper.getAttribute2property().get("CONTRACT_DURATION")); - assertEquals("PAY_PER_HOUR", contractEmployeeClassMapper.getProperty2attribute().get("payPerHour")); - assertEquals("CONTRACT_DURATION", contractEmployeeClassMapper.getProperty2attribute().get("contractDuration")); - - assertEquals(1, mapper.getEVClassMappersByVertex(countryVertexType).size()); - EVClassMapper countryClassMapper = mapper.getEVClassMappersByVertex(countryVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(countryEntity).size()); - assertEquals(countryClassMapper, mapper.getEVClassMappersByEntity(countryEntity).get(0)); - assertEquals(countryClassMapper.getEntity(), countryEntity); - assertEquals(countryClassMapper.getVertexType(), countryVertexType); - - assertEquals(3, countryClassMapper.getAttribute2property().size()); - assertEquals(3, countryClassMapper.getProperty2attribute().size()); - assertEquals("id", countryClassMapper.getAttribute2property().get("ID")); - assertEquals("name", countryClassMapper.getAttribute2property().get("NAME")); - assertEquals("continent", countryClassMapper.getAttribute2property().get("CONTINENT")); - assertEquals("ID", countryClassMapper.getProperty2attribute().get("id")); - assertEquals("NAME", countryClassMapper.getProperty2attribute().get("name")); - assertEquals("CONTINENT", countryClassMapper.getProperty2attribute().get("continent")); - - assertEquals(1, mapper.getEVClassMappersByVertex(managerVertexType).size()); - EVClassMapper managerClassMapper = mapper.getEVClassMappersByVertex(managerVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(managerEntity).size()); - assertEquals(managerClassMapper, mapper.getEVClassMappersByEntity(managerEntity).get(0)); - assertEquals(managerClassMapper.getEntity(), managerEntity); - assertEquals(managerClassMapper.getVertexType(), managerVertexType); - - assertEquals(2, managerClassMapper.getAttribute2property().size()); - assertEquals(2, managerClassMapper.getProperty2attribute().size()); - assertEquals("id", managerClassMapper.getAttribute2property().get("ID")); - assertEquals("name", managerClassMapper.getAttribute2property().get("NAME")); - assertEquals("ID", managerClassMapper.getProperty2attribute().get("id")); - assertEquals("NAME", managerClassMapper.getProperty2attribute().get("name")); - - assertEquals(1, mapper.getEVClassMappersByVertex(projectManagerVertexType).size()); - EVClassMapper projectManagerClassMapper = mapper.getEVClassMappersByVertex(projectManagerVertexType).get(0); - - assertEquals(projectManagerClassMapper, mapper.getEVClassMappersByEntity(projectManagerEntity).get(0)); - assertEquals(projectManagerClassMapper.getEntity(), projectManagerEntity); - assertEquals(projectManagerClassMapper.getVertexType(), projectManagerVertexType); - - assertEquals(1, projectManagerClassMapper.getAttribute2property().size()); - assertEquals(1, projectManagerClassMapper.getProperty2attribute().size()); - assertEquals("project", projectManagerClassMapper.getAttribute2property().get("PROJECT")); - assertEquals("PROJECT", projectManagerClassMapper.getProperty2attribute().get("project")); - - // Relationships-Edges Mapping - - Iterator itRelationships = employeeEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship hasManagerRelationship = itRelationships.next(); - assertFalse(itRelationships.hasNext()); - - EdgeType hasManagerEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasManager"); - - assertEquals(1, mapper.getRelationship2edgeType().size()); - assertEquals(hasManagerEdgeType, mapper.getRelationship2edgeType().get(hasManagerRelationship)); - - assertEquals(1, mapper.getEdgeType2relationships().size()); - assertEquals(1, mapper.getEdgeType2relationships().get(hasManagerEdgeType).size()); - assertTrue(mapper.getEdgeType2relationships().get(hasManagerEdgeType).contains(hasManagerRelationship)); - - // JoinVertexes-AggregatorEdges Mapping - - assertEquals(0, mapper.getJoinVertex2aggregatorEdges().size()); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } finally { - try { - // Dropping Source DB Schema and OrientGraph - String dbDropping = "drop schema public cascade"; - st.execute(dbDropping); - connection.close(); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } - } + } + + /* + * Filtering out a table through include-tables (with Table per Hierarchy inheritance). + */ @Test + void filterOutThroughIncludeWithTablePerHierarchyInheritance() { + Connection connection = null; + Statement st = null; + + try { + Class.forName(this.driver); + connection = DriverManager.getConnection(this.jurl, this.username, this.password); + + String countryTableBuilding = + "create memory table COUNTRY(ID varchar(256) not null, NAME varchar(256), CONTINENT" + + " varchar(256), primary key (ID))"; + st = connection.createStatement(); + st.execute(countryTableBuilding); + + String residenceTableBuilding = + "create memory table RESIDENCE(ID varchar(256) not null, CITY varchar(256), COUNTRY" + + " varchar(256), primary key (ID), foreign key (COUNTRY) references COUNTRY(ID))"; + st.execute(residenceTableBuilding); + + String managerTableBuilding = + "create memory table MANAGER(ID varchar(256) not null, TYPE varchar(256), NAME" + + " varchar(256), PROJECT varchar(256), primary key (ID))"; + st.execute(managerTableBuilding); + + String employeeTableBuilding = + "create memory table EMPLOYEE (ID varchar(256) not null, TYPE varchar(256), NAME" + + " varchar(256), SALARY decimal(10,2), BONUS decimal(10,0), PAY_PER_HOUR" + + " decimal(10,2), CONTRACT_DURATION varchar(256), RESIDENCE varchar(256), MANAGER" + + " varchar(256), primary key (id), foreign key (RESIDENCE) references RESIDENCE(ID)," + + " foreign key (MANAGER) references MANAGER(ID))"; + st.execute(employeeTableBuilding); + + // Records Inserting + + String countryFilling = + "insert into country (ID,NAME,CONTINENT) values (" + "('C001','Italy','Europe'))"; + st.execute(countryFilling); + + String residenceFilling = + "insert into RESIDENCE (ID,CITY,COUNTRY) values (" + + "('R001','Rome','C001')," + + "('R002','Milan','C001'))"; + st.execute(residenceFilling); + + String managerFilling = + "insert into MANAGER (ID,TYPE,NAME,PROJECT) values (" + + "('M001','prj_mgr','Bill Right','New World'))"; + st.execute(managerFilling); + + String employeeFilling = + "insert into EMPLOYEE" + + " (ID,TYPE,NAME,SALARY,BONUS,PAY_PER_HOUR,CONTRACT_DURATION,RESIDENCE,MANAGER)" + + " values (('E001','emp','John" + + " Black',null,null,null,null,'R001',null),('E002','reg_emp','Andrew" + + " Brown','1000.00','10',null,null,'R001','M001'),('E003','cont_emp','Jack" + + " Johnson',null,null,'50.00','6','R002',null))"; + st.execute(employeeFilling); + + List includedTables = new ArrayList(); + includedTables.add("COUNTRY"); + includedTables.add("MANAGER"); + includedTables.add("EMPLOYEE"); + + this.mapper = + new Hibernate2GraphMapper( + dataSource, + FilterTableMappingTest.XML_TABLE_PER_CLASS, + includedTables, + null, + dbQueryEngine, + dataTypeHandler, + executionStrategy, + nameResolver, + statistics); + mapper.buildSourceDatabaseSchema(); + mapper.buildGraphModel(new JavaConventionNameResolver()); + + /* + * Testing context information + */ + + assertThat(statistics.totalNumberOfEntities).isEqualTo(3); + assertThat(statistics.builtEntities).isEqualTo(3); + assertThat(statistics.totalNumberOfRelationships).isEqualTo(1); + assertThat(statistics.builtRelationships).isEqualTo(1); + + assertThat(statistics.totalNumberOfModelVertices).isEqualTo(6); + assertThat(statistics.builtModelVertexTypes).isEqualTo(6); + assertThat(statistics.totalNumberOfModelEdges).isEqualTo(1); + assertThat(statistics.builtModelEdgeTypes).isEqualTo(1); + + /* + * Testing built source db schema + */ + + Entity employeeEntity = mapper.getDataBaseSchema().getEntityByName("EMPLOYEE"); + Entity regularEmployeeEntity = + mapper.getDataBaseSchema().getEntityByNameIgnoreCase("REGULAR_EMPLOYEE"); + Entity contractEmployeeEntity = + mapper.getDataBaseSchema().getEntityByNameIgnoreCase("CONTRACT_EMPLOYEE"); + Entity countryEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("COUNTRY"); + Entity managerEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("MANAGER"); + Entity projectManagerEntity = + mapper.getDataBaseSchema().getEntityByNameIgnoreCase("PROJECT_MANAGER"); + Entity residenceEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("RESIDENCE"); + + // entities check + assertThat(mapper.getDataBaseSchema().getEntities().size()).isEqualTo(6); + assertThat(mapper.getDataBaseSchema().getCanonicalRelationships().size()).isEqualTo(1); + assertThat(employeeEntity).isNotNull(); + assertThat(regularEmployeeEntity).isNotNull(); + assertThat(contractEmployeeEntity).isNotNull(); + assertThat(countryEntity).isNotNull(); + assertThat(managerEntity).isNotNull(); + assertThat(residenceEntity).isNull(); + + // attributes check + assertThat(employeeEntity.getAttributes().size()).isEqualTo(4); + + assertThat(employeeEntity.getAttributeByName("ID")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(employeeEntity.getAttributeByName("ID").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("ID").getOrdinalPosition()).isEqualTo(1); + assertThat(employeeEntity.getAttributeByName("ID").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(employeeEntity.getAttributeByName("NAME")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("NAME").getName()).isEqualTo("NAME"); + assertThat(employeeEntity.getAttributeByName("NAME").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("NAME").getOrdinalPosition()).isEqualTo(2); + assertThat(employeeEntity.getAttributeByName("NAME").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(employeeEntity.getAttributeByName("RESIDENCE")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getName()).isEqualTo("RESIDENCE"); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getOrdinalPosition()).isEqualTo(3); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(employeeEntity.getAttributeByName("MANAGER")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("MANAGER").getName()).isEqualTo("MANAGER"); + assertThat(employeeEntity.getAttributeByName("MANAGER").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("MANAGER").getOrdinalPosition()).isEqualTo(4); + assertThat(employeeEntity.getAttributeByName("MANAGER").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(regularEmployeeEntity.getAttributes().size()).isEqualTo(2); + + assertThat(regularEmployeeEntity.getAttributeByName("SALARY")).isNotNull(); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getName()).isEqualTo("SALARY"); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getDataType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getOrdinalPosition()) + .isEqualTo(1); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getBelongingEntity().getName()) + .isEqualTo("Regular_Employee"); + + assertThat(regularEmployeeEntity.getAttributeByName("BONUS")).isNotNull(); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getName()).isEqualTo("BONUS"); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getDataType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getOrdinalPosition()) + .isEqualTo(2); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getBelongingEntity().getName()) + .isEqualTo("Regular_Employee"); + + assertThat(contractEmployeeEntity.getAttributes().size()).isEqualTo(2); + + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR")).isNotNull(); + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getName()) + .isEqualTo("PAY_PER_HOUR"); + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getDataType()) + .isEqualTo("DECIMAL"); + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getOrdinalPosition()) + .isEqualTo(1); + assertThat( + contractEmployeeEntity + .getAttributeByName("PAY_PER_HOUR") + .getBelongingEntity() + .getName()) + .isEqualTo("Contract_Employee"); + + assertThat(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION")).isNotNull(); + assertThat(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getName()) + .isEqualTo("CONTRACT_DURATION"); + assertThat(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + contractEmployeeEntity + .getAttributeByName("CONTRACT_DURATION") + .getBelongingEntity() + .getName()) + .isEqualTo("Contract_Employee"); + + assertThat(countryEntity.getAttributes().size()).isEqualTo(3); + + assertThat(countryEntity.getAttributeByName("ID")).isNotNull(); + assertThat(countryEntity.getAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(countryEntity.getAttributeByName("ID").getDataType()).isEqualTo("VARCHAR"); + assertThat(countryEntity.getAttributeByName("ID").getOrdinalPosition()).isEqualTo(1); + assertThat(countryEntity.getAttributeByName("ID").getBelongingEntity().getName()) + .isEqualTo("COUNTRY"); + + assertThat(countryEntity.getAttributeByName("NAME")).isNotNull(); + assertThat(countryEntity.getAttributeByName("NAME").getName()).isEqualTo("NAME"); + assertThat(countryEntity.getAttributeByName("NAME").getDataType()).isEqualTo("VARCHAR"); + assertThat(countryEntity.getAttributeByName("NAME").getOrdinalPosition()).isEqualTo(2); + assertThat(countryEntity.getAttributeByName("NAME").getBelongingEntity().getName()) + .isEqualTo("COUNTRY"); + + assertThat(countryEntity.getAttributeByName("CONTINENT")).isNotNull(); + assertThat(countryEntity.getAttributeByName("CONTINENT").getName()).isEqualTo("CONTINENT"); + assertThat(countryEntity.getAttributeByName("CONTINENT").getDataType()).isEqualTo("VARCHAR"); + assertThat(countryEntity.getAttributeByName("CONTINENT").getOrdinalPosition()).isEqualTo(3); + assertThat(countryEntity.getAttributeByName("CONTINENT").getBelongingEntity().getName()) + .isEqualTo("COUNTRY"); + + assertThat(managerEntity.getAttributes().size()).isEqualTo(2); + + assertThat(managerEntity.getAttributeByName("ID")).isNotNull(); + assertThat(managerEntity.getAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(managerEntity.getAttributeByName("ID").getDataType()).isEqualTo("VARCHAR"); + assertThat(managerEntity.getAttributeByName("ID").getOrdinalPosition()).isEqualTo(1); + assertThat(managerEntity.getAttributeByName("ID").getBelongingEntity().getName()) + .isEqualTo("MANAGER"); + + assertThat(managerEntity.getAttributeByName("NAME")).isNotNull(); + assertThat(managerEntity.getAttributeByName("NAME").getName()).isEqualTo("NAME"); + assertThat(managerEntity.getAttributeByName("NAME").getDataType()).isEqualTo("VARCHAR"); + assertThat(managerEntity.getAttributeByName("NAME").getOrdinalPosition()).isEqualTo(2); + assertThat(managerEntity.getAttributeByName("NAME").getBelongingEntity().getName()) + .isEqualTo("MANAGER"); + + assertThat(projectManagerEntity.getAttributes().size()).isEqualTo(1); + + assertThat(projectManagerEntity.getAttributeByName("PROJECT")).isNotNull(); + assertThat(projectManagerEntity.getAttributeByName("PROJECT").getName()).isEqualTo("PROJECT"); + assertThat(projectManagerEntity.getAttributeByName("PROJECT").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(projectManagerEntity.getAttributeByName("PROJECT").getOrdinalPosition()) + .isEqualTo(1); + assertThat(projectManagerEntity.getAttributeByName("PROJECT").getBelongingEntity().getName()) + .isEqualTo("Project_Manager"); + + // inherited attributes check + assertThat(employeeEntity.getInheritedAttributes().size()).isEqualTo(0); + + assertThat(regularEmployeeEntity.getInheritedAttributes().size()).isEqualTo(4); + + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID")).isNotNull(); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()) + .isEqualTo(1); + assertThat( + regularEmployeeEntity + .getInheritedAttributeByName("ID") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME")).isNotNull(); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME").getName()) + .isEqualTo("NAME"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + regularEmployeeEntity + .getInheritedAttributeByName("NAME") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE")).isNotNull(); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()) + .isEqualTo("RESIDENCE"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()) + .isEqualTo(3); + assertThat( + regularEmployeeEntity + .getInheritedAttributeByName("RESIDENCE") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(regularEmployeeEntity.getInheritedAttributeByName("MANAGER")).isNotNull(); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("MANAGER").getName()) + .isEqualTo("MANAGER"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("MANAGER").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("MANAGER").getOrdinalPosition()) + .isEqualTo(4); + assertThat( + regularEmployeeEntity + .getInheritedAttributeByName("MANAGER") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(contractEmployeeEntity.getInheritedAttributes().size()).isEqualTo(4); + + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID")).isNotNull(); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID").getName()) + .isEqualTo("ID"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()) + .isEqualTo(1); + assertThat( + contractEmployeeEntity + .getInheritedAttributeByName("ID") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME")).isNotNull(); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME").getName()) + .isEqualTo("NAME"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + contractEmployeeEntity + .getInheritedAttributeByName("NAME") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE")).isNotNull(); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()) + .isEqualTo("RESIDENCE"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()) + .isEqualTo(3); + assertThat( + contractEmployeeEntity + .getInheritedAttributeByName("RESIDENCE") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(contractEmployeeEntity.getInheritedAttributeByName("MANAGER")).isNotNull(); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("MANAGER").getName()) + .isEqualTo("MANAGER"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("MANAGER").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("MANAGER").getOrdinalPosition()) + .isEqualTo(4); + assertThat( + contractEmployeeEntity + .getInheritedAttributeByName("MANAGER") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(projectManagerEntity.getInheritedAttributes().size()).isEqualTo(2); + + assertThat(projectManagerEntity.getInheritedAttributeByName("ID")).isNotNull(); + assertThat(projectManagerEntity.getInheritedAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(projectManagerEntity.getInheritedAttributeByName("ID").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(projectManagerEntity.getInheritedAttributeByName("ID").getOrdinalPosition()) + .isEqualTo(1); + assertThat( + projectManagerEntity.getInheritedAttributeByName("ID").getBelongingEntity().getName()) + .isEqualTo("MANAGER"); + + assertThat(projectManagerEntity.getInheritedAttributeByName("NAME")).isNotNull(); + assertThat(projectManagerEntity.getInheritedAttributeByName("NAME").getName()) + .isEqualTo("NAME"); + assertThat(projectManagerEntity.getInheritedAttributeByName("NAME").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(projectManagerEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + projectManagerEntity + .getInheritedAttributeByName("NAME") + .getBelongingEntity() + .getName()) + .isEqualTo("MANAGER"); + + assertThat(countryEntity.getInheritedAttributes().size()).isEqualTo(0); + assertThat(managerEntity.getInheritedAttributes().size()).isEqualTo(0); + + // primary key check + assertThat(regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()).isEqualTo(1); + assertThat(regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()) + .isEqualTo("ID"); + assertThat(regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + regularEmployeeEntity + .getPrimaryKey() + .getInvolvedAttributes() + .get(0) + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()) + .isEqualTo(1); + assertThat(contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()) + .isEqualTo("ID"); + assertThat( + contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeEntity + .getPrimaryKey() + .getInvolvedAttributes() + .get(0) + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(projectManagerEntity.getPrimaryKey().getInvolvedAttributes().size()).isEqualTo(1); + assertThat(projectManagerEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()) + .isEqualTo("ID"); + assertThat(projectManagerEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + projectManagerEntity + .getPrimaryKey() + .getInvolvedAttributes() + .get(0) + .getBelongingEntity() + .getName()) + .isEqualTo("MANAGER"); + + // relationship, primary and foreign key check + assertThat(regularEmployeeEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(contractEmployeeEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(employeeEntity.getOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(countryEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(managerEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(regularEmployeeEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(contractEmployeeEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(employeeEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(countryEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(managerEntity.getInCanonicalRelationships().size()).isEqualTo(1); + + assertThat(regularEmployeeEntity.getForeignKeys().size()).isEqualTo(0); + assertThat(contractEmployeeEntity.getForeignKeys().size()).isEqualTo(0); + assertThat(employeeEntity.getForeignKeys().size()).isEqualTo(1); + assertThat(countryEntity.getForeignKeys().size()).isEqualTo(0); + assertThat(managerEntity.getForeignKeys().size()).isEqualTo(0); + + Iterator itEmp = + employeeEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship currentEmpRel = itEmp.next(); + assertThat(currentEmpRel.getParentEntity().getName()).isEqualTo("MANAGER"); + assertThat(currentEmpRel.getForeignEntity().getName()).isEqualTo("EMPLOYEE"); + assertThat(currentEmpRel.getPrimaryKey()).isEqualTo(managerEntity.getPrimaryKey()); + assertThat(currentEmpRel.getForeignKey()).isEqualTo(employeeEntity.getForeignKeys().get(0)); + assertThat(itEmp.hasNext()).isFalse(); + + Iterator itManager = + managerEntity.getInCanonicalRelationships().iterator(); + CanonicalRelationship currentManRel = itManager.next(); + assertThat(currentManRel).isEqualTo(currentEmpRel); + + // inherited relationships check + assertThat(regularEmployeeEntity.getInheritedOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(contractEmployeeEntity.getInheritedOutCanonicalRelationships().size()) + .isEqualTo(1); + assertThat(employeeEntity.getInheritedOutCanonicalRelationships().size()).isEqualTo(0); + + Iterator itRegEmp = + regularEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); + Iterator itContEmp = + contractEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); + CanonicalRelationship currentRegEmpRel = itRegEmp.next(); + CanonicalRelationship currentContEmpRel = itContEmp.next(); + assertThat(currentRegEmpRel.getParentEntity().getName()).isEqualTo("MANAGER"); + assertThat(currentRegEmpRel.getForeignEntity().getName()).isEqualTo("EMPLOYEE"); + assertThat(currentContEmpRel.getParentEntity().getName()).isEqualTo("MANAGER"); + assertThat(currentContEmpRel.getForeignEntity().getName()).isEqualTo("EMPLOYEE"); + assertThat(currentRegEmpRel.getPrimaryKey()).isEqualTo(managerEntity.getPrimaryKey()); + assertThat(currentRegEmpRel.getFromColumns().size()).isEqualTo(1); + assertThat(currentRegEmpRel.getFromColumns().get(0).getName()).isEqualTo("MANAGER"); + assertThat(currentContEmpRel.getPrimaryKey()).isEqualTo(managerEntity.getPrimaryKey()); + assertThat(currentContEmpRel.getFromColumns().size()).isEqualTo(1); + assertThat(currentContEmpRel.getFromColumns().get(0).getName()).isEqualTo("MANAGER"); + assertThat(itRegEmp.hasNext()).isFalse(); + assertThat(itContEmp.hasNext()).isFalse(); + + // inheritance check + assertThat(regularEmployeeEntity.getParentEntity()).isEqualTo(employeeEntity); + assertThat(contractEmployeeEntity.getParentEntity()).isEqualTo(employeeEntity); + assertThat(employeeEntity.getParentEntity()).isNull(); + + assertThat(regularEmployeeEntity.getInheritanceLevel()).isEqualTo(1); + assertThat(contractEmployeeEntity.getInheritanceLevel()).isEqualTo(1); + assertThat(employeeEntity.getInheritanceLevel()).isEqualTo(0); + + // Hierarchical Bag check + assertThat(mapper.getDataBaseSchema().getHierarchicalBags().size()).isEqualTo(2); + + HierarchicalBag hierarchicalBag1 = mapper.getDataBaseSchema().getHierarchicalBags().get(0); + HierarchicalBag hierarchicalBag2 = mapper.getDataBaseSchema().getHierarchicalBags().get(1); + assertThat(hierarchicalBag1.getInheritancePattern()).isEqualTo("table-per-hierarchy"); + assertThat(hierarchicalBag2.getInheritancePattern()).isEqualTo("table-per-hierarchy"); + + assertThat(hierarchicalBag1.getDepth2entities().size()).isEqualTo(2); + + assertThat(hierarchicalBag1.getDepth2entities().get(0).size()).isEqualTo(1); + Iterator it = hierarchicalBag1.getDepth2entities().get(0).iterator(); + assertThat(it.next().getName()).isEqualTo("EMPLOYEE"); + assertThat(it.hasNext()).isFalse(); + + assertThat(hierarchicalBag1.getDepth2entities().get(1).size()).isEqualTo(2); + it = hierarchicalBag1.getDepth2entities().get(1).iterator(); + assertThat(it.next().getName()).isEqualTo("Regular_Employee"); + assertThat(it.next().getName()).isEqualTo("Contract_Employee"); + assertThat(it.hasNext()).isFalse(); + + assertThat(employeeEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag1); + assertThat(regularEmployeeEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag1); + assertThat(contractEmployeeEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag1); + + assertThat(hierarchicalBag1.getDiscriminatorColumn()).isNotNull(); + assertThat(hierarchicalBag1.getDiscriminatorColumn()).isEqualTo("TYPE"); + + assertThat(hierarchicalBag1.getEntityName2discriminatorValue().size()).isEqualTo(3); + assertThat(hierarchicalBag1.getEntityName2discriminatorValue().get("EMPLOYEE")) + .isEqualTo("emp"); + assertThat(hierarchicalBag1.getEntityName2discriminatorValue().get("Regular_Employee")) + .isEqualTo("reg_emp"); + assertThat(hierarchicalBag1.getEntityName2discriminatorValue().get("Contract_Employee")) + .isEqualTo("cont_emp"); + + assertThat(hierarchicalBag2.getDepth2entities().size()).isEqualTo(2); + + assertThat(hierarchicalBag2.getDepth2entities().get(0).size()).isEqualTo(1); + it = hierarchicalBag2.getDepth2entities().get(0).iterator(); + assertThat(it.next().getName()).isEqualTo("MANAGER"); + assertThat(it.hasNext()).isFalse(); + + assertThat(hierarchicalBag2.getDepth2entities().get(1).size()).isEqualTo(1); + it = hierarchicalBag2.getDepth2entities().get(1).iterator(); + assertThat(it.next().getName()).isEqualTo("Project_Manager"); + assertThat(it.hasNext()).isFalse(); + + assertThat(managerEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag2); + assertThat(projectManagerEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag2); + + assertThat(hierarchicalBag2.getDiscriminatorColumn()).isNotNull(); + assertThat(hierarchicalBag2.getDiscriminatorColumn()).isEqualTo("TYPE"); + + assertThat(hierarchicalBag2.getEntityName2discriminatorValue().size()).isEqualTo(2); + assertThat(hierarchicalBag2.getEntityName2discriminatorValue().get("MANAGER")) + .isEqualTo("mgr"); + assertThat(hierarchicalBag2.getEntityName2discriminatorValue().get("Project_Manager")) + .isEqualTo("prj_mgr"); + + /* + * Testing built graph model + */ + + VertexType employeeVertexType = mapper.getGraphModel().getVertexTypeByName("Employee"); + VertexType regularEmployeeVertexType = + mapper.getGraphModel().getVertexTypeByName("RegularEmployee"); + VertexType contractEmployeeVertexType = + mapper.getGraphModel().getVertexTypeByName("ContractEmployee"); + VertexType countryVertexType = mapper.getGraphModel().getVertexTypeByName("Country"); + VertexType managerVertexType = mapper.getGraphModel().getVertexTypeByName("Manager"); + VertexType projectManagerVertexType = + mapper.getGraphModel().getVertexTypeByName("ProjectManager"); + VertexType residenceVertexType = mapper.getGraphModel().getVertexTypeByName("Residence"); + + // vertices check + assertThat(mapper.getGraphModel().getVerticesType().size()).isEqualTo(6); + assertThat(employeeVertexType).isNotNull(); + assertThat(regularEmployeeVertexType).isNotNull(); + assertThat(contractEmployeeVertexType).isNotNull(); + assertThat(countryVertexType).isNotNull(); + assertThat(managerVertexType).isNotNull(); + assertThat(projectManagerVertexType).isNotNull(); + assertThat(residenceVertexType).isNull(); + + // properties check + assertThat(employeeVertexType.getProperties().size()).isEqualTo(4); + + assertThat(employeeVertexType.getPropertyByName("id")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(employeeVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(employeeVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(employeeVertexType.getPropertyByName("name")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("name").getName()).isEqualTo("name"); + assertThat(employeeVertexType.getPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("name").getOrdinalPosition()).isEqualTo(2); + assertThat(employeeVertexType.getPropertyByName("name").isFromPrimaryKey()).isFalse(); + + assertThat(employeeVertexType.getPropertyByName("residence")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("residence").getName()) + .isEqualTo("residence"); + assertThat(employeeVertexType.getPropertyByName("residence").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("residence").getOrdinalPosition()) + .isEqualTo(3); + assertThat(employeeVertexType.getPropertyByName("residence").isFromPrimaryKey()).isFalse(); + + assertThat(employeeVertexType.getPropertyByName("manager")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("manager").getName()).isEqualTo("manager"); + assertThat(employeeVertexType.getPropertyByName("manager").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("manager").getOrdinalPosition()).isEqualTo(4); + assertThat(employeeVertexType.getPropertyByName("manager").isFromPrimaryKey()).isFalse(); + + assertThat(regularEmployeeVertexType.getProperties().size()).isEqualTo(2); + + assertThat(regularEmployeeVertexType.getPropertyByName("salary")).isNotNull(); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").getName()) + .isEqualTo("salary"); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").getOriginalType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").getOrdinalPosition()) + .isEqualTo(1); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").isFromPrimaryKey()) + .isFalse(); + + assertThat(regularEmployeeVertexType.getPropertyByName("bonus")).isNotNull(); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").getName()).isEqualTo("bonus"); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").getOriginalType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").getOrdinalPosition()) + .isEqualTo(2); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").isFromPrimaryKey()).isFalse(); + + assertThat(contractEmployeeVertexType.getProperties().size()).isEqualTo(2); + + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour")).isNotNull(); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").getName()) + .isEqualTo("payPerHour"); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").getOriginalType()) + .isEqualTo("DECIMAL"); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").getOrdinalPosition()) + .isEqualTo(1); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getPropertyByName("contractDuration")).isNotNull(); + assertThat(contractEmployeeVertexType.getPropertyByName("contractDuration").getName()) + .isEqualTo("contractDuration"); + assertThat(contractEmployeeVertexType.getPropertyByName("contractDuration").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeVertexType.getPropertyByName("contractDuration").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + contractEmployeeVertexType.getPropertyByName("contractDuration").isFromPrimaryKey()) + .isFalse(); + + assertThat(countryVertexType.getProperties().size()).isEqualTo(3); + + assertThat(countryVertexType.getPropertyByName("id")).isNotNull(); + assertThat(countryVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(countryVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(countryVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(countryVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(countryVertexType.getPropertyByName("name")).isNotNull(); + assertThat(countryVertexType.getPropertyByName("name").getName()).isEqualTo("name"); + assertThat(countryVertexType.getPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(countryVertexType.getPropertyByName("name").getOrdinalPosition()).isEqualTo(2); + assertThat(countryVertexType.getPropertyByName("name").isFromPrimaryKey()).isFalse(); + + assertThat(countryVertexType.getPropertyByName("continent")).isNotNull(); + assertThat(countryVertexType.getPropertyByName("continent").getName()).isEqualTo("continent"); + assertThat(countryVertexType.getPropertyByName("continent").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(countryVertexType.getPropertyByName("continent").getOrdinalPosition()) + .isEqualTo(3); + assertThat(countryVertexType.getPropertyByName("continent").isFromPrimaryKey()).isFalse(); + + assertThat(managerVertexType.getProperties().size()).isEqualTo(2); + + assertThat(managerVertexType.getPropertyByName("id")).isNotNull(); + assertThat(managerVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(managerVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(managerVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(managerVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(managerVertexType.getPropertyByName("name")).isNotNull(); + assertThat(managerVertexType.getPropertyByName("name").getName()).isEqualTo("name"); + assertThat(managerVertexType.getPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(managerVertexType.getPropertyByName("name").getOrdinalPosition()).isEqualTo(2); + assertThat(managerVertexType.getPropertyByName("name").isFromPrimaryKey()).isFalse(); + + assertThat(projectManagerVertexType.getProperties().size()).isEqualTo(1); + + assertThat(projectManagerVertexType.getPropertyByName("project")).isNotNull(); + assertThat(projectManagerVertexType.getPropertyByName("project").getName()) + .isEqualTo("project"); + assertThat(projectManagerVertexType.getPropertyByName("project").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(projectManagerVertexType.getPropertyByName("project").getOrdinalPosition()) + .isEqualTo(1); + assertThat(projectManagerVertexType.getPropertyByName("project").isFromPrimaryKey()) + .isFalse(); + + // inherited properties check + assertThat(employeeVertexType.getInheritedProperties().size()).isEqualTo(0); + + assertThat(regularEmployeeVertexType.getInheritedProperties().size()).isEqualTo(4); + + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id")).isNotNull(); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").getName()) + .isEqualTo("id"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()) + .isEqualTo(1); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()) + .isTrue(); + + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name")).isNotNull(); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").getName()) + .isEqualTo("name"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()) + .isEqualTo(2); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()) + .isFalse(); + + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("residence")).isNotNull(); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("residence").getName()) + .isEqualTo("residence"); + assertThat( + regularEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + regularEmployeeVertexType + .getInheritedPropertyByName("residence") + .getOrdinalPosition()) + .isEqualTo(3); + assertThat( + regularEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()) + .isFalse(); + + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("manager")).isNotNull(); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("manager").getName()) + .isEqualTo("manager"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("manager").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + regularEmployeeVertexType.getInheritedPropertyByName("manager").getOrdinalPosition()) + .isEqualTo(4); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("manager").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getInheritedProperties().size()).isEqualTo(4); + + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id")).isNotNull(); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").getName()) + .isEqualTo("id"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()) + .isEqualTo(1); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()) + .isTrue(); + + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name")).isNotNull(); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").getName()) + .isEqualTo("name"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()) + .isEqualTo(2); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("residence")).isNotNull(); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("residence").getName()) + .isEqualTo("residence"); + assertThat( + contractEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeVertexType + .getInheritedPropertyByName("residence") + .getOrdinalPosition()) + .isEqualTo(3); + assertThat( + contractEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("manager")).isNotNull(); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("manager").getName()) + .isEqualTo("manager"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("manager").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeVertexType.getInheritedPropertyByName("manager").getOrdinalPosition()) + .isEqualTo(4); + assertThat( + contractEmployeeVertexType.getInheritedPropertyByName("manager").isFromPrimaryKey()) + .isFalse(); + + assertThat(projectManagerVertexType.getInheritedProperties().size()).isEqualTo(2); + + assertThat(projectManagerVertexType.getInheritedPropertyByName("id")).isNotNull(); + assertThat(projectManagerVertexType.getInheritedPropertyByName("id").getName()) + .isEqualTo("id"); + assertThat(projectManagerVertexType.getInheritedPropertyByName("id").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(projectManagerVertexType.getInheritedPropertyByName("id").getOrdinalPosition()) + .isEqualTo(1); + assertThat(projectManagerVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()) + .isTrue(); + + assertThat(projectManagerVertexType.getInheritedPropertyByName("name")).isNotNull(); + assertThat(projectManagerVertexType.getInheritedPropertyByName("name").getName()) + .isEqualTo("name"); + assertThat(projectManagerVertexType.getInheritedPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(projectManagerVertexType.getInheritedPropertyByName("name").getOrdinalPosition()) + .isEqualTo(2); + assertThat(projectManagerVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()) + .isFalse(); + + assertThat(countryVertexType.getInheritedProperties().size()).isEqualTo(0); + assertThat(managerVertexType.getInheritedProperties().size()).isEqualTo(0); + + // edges check + + assertThat(mapper.getRelationship2edgeType().size()).isEqualTo(1); + + assertThat(mapper.getGraphModel().getEdgesType().size()).isEqualTo(1); + assertThat(mapper.getGraphModel().getEdgesType().get(0).getName()).isEqualTo("HasManager"); + + assertThat(employeeVertexType.getOutEdgesType().size()).isEqualTo(1); + assertThat(employeeVertexType.getOutEdgesType().get(0).getName()).isEqualTo("HasManager"); + + assertThat(regularEmployeeVertexType.getOutEdgesType().size()).isEqualTo(1); + assertThat(regularEmployeeVertexType.getOutEdgesType().get(0).getName()) + .isEqualTo("HasManager"); + + assertThat(contractEmployeeVertexType.getOutEdgesType().size()).isEqualTo(1); + assertThat(contractEmployeeVertexType.getOutEdgesType().get(0).getName()) + .isEqualTo("HasManager"); + + /* + * Rules check + */ + + // Classes Mapping + + assertThat(mapper.getVertexType2EVClassMappers().size()).isEqualTo(6); + assertThat(mapper.getEntity2EVClassMappers().size()).isEqualTo(6); + + assertThat(mapper.getEVClassMappersByVertex(employeeVertexType).size()).isEqualTo(1); + EVClassMapper employeeClassMapper = + mapper.getEVClassMappersByVertex(employeeVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(employeeEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(employeeEntity).get(0)) + .isEqualTo(employeeClassMapper); + assertThat(employeeEntity).isEqualTo(employeeClassMapper.getEntity()); + assertThat(employeeVertexType).isEqualTo(employeeClassMapper.getVertexType()); + + assertThat(employeeClassMapper.getAttribute2property().size()).isEqualTo(4); + assertThat(employeeClassMapper.getProperty2attribute().size()).isEqualTo(4); + assertThat(employeeClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(employeeClassMapper.getAttribute2property().get("NAME")).isEqualTo("name"); + assertThat(employeeClassMapper.getAttribute2property().get("RESIDENCE")) + .isEqualTo("residence"); + assertThat(employeeClassMapper.getAttribute2property().get("MANAGER")).isEqualTo("manager"); + assertThat(employeeClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(employeeClassMapper.getProperty2attribute().get("name")).isEqualTo("NAME"); + assertThat(employeeClassMapper.getProperty2attribute().get("residence")) + .isEqualTo("RESIDENCE"); + assertThat(employeeClassMapper.getProperty2attribute().get("manager")).isEqualTo("MANAGER"); + + assertThat(mapper.getEVClassMappersByVertex(regularEmployeeVertexType).size()).isEqualTo(1); + EVClassMapper regularEmployeeClassMapper = + mapper.getEVClassMappersByVertex(regularEmployeeVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(regularEmployeeEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(regularEmployeeEntity).get(0)) + .isEqualTo(regularEmployeeClassMapper); + assertThat(regularEmployeeEntity).isEqualTo(regularEmployeeClassMapper.getEntity()); + assertThat(regularEmployeeVertexType).isEqualTo(regularEmployeeClassMapper.getVertexType()); + + assertThat(regularEmployeeClassMapper.getAttribute2property().size()).isEqualTo(2); + assertThat(regularEmployeeClassMapper.getProperty2attribute().size()).isEqualTo(2); + assertThat(regularEmployeeClassMapper.getAttribute2property().get("SALARY")) + .isEqualTo("salary"); + assertThat(regularEmployeeClassMapper.getAttribute2property().get("BONUS")) + .isEqualTo("bonus"); + assertThat(regularEmployeeClassMapper.getProperty2attribute().get("salary")) + .isEqualTo("SALARY"); + assertThat(regularEmployeeClassMapper.getProperty2attribute().get("bonus")) + .isEqualTo("BONUS"); + + assertThat(mapper.getEVClassMappersByVertex(contractEmployeeVertexType).size()).isEqualTo(1); + EVClassMapper contractEmployeeClassMapper = + mapper.getEVClassMappersByVertex(contractEmployeeVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(contractEmployeeEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(contractEmployeeEntity).get(0)) + .isEqualTo(contractEmployeeClassMapper); + assertThat(contractEmployeeEntity).isEqualTo(contractEmployeeClassMapper.getEntity()); + assertThat(contractEmployeeVertexType).isEqualTo(contractEmployeeClassMapper.getVertexType()); + + assertThat(contractEmployeeClassMapper.getAttribute2property().size()).isEqualTo(2); + assertThat(contractEmployeeClassMapper.getProperty2attribute().size()).isEqualTo(2); + assertThat(contractEmployeeClassMapper.getAttribute2property().get("PAY_PER_HOUR")) + .isEqualTo("payPerHour"); + assertThat(contractEmployeeClassMapper.getAttribute2property().get("CONTRACT_DURATION")) + .isEqualTo("contractDuration"); + assertThat(contractEmployeeClassMapper.getProperty2attribute().get("payPerHour")) + .isEqualTo("PAY_PER_HOUR"); + assertThat(contractEmployeeClassMapper.getProperty2attribute().get("contractDuration")) + .isEqualTo("CONTRACT_DURATION"); + + assertThat(mapper.getEVClassMappersByVertex(countryVertexType).size()).isEqualTo(1); + EVClassMapper countryClassMapper = mapper.getEVClassMappersByVertex(countryVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(countryEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(countryEntity).get(0)) + .isEqualTo(countryClassMapper); + assertThat(countryEntity).isEqualTo(countryClassMapper.getEntity()); + assertThat(countryVertexType).isEqualTo(countryClassMapper.getVertexType()); + + assertThat(countryClassMapper.getAttribute2property().size()).isEqualTo(3); + assertThat(countryClassMapper.getProperty2attribute().size()).isEqualTo(3); + assertThat(countryClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(countryClassMapper.getAttribute2property().get("NAME")).isEqualTo("name"); + assertThat(countryClassMapper.getAttribute2property().get("CONTINENT")) + .isEqualTo("continent"); + assertThat(countryClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(countryClassMapper.getProperty2attribute().get("name")).isEqualTo("NAME"); + assertThat(countryClassMapper.getProperty2attribute().get("continent")) + .isEqualTo("CONTINENT"); + + assertThat(mapper.getEVClassMappersByVertex(managerVertexType).size()).isEqualTo(1); + EVClassMapper managerClassMapper = mapper.getEVClassMappersByVertex(managerVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(managerEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(managerEntity).get(0)) + .isEqualTo(managerClassMapper); + assertThat(managerEntity).isEqualTo(managerClassMapper.getEntity()); + assertThat(managerVertexType).isEqualTo(managerClassMapper.getVertexType()); + + assertThat(managerClassMapper.getAttribute2property().size()).isEqualTo(2); + assertThat(managerClassMapper.getProperty2attribute().size()).isEqualTo(2); + assertThat(managerClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(managerClassMapper.getAttribute2property().get("NAME")).isEqualTo("name"); + assertThat(managerClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(managerClassMapper.getProperty2attribute().get("name")).isEqualTo("NAME"); + + assertThat(mapper.getEVClassMappersByVertex(projectManagerVertexType).size()).isEqualTo(1); + EVClassMapper projectManagerClassMapper = + mapper.getEVClassMappersByVertex(projectManagerVertexType).get(0); + + assertThat(mapper.getEVClassMappersByEntity(projectManagerEntity).get(0)) + .isEqualTo(projectManagerClassMapper); + assertThat(projectManagerEntity).isEqualTo(projectManagerClassMapper.getEntity()); + assertThat(projectManagerVertexType).isEqualTo(projectManagerClassMapper.getVertexType()); + + assertThat(projectManagerClassMapper.getAttribute2property().size()).isEqualTo(1); + assertThat(projectManagerClassMapper.getProperty2attribute().size()).isEqualTo(1); + assertThat(projectManagerClassMapper.getAttribute2property().get("PROJECT")) + .isEqualTo("project"); + assertThat(projectManagerClassMapper.getProperty2attribute().get("project")) + .isEqualTo("PROJECT"); + + // Relationships-Edges Mapping + + Iterator itRelationships = + employeeEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship hasManagerRelationship = itRelationships.next(); + assertThat(itRelationships.hasNext()).isFalse(); + + EdgeType hasManagerEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasManager"); + + assertThat(mapper.getRelationship2edgeType().size()).isEqualTo(1); + assertThat(mapper.getRelationship2edgeType().get(hasManagerRelationship)) + .isEqualTo(hasManagerEdgeType); + + assertThat(mapper.getEdgeType2relationships().size()).isEqualTo(1); + assertThat(mapper.getEdgeType2relationships().get(hasManagerEdgeType).size()).isEqualTo(1); + assertThat( + mapper + .getEdgeType2relationships() + .get(hasManagerEdgeType) + .contains(hasManagerRelationship)) + .isTrue(); + + // JoinVertexes-AggregatorEdges Mapping + + assertThat(mapper.getJoinVertex2aggregatorEdges().size()).isEqualTo(0); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } finally { + try { + // Dropping Source DB Schema and OrientGraph + String dbDropping = "drop schema public cascade"; + st.execute(dbDropping); + connection.close(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } } - - @Test - /* - * Filtering out a table through include-tables (with Table per Type inheritance). - */public void filterOutThroughIncludeWithTablePerTypeInheritance() { - Connection connection = null; - Statement st = null; - - try { - Class.forName(this.driver); - connection = DriverManager.getConnection(this.jurl, this.username, this.password); - - String countryTableBuilding = "create memory table COUNTRY(ID varchar(256) not null, NAME varchar(256), CONTINENT varchar(256), primary key (ID))"; - st = connection.createStatement(); - st.execute(countryTableBuilding); - - String residenceTableBuilding = - "create memory table RESIDENCE(ID varchar(256) not null, CITY varchar(256), COUNTRY varchar(256), primary key (ID))"; - st = connection.createStatement(); - st.execute(residenceTableBuilding); - - String managerTableBuilding = "create memory table MANAGER(ID varchar(256) not null, NAME varchar(256), primary key (ID))"; - st.execute(managerTableBuilding); - - String projectManagerTableBuilding = - "create memory table PROJECT_MANAGER(EID varchar(256) not null, PROJECT varchar(256), primary key (EID), foreign key (EID) references MANAGER(ID))"; - st.execute(projectManagerTableBuilding); - - String employeeTableBuilding = - "create memory table EMPLOYEE (ID varchar(256) not null," + - " NAME varchar(256), RESIDENCE varchar(256), MANAGER varchar(256), primary key (ID), " + - "foreign key (RESIDENCE) references RESIDENCE(ID), foreign key (MANAGER) references MANAGER(ID))"; - st.execute(employeeTableBuilding); - - String regularEmployeeTableBuilding = - "create memory table REGULAR_EMPLOYEE (EID varchar(256) not null, " + - "SALARY decimal(10,2), BONUS decimal(10,0), primary key (EID), foreign key (EID) references EMPLOYEE(ID))"; - st.execute(regularEmployeeTableBuilding); - - String contractEmployeeTableBuilding = - "create memory table CONTRACT_EMPLOYEE (EID varchar(256) not null, " + - "PAY_PER_HOUR decimal(10,2), CONTRACT_DURATION varchar(256), primary key (EID), foreign key (EID) references EMPLOYEE(ID))"; - st.execute(contractEmployeeTableBuilding); - - // Records Inserting - - String countryFilling = "insert into COUNTRY (ID,NAME,CONTINENT) values (" + "('C001','Italy','Europe'))"; - st.execute(countryFilling); - - String residenceFilling = "insert into RESIDENCE (ID,CITY,COUNTRY) values (" + "('R001','Rome','C001')," + "('R002','Milan','C001'))"; - st.execute(residenceFilling); - - String managerFilling = "insert into MANAGER (ID,NAME) values (" + "('M001','Bill Right'))"; - st.execute(managerFilling); - - String projectManagerFilling = "insert into PROJECT_MANAGER (EID,PROJECT) values (" + "('M001','New World'))"; - st.execute(projectManagerFilling); - - String employeeFilling = - "insert into EMPLOYEE (ID,NAME,RESIDENCE,MANAGER) values (" + - "('E001','John Black','R001',null)," + - "('E002','Andrew Brown','R001','M001')," + - "('E003','Jack Johnson','R002',null))"; - st.execute(employeeFilling); - - String regularEmployeeFilling = "insert into REGULAR_EMPLOYEE (EID,SALARY,BONUS) values (" + "('E002','1000.00','10'))"; - st.execute(regularEmployeeFilling); - - String contractEmployeeFilling = "insert into CONTRACT_EMPLOYEE (EID,PAY_PER_HOUR,CONTRACT_DURATION) values (" + "('E003','50.00','6'))"; - st.execute(contractEmployeeFilling); - - List includedTables = new ArrayList(); - includedTables.add("COUNTRY"); - includedTables.add("MANAGER"); - includedTables.add("PROJECT_MANAGER"); - includedTables.add("EMPLOYEE"); - includedTables.add("REGULAR_EMPLOYEE"); - includedTables.add("CONTRACT_EMPLOYEE"); - - this.mapper = - new Hibernate2GraphMapper( - dataSource, - FilterTableMappingTest.XML_TABLE_PER_SUBCLASS1, - includedTables, - null, - dbQueryEngine, - dataTypeHandler, - executionStrategy, - nameResolver, - statistics - ); - mapper.buildSourceDatabaseSchema(); - mapper.buildGraphModel(new JavaConventionNameResolver()); - - /* - * Testing context information - */ - - assertEquals(6, statistics.totalNumberOfEntities); - assertEquals(6, statistics.builtEntities); - assertEquals(4, statistics.totalNumberOfRelationships); - assertEquals(4, statistics.builtRelationships); // 3 of these are hierarchical relationships - - assertEquals(6, statistics.totalNumberOfModelVertices); - assertEquals(6, statistics.builtModelVertexTypes); - assertEquals(1, statistics.totalNumberOfModelEdges); - assertEquals(1, statistics.builtModelEdgeTypes); - - /* - * Testing built source db schema - */ - - Entity employeeEntity = mapper.getDataBaseSchema().getEntityByName("EMPLOYEE"); - Entity regularEmployeeEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("REGULAR_EMPLOYEE"); - Entity contractEmployeeEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("CONTRACT_EMPLOYEE"); - Entity countryEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("COUNTRY"); - Entity managerEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("MANAGER"); - Entity projectManagerEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("PROJECT_MANAGER"); - Entity residenceEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("RESIDENCE"); - - // entities check - assertEquals(6, mapper.getDataBaseSchema().getEntities().size()); - assertEquals(4, mapper.getDataBaseSchema().getCanonicalRelationships().size()); - assertNotNull(employeeEntity); - assertNotNull(regularEmployeeEntity); - assertNotNull(contractEmployeeEntity); - assertNotNull(countryEntity); - assertNotNull(managerEntity); - assertNull(residenceEntity); - - // attributes check - assertEquals(4, employeeEntity.getAttributes().size()); - - assertNotNull(employeeEntity.getAttributeByName("ID")); - assertEquals("ID", employeeEntity.getAttributeByName("ID").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("ID").getDataType()); - assertEquals(1, employeeEntity.getAttributeByName("ID").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(employeeEntity.getAttributeByName("NAME")); - assertEquals("NAME", employeeEntity.getAttributeByName("NAME").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("NAME").getDataType()); - assertEquals(2, employeeEntity.getAttributeByName("NAME").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(employeeEntity.getAttributeByName("RESIDENCE")); - assertEquals("RESIDENCE", employeeEntity.getAttributeByName("RESIDENCE").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("RESIDENCE").getDataType()); - assertEquals(3, employeeEntity.getAttributeByName("RESIDENCE").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("RESIDENCE").getBelongingEntity().getName()); - - assertNotNull(employeeEntity.getAttributeByName("MANAGER")); - assertEquals("MANAGER", employeeEntity.getAttributeByName("MANAGER").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("MANAGER").getDataType()); - assertEquals(4, employeeEntity.getAttributeByName("MANAGER").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("MANAGER").getBelongingEntity().getName()); - - assertEquals(2, regularEmployeeEntity.getAttributes().size()); - - assertNotNull(regularEmployeeEntity.getAttributeByName("SALARY")); - assertEquals("SALARY", regularEmployeeEntity.getAttributeByName("SALARY").getName()); - assertEquals("DECIMAL", regularEmployeeEntity.getAttributeByName("SALARY").getDataType()); - assertEquals(1, regularEmployeeEntity.getAttributeByName("SALARY").getOrdinalPosition()); - assertEquals("REGULAR_EMPLOYEE", regularEmployeeEntity.getAttributeByName("SALARY").getBelongingEntity().getName()); - - assertNotNull(regularEmployeeEntity.getAttributeByName("BONUS")); - assertEquals("BONUS", regularEmployeeEntity.getAttributeByName("BONUS").getName()); - assertEquals("DECIMAL", regularEmployeeEntity.getAttributeByName("BONUS").getDataType()); - assertEquals(2, regularEmployeeEntity.getAttributeByName("BONUS").getOrdinalPosition()); - assertEquals("REGULAR_EMPLOYEE", regularEmployeeEntity.getAttributeByName("BONUS").getBelongingEntity().getName()); - - assertEquals(2, contractEmployeeEntity.getAttributes().size()); - - assertNotNull(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR")); - assertEquals("PAY_PER_HOUR", contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getName()); - assertEquals("DECIMAL", contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getDataType()); - assertEquals(1, contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getOrdinalPosition()); - assertEquals("CONTRACT_EMPLOYEE", contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getBelongingEntity().getName()); - - assertNotNull(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION")); - assertEquals("CONTRACT_DURATION", contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getDataType()); - assertEquals(2, contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getOrdinalPosition()); - assertEquals("CONTRACT_EMPLOYEE", contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getBelongingEntity().getName()); - - assertEquals(3, countryEntity.getAttributes().size()); - - assertNotNull(countryEntity.getAttributeByName("ID")); - assertEquals("ID", countryEntity.getAttributeByName("ID").getName()); - assertEquals("VARCHAR", countryEntity.getAttributeByName("ID").getDataType()); - assertEquals(1, countryEntity.getAttributeByName("ID").getOrdinalPosition()); - assertEquals("COUNTRY", countryEntity.getAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(countryEntity.getAttributeByName("NAME")); - assertEquals("NAME", countryEntity.getAttributeByName("NAME").getName()); - assertEquals("VARCHAR", countryEntity.getAttributeByName("NAME").getDataType()); - assertEquals(2, countryEntity.getAttributeByName("NAME").getOrdinalPosition()); - assertEquals("COUNTRY", countryEntity.getAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(countryEntity.getAttributeByName("CONTINENT")); - assertEquals("CONTINENT", countryEntity.getAttributeByName("CONTINENT").getName()); - assertEquals("VARCHAR", countryEntity.getAttributeByName("CONTINENT").getDataType()); - assertEquals(3, countryEntity.getAttributeByName("CONTINENT").getOrdinalPosition()); - assertEquals("COUNTRY", countryEntity.getAttributeByName("CONTINENT").getBelongingEntity().getName()); - - assertEquals(2, managerEntity.getAttributes().size()); - - assertNotNull(managerEntity.getAttributeByName("ID")); - assertEquals("ID", managerEntity.getAttributeByName("ID").getName()); - assertEquals("VARCHAR", managerEntity.getAttributeByName("ID").getDataType()); - assertEquals(1, managerEntity.getAttributeByName("ID").getOrdinalPosition()); - assertEquals("MANAGER", managerEntity.getAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(managerEntity.getAttributeByName("NAME")); - assertEquals("NAME", managerEntity.getAttributeByName("NAME").getName()); - assertEquals("VARCHAR", managerEntity.getAttributeByName("NAME").getDataType()); - assertEquals(2, managerEntity.getAttributeByName("NAME").getOrdinalPosition()); - assertEquals("MANAGER", managerEntity.getAttributeByName("NAME").getBelongingEntity().getName()); - - assertEquals(1, projectManagerEntity.getAttributes().size()); - - assertNotNull(projectManagerEntity.getAttributeByName("PROJECT")); - assertEquals("PROJECT", projectManagerEntity.getAttributeByName("PROJECT").getName()); - assertEquals("VARCHAR", projectManagerEntity.getAttributeByName("PROJECT").getDataType()); - assertEquals(1, projectManagerEntity.getAttributeByName("PROJECT").getOrdinalPosition()); - assertEquals("PROJECT_MANAGER", projectManagerEntity.getAttributeByName("PROJECT").getBelongingEntity().getName()); - - // inherited attributes check - assertEquals(0, employeeEntity.getInheritedAttributes().size()); - - assertEquals(4, regularEmployeeEntity.getInheritedAttributes().size()); - - assertNotNull(regularEmployeeEntity.getInheritedAttributeByName("ID")); - assertEquals("ID", regularEmployeeEntity.getInheritedAttributeByName("ID").getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getInheritedAttributeByName("ID").getDataType()); - assertEquals(1, regularEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()); - assertEquals("EMPLOYEE", regularEmployeeEntity.getInheritedAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(regularEmployeeEntity.getInheritedAttributeByName("NAME")); - assertEquals("NAME", regularEmployeeEntity.getInheritedAttributeByName("NAME").getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()); - assertEquals(2, regularEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()); - assertEquals("EMPLOYEE", regularEmployeeEntity.getInheritedAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE")); - assertEquals("RESIDENCE", regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()); - assertEquals(3, regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()); - assertEquals("EMPLOYEE", regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getBelongingEntity().getName()); - - assertNotNull(regularEmployeeEntity.getInheritedAttributeByName("MANAGER")); - assertEquals("MANAGER", regularEmployeeEntity.getInheritedAttributeByName("MANAGER").getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getInheritedAttributeByName("MANAGER").getDataType()); - assertEquals(4, regularEmployeeEntity.getInheritedAttributeByName("MANAGER").getOrdinalPosition()); - assertEquals("EMPLOYEE", regularEmployeeEntity.getInheritedAttributeByName("MANAGER").getBelongingEntity().getName()); - - assertEquals(4, contractEmployeeEntity.getInheritedAttributes().size()); - - assertNotNull(contractEmployeeEntity.getInheritedAttributeByName("ID")); - assertEquals("ID", contractEmployeeEntity.getInheritedAttributeByName("ID").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getInheritedAttributeByName("ID").getDataType()); - assertEquals(1, contractEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()); - assertEquals("EMPLOYEE", contractEmployeeEntity.getInheritedAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(contractEmployeeEntity.getInheritedAttributeByName("NAME")); - assertEquals("NAME", contractEmployeeEntity.getInheritedAttributeByName("NAME").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()); - assertEquals(2, contractEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()); - assertEquals("EMPLOYEE", contractEmployeeEntity.getInheritedAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE")); - assertEquals("RESIDENCE", contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()); - assertEquals(3, contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()); - assertEquals("EMPLOYEE", contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getBelongingEntity().getName()); - - assertNotNull(contractEmployeeEntity.getInheritedAttributeByName("MANAGER")); - assertEquals("MANAGER", contractEmployeeEntity.getInheritedAttributeByName("MANAGER").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getInheritedAttributeByName("MANAGER").getDataType()); - assertEquals(4, contractEmployeeEntity.getInheritedAttributeByName("MANAGER").getOrdinalPosition()); - assertEquals("EMPLOYEE", contractEmployeeEntity.getInheritedAttributeByName("MANAGER").getBelongingEntity().getName()); - - assertEquals(2, projectManagerEntity.getInheritedAttributes().size()); - - assertNotNull(projectManagerEntity.getInheritedAttributeByName("ID")); - assertEquals("ID", projectManagerEntity.getInheritedAttributeByName("ID").getName()); - assertEquals("VARCHAR", projectManagerEntity.getInheritedAttributeByName("ID").getDataType()); - assertEquals(1, projectManagerEntity.getInheritedAttributeByName("ID").getOrdinalPosition()); - assertEquals("MANAGER", projectManagerEntity.getInheritedAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(projectManagerEntity.getInheritedAttributeByName("NAME")); - assertEquals("NAME", projectManagerEntity.getInheritedAttributeByName("NAME").getName()); - assertEquals("VARCHAR", projectManagerEntity.getInheritedAttributeByName("NAME").getDataType()); - assertEquals(2, projectManagerEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()); - assertEquals("MANAGER", projectManagerEntity.getInheritedAttributeByName("NAME").getBelongingEntity().getName()); - - assertEquals(0, countryEntity.getInheritedAttributes().size()); - assertEquals(0, managerEntity.getInheritedAttributes().size()); - - // primary key check - assertEquals(1, regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()); - assertEquals("EID", regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()); - assertEquals("REGULAR_EMPLOYEE", regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getBelongingEntity().getName()); - - assertEquals(1, contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()); - assertEquals("EID", contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()); - assertEquals("CONTRACT_EMPLOYEE", contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getBelongingEntity().getName()); - - assertEquals(1, projectManagerEntity.getPrimaryKey().getInvolvedAttributes().size()); - assertEquals("EID", projectManagerEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()); - assertEquals("VARCHAR", projectManagerEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()); - assertEquals("PROJECT_MANAGER", projectManagerEntity.getPrimaryKey().getInvolvedAttributes().get(0).getBelongingEntity().getName()); - - // relationship, primary and foreign key check - assertEquals(1, regularEmployeeEntity.getOutCanonicalRelationships().size()); - assertEquals(1, contractEmployeeEntity.getOutCanonicalRelationships().size()); - assertEquals(1, employeeEntity.getOutCanonicalRelationships().size()); - assertEquals(1, projectManagerEntity.getOutCanonicalRelationships().size()); - assertEquals(0, managerEntity.getOutCanonicalRelationships().size()); - assertEquals(0, countryEntity.getOutCanonicalRelationships().size()); - assertEquals(0, regularEmployeeEntity.getInCanonicalRelationships().size()); - assertEquals(0, contractEmployeeEntity.getInCanonicalRelationships().size()); - assertEquals(2, employeeEntity.getInCanonicalRelationships().size()); - assertEquals(0, projectManagerEntity.getInCanonicalRelationships().size()); - assertEquals(2, managerEntity.getInCanonicalRelationships().size()); - assertEquals(0, countryEntity.getInCanonicalRelationships().size()); - - assertEquals(1, regularEmployeeEntity.getForeignKeys().size()); - assertEquals(1, contractEmployeeEntity.getForeignKeys().size()); - assertEquals(1, employeeEntity.getForeignKeys().size()); - assertEquals(1, projectManagerEntity.getForeignKeys().size()); - assertEquals(0, managerEntity.getForeignKeys().size()); - assertEquals(0, countryEntity.getForeignKeys().size()); - - Iterator itEmp = employeeEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship currentEmpRel = itEmp.next(); - assertEquals("MANAGER", currentEmpRel.getParentEntity().getName()); - assertEquals("EMPLOYEE", currentEmpRel.getForeignEntity().getName()); - assertEquals(managerEntity.getPrimaryKey(), currentEmpRel.getPrimaryKey()); - assertEquals(employeeEntity.getForeignKeys().get(0), currentEmpRel.getForeignKey()); - assertFalse(itEmp.hasNext()); - - Iterator itManager = managerEntity.getInCanonicalRelationships().iterator(); - CanonicalRelationship currentManRel = itManager.next(); - assertEquals(currentEmpRel, currentManRel); - - Iterator itContEmp = contractEmployeeEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship currentContEmpRel = itContEmp.next(); - itEmp = employeeEntity.getInCanonicalRelationships().iterator(); - currentEmpRel = itEmp.next(); - assertEquals(currentContEmpRel, currentEmpRel); - - Iterator itRegEmp = regularEmployeeEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship currentRegEmpRel = itRegEmp.next(); - currentEmpRel = itEmp.next(); - assertEquals(currentRegEmpRel, currentEmpRel); - - // inherited relationships check - assertEquals(1, regularEmployeeEntity.getInheritedOutCanonicalRelationships().size()); - assertEquals(1, contractEmployeeEntity.getInheritedOutCanonicalRelationships().size()); - assertEquals(0, employeeEntity.getInheritedOutCanonicalRelationships().size()); - - itRegEmp = regularEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); - itContEmp = contractEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); - currentRegEmpRel = itRegEmp.next(); - currentContEmpRel = itContEmp.next(); - assertEquals("MANAGER", currentRegEmpRel.getParentEntity().getName()); - assertEquals("EMPLOYEE", currentRegEmpRel.getForeignEntity().getName()); - assertEquals("MANAGER", currentContEmpRel.getParentEntity().getName()); - assertEquals("EMPLOYEE", currentContEmpRel.getForeignEntity().getName()); - assertEquals(managerEntity.getPrimaryKey(), currentRegEmpRel.getPrimaryKey()); - assertEquals(1, currentRegEmpRel.getFromColumns().size()); - assertEquals("MANAGER", currentRegEmpRel.getFromColumns().get(0).getName()); - assertEquals(managerEntity.getPrimaryKey(), currentContEmpRel.getPrimaryKey()); - assertEquals(1, currentContEmpRel.getFromColumns().size()); - assertEquals("MANAGER", currentContEmpRel.getFromColumns().get(0).getName()); - assertFalse(itRegEmp.hasNext()); - assertFalse(itContEmp.hasNext()); - - // inheritance check - assertEquals(employeeEntity, regularEmployeeEntity.getParentEntity()); - assertEquals(employeeEntity, contractEmployeeEntity.getParentEntity()); - assertNull(employeeEntity.getParentEntity()); - - assertEquals(1, regularEmployeeEntity.getInheritanceLevel()); - assertEquals(1, contractEmployeeEntity.getInheritanceLevel()); - assertEquals(0, employeeEntity.getInheritanceLevel()); - - // Hierarchical Bag check - assertEquals(2, mapper.getDataBaseSchema().getHierarchicalBags().size()); - - HierarchicalBag hierarchicalBag1 = mapper.getDataBaseSchema().getHierarchicalBags().get(0); - HierarchicalBag hierarchicalBag2 = mapper.getDataBaseSchema().getHierarchicalBags().get(1); - assertEquals("table-per-type", hierarchicalBag1.getInheritancePattern()); - assertEquals("table-per-type", hierarchicalBag2.getInheritancePattern()); - - assertEquals(2, hierarchicalBag1.getDepth2entities().size()); - - assertEquals(1, hierarchicalBag1.getDepth2entities().get(0).size()); - Iterator it = hierarchicalBag1.getDepth2entities().get(0).iterator(); - assertEquals("EMPLOYEE", it.next().getName()); - assertTrue(!it.hasNext()); - - assertEquals(2, hierarchicalBag1.getDepth2entities().get(1).size()); - it = hierarchicalBag1.getDepth2entities().get(1).iterator(); - assertEquals("REGULAR_EMPLOYEE", it.next().getName()); - assertEquals("CONTRACT_EMPLOYEE", it.next().getName()); - assertTrue(!it.hasNext()); - - assertEquals(hierarchicalBag1, employeeEntity.getHierarchicalBag()); - assertEquals(hierarchicalBag1, regularEmployeeEntity.getHierarchicalBag()); - assertEquals(hierarchicalBag1, contractEmployeeEntity.getHierarchicalBag()); - - assertNull(hierarchicalBag1.getDiscriminatorColumn()); - - assertEquals(2, hierarchicalBag2.getDepth2entities().size()); - - assertEquals(1, hierarchicalBag2.getDepth2entities().get(0).size()); - it = hierarchicalBag2.getDepth2entities().get(0).iterator(); - assertEquals("MANAGER", it.next().getName()); - assertTrue(!it.hasNext()); - - assertEquals(1, hierarchicalBag2.getDepth2entities().get(1).size()); - it = hierarchicalBag2.getDepth2entities().get(1).iterator(); - assertEquals("PROJECT_MANAGER", it.next().getName()); - assertTrue(!it.hasNext()); - - assertEquals(hierarchicalBag2, managerEntity.getHierarchicalBag()); - assertEquals(hierarchicalBag2, projectManagerEntity.getHierarchicalBag()); - - assertNull(hierarchicalBag2.getDiscriminatorColumn()); - - /* - * Testing built graph model - */ - - VertexType employeeVertexType = mapper.getGraphModel().getVertexTypeByName("Employee"); - VertexType regularEmployeeVertexType = mapper.getGraphModel().getVertexTypeByName("RegularEmployee"); - VertexType contractEmployeeVertexType = mapper.getGraphModel().getVertexTypeByName("ContractEmployee"); - VertexType countryVertexType = mapper.getGraphModel().getVertexTypeByName("Country"); - VertexType managerVertexType = mapper.getGraphModel().getVertexTypeByName("Manager"); - VertexType projectManagerVertexType = mapper.getGraphModel().getVertexTypeByName("ProjectManager"); - VertexType residenceVertexType = mapper.getGraphModel().getVertexTypeByName("Residence"); - - // vertices check - assertEquals(6, mapper.getGraphModel().getVerticesType().size()); - assertNotNull(employeeVertexType); - assertNotNull(regularEmployeeVertexType); - assertNotNull(contractEmployeeVertexType); - assertNotNull(countryVertexType); - assertNotNull(managerVertexType); - assertNotNull(projectManagerVertexType); - assertNull(residenceVertexType); - - // properties check - assertEquals(4, employeeVertexType.getProperties().size()); - - assertNotNull(employeeVertexType.getPropertyByName("id")); - assertEquals("id", employeeVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, employeeVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, employeeVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(employeeVertexType.getPropertyByName("name")); - assertEquals("name", employeeVertexType.getPropertyByName("name").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("name").getOriginalType()); - assertEquals(2, employeeVertexType.getPropertyByName("name").getOrdinalPosition()); - assertEquals(false, employeeVertexType.getPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(employeeVertexType.getPropertyByName("residence")); - assertEquals("residence", employeeVertexType.getPropertyByName("residence").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("residence").getOriginalType()); - assertEquals(3, employeeVertexType.getPropertyByName("residence").getOrdinalPosition()); - assertEquals(false, employeeVertexType.getPropertyByName("residence").isFromPrimaryKey()); - - assertNotNull(employeeVertexType.getPropertyByName("manager")); - assertEquals("manager", employeeVertexType.getPropertyByName("manager").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("manager").getOriginalType()); - assertEquals(4, employeeVertexType.getPropertyByName("manager").getOrdinalPosition()); - assertEquals(false, employeeVertexType.getPropertyByName("manager").isFromPrimaryKey()); - - assertEquals(2, regularEmployeeVertexType.getProperties().size()); - - assertNotNull(regularEmployeeVertexType.getPropertyByName("salary")); - assertEquals("salary", regularEmployeeVertexType.getPropertyByName("salary").getName()); - assertEquals("DECIMAL", regularEmployeeVertexType.getPropertyByName("salary").getOriginalType()); - assertEquals(1, regularEmployeeVertexType.getPropertyByName("salary").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getPropertyByName("salary").isFromPrimaryKey()); - - assertNotNull(regularEmployeeVertexType.getPropertyByName("bonus")); - assertEquals("bonus", regularEmployeeVertexType.getPropertyByName("bonus").getName()); - assertEquals("DECIMAL", regularEmployeeVertexType.getPropertyByName("bonus").getOriginalType()); - assertEquals(2, regularEmployeeVertexType.getPropertyByName("bonus").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getPropertyByName("bonus").isFromPrimaryKey()); - - assertEquals(2, contractEmployeeVertexType.getProperties().size()); - - assertNotNull(contractEmployeeVertexType.getPropertyByName("payPerHour")); - assertEquals("payPerHour", contractEmployeeVertexType.getPropertyByName("payPerHour").getName()); - assertEquals("DECIMAL", contractEmployeeVertexType.getPropertyByName("payPerHour").getOriginalType()); - assertEquals(1, contractEmployeeVertexType.getPropertyByName("payPerHour").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getPropertyByName("payPerHour").isFromPrimaryKey()); - - assertNotNull(contractEmployeeVertexType.getPropertyByName("contractDuration")); - assertEquals("contractDuration", contractEmployeeVertexType.getPropertyByName("contractDuration").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getPropertyByName("contractDuration").getOriginalType()); - assertEquals(2, contractEmployeeVertexType.getPropertyByName("contractDuration").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getPropertyByName("contractDuration").isFromPrimaryKey()); - - assertEquals(3, countryVertexType.getProperties().size()); - - assertNotNull(countryVertexType.getPropertyByName("id")); - assertEquals("id", countryVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", countryVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, countryVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, countryVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(countryVertexType.getPropertyByName("name")); - assertEquals("name", countryVertexType.getPropertyByName("name").getName()); - assertEquals("VARCHAR", countryVertexType.getPropertyByName("name").getOriginalType()); - assertEquals(2, countryVertexType.getPropertyByName("name").getOrdinalPosition()); - assertEquals(false, countryVertexType.getPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(countryVertexType.getPropertyByName("continent")); - assertEquals("continent", countryVertexType.getPropertyByName("continent").getName()); - assertEquals("VARCHAR", countryVertexType.getPropertyByName("continent").getOriginalType()); - assertEquals(3, countryVertexType.getPropertyByName("continent").getOrdinalPosition()); - assertEquals(false, countryVertexType.getPropertyByName("continent").isFromPrimaryKey()); - - assertEquals(2, managerVertexType.getProperties().size()); - - assertNotNull(managerVertexType.getPropertyByName("id")); - assertEquals("id", managerVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", managerVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, managerVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, managerVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(managerVertexType.getPropertyByName("name")); - assertEquals("name", managerVertexType.getPropertyByName("name").getName()); - assertEquals("VARCHAR", managerVertexType.getPropertyByName("name").getOriginalType()); - assertEquals(2, managerVertexType.getPropertyByName("name").getOrdinalPosition()); - assertEquals(false, managerVertexType.getPropertyByName("name").isFromPrimaryKey()); - - assertEquals(1, projectManagerVertexType.getProperties().size()); - - assertNotNull(projectManagerVertexType.getPropertyByName("project")); - assertEquals("project", projectManagerVertexType.getPropertyByName("project").getName()); - assertEquals("VARCHAR", projectManagerVertexType.getPropertyByName("project").getOriginalType()); - assertEquals(1, projectManagerVertexType.getPropertyByName("project").getOrdinalPosition()); - assertEquals(false, projectManagerVertexType.getPropertyByName("project").isFromPrimaryKey()); - - // inherited properties check - assertEquals(0, employeeVertexType.getInheritedProperties().size()); - - assertEquals(4, regularEmployeeVertexType.getInheritedProperties().size()); - - assertNotNull(regularEmployeeVertexType.getInheritedPropertyByName("id")); - assertEquals("id", regularEmployeeVertexType.getInheritedPropertyByName("id").getName()); - assertEquals("VARCHAR", regularEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()); - assertEquals(1, regularEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(regularEmployeeVertexType.getInheritedPropertyByName("name")); - assertEquals("name", regularEmployeeVertexType.getInheritedPropertyByName("name").getName()); - assertEquals("VARCHAR", regularEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()); - assertEquals(2, regularEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(regularEmployeeVertexType.getInheritedPropertyByName("residence")); - assertEquals("residence", regularEmployeeVertexType.getInheritedPropertyByName("residence").getName()); - assertEquals("VARCHAR", regularEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()); - assertEquals(3, regularEmployeeVertexType.getInheritedPropertyByName("residence").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()); - - assertNotNull(regularEmployeeVertexType.getInheritedPropertyByName("manager")); - assertEquals("manager", regularEmployeeVertexType.getInheritedPropertyByName("manager").getName()); - assertEquals("VARCHAR", regularEmployeeVertexType.getInheritedPropertyByName("manager").getOriginalType()); - assertEquals(4, regularEmployeeVertexType.getInheritedPropertyByName("manager").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getInheritedPropertyByName("manager").isFromPrimaryKey()); - - assertEquals(4, contractEmployeeVertexType.getInheritedProperties().size()); - - assertNotNull(contractEmployeeVertexType.getInheritedPropertyByName("id")); - assertEquals("id", contractEmployeeVertexType.getInheritedPropertyByName("id").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()); - assertEquals(1, contractEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(contractEmployeeVertexType.getInheritedPropertyByName("name")); - assertEquals("name", contractEmployeeVertexType.getInheritedPropertyByName("name").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()); - assertEquals(2, contractEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(contractEmployeeVertexType.getInheritedPropertyByName("residence")); - assertEquals("residence", contractEmployeeVertexType.getInheritedPropertyByName("residence").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()); - assertEquals(3, contractEmployeeVertexType.getInheritedPropertyByName("residence").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()); - - assertNotNull(contractEmployeeVertexType.getInheritedPropertyByName("manager")); - assertEquals("manager", contractEmployeeVertexType.getInheritedPropertyByName("manager").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getInheritedPropertyByName("manager").getOriginalType()); - assertEquals(4, contractEmployeeVertexType.getInheritedPropertyByName("manager").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getInheritedPropertyByName("manager").isFromPrimaryKey()); - - assertEquals(2, projectManagerVertexType.getInheritedProperties().size()); - - assertNotNull(projectManagerVertexType.getInheritedPropertyByName("id")); - assertEquals("id", projectManagerVertexType.getInheritedPropertyByName("id").getName()); - assertEquals("VARCHAR", projectManagerVertexType.getInheritedPropertyByName("id").getOriginalType()); - assertEquals(1, projectManagerVertexType.getInheritedPropertyByName("id").getOrdinalPosition()); - assertEquals(false, projectManagerVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(projectManagerVertexType.getInheritedPropertyByName("name")); - assertEquals("name", projectManagerVertexType.getInheritedPropertyByName("name").getName()); - assertEquals("VARCHAR", projectManagerVertexType.getInheritedPropertyByName("name").getOriginalType()); - assertEquals(2, projectManagerVertexType.getInheritedPropertyByName("name").getOrdinalPosition()); - assertEquals(false, projectManagerVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()); - - assertEquals(0, countryVertexType.getInheritedProperties().size()); - assertEquals(0, managerVertexType.getInheritedProperties().size()); - - // edges check - - assertEquals(1, mapper.getRelationship2edgeType().size()); - - assertEquals(1, mapper.getGraphModel().getEdgesType().size()); - assertEquals("HasManager", mapper.getGraphModel().getEdgesType().get(0).getName()); - - assertEquals(1, employeeVertexType.getOutEdgesType().size()); - assertEquals("HasManager", employeeVertexType.getOutEdgesType().get(0).getName()); - - assertEquals(1, regularEmployeeVertexType.getOutEdgesType().size()); - assertEquals("HasManager", regularEmployeeVertexType.getOutEdgesType().get(0).getName()); - - assertEquals(1, contractEmployeeVertexType.getOutEdgesType().size()); - assertEquals("HasManager", contractEmployeeVertexType.getOutEdgesType().get(0).getName()); - - /* - * Rules check - */ - - // Classes Mapping - - assertEquals(6, mapper.getVertexType2EVClassMappers().size()); - assertEquals(6, mapper.getEntity2EVClassMappers().size()); - - assertEquals(1, mapper.getEVClassMappersByVertex(employeeVertexType).size()); - EVClassMapper employeeClassMapper = mapper.getEVClassMappersByVertex(employeeVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(employeeEntity).size()); - assertEquals(employeeClassMapper, mapper.getEVClassMappersByEntity(employeeEntity).get(0)); - assertEquals(employeeClassMapper.getEntity(), employeeEntity); - assertEquals(employeeClassMapper.getVertexType(), employeeVertexType); - - assertEquals(4, employeeClassMapper.getAttribute2property().size()); - assertEquals(4, employeeClassMapper.getProperty2attribute().size()); - assertEquals("id", employeeClassMapper.getAttribute2property().get("ID")); - assertEquals("name", employeeClassMapper.getAttribute2property().get("NAME")); - assertEquals("residence", employeeClassMapper.getAttribute2property().get("RESIDENCE")); - assertEquals("manager", employeeClassMapper.getAttribute2property().get("MANAGER")); - assertEquals("ID", employeeClassMapper.getProperty2attribute().get("id")); - assertEquals("NAME", employeeClassMapper.getProperty2attribute().get("name")); - assertEquals("RESIDENCE", employeeClassMapper.getProperty2attribute().get("residence")); - assertEquals("MANAGER", employeeClassMapper.getProperty2attribute().get("manager")); - - assertEquals(1, mapper.getEVClassMappersByVertex(regularEmployeeVertexType).size()); - EVClassMapper regularEmployeeClassMapper = mapper.getEVClassMappersByVertex(regularEmployeeVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(regularEmployeeEntity).size()); - assertEquals(regularEmployeeClassMapper, mapper.getEVClassMappersByEntity(regularEmployeeEntity).get(0)); - assertEquals(regularEmployeeClassMapper.getEntity(), regularEmployeeEntity); - assertEquals(regularEmployeeClassMapper.getVertexType(), regularEmployeeVertexType); - - assertEquals(2, regularEmployeeClassMapper.getAttribute2property().size()); - assertEquals(2, regularEmployeeClassMapper.getProperty2attribute().size()); - assertEquals("salary", regularEmployeeClassMapper.getAttribute2property().get("SALARY")); - assertEquals("bonus", regularEmployeeClassMapper.getAttribute2property().get("BONUS")); - assertEquals("SALARY", regularEmployeeClassMapper.getProperty2attribute().get("salary")); - assertEquals("BONUS", regularEmployeeClassMapper.getProperty2attribute().get("bonus")); - - assertEquals(1, mapper.getEVClassMappersByVertex(contractEmployeeVertexType).size()); - EVClassMapper contractEmployeeClassMapper = mapper.getEVClassMappersByVertex(contractEmployeeVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(contractEmployeeEntity).size()); - assertEquals(contractEmployeeClassMapper, mapper.getEVClassMappersByEntity(contractEmployeeEntity).get(0)); - assertEquals(contractEmployeeClassMapper.getEntity(), contractEmployeeEntity); - assertEquals(contractEmployeeClassMapper.getVertexType(), contractEmployeeVertexType); - - assertEquals(2, contractEmployeeClassMapper.getAttribute2property().size()); - assertEquals(2, contractEmployeeClassMapper.getProperty2attribute().size()); - assertEquals("payPerHour", contractEmployeeClassMapper.getAttribute2property().get("PAY_PER_HOUR")); - assertEquals("contractDuration", contractEmployeeClassMapper.getAttribute2property().get("CONTRACT_DURATION")); - assertEquals("PAY_PER_HOUR", contractEmployeeClassMapper.getProperty2attribute().get("payPerHour")); - assertEquals("CONTRACT_DURATION", contractEmployeeClassMapper.getProperty2attribute().get("contractDuration")); - - assertEquals(1, mapper.getEVClassMappersByVertex(countryVertexType).size()); - EVClassMapper countryClassMapper = mapper.getEVClassMappersByVertex(countryVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(countryEntity).size()); - assertEquals(countryClassMapper, mapper.getEVClassMappersByEntity(countryEntity).get(0)); - assertEquals(countryClassMapper.getEntity(), countryEntity); - assertEquals(countryClassMapper.getVertexType(), countryVertexType); - - assertEquals(3, countryClassMapper.getAttribute2property().size()); - assertEquals(3, countryClassMapper.getProperty2attribute().size()); - assertEquals("id", countryClassMapper.getAttribute2property().get("ID")); - assertEquals("name", countryClassMapper.getAttribute2property().get("NAME")); - assertEquals("continent", countryClassMapper.getAttribute2property().get("CONTINENT")); - assertEquals("ID", countryClassMapper.getProperty2attribute().get("id")); - assertEquals("NAME", countryClassMapper.getProperty2attribute().get("name")); - assertEquals("CONTINENT", countryClassMapper.getProperty2attribute().get("continent")); - - assertEquals(1, mapper.getEVClassMappersByVertex(managerVertexType).size()); - EVClassMapper managerClassMapper = mapper.getEVClassMappersByVertex(managerVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(managerEntity).size()); - assertEquals(managerClassMapper, mapper.getEVClassMappersByEntity(managerEntity).get(0)); - assertEquals(managerClassMapper.getEntity(), managerEntity); - assertEquals(managerClassMapper.getVertexType(), managerVertexType); - - assertEquals(2, managerClassMapper.getAttribute2property().size()); - assertEquals(2, managerClassMapper.getProperty2attribute().size()); - assertEquals("id", managerClassMapper.getAttribute2property().get("ID")); - assertEquals("name", managerClassMapper.getAttribute2property().get("NAME")); - assertEquals("ID", managerClassMapper.getProperty2attribute().get("id")); - assertEquals("NAME", managerClassMapper.getProperty2attribute().get("name")); - - assertEquals(1, mapper.getEVClassMappersByVertex(projectManagerVertexType).size()); - EVClassMapper projectManagerClassMapper = mapper.getEVClassMappersByVertex(projectManagerVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(projectManagerEntity).size()); - assertEquals(projectManagerClassMapper, mapper.getEVClassMappersByEntity(projectManagerEntity).get(0)); - assertEquals(projectManagerClassMapper.getEntity(), projectManagerEntity); - assertEquals(projectManagerClassMapper.getVertexType(), projectManagerVertexType); - - assertEquals(1, projectManagerClassMapper.getAttribute2property().size()); - assertEquals(1, projectManagerClassMapper.getProperty2attribute().size()); - assertEquals("project", projectManagerClassMapper.getAttribute2property().get("PROJECT")); - assertEquals("PROJECT", projectManagerClassMapper.getProperty2attribute().get("project")); - - // Relationships-Edges Mapping - - Iterator itRelationships = employeeEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship hasManagerRelationship = itRelationships.next(); - assertFalse(itRelationships.hasNext()); - - EdgeType hasManagerEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasManager"); - - assertEquals(1, mapper.getRelationship2edgeType().size()); - assertEquals(hasManagerEdgeType, mapper.getRelationship2edgeType().get(hasManagerRelationship)); - - assertEquals(1, mapper.getEdgeType2relationships().size()); - assertEquals(1, mapper.getEdgeType2relationships().get(hasManagerEdgeType).size()); - assertTrue(mapper.getEdgeType2relationships().get(hasManagerEdgeType).contains(hasManagerRelationship)); - - // JoinVertexes-AggregatorEdges Mapping - - assertEquals(0, mapper.getJoinVertex2aggregatorEdges().size()); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } finally { - try { - // Dropping Source DB Schema and OrientGraph - String dbDropping = "drop schema public cascade"; - st.execute(dbDropping); - connection.close(); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } - } + } + + /* + * Filtering out a table through include-tables (with Table per Type inheritance). + */ @Test + void filterOutThroughIncludeWithTablePerTypeInheritance() { + Connection connection = null; + Statement st = null; + + try { + Class.forName(this.driver); + connection = DriverManager.getConnection(this.jurl, this.username, this.password); + + String countryTableBuilding = + "create memory table COUNTRY(ID varchar(256) not null, NAME varchar(256), CONTINENT" + + " varchar(256), primary key (ID))"; + st = connection.createStatement(); + st.execute(countryTableBuilding); + + String residenceTableBuilding = + "create memory table RESIDENCE(ID varchar(256) not null, CITY varchar(256), COUNTRY" + + " varchar(256), primary key (ID))"; + st = connection.createStatement(); + st.execute(residenceTableBuilding); + + String managerTableBuilding = + "create memory table MANAGER(ID varchar(256) not null, NAME varchar(256), primary key" + + " (ID))"; + st.execute(managerTableBuilding); + + String projectManagerTableBuilding = + "create memory table PROJECT_MANAGER(EID varchar(256) not null, PROJECT varchar(256)," + + " primary key (EID), foreign key (EID) references MANAGER(ID))"; + st.execute(projectManagerTableBuilding); + + String employeeTableBuilding = + "create memory table EMPLOYEE (ID varchar(256) not null, NAME varchar(256), RESIDENCE" + + " varchar(256), MANAGER varchar(256), primary key (ID), foreign key (RESIDENCE)" + + " references RESIDENCE(ID), foreign key (MANAGER) references MANAGER(ID))"; + st.execute(employeeTableBuilding); + + String regularEmployeeTableBuilding = + "create memory table REGULAR_EMPLOYEE (EID varchar(256) not null, SALARY decimal(10,2)," + + " BONUS decimal(10,0), primary key (EID), foreign key (EID) references" + + " EMPLOYEE(ID))"; + st.execute(regularEmployeeTableBuilding); + + String contractEmployeeTableBuilding = + "create memory table CONTRACT_EMPLOYEE (EID varchar(256) not null, PAY_PER_HOUR" + + " decimal(10,2), CONTRACT_DURATION varchar(256), primary key (EID), foreign key" + + " (EID) references EMPLOYEE(ID))"; + st.execute(contractEmployeeTableBuilding); + + // Records Inserting + + String countryFilling = + "insert into COUNTRY (ID,NAME,CONTINENT) values (" + "('C001','Italy','Europe'))"; + st.execute(countryFilling); + + String residenceFilling = + "insert into RESIDENCE (ID,CITY,COUNTRY) values (" + + "('R001','Rome','C001')," + + "('R002','Milan','C001'))"; + st.execute(residenceFilling); + + String managerFilling = "insert into MANAGER (ID,NAME) values (" + "('M001','Bill Right'))"; + st.execute(managerFilling); + + String projectManagerFilling = + "insert into PROJECT_MANAGER (EID,PROJECT) values (" + "('M001','New World'))"; + st.execute(projectManagerFilling); + + String employeeFilling = + "insert into EMPLOYEE (ID,NAME,RESIDENCE,MANAGER) values (" + + "('E001','John Black','R001',null)," + + "('E002','Andrew Brown','R001','M001')," + + "('E003','Jack Johnson','R002',null))"; + st.execute(employeeFilling); + + String regularEmployeeFilling = + "insert into REGULAR_EMPLOYEE (EID,SALARY,BONUS) values (" + "('E002','1000.00','10'))"; + st.execute(regularEmployeeFilling); + + String contractEmployeeFilling = + "insert into CONTRACT_EMPLOYEE (EID,PAY_PER_HOUR,CONTRACT_DURATION) values (" + + "('E003','50.00','6'))"; + st.execute(contractEmployeeFilling); + + List includedTables = new ArrayList(); + includedTables.add("COUNTRY"); + includedTables.add("MANAGER"); + includedTables.add("PROJECT_MANAGER"); + includedTables.add("EMPLOYEE"); + includedTables.add("REGULAR_EMPLOYEE"); + includedTables.add("CONTRACT_EMPLOYEE"); + + this.mapper = + new Hibernate2GraphMapper( + dataSource, + FilterTableMappingTest.XML_TABLE_PER_SUBCLASS1, + includedTables, + null, + dbQueryEngine, + dataTypeHandler, + executionStrategy, + nameResolver, + statistics); + mapper.buildSourceDatabaseSchema(); + mapper.buildGraphModel(new JavaConventionNameResolver()); + + /* + * Testing context information + */ + + assertThat(statistics.totalNumberOfEntities).isEqualTo(6); + assertThat(statistics.builtEntities).isEqualTo(6); + assertThat(statistics.totalNumberOfRelationships).isEqualTo(4); + assertThat(statistics.builtRelationships) + .isEqualTo(4); // 3 of these are hierarchical relationships + + assertThat(statistics.totalNumberOfModelVertices).isEqualTo(6); + assertThat(statistics.builtModelVertexTypes).isEqualTo(6); + assertThat(statistics.totalNumberOfModelEdges).isEqualTo(1); + assertThat(statistics.builtModelEdgeTypes).isEqualTo(1); + + /* + * Testing built source db schema + */ + + Entity employeeEntity = mapper.getDataBaseSchema().getEntityByName("EMPLOYEE"); + Entity regularEmployeeEntity = + mapper.getDataBaseSchema().getEntityByNameIgnoreCase("REGULAR_EMPLOYEE"); + Entity contractEmployeeEntity = + mapper.getDataBaseSchema().getEntityByNameIgnoreCase("CONTRACT_EMPLOYEE"); + Entity countryEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("COUNTRY"); + Entity managerEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("MANAGER"); + Entity projectManagerEntity = + mapper.getDataBaseSchema().getEntityByNameIgnoreCase("PROJECT_MANAGER"); + Entity residenceEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("RESIDENCE"); + + // entities check + assertThat(mapper.getDataBaseSchema().getEntities().size()).isEqualTo(6); + assertThat(mapper.getDataBaseSchema().getCanonicalRelationships().size()).isEqualTo(4); + assertThat(employeeEntity).isNotNull(); + assertThat(regularEmployeeEntity).isNotNull(); + assertThat(contractEmployeeEntity).isNotNull(); + assertThat(countryEntity).isNotNull(); + assertThat(managerEntity).isNotNull(); + assertThat(residenceEntity).isNull(); + + // attributes check + assertThat(employeeEntity.getAttributes().size()).isEqualTo(4); + + assertThat(employeeEntity.getAttributeByName("ID")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(employeeEntity.getAttributeByName("ID").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("ID").getOrdinalPosition()).isEqualTo(1); + assertThat(employeeEntity.getAttributeByName("ID").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(employeeEntity.getAttributeByName("NAME")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("NAME").getName()).isEqualTo("NAME"); + assertThat(employeeEntity.getAttributeByName("NAME").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("NAME").getOrdinalPosition()).isEqualTo(2); + assertThat(employeeEntity.getAttributeByName("NAME").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(employeeEntity.getAttributeByName("RESIDENCE")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getName()).isEqualTo("RESIDENCE"); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getOrdinalPosition()).isEqualTo(3); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(employeeEntity.getAttributeByName("MANAGER")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("MANAGER").getName()).isEqualTo("MANAGER"); + assertThat(employeeEntity.getAttributeByName("MANAGER").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("MANAGER").getOrdinalPosition()).isEqualTo(4); + assertThat(employeeEntity.getAttributeByName("MANAGER").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(regularEmployeeEntity.getAttributes().size()).isEqualTo(2); + + assertThat(regularEmployeeEntity.getAttributeByName("SALARY")).isNotNull(); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getName()).isEqualTo("SALARY"); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getDataType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getOrdinalPosition()) + .isEqualTo(1); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getBelongingEntity().getName()) + .isEqualTo("REGULAR_EMPLOYEE"); + + assertThat(regularEmployeeEntity.getAttributeByName("BONUS")).isNotNull(); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getName()).isEqualTo("BONUS"); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getDataType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getOrdinalPosition()) + .isEqualTo(2); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getBelongingEntity().getName()) + .isEqualTo("REGULAR_EMPLOYEE"); + + assertThat(contractEmployeeEntity.getAttributes().size()).isEqualTo(2); + + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR")).isNotNull(); + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getName()) + .isEqualTo("PAY_PER_HOUR"); + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getDataType()) + .isEqualTo("DECIMAL"); + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getOrdinalPosition()) + .isEqualTo(1); + assertThat( + contractEmployeeEntity + .getAttributeByName("PAY_PER_HOUR") + .getBelongingEntity() + .getName()) + .isEqualTo("CONTRACT_EMPLOYEE"); + + assertThat(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION")).isNotNull(); + assertThat(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getName()) + .isEqualTo("CONTRACT_DURATION"); + assertThat(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + contractEmployeeEntity + .getAttributeByName("CONTRACT_DURATION") + .getBelongingEntity() + .getName()) + .isEqualTo("CONTRACT_EMPLOYEE"); + + assertThat(countryEntity.getAttributes().size()).isEqualTo(3); + + assertThat(countryEntity.getAttributeByName("ID")).isNotNull(); + assertThat(countryEntity.getAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(countryEntity.getAttributeByName("ID").getDataType()).isEqualTo("VARCHAR"); + assertThat(countryEntity.getAttributeByName("ID").getOrdinalPosition()).isEqualTo(1); + assertThat(countryEntity.getAttributeByName("ID").getBelongingEntity().getName()) + .isEqualTo("COUNTRY"); + + assertThat(countryEntity.getAttributeByName("NAME")).isNotNull(); + assertThat(countryEntity.getAttributeByName("NAME").getName()).isEqualTo("NAME"); + assertThat(countryEntity.getAttributeByName("NAME").getDataType()).isEqualTo("VARCHAR"); + assertThat(countryEntity.getAttributeByName("NAME").getOrdinalPosition()).isEqualTo(2); + assertThat(countryEntity.getAttributeByName("NAME").getBelongingEntity().getName()) + .isEqualTo("COUNTRY"); + + assertThat(countryEntity.getAttributeByName("CONTINENT")).isNotNull(); + assertThat(countryEntity.getAttributeByName("CONTINENT").getName()).isEqualTo("CONTINENT"); + assertThat(countryEntity.getAttributeByName("CONTINENT").getDataType()).isEqualTo("VARCHAR"); + assertThat(countryEntity.getAttributeByName("CONTINENT").getOrdinalPosition()).isEqualTo(3); + assertThat(countryEntity.getAttributeByName("CONTINENT").getBelongingEntity().getName()) + .isEqualTo("COUNTRY"); + + assertThat(managerEntity.getAttributes().size()).isEqualTo(2); + + assertThat(managerEntity.getAttributeByName("ID")).isNotNull(); + assertThat(managerEntity.getAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(managerEntity.getAttributeByName("ID").getDataType()).isEqualTo("VARCHAR"); + assertThat(managerEntity.getAttributeByName("ID").getOrdinalPosition()).isEqualTo(1); + assertThat(managerEntity.getAttributeByName("ID").getBelongingEntity().getName()) + .isEqualTo("MANAGER"); + + assertThat(managerEntity.getAttributeByName("NAME")).isNotNull(); + assertThat(managerEntity.getAttributeByName("NAME").getName()).isEqualTo("NAME"); + assertThat(managerEntity.getAttributeByName("NAME").getDataType()).isEqualTo("VARCHAR"); + assertThat(managerEntity.getAttributeByName("NAME").getOrdinalPosition()).isEqualTo(2); + assertThat(managerEntity.getAttributeByName("NAME").getBelongingEntity().getName()) + .isEqualTo("MANAGER"); + + assertThat(projectManagerEntity.getAttributes().size()).isEqualTo(1); + + assertThat(projectManagerEntity.getAttributeByName("PROJECT")).isNotNull(); + assertThat(projectManagerEntity.getAttributeByName("PROJECT").getName()).isEqualTo("PROJECT"); + assertThat(projectManagerEntity.getAttributeByName("PROJECT").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(projectManagerEntity.getAttributeByName("PROJECT").getOrdinalPosition()) + .isEqualTo(1); + assertThat(projectManagerEntity.getAttributeByName("PROJECT").getBelongingEntity().getName()) + .isEqualTo("PROJECT_MANAGER"); + + // inherited attributes check + assertThat(employeeEntity.getInheritedAttributes().size()).isEqualTo(0); + + assertThat(regularEmployeeEntity.getInheritedAttributes().size()).isEqualTo(4); + + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID")).isNotNull(); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()) + .isEqualTo(1); + assertThat( + regularEmployeeEntity + .getInheritedAttributeByName("ID") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME")).isNotNull(); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME").getName()) + .isEqualTo("NAME"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + regularEmployeeEntity + .getInheritedAttributeByName("NAME") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE")).isNotNull(); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()) + .isEqualTo("RESIDENCE"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()) + .isEqualTo(3); + assertThat( + regularEmployeeEntity + .getInheritedAttributeByName("RESIDENCE") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(regularEmployeeEntity.getInheritedAttributeByName("MANAGER")).isNotNull(); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("MANAGER").getName()) + .isEqualTo("MANAGER"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("MANAGER").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("MANAGER").getOrdinalPosition()) + .isEqualTo(4); + assertThat( + regularEmployeeEntity + .getInheritedAttributeByName("MANAGER") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(contractEmployeeEntity.getInheritedAttributes().size()).isEqualTo(4); + + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID")).isNotNull(); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID").getName()) + .isEqualTo("ID"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()) + .isEqualTo(1); + assertThat( + contractEmployeeEntity + .getInheritedAttributeByName("ID") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME")).isNotNull(); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME").getName()) + .isEqualTo("NAME"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + contractEmployeeEntity + .getInheritedAttributeByName("NAME") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE")).isNotNull(); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()) + .isEqualTo("RESIDENCE"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()) + .isEqualTo(3); + assertThat( + contractEmployeeEntity + .getInheritedAttributeByName("RESIDENCE") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(contractEmployeeEntity.getInheritedAttributeByName("MANAGER")).isNotNull(); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("MANAGER").getName()) + .isEqualTo("MANAGER"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("MANAGER").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("MANAGER").getOrdinalPosition()) + .isEqualTo(4); + assertThat( + contractEmployeeEntity + .getInheritedAttributeByName("MANAGER") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(projectManagerEntity.getInheritedAttributes().size()).isEqualTo(2); + + assertThat(projectManagerEntity.getInheritedAttributeByName("ID")).isNotNull(); + assertThat(projectManagerEntity.getInheritedAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(projectManagerEntity.getInheritedAttributeByName("ID").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(projectManagerEntity.getInheritedAttributeByName("ID").getOrdinalPosition()) + .isEqualTo(1); + assertThat( + projectManagerEntity.getInheritedAttributeByName("ID").getBelongingEntity().getName()) + .isEqualTo("MANAGER"); + + assertThat(projectManagerEntity.getInheritedAttributeByName("NAME")).isNotNull(); + assertThat(projectManagerEntity.getInheritedAttributeByName("NAME").getName()) + .isEqualTo("NAME"); + assertThat(projectManagerEntity.getInheritedAttributeByName("NAME").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(projectManagerEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + projectManagerEntity + .getInheritedAttributeByName("NAME") + .getBelongingEntity() + .getName()) + .isEqualTo("MANAGER"); + + assertThat(countryEntity.getInheritedAttributes().size()).isEqualTo(0); + assertThat(managerEntity.getInheritedAttributes().size()).isEqualTo(0); + + // primary key check + assertThat(regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()).isEqualTo(1); + assertThat(regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()) + .isEqualTo("EID"); + assertThat(regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + regularEmployeeEntity + .getPrimaryKey() + .getInvolvedAttributes() + .get(0) + .getBelongingEntity() + .getName()) + .isEqualTo("REGULAR_EMPLOYEE"); + + assertThat(contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()) + .isEqualTo(1); + assertThat(contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()) + .isEqualTo("EID"); + assertThat( + contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeEntity + .getPrimaryKey() + .getInvolvedAttributes() + .get(0) + .getBelongingEntity() + .getName()) + .isEqualTo("CONTRACT_EMPLOYEE"); + + assertThat(projectManagerEntity.getPrimaryKey().getInvolvedAttributes().size()).isEqualTo(1); + assertThat(projectManagerEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()) + .isEqualTo("EID"); + assertThat(projectManagerEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + projectManagerEntity + .getPrimaryKey() + .getInvolvedAttributes() + .get(0) + .getBelongingEntity() + .getName()) + .isEqualTo("PROJECT_MANAGER"); + + // relationship, primary and foreign key check + assertThat(regularEmployeeEntity.getOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(contractEmployeeEntity.getOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(employeeEntity.getOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(projectManagerEntity.getOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(managerEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(countryEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(regularEmployeeEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(contractEmployeeEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(employeeEntity.getInCanonicalRelationships().size()).isEqualTo(2); + assertThat(projectManagerEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(managerEntity.getInCanonicalRelationships().size()).isEqualTo(2); + assertThat(countryEntity.getInCanonicalRelationships().size()).isEqualTo(0); + + assertThat(regularEmployeeEntity.getForeignKeys().size()).isEqualTo(1); + assertThat(contractEmployeeEntity.getForeignKeys().size()).isEqualTo(1); + assertThat(employeeEntity.getForeignKeys().size()).isEqualTo(1); + assertThat(projectManagerEntity.getForeignKeys().size()).isEqualTo(1); + assertThat(managerEntity.getForeignKeys().size()).isEqualTo(0); + assertThat(countryEntity.getForeignKeys().size()).isEqualTo(0); + + Iterator itEmp = + employeeEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship currentEmpRel = itEmp.next(); + assertThat(currentEmpRel.getParentEntity().getName()).isEqualTo("MANAGER"); + assertThat(currentEmpRel.getForeignEntity().getName()).isEqualTo("EMPLOYEE"); + assertThat(currentEmpRel.getPrimaryKey()).isEqualTo(managerEntity.getPrimaryKey()); + assertThat(currentEmpRel.getForeignKey()).isEqualTo(employeeEntity.getForeignKeys().get(0)); + assertThat(itEmp.hasNext()).isFalse(); + + Iterator itManager = + managerEntity.getInCanonicalRelationships().iterator(); + CanonicalRelationship currentManRel = itManager.next(); + assertThat(currentManRel).isEqualTo(currentEmpRel); + + Iterator itContEmp = + contractEmployeeEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship currentContEmpRel = itContEmp.next(); + itEmp = employeeEntity.getInCanonicalRelationships().iterator(); + currentEmpRel = itEmp.next(); + assertThat(currentEmpRel).isEqualTo(currentContEmpRel); + + Iterator itRegEmp = + regularEmployeeEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship currentRegEmpRel = itRegEmp.next(); + currentEmpRel = itEmp.next(); + assertThat(currentEmpRel).isEqualTo(currentRegEmpRel); + + // inherited relationships check + assertThat(regularEmployeeEntity.getInheritedOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(contractEmployeeEntity.getInheritedOutCanonicalRelationships().size()) + .isEqualTo(1); + assertThat(employeeEntity.getInheritedOutCanonicalRelationships().size()).isEqualTo(0); + + itRegEmp = regularEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); + itContEmp = contractEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); + currentRegEmpRel = itRegEmp.next(); + currentContEmpRel = itContEmp.next(); + assertThat(currentRegEmpRel.getParentEntity().getName()).isEqualTo("MANAGER"); + assertThat(currentRegEmpRel.getForeignEntity().getName()).isEqualTo("EMPLOYEE"); + assertThat(currentContEmpRel.getParentEntity().getName()).isEqualTo("MANAGER"); + assertThat(currentContEmpRel.getForeignEntity().getName()).isEqualTo("EMPLOYEE"); + assertThat(currentRegEmpRel.getPrimaryKey()).isEqualTo(managerEntity.getPrimaryKey()); + assertThat(currentRegEmpRel.getFromColumns().size()).isEqualTo(1); + assertThat(currentRegEmpRel.getFromColumns().get(0).getName()).isEqualTo("MANAGER"); + assertThat(currentContEmpRel.getPrimaryKey()).isEqualTo(managerEntity.getPrimaryKey()); + assertThat(currentContEmpRel.getFromColumns().size()).isEqualTo(1); + assertThat(currentContEmpRel.getFromColumns().get(0).getName()).isEqualTo("MANAGER"); + assertThat(itRegEmp.hasNext()).isFalse(); + assertThat(itContEmp.hasNext()).isFalse(); + + // inheritance check + assertThat(regularEmployeeEntity.getParentEntity()).isEqualTo(employeeEntity); + assertThat(contractEmployeeEntity.getParentEntity()).isEqualTo(employeeEntity); + assertThat(employeeEntity.getParentEntity()).isNull(); + + assertThat(regularEmployeeEntity.getInheritanceLevel()).isEqualTo(1); + assertThat(contractEmployeeEntity.getInheritanceLevel()).isEqualTo(1); + assertThat(employeeEntity.getInheritanceLevel()).isEqualTo(0); + + // Hierarchical Bag check + assertThat(mapper.getDataBaseSchema().getHierarchicalBags().size()).isEqualTo(2); + + HierarchicalBag hierarchicalBag1 = mapper.getDataBaseSchema().getHierarchicalBags().get(0); + HierarchicalBag hierarchicalBag2 = mapper.getDataBaseSchema().getHierarchicalBags().get(1); + assertThat(hierarchicalBag1.getInheritancePattern()).isEqualTo("table-per-type"); + assertThat(hierarchicalBag2.getInheritancePattern()).isEqualTo("table-per-type"); + + assertThat(hierarchicalBag1.getDepth2entities().size()).isEqualTo(2); + + assertThat(hierarchicalBag1.getDepth2entities().get(0).size()).isEqualTo(1); + Iterator it = hierarchicalBag1.getDepth2entities().get(0).iterator(); + assertThat(it.next().getName()).isEqualTo("EMPLOYEE"); + assertThat(it.hasNext()).isFalse(); + + assertThat(hierarchicalBag1.getDepth2entities().get(1).size()).isEqualTo(2); + it = hierarchicalBag1.getDepth2entities().get(1).iterator(); + assertThat(it.next().getName()).isEqualTo("REGULAR_EMPLOYEE"); + assertThat(it.next().getName()).isEqualTo("CONTRACT_EMPLOYEE"); + assertThat(it.hasNext()).isFalse(); + + assertThat(employeeEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag1); + assertThat(regularEmployeeEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag1); + assertThat(contractEmployeeEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag1); + + assertThat(hierarchicalBag1.getDiscriminatorColumn()).isNull(); + + assertThat(hierarchicalBag2.getDepth2entities().size()).isEqualTo(2); + + assertThat(hierarchicalBag2.getDepth2entities().get(0).size()).isEqualTo(1); + it = hierarchicalBag2.getDepth2entities().get(0).iterator(); + assertThat(it.next().getName()).isEqualTo("MANAGER"); + assertThat(it.hasNext()).isFalse(); + + assertThat(hierarchicalBag2.getDepth2entities().get(1).size()).isEqualTo(1); + it = hierarchicalBag2.getDepth2entities().get(1).iterator(); + assertThat(it.next().getName()).isEqualTo("PROJECT_MANAGER"); + assertThat(it.hasNext()).isFalse(); + + assertThat(managerEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag2); + assertThat(projectManagerEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag2); + + assertThat(hierarchicalBag2.getDiscriminatorColumn()).isNull(); + + /* + * Testing built graph model + */ + + VertexType employeeVertexType = mapper.getGraphModel().getVertexTypeByName("Employee"); + VertexType regularEmployeeVertexType = + mapper.getGraphModel().getVertexTypeByName("RegularEmployee"); + VertexType contractEmployeeVertexType = + mapper.getGraphModel().getVertexTypeByName("ContractEmployee"); + VertexType countryVertexType = mapper.getGraphModel().getVertexTypeByName("Country"); + VertexType managerVertexType = mapper.getGraphModel().getVertexTypeByName("Manager"); + VertexType projectManagerVertexType = + mapper.getGraphModel().getVertexTypeByName("ProjectManager"); + VertexType residenceVertexType = mapper.getGraphModel().getVertexTypeByName("Residence"); + + // vertices check + assertThat(mapper.getGraphModel().getVerticesType().size()).isEqualTo(6); + assertThat(employeeVertexType).isNotNull(); + assertThat(regularEmployeeVertexType).isNotNull(); + assertThat(contractEmployeeVertexType).isNotNull(); + assertThat(countryVertexType).isNotNull(); + assertThat(managerVertexType).isNotNull(); + assertThat(projectManagerVertexType).isNotNull(); + assertThat(residenceVertexType).isNull(); + + // properties check + assertThat(employeeVertexType.getProperties().size()).isEqualTo(4); + + assertThat(employeeVertexType.getPropertyByName("id")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(employeeVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(employeeVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(employeeVertexType.getPropertyByName("name")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("name").getName()).isEqualTo("name"); + assertThat(employeeVertexType.getPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("name").getOrdinalPosition()).isEqualTo(2); + assertThat(employeeVertexType.getPropertyByName("name").isFromPrimaryKey()).isFalse(); + + assertThat(employeeVertexType.getPropertyByName("residence")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("residence").getName()) + .isEqualTo("residence"); + assertThat(employeeVertexType.getPropertyByName("residence").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("residence").getOrdinalPosition()) + .isEqualTo(3); + assertThat(employeeVertexType.getPropertyByName("residence").isFromPrimaryKey()).isFalse(); + + assertThat(employeeVertexType.getPropertyByName("manager")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("manager").getName()).isEqualTo("manager"); + assertThat(employeeVertexType.getPropertyByName("manager").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("manager").getOrdinalPosition()).isEqualTo(4); + assertThat(employeeVertexType.getPropertyByName("manager").isFromPrimaryKey()).isFalse(); + + assertThat(regularEmployeeVertexType.getProperties().size()).isEqualTo(2); + + assertThat(regularEmployeeVertexType.getPropertyByName("salary")).isNotNull(); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").getName()) + .isEqualTo("salary"); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").getOriginalType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").getOrdinalPosition()) + .isEqualTo(1); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").isFromPrimaryKey()) + .isFalse(); + + assertThat(regularEmployeeVertexType.getPropertyByName("bonus")).isNotNull(); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").getName()).isEqualTo("bonus"); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").getOriginalType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").getOrdinalPosition()) + .isEqualTo(2); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").isFromPrimaryKey()).isFalse(); + + assertThat(contractEmployeeVertexType.getProperties().size()).isEqualTo(2); + + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour")).isNotNull(); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").getName()) + .isEqualTo("payPerHour"); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").getOriginalType()) + .isEqualTo("DECIMAL"); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").getOrdinalPosition()) + .isEqualTo(1); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getPropertyByName("contractDuration")).isNotNull(); + assertThat(contractEmployeeVertexType.getPropertyByName("contractDuration").getName()) + .isEqualTo("contractDuration"); + assertThat(contractEmployeeVertexType.getPropertyByName("contractDuration").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeVertexType.getPropertyByName("contractDuration").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + contractEmployeeVertexType.getPropertyByName("contractDuration").isFromPrimaryKey()) + .isFalse(); + + assertThat(countryVertexType.getProperties().size()).isEqualTo(3); + + assertThat(countryVertexType.getPropertyByName("id")).isNotNull(); + assertThat(countryVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(countryVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(countryVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(countryVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(countryVertexType.getPropertyByName("name")).isNotNull(); + assertThat(countryVertexType.getPropertyByName("name").getName()).isEqualTo("name"); + assertThat(countryVertexType.getPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(countryVertexType.getPropertyByName("name").getOrdinalPosition()).isEqualTo(2); + assertThat(countryVertexType.getPropertyByName("name").isFromPrimaryKey()).isFalse(); + + assertThat(countryVertexType.getPropertyByName("continent")).isNotNull(); + assertThat(countryVertexType.getPropertyByName("continent").getName()).isEqualTo("continent"); + assertThat(countryVertexType.getPropertyByName("continent").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(countryVertexType.getPropertyByName("continent").getOrdinalPosition()) + .isEqualTo(3); + assertThat(countryVertexType.getPropertyByName("continent").isFromPrimaryKey()).isFalse(); + + assertThat(managerVertexType.getProperties().size()).isEqualTo(2); + + assertThat(managerVertexType.getPropertyByName("id")).isNotNull(); + assertThat(managerVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(managerVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(managerVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(managerVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(managerVertexType.getPropertyByName("name")).isNotNull(); + assertThat(managerVertexType.getPropertyByName("name").getName()).isEqualTo("name"); + assertThat(managerVertexType.getPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(managerVertexType.getPropertyByName("name").getOrdinalPosition()).isEqualTo(2); + assertThat(managerVertexType.getPropertyByName("name").isFromPrimaryKey()).isFalse(); + + assertThat(projectManagerVertexType.getProperties().size()).isEqualTo(1); + + assertThat(projectManagerVertexType.getPropertyByName("project")).isNotNull(); + assertThat(projectManagerVertexType.getPropertyByName("project").getName()) + .isEqualTo("project"); + assertThat(projectManagerVertexType.getPropertyByName("project").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(projectManagerVertexType.getPropertyByName("project").getOrdinalPosition()) + .isEqualTo(1); + assertThat(projectManagerVertexType.getPropertyByName("project").isFromPrimaryKey()) + .isFalse(); + + // inherited properties check + assertThat(employeeVertexType.getInheritedProperties().size()).isEqualTo(0); + + assertThat(regularEmployeeVertexType.getInheritedProperties().size()).isEqualTo(4); + + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id")).isNotNull(); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").getName()) + .isEqualTo("id"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()) + .isEqualTo(1); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()) + .isFalse(); + + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name")).isNotNull(); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").getName()) + .isEqualTo("name"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()) + .isEqualTo(2); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()) + .isFalse(); + + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("residence")).isNotNull(); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("residence").getName()) + .isEqualTo("residence"); + assertThat( + regularEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + regularEmployeeVertexType + .getInheritedPropertyByName("residence") + .getOrdinalPosition()) + .isEqualTo(3); + assertThat( + regularEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()) + .isFalse(); + + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("manager")).isNotNull(); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("manager").getName()) + .isEqualTo("manager"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("manager").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + regularEmployeeVertexType.getInheritedPropertyByName("manager").getOrdinalPosition()) + .isEqualTo(4); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("manager").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getInheritedProperties().size()).isEqualTo(4); + + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id")).isNotNull(); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").getName()) + .isEqualTo("id"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()) + .isEqualTo(1); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name")).isNotNull(); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").getName()) + .isEqualTo("name"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()) + .isEqualTo(2); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("residence")).isNotNull(); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("residence").getName()) + .isEqualTo("residence"); + assertThat( + contractEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeVertexType + .getInheritedPropertyByName("residence") + .getOrdinalPosition()) + .isEqualTo(3); + assertThat( + contractEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("manager")).isNotNull(); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("manager").getName()) + .isEqualTo("manager"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("manager").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeVertexType.getInheritedPropertyByName("manager").getOrdinalPosition()) + .isEqualTo(4); + assertThat( + contractEmployeeVertexType.getInheritedPropertyByName("manager").isFromPrimaryKey()) + .isFalse(); + + assertThat(projectManagerVertexType.getInheritedProperties().size()).isEqualTo(2); + + assertThat(projectManagerVertexType.getInheritedPropertyByName("id")).isNotNull(); + assertThat(projectManagerVertexType.getInheritedPropertyByName("id").getName()) + .isEqualTo("id"); + assertThat(projectManagerVertexType.getInheritedPropertyByName("id").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(projectManagerVertexType.getInheritedPropertyByName("id").getOrdinalPosition()) + .isEqualTo(1); + assertThat(projectManagerVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()) + .isFalse(); + + assertThat(projectManagerVertexType.getInheritedPropertyByName("name")).isNotNull(); + assertThat(projectManagerVertexType.getInheritedPropertyByName("name").getName()) + .isEqualTo("name"); + assertThat(projectManagerVertexType.getInheritedPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(projectManagerVertexType.getInheritedPropertyByName("name").getOrdinalPosition()) + .isEqualTo(2); + assertThat(projectManagerVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()) + .isFalse(); + + assertThat(countryVertexType.getInheritedProperties().size()).isEqualTo(0); + assertThat(managerVertexType.getInheritedProperties().size()).isEqualTo(0); + + // edges check + + assertThat(mapper.getRelationship2edgeType().size()).isEqualTo(1); + + assertThat(mapper.getGraphModel().getEdgesType().size()).isEqualTo(1); + assertThat(mapper.getGraphModel().getEdgesType().get(0).getName()).isEqualTo("HasManager"); + + assertThat(employeeVertexType.getOutEdgesType().size()).isEqualTo(1); + assertThat(employeeVertexType.getOutEdgesType().get(0).getName()).isEqualTo("HasManager"); + + assertThat(regularEmployeeVertexType.getOutEdgesType().size()).isEqualTo(1); + assertThat(regularEmployeeVertexType.getOutEdgesType().get(0).getName()) + .isEqualTo("HasManager"); + + assertThat(contractEmployeeVertexType.getOutEdgesType().size()).isEqualTo(1); + assertThat(contractEmployeeVertexType.getOutEdgesType().get(0).getName()) + .isEqualTo("HasManager"); + + /* + * Rules check + */ + + // Classes Mapping + + assertThat(mapper.getVertexType2EVClassMappers().size()).isEqualTo(6); + assertThat(mapper.getEntity2EVClassMappers().size()).isEqualTo(6); + + assertThat(mapper.getEVClassMappersByVertex(employeeVertexType).size()).isEqualTo(1); + EVClassMapper employeeClassMapper = + mapper.getEVClassMappersByVertex(employeeVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(employeeEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(employeeEntity).get(0)) + .isEqualTo(employeeClassMapper); + assertThat(employeeEntity).isEqualTo(employeeClassMapper.getEntity()); + assertThat(employeeVertexType).isEqualTo(employeeClassMapper.getVertexType()); + + assertThat(employeeClassMapper.getAttribute2property().size()).isEqualTo(4); + assertThat(employeeClassMapper.getProperty2attribute().size()).isEqualTo(4); + assertThat(employeeClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(employeeClassMapper.getAttribute2property().get("NAME")).isEqualTo("name"); + assertThat(employeeClassMapper.getAttribute2property().get("RESIDENCE")) + .isEqualTo("residence"); + assertThat(employeeClassMapper.getAttribute2property().get("MANAGER")).isEqualTo("manager"); + assertThat(employeeClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(employeeClassMapper.getProperty2attribute().get("name")).isEqualTo("NAME"); + assertThat(employeeClassMapper.getProperty2attribute().get("residence")) + .isEqualTo("RESIDENCE"); + assertThat(employeeClassMapper.getProperty2attribute().get("manager")).isEqualTo("MANAGER"); + + assertThat(mapper.getEVClassMappersByVertex(regularEmployeeVertexType).size()).isEqualTo(1); + EVClassMapper regularEmployeeClassMapper = + mapper.getEVClassMappersByVertex(regularEmployeeVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(regularEmployeeEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(regularEmployeeEntity).get(0)) + .isEqualTo(regularEmployeeClassMapper); + assertThat(regularEmployeeEntity).isEqualTo(regularEmployeeClassMapper.getEntity()); + assertThat(regularEmployeeVertexType).isEqualTo(regularEmployeeClassMapper.getVertexType()); + + assertThat(regularEmployeeClassMapper.getAttribute2property().size()).isEqualTo(2); + assertThat(regularEmployeeClassMapper.getProperty2attribute().size()).isEqualTo(2); + assertThat(regularEmployeeClassMapper.getAttribute2property().get("SALARY")) + .isEqualTo("salary"); + assertThat(regularEmployeeClassMapper.getAttribute2property().get("BONUS")) + .isEqualTo("bonus"); + assertThat(regularEmployeeClassMapper.getProperty2attribute().get("salary")) + .isEqualTo("SALARY"); + assertThat(regularEmployeeClassMapper.getProperty2attribute().get("bonus")) + .isEqualTo("BONUS"); + + assertThat(mapper.getEVClassMappersByVertex(contractEmployeeVertexType).size()).isEqualTo(1); + EVClassMapper contractEmployeeClassMapper = + mapper.getEVClassMappersByVertex(contractEmployeeVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(contractEmployeeEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(contractEmployeeEntity).get(0)) + .isEqualTo(contractEmployeeClassMapper); + assertThat(contractEmployeeEntity).isEqualTo(contractEmployeeClassMapper.getEntity()); + assertThat(contractEmployeeVertexType).isEqualTo(contractEmployeeClassMapper.getVertexType()); + + assertThat(contractEmployeeClassMapper.getAttribute2property().size()).isEqualTo(2); + assertThat(contractEmployeeClassMapper.getProperty2attribute().size()).isEqualTo(2); + assertThat(contractEmployeeClassMapper.getAttribute2property().get("PAY_PER_HOUR")) + .isEqualTo("payPerHour"); + assertThat(contractEmployeeClassMapper.getAttribute2property().get("CONTRACT_DURATION")) + .isEqualTo("contractDuration"); + assertThat(contractEmployeeClassMapper.getProperty2attribute().get("payPerHour")) + .isEqualTo("PAY_PER_HOUR"); + assertThat(contractEmployeeClassMapper.getProperty2attribute().get("contractDuration")) + .isEqualTo("CONTRACT_DURATION"); + + assertThat(mapper.getEVClassMappersByVertex(countryVertexType).size()).isEqualTo(1); + EVClassMapper countryClassMapper = mapper.getEVClassMappersByVertex(countryVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(countryEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(countryEntity).get(0)) + .isEqualTo(countryClassMapper); + assertThat(countryEntity).isEqualTo(countryClassMapper.getEntity()); + assertThat(countryVertexType).isEqualTo(countryClassMapper.getVertexType()); + + assertThat(countryClassMapper.getAttribute2property().size()).isEqualTo(3); + assertThat(countryClassMapper.getProperty2attribute().size()).isEqualTo(3); + assertThat(countryClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(countryClassMapper.getAttribute2property().get("NAME")).isEqualTo("name"); + assertThat(countryClassMapper.getAttribute2property().get("CONTINENT")) + .isEqualTo("continent"); + assertThat(countryClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(countryClassMapper.getProperty2attribute().get("name")).isEqualTo("NAME"); + assertThat(countryClassMapper.getProperty2attribute().get("continent")) + .isEqualTo("CONTINENT"); + + assertThat(mapper.getEVClassMappersByVertex(managerVertexType).size()).isEqualTo(1); + EVClassMapper managerClassMapper = mapper.getEVClassMappersByVertex(managerVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(managerEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(managerEntity).get(0)) + .isEqualTo(managerClassMapper); + assertThat(managerEntity).isEqualTo(managerClassMapper.getEntity()); + assertThat(managerVertexType).isEqualTo(managerClassMapper.getVertexType()); + + assertThat(managerClassMapper.getAttribute2property().size()).isEqualTo(2); + assertThat(managerClassMapper.getProperty2attribute().size()).isEqualTo(2); + assertThat(managerClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(managerClassMapper.getAttribute2property().get("NAME")).isEqualTo("name"); + assertThat(managerClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(managerClassMapper.getProperty2attribute().get("name")).isEqualTo("NAME"); + + assertThat(mapper.getEVClassMappersByVertex(projectManagerVertexType).size()).isEqualTo(1); + EVClassMapper projectManagerClassMapper = + mapper.getEVClassMappersByVertex(projectManagerVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(projectManagerEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(projectManagerEntity).get(0)) + .isEqualTo(projectManagerClassMapper); + assertThat(projectManagerEntity).isEqualTo(projectManagerClassMapper.getEntity()); + assertThat(projectManagerVertexType).isEqualTo(projectManagerClassMapper.getVertexType()); + + assertThat(projectManagerClassMapper.getAttribute2property().size()).isEqualTo(1); + assertThat(projectManagerClassMapper.getProperty2attribute().size()).isEqualTo(1); + assertThat(projectManagerClassMapper.getAttribute2property().get("PROJECT")) + .isEqualTo("project"); + assertThat(projectManagerClassMapper.getProperty2attribute().get("project")) + .isEqualTo("PROJECT"); + + // Relationships-Edges Mapping + + Iterator itRelationships = + employeeEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship hasManagerRelationship = itRelationships.next(); + assertThat(itRelationships.hasNext()).isFalse(); + + EdgeType hasManagerEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasManager"); + + assertThat(mapper.getRelationship2edgeType().size()).isEqualTo(1); + assertThat(mapper.getRelationship2edgeType().get(hasManagerRelationship)) + .isEqualTo(hasManagerEdgeType); + + assertThat(mapper.getEdgeType2relationships().size()).isEqualTo(1); + assertThat(mapper.getEdgeType2relationships().get(hasManagerEdgeType).size()).isEqualTo(1); + assertThat( + mapper + .getEdgeType2relationships() + .get(hasManagerEdgeType) + .contains(hasManagerRelationship)) + .isTrue(); + + // JoinVertexes-AggregatorEdges Mapping + + assertThat(mapper.getJoinVertex2aggregatorEdges().size()).isEqualTo(0); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } finally { + try { + // Dropping Source DB Schema and OrientGraph + String dbDropping = "drop schema public cascade"; + st.execute(dbDropping); + connection.close(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } } - - @Test - /* - * Filtering out a table through exclude-tables (with Table per Type inheritance). - */public void filterOutThroughExcludeWithTablePerTypeInheritance() { - Connection connection = null; - Statement st = null; - - try { - Class.forName(this.driver); - connection = DriverManager.getConnection(this.jurl, this.username, this.password); - - String countryTableBuilding = "create memory table COUNTRY(ID varchar(256) not null, NAME varchar(256), CONTINENT varchar(256), primary key (ID))"; - st = connection.createStatement(); - st.execute(countryTableBuilding); - - String residenceTableBuilding = - "create memory table RESIDENCE(ID varchar(256) not null, CITY varchar(256), COUNTRY varchar(256), primary key (ID))"; - st = connection.createStatement(); - st.execute(residenceTableBuilding); - - String managerTableBuilding = "create memory table MANAGER(ID varchar(256) not null, NAME varchar(256), primary key (ID))"; - st.execute(managerTableBuilding); - - String projectManagerTableBuilding = - "create memory table PROJECT_MANAGER(EID varchar(256) not null, PROJECT varchar(256), primary key (EID), foreign key (EID) references MANAGER(ID))"; - st.execute(projectManagerTableBuilding); - - String employeeTableBuilding = - "create memory table EMPLOYEE (ID varchar(256) not null," + - " NAME varchar(256), RESIDENCE varchar(256), MANAGER varchar(256), primary key (ID), " + - "foreign key (RESIDENCE) references RESIDENCE(ID), foreign key (MANAGER) references MANAGER(ID))"; - st.execute(employeeTableBuilding); - - String regularEmployeeTableBuilding = - "create memory table REGULAR_EMPLOYEE (EID varchar(256) not null, " + - "SALARY decimal(10,2), BONUS decimal(10,0), primary key (EID), foreign key (EID) references EMPLOYEE(ID))"; - st.execute(regularEmployeeTableBuilding); - - String contractEmployeeTableBuilding = - "create memory table CONTRACT_EMPLOYEE (EID varchar(256) not null, " + - "PAY_PER_HOUR decimal(10,2), CONTRACT_DURATION varchar(256), primary key (EID), foreign key (EID) references EMPLOYEE(ID))"; - st.execute(contractEmployeeTableBuilding); - - // Records Inserting - - String countryFilling = "insert into COUNTRY (ID,NAME,CONTINENT) values (" + "('C001','Italy','Europe'))"; - st.execute(countryFilling); - - String residenceFilling = "insert into RESIDENCE (ID,CITY,COUNTRY) values (" + "('R001','Rome','C001')," + "('R002','Milan','C001'))"; - st.execute(residenceFilling); - - String managerFilling = "insert into MANAGER (ID,NAME) values (" + "('M001','Bill Right'))"; - st.execute(managerFilling); - - String projectManagerFilling = "insert into PROJECT_MANAGER (EID,PROJECT) values (" + "('M001','New World'))"; - st.execute(projectManagerFilling); - - String employeeFilling = - "insert into EMPLOYEE (ID,NAME,RESIDENCE,MANAGER) values (" + - "('E001','John Black','R001',null)," + - "('E002','Andrew Brown','R001','M001')," + - "('E003','Jack Johnson','R002',null))"; - st.execute(employeeFilling); - - String regularEmployeeFilling = "insert into REGULAR_EMPLOYEE (EID,SALARY,BONUS) values (" + "('E002','1000.00','10'))"; - st.execute(regularEmployeeFilling); - - String contractEmployeeFilling = "insert into CONTRACT_EMPLOYEE (EID,PAY_PER_HOUR,CONTRACT_DURATION) values (" + "('E003','50.00','6'))"; - st.execute(contractEmployeeFilling); - - List excludedTables = new ArrayList(); - excludedTables.add("RESIDENCE"); - - this.mapper = - new Hibernate2GraphMapper( - dataSource, - FilterTableMappingTest.XML_TABLE_PER_SUBCLASS2, - null, - excludedTables, - dbQueryEngine, - dataTypeHandler, - executionStrategy, - nameResolver, - statistics - ); - - mapper.buildSourceDatabaseSchema(); - mapper.buildGraphModel(new JavaConventionNameResolver()); - - /* - * Testing context information - */ - - assertEquals(6, statistics.totalNumberOfEntities); - assertEquals(6, statistics.builtEntities); - assertEquals(4, statistics.totalNumberOfRelationships); - assertEquals(4, statistics.builtRelationships); // 3 of these are hierarchical relationships - - assertEquals(6, statistics.totalNumberOfModelVertices); - assertEquals(6, statistics.builtModelVertexTypes); - assertEquals(1, statistics.totalNumberOfModelEdges); - assertEquals(1, statistics.builtModelEdgeTypes); - - /* - * Testing built source db schema - */ - - Entity employeeEntity = mapper.getDataBaseSchema().getEntityByName("EMPLOYEE"); - Entity regularEmployeeEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("REGULAR_EMPLOYEE"); - Entity contractEmployeeEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("CONTRACT_EMPLOYEE"); - Entity countryEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("COUNTRY"); - Entity managerEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("MANAGER"); - Entity projectManagerEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("PROJECT_MANAGER"); - Entity residenceEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("RESIDENCE"); - - // entities check - assertEquals(6, mapper.getDataBaseSchema().getEntities().size()); - assertEquals(4, mapper.getDataBaseSchema().getCanonicalRelationships().size()); - assertNotNull(employeeEntity); - assertNotNull(regularEmployeeEntity); - assertNotNull(contractEmployeeEntity); - assertNotNull(countryEntity); - assertNotNull(managerEntity); - assertNull(residenceEntity); - - // attributes check - assertEquals(4, employeeEntity.getAttributes().size()); - - assertNotNull(employeeEntity.getAttributeByName("ID")); - assertEquals("ID", employeeEntity.getAttributeByName("ID").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("ID").getDataType()); - assertEquals(1, employeeEntity.getAttributeByName("ID").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(employeeEntity.getAttributeByName("NAME")); - assertEquals("NAME", employeeEntity.getAttributeByName("NAME").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("NAME").getDataType()); - assertEquals(2, employeeEntity.getAttributeByName("NAME").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(employeeEntity.getAttributeByName("RESIDENCE")); - assertEquals("RESIDENCE", employeeEntity.getAttributeByName("RESIDENCE").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("RESIDENCE").getDataType()); - assertEquals(3, employeeEntity.getAttributeByName("RESIDENCE").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("RESIDENCE").getBelongingEntity().getName()); - - assertNotNull(employeeEntity.getAttributeByName("MANAGER")); - assertEquals("MANAGER", employeeEntity.getAttributeByName("MANAGER").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("MANAGER").getDataType()); - assertEquals(4, employeeEntity.getAttributeByName("MANAGER").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("MANAGER").getBelongingEntity().getName()); - - assertEquals(2, regularEmployeeEntity.getAttributes().size()); - - assertNotNull(regularEmployeeEntity.getAttributeByName("SALARY")); - assertEquals("SALARY", regularEmployeeEntity.getAttributeByName("SALARY").getName()); - assertEquals("DECIMAL", regularEmployeeEntity.getAttributeByName("SALARY").getDataType()); - assertEquals(1, regularEmployeeEntity.getAttributeByName("SALARY").getOrdinalPosition()); - assertEquals("REGULAR_EMPLOYEE", regularEmployeeEntity.getAttributeByName("SALARY").getBelongingEntity().getName()); - - assertNotNull(regularEmployeeEntity.getAttributeByName("BONUS")); - assertEquals("BONUS", regularEmployeeEntity.getAttributeByName("BONUS").getName()); - assertEquals("DECIMAL", regularEmployeeEntity.getAttributeByName("BONUS").getDataType()); - assertEquals(2, regularEmployeeEntity.getAttributeByName("BONUS").getOrdinalPosition()); - assertEquals("REGULAR_EMPLOYEE", regularEmployeeEntity.getAttributeByName("BONUS").getBelongingEntity().getName()); - - assertEquals(2, contractEmployeeEntity.getAttributes().size()); - - assertNotNull(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR")); - assertEquals("PAY_PER_HOUR", contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getName()); - assertEquals("DECIMAL", contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getDataType()); - assertEquals(1, contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getOrdinalPosition()); - assertEquals("CONTRACT_EMPLOYEE", contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getBelongingEntity().getName()); - - assertNotNull(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION")); - assertEquals("CONTRACT_DURATION", contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getDataType()); - assertEquals(2, contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getOrdinalPosition()); - assertEquals("CONTRACT_EMPLOYEE", contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getBelongingEntity().getName()); - - assertEquals(3, countryEntity.getAttributes().size()); - - assertNotNull(countryEntity.getAttributeByName("ID")); - assertEquals("ID", countryEntity.getAttributeByName("ID").getName()); - assertEquals("VARCHAR", countryEntity.getAttributeByName("ID").getDataType()); - assertEquals(1, countryEntity.getAttributeByName("ID").getOrdinalPosition()); - assertEquals("COUNTRY", countryEntity.getAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(countryEntity.getAttributeByName("NAME")); - assertEquals("NAME", countryEntity.getAttributeByName("NAME").getName()); - assertEquals("VARCHAR", countryEntity.getAttributeByName("NAME").getDataType()); - assertEquals(2, countryEntity.getAttributeByName("NAME").getOrdinalPosition()); - assertEquals("COUNTRY", countryEntity.getAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(countryEntity.getAttributeByName("CONTINENT")); - assertEquals("CONTINENT", countryEntity.getAttributeByName("CONTINENT").getName()); - assertEquals("VARCHAR", countryEntity.getAttributeByName("CONTINENT").getDataType()); - assertEquals(3, countryEntity.getAttributeByName("CONTINENT").getOrdinalPosition()); - assertEquals("COUNTRY", countryEntity.getAttributeByName("CONTINENT").getBelongingEntity().getName()); - - assertEquals(2, managerEntity.getAttributes().size()); - - assertNotNull(managerEntity.getAttributeByName("ID")); - assertEquals("ID", managerEntity.getAttributeByName("ID").getName()); - assertEquals("VARCHAR", managerEntity.getAttributeByName("ID").getDataType()); - assertEquals(1, managerEntity.getAttributeByName("ID").getOrdinalPosition()); - assertEquals("MANAGER", managerEntity.getAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(managerEntity.getAttributeByName("NAME")); - assertEquals("NAME", managerEntity.getAttributeByName("NAME").getName()); - assertEquals("VARCHAR", managerEntity.getAttributeByName("NAME").getDataType()); - assertEquals(2, managerEntity.getAttributeByName("NAME").getOrdinalPosition()); - assertEquals("MANAGER", managerEntity.getAttributeByName("NAME").getBelongingEntity().getName()); - - assertEquals(1, projectManagerEntity.getAttributes().size()); - - assertNotNull(projectManagerEntity.getAttributeByName("PROJECT")); - assertEquals("PROJECT", projectManagerEntity.getAttributeByName("PROJECT").getName()); - assertEquals("VARCHAR", projectManagerEntity.getAttributeByName("PROJECT").getDataType()); - assertEquals(1, projectManagerEntity.getAttributeByName("PROJECT").getOrdinalPosition()); - assertEquals("PROJECT_MANAGER", projectManagerEntity.getAttributeByName("PROJECT").getBelongingEntity().getName()); - - // inherited attributes check - assertEquals(0, employeeEntity.getInheritedAttributes().size()); - - assertEquals(4, regularEmployeeEntity.getInheritedAttributes().size()); - - assertNotNull(regularEmployeeEntity.getInheritedAttributeByName("ID")); - assertEquals("ID", regularEmployeeEntity.getInheritedAttributeByName("ID").getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getInheritedAttributeByName("ID").getDataType()); - assertEquals(1, regularEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()); - assertEquals("EMPLOYEE", regularEmployeeEntity.getInheritedAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(regularEmployeeEntity.getInheritedAttributeByName("NAME")); - assertEquals("NAME", regularEmployeeEntity.getInheritedAttributeByName("NAME").getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()); - assertEquals(2, regularEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()); - assertEquals("EMPLOYEE", regularEmployeeEntity.getInheritedAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE")); - assertEquals("RESIDENCE", regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()); - assertEquals(3, regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()); - assertEquals("EMPLOYEE", regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getBelongingEntity().getName()); - - assertNotNull(regularEmployeeEntity.getInheritedAttributeByName("MANAGER")); - assertEquals("MANAGER", regularEmployeeEntity.getInheritedAttributeByName("MANAGER").getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getInheritedAttributeByName("MANAGER").getDataType()); - assertEquals(4, regularEmployeeEntity.getInheritedAttributeByName("MANAGER").getOrdinalPosition()); - assertEquals("EMPLOYEE", regularEmployeeEntity.getInheritedAttributeByName("MANAGER").getBelongingEntity().getName()); - - assertEquals(4, contractEmployeeEntity.getInheritedAttributes().size()); - - assertNotNull(contractEmployeeEntity.getInheritedAttributeByName("ID")); - assertEquals("ID", contractEmployeeEntity.getInheritedAttributeByName("ID").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getInheritedAttributeByName("ID").getDataType()); - assertEquals(1, contractEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()); - assertEquals("EMPLOYEE", contractEmployeeEntity.getInheritedAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(contractEmployeeEntity.getInheritedAttributeByName("NAME")); - assertEquals("NAME", contractEmployeeEntity.getInheritedAttributeByName("NAME").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()); - assertEquals(2, contractEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()); - assertEquals("EMPLOYEE", contractEmployeeEntity.getInheritedAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE")); - assertEquals("RESIDENCE", contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()); - assertEquals(3, contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()); - assertEquals("EMPLOYEE", contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getBelongingEntity().getName()); - - assertNotNull(contractEmployeeEntity.getInheritedAttributeByName("MANAGER")); - assertEquals("MANAGER", contractEmployeeEntity.getInheritedAttributeByName("MANAGER").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getInheritedAttributeByName("MANAGER").getDataType()); - assertEquals(4, contractEmployeeEntity.getInheritedAttributeByName("MANAGER").getOrdinalPosition()); - assertEquals("EMPLOYEE", contractEmployeeEntity.getInheritedAttributeByName("MANAGER").getBelongingEntity().getName()); - - assertEquals(2, projectManagerEntity.getInheritedAttributes().size()); - - assertNotNull(projectManagerEntity.getInheritedAttributeByName("ID")); - assertEquals("ID", projectManagerEntity.getInheritedAttributeByName("ID").getName()); - assertEquals("VARCHAR", projectManagerEntity.getInheritedAttributeByName("ID").getDataType()); - assertEquals(1, projectManagerEntity.getInheritedAttributeByName("ID").getOrdinalPosition()); - assertEquals("MANAGER", projectManagerEntity.getInheritedAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(projectManagerEntity.getInheritedAttributeByName("NAME")); - assertEquals("NAME", projectManagerEntity.getInheritedAttributeByName("NAME").getName()); - assertEquals("VARCHAR", projectManagerEntity.getInheritedAttributeByName("NAME").getDataType()); - assertEquals(2, projectManagerEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()); - assertEquals("MANAGER", projectManagerEntity.getInheritedAttributeByName("NAME").getBelongingEntity().getName()); - - assertEquals(0, countryEntity.getInheritedAttributes().size()); - assertEquals(0, managerEntity.getInheritedAttributes().size()); - - // primary key check - assertEquals(1, regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()); - assertEquals("EID", regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()); - assertEquals("REGULAR_EMPLOYEE", regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getBelongingEntity().getName()); - - assertEquals(1, contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()); - assertEquals("EID", contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()); - assertEquals("CONTRACT_EMPLOYEE", contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getBelongingEntity().getName()); - - assertEquals(1, projectManagerEntity.getPrimaryKey().getInvolvedAttributes().size()); - assertEquals("EID", projectManagerEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()); - assertEquals("VARCHAR", projectManagerEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()); - assertEquals("PROJECT_MANAGER", projectManagerEntity.getPrimaryKey().getInvolvedAttributes().get(0).getBelongingEntity().getName()); - - // relationship, primary and foreign key check - assertEquals(1, regularEmployeeEntity.getOutCanonicalRelationships().size()); - assertEquals(1, contractEmployeeEntity.getOutCanonicalRelationships().size()); - assertEquals(1, employeeEntity.getOutCanonicalRelationships().size()); - assertEquals(1, projectManagerEntity.getOutCanonicalRelationships().size()); - assertEquals(0, managerEntity.getOutCanonicalRelationships().size()); - assertEquals(0, countryEntity.getOutCanonicalRelationships().size()); - assertEquals(0, regularEmployeeEntity.getInCanonicalRelationships().size()); - assertEquals(0, contractEmployeeEntity.getInCanonicalRelationships().size()); - assertEquals(2, employeeEntity.getInCanonicalRelationships().size()); - assertEquals(0, projectManagerEntity.getInCanonicalRelationships().size()); - assertEquals(2, managerEntity.getInCanonicalRelationships().size()); - assertEquals(0, countryEntity.getInCanonicalRelationships().size()); - - assertEquals(1, regularEmployeeEntity.getForeignKeys().size()); - assertEquals(1, contractEmployeeEntity.getForeignKeys().size()); - assertEquals(1, employeeEntity.getForeignKeys().size()); - assertEquals(1, projectManagerEntity.getForeignKeys().size()); - assertEquals(0, managerEntity.getForeignKeys().size()); - assertEquals(0, countryEntity.getForeignKeys().size()); - - Iterator itEmp = employeeEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship currentEmpRel = itEmp.next(); - assertEquals("MANAGER", currentEmpRel.getParentEntity().getName()); - assertEquals("EMPLOYEE", currentEmpRel.getForeignEntity().getName()); - assertEquals(managerEntity.getPrimaryKey(), currentEmpRel.getPrimaryKey()); - assertEquals(employeeEntity.getForeignKeys().get(0), currentEmpRel.getForeignKey()); - assertFalse(itEmp.hasNext()); - - Iterator itManager = managerEntity.getInCanonicalRelationships().iterator(); - CanonicalRelationship currentManRel = itManager.next(); - assertEquals(currentEmpRel, currentManRel); - - Iterator itContEmp = contractEmployeeEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship currentContEmpRel = itContEmp.next(); - itEmp = employeeEntity.getInCanonicalRelationships().iterator(); - currentEmpRel = itEmp.next(); - assertEquals(currentContEmpRel, currentEmpRel); - - Iterator itRegEmp = regularEmployeeEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship currentRegEmpRel = itRegEmp.next(); - currentEmpRel = itEmp.next(); - assertEquals(currentRegEmpRel, currentEmpRel); - - // inherited relationships check - assertEquals(1, regularEmployeeEntity.getInheritedOutCanonicalRelationships().size()); - assertEquals(1, contractEmployeeEntity.getInheritedOutCanonicalRelationships().size()); - assertEquals(0, employeeEntity.getInheritedOutCanonicalRelationships().size()); - - itRegEmp = regularEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); - itContEmp = contractEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); - currentRegEmpRel = itRegEmp.next(); - currentContEmpRel = itContEmp.next(); - assertEquals("MANAGER", currentRegEmpRel.getParentEntity().getName()); - assertEquals("EMPLOYEE", currentRegEmpRel.getForeignEntity().getName()); - assertEquals("MANAGER", currentContEmpRel.getParentEntity().getName()); - assertEquals("EMPLOYEE", currentContEmpRel.getForeignEntity().getName()); - assertEquals(managerEntity.getPrimaryKey(), currentRegEmpRel.getPrimaryKey()); - assertEquals(1, currentRegEmpRel.getFromColumns().size()); - assertEquals("MANAGER", currentRegEmpRel.getFromColumns().get(0).getName()); - assertEquals(managerEntity.getPrimaryKey(), currentContEmpRel.getPrimaryKey()); - assertEquals(1, currentContEmpRel.getFromColumns().size()); - assertEquals("MANAGER", currentContEmpRel.getFromColumns().get(0).getName()); - assertFalse(itRegEmp.hasNext()); - assertFalse(itContEmp.hasNext()); - - // inheritance check - assertEquals(employeeEntity, regularEmployeeEntity.getParentEntity()); - assertEquals(employeeEntity, contractEmployeeEntity.getParentEntity()); - assertNull(employeeEntity.getParentEntity()); - - assertEquals(1, regularEmployeeEntity.getInheritanceLevel()); - assertEquals(1, contractEmployeeEntity.getInheritanceLevel()); - assertEquals(0, employeeEntity.getInheritanceLevel()); - - // Hierarchical Bag check - assertEquals(2, mapper.getDataBaseSchema().getHierarchicalBags().size()); - - HierarchicalBag hierarchicalBag1 = mapper.getDataBaseSchema().getHierarchicalBags().get(0); - HierarchicalBag hierarchicalBag2 = mapper.getDataBaseSchema().getHierarchicalBags().get(1); - assertEquals("table-per-type", hierarchicalBag1.getInheritancePattern()); - assertEquals("table-per-type", hierarchicalBag2.getInheritancePattern()); - - assertEquals(2, hierarchicalBag1.getDepth2entities().size()); - - assertEquals(1, hierarchicalBag1.getDepth2entities().get(0).size()); - Iterator it = hierarchicalBag1.getDepth2entities().get(0).iterator(); - assertEquals("EMPLOYEE", it.next().getName()); - assertTrue(!it.hasNext()); - - assertEquals(2, hierarchicalBag1.getDepth2entities().get(1).size()); - it = hierarchicalBag1.getDepth2entities().get(1).iterator(); - assertEquals("REGULAR_EMPLOYEE", it.next().getName()); - assertEquals("CONTRACT_EMPLOYEE", it.next().getName()); - assertTrue(!it.hasNext()); - - assertEquals(hierarchicalBag1, employeeEntity.getHierarchicalBag()); - assertEquals(hierarchicalBag1, regularEmployeeEntity.getHierarchicalBag()); - assertEquals(hierarchicalBag1, contractEmployeeEntity.getHierarchicalBag()); - - assertNotNull(hierarchicalBag1.getDiscriminatorColumn()); - - assertEquals(2, hierarchicalBag2.getDepth2entities().size()); - - assertEquals(1, hierarchicalBag2.getDepth2entities().get(0).size()); - it = hierarchicalBag2.getDepth2entities().get(0).iterator(); - assertEquals("MANAGER", it.next().getName()); - assertTrue(!it.hasNext()); - - assertEquals(1, hierarchicalBag2.getDepth2entities().get(1).size()); - it = hierarchicalBag2.getDepth2entities().get(1).iterator(); - assertEquals("PROJECT_MANAGER", it.next().getName()); - assertTrue(!it.hasNext()); - - assertEquals(hierarchicalBag2, managerEntity.getHierarchicalBag()); - assertEquals(hierarchicalBag2, projectManagerEntity.getHierarchicalBag()); - - assertNotNull(hierarchicalBag2.getDiscriminatorColumn()); - - /* - * Testing built graph model - */ - - VertexType employeeVertexType = mapper.getGraphModel().getVertexTypeByName("Employee"); - VertexType regularEmployeeVertexType = mapper.getGraphModel().getVertexTypeByName("RegularEmployee"); - VertexType contractEmployeeVertexType = mapper.getGraphModel().getVertexTypeByName("ContractEmployee"); - VertexType countryVertexType = mapper.getGraphModel().getVertexTypeByName("Country"); - VertexType managerVertexType = mapper.getGraphModel().getVertexTypeByName("Manager"); - VertexType projectManagerVertexType = mapper.getGraphModel().getVertexTypeByName("ProjectManager"); - VertexType residenceVertexType = mapper.getGraphModel().getVertexTypeByName("Residence"); - - // vertices check - assertEquals(6, mapper.getGraphModel().getVerticesType().size()); - assertNotNull(employeeVertexType); - assertNotNull(regularEmployeeVertexType); - assertNotNull(contractEmployeeVertexType); - assertNotNull(countryVertexType); - assertNotNull(managerVertexType); - assertNotNull(projectManagerVertexType); - assertNull(residenceVertexType); - - // properties check - assertEquals(4, employeeVertexType.getProperties().size()); - - assertNotNull(employeeVertexType.getPropertyByName("id")); - assertEquals("id", employeeVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, employeeVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, employeeVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(employeeVertexType.getPropertyByName("name")); - assertEquals("name", employeeVertexType.getPropertyByName("name").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("name").getOriginalType()); - assertEquals(2, employeeVertexType.getPropertyByName("name").getOrdinalPosition()); - assertEquals(false, employeeVertexType.getPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(employeeVertexType.getPropertyByName("residence")); - assertEquals("residence", employeeVertexType.getPropertyByName("residence").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("residence").getOriginalType()); - assertEquals(3, employeeVertexType.getPropertyByName("residence").getOrdinalPosition()); - assertEquals(false, employeeVertexType.getPropertyByName("residence").isFromPrimaryKey()); - - assertNotNull(employeeVertexType.getPropertyByName("manager")); - assertEquals("manager", employeeVertexType.getPropertyByName("manager").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("manager").getOriginalType()); - assertEquals(4, employeeVertexType.getPropertyByName("manager").getOrdinalPosition()); - assertEquals(false, employeeVertexType.getPropertyByName("manager").isFromPrimaryKey()); - - assertEquals(2, regularEmployeeVertexType.getProperties().size()); - - assertNotNull(regularEmployeeVertexType.getPropertyByName("salary")); - assertEquals("salary", regularEmployeeVertexType.getPropertyByName("salary").getName()); - assertEquals("DECIMAL", regularEmployeeVertexType.getPropertyByName("salary").getOriginalType()); - assertEquals(1, regularEmployeeVertexType.getPropertyByName("salary").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getPropertyByName("salary").isFromPrimaryKey()); - - assertNotNull(regularEmployeeVertexType.getPropertyByName("bonus")); - assertEquals("bonus", regularEmployeeVertexType.getPropertyByName("bonus").getName()); - assertEquals("DECIMAL", regularEmployeeVertexType.getPropertyByName("bonus").getOriginalType()); - assertEquals(2, regularEmployeeVertexType.getPropertyByName("bonus").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getPropertyByName("bonus").isFromPrimaryKey()); - - assertEquals(2, contractEmployeeVertexType.getProperties().size()); - - assertNotNull(contractEmployeeVertexType.getPropertyByName("payPerHour")); - assertEquals("payPerHour", contractEmployeeVertexType.getPropertyByName("payPerHour").getName()); - assertEquals("DECIMAL", contractEmployeeVertexType.getPropertyByName("payPerHour").getOriginalType()); - assertEquals(1, contractEmployeeVertexType.getPropertyByName("payPerHour").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getPropertyByName("payPerHour").isFromPrimaryKey()); - - assertNotNull(contractEmployeeVertexType.getPropertyByName("contractDuration")); - assertEquals("contractDuration", contractEmployeeVertexType.getPropertyByName("contractDuration").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getPropertyByName("contractDuration").getOriginalType()); - assertEquals(2, contractEmployeeVertexType.getPropertyByName("contractDuration").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getPropertyByName("contractDuration").isFromPrimaryKey()); - - assertEquals(3, countryVertexType.getProperties().size()); - - assertNotNull(countryVertexType.getPropertyByName("id")); - assertEquals("id", countryVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", countryVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, countryVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, countryVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(countryVertexType.getPropertyByName("name")); - assertEquals("name", countryVertexType.getPropertyByName("name").getName()); - assertEquals("VARCHAR", countryVertexType.getPropertyByName("name").getOriginalType()); - assertEquals(2, countryVertexType.getPropertyByName("name").getOrdinalPosition()); - assertEquals(false, countryVertexType.getPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(countryVertexType.getPropertyByName("continent")); - assertEquals("continent", countryVertexType.getPropertyByName("continent").getName()); - assertEquals("VARCHAR", countryVertexType.getPropertyByName("continent").getOriginalType()); - assertEquals(3, countryVertexType.getPropertyByName("continent").getOrdinalPosition()); - assertEquals(false, countryVertexType.getPropertyByName("continent").isFromPrimaryKey()); - - assertEquals(2, managerVertexType.getProperties().size()); - - assertNotNull(managerVertexType.getPropertyByName("id")); - assertEquals("id", managerVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", managerVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, managerVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, managerVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(managerVertexType.getPropertyByName("name")); - assertEquals("name", managerVertexType.getPropertyByName("name").getName()); - assertEquals("VARCHAR", managerVertexType.getPropertyByName("name").getOriginalType()); - assertEquals(2, managerVertexType.getPropertyByName("name").getOrdinalPosition()); - assertEquals(false, managerVertexType.getPropertyByName("name").isFromPrimaryKey()); - - assertEquals(1, projectManagerVertexType.getProperties().size()); - - assertNotNull(projectManagerVertexType.getPropertyByName("project")); - assertEquals("project", projectManagerVertexType.getPropertyByName("project").getName()); - assertEquals("VARCHAR", projectManagerVertexType.getPropertyByName("project").getOriginalType()); - assertEquals(1, projectManagerVertexType.getPropertyByName("project").getOrdinalPosition()); - assertEquals(false, projectManagerVertexType.getPropertyByName("project").isFromPrimaryKey()); - - // inherited properties check - assertEquals(0, employeeVertexType.getInheritedProperties().size()); - - assertEquals(4, regularEmployeeVertexType.getInheritedProperties().size()); - - assertNotNull(regularEmployeeVertexType.getInheritedPropertyByName("id")); - assertEquals("id", regularEmployeeVertexType.getInheritedPropertyByName("id").getName()); - assertEquals("VARCHAR", regularEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()); - assertEquals(1, regularEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(regularEmployeeVertexType.getInheritedPropertyByName("name")); - assertEquals("name", regularEmployeeVertexType.getInheritedPropertyByName("name").getName()); - assertEquals("VARCHAR", regularEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()); - assertEquals(2, regularEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(regularEmployeeVertexType.getInheritedPropertyByName("residence")); - assertEquals("residence", regularEmployeeVertexType.getInheritedPropertyByName("residence").getName()); - assertEquals("VARCHAR", regularEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()); - assertEquals(3, regularEmployeeVertexType.getInheritedPropertyByName("residence").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()); - - assertNotNull(regularEmployeeVertexType.getInheritedPropertyByName("manager")); - assertEquals("manager", regularEmployeeVertexType.getInheritedPropertyByName("manager").getName()); - assertEquals("VARCHAR", regularEmployeeVertexType.getInheritedPropertyByName("manager").getOriginalType()); - assertEquals(4, regularEmployeeVertexType.getInheritedPropertyByName("manager").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getInheritedPropertyByName("manager").isFromPrimaryKey()); - - assertEquals(4, contractEmployeeVertexType.getInheritedProperties().size()); - - assertNotNull(contractEmployeeVertexType.getInheritedPropertyByName("id")); - assertEquals("id", contractEmployeeVertexType.getInheritedPropertyByName("id").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()); - assertEquals(1, contractEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(contractEmployeeVertexType.getInheritedPropertyByName("name")); - assertEquals("name", contractEmployeeVertexType.getInheritedPropertyByName("name").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()); - assertEquals(2, contractEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(contractEmployeeVertexType.getInheritedPropertyByName("residence")); - assertEquals("residence", contractEmployeeVertexType.getInheritedPropertyByName("residence").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()); - assertEquals(3, contractEmployeeVertexType.getInheritedPropertyByName("residence").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()); - - assertNotNull(contractEmployeeVertexType.getInheritedPropertyByName("manager")); - assertEquals("manager", contractEmployeeVertexType.getInheritedPropertyByName("manager").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getInheritedPropertyByName("manager").getOriginalType()); - assertEquals(4, contractEmployeeVertexType.getInheritedPropertyByName("manager").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getInheritedPropertyByName("manager").isFromPrimaryKey()); - - assertEquals(2, projectManagerVertexType.getInheritedProperties().size()); - - assertNotNull(projectManagerVertexType.getInheritedPropertyByName("id")); - assertEquals("id", projectManagerVertexType.getInheritedPropertyByName("id").getName()); - assertEquals("VARCHAR", projectManagerVertexType.getInheritedPropertyByName("id").getOriginalType()); - assertEquals(1, projectManagerVertexType.getInheritedPropertyByName("id").getOrdinalPosition()); - assertEquals(false, projectManagerVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(projectManagerVertexType.getInheritedPropertyByName("name")); - assertEquals("name", projectManagerVertexType.getInheritedPropertyByName("name").getName()); - assertEquals("VARCHAR", projectManagerVertexType.getInheritedPropertyByName("name").getOriginalType()); - assertEquals(2, projectManagerVertexType.getInheritedPropertyByName("name").getOrdinalPosition()); - assertEquals(false, projectManagerVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()); - - assertEquals(0, countryVertexType.getInheritedProperties().size()); - assertEquals(0, managerVertexType.getInheritedProperties().size()); - - // edges check - - assertEquals(1, mapper.getRelationship2edgeType().size()); - - assertEquals(1, mapper.getGraphModel().getEdgesType().size()); - assertEquals("HasManager", mapper.getGraphModel().getEdgesType().get(0).getName()); - - assertEquals(1, employeeVertexType.getOutEdgesType().size()); - assertEquals("HasManager", employeeVertexType.getOutEdgesType().get(0).getName()); - - assertEquals(1, regularEmployeeVertexType.getOutEdgesType().size()); - assertEquals("HasManager", regularEmployeeVertexType.getOutEdgesType().get(0).getName()); - - assertEquals(1, contractEmployeeVertexType.getOutEdgesType().size()); - assertEquals("HasManager", contractEmployeeVertexType.getOutEdgesType().get(0).getName()); - - /* - * Rules check - */ - - // Classes Mapping - - assertEquals(6, mapper.getVertexType2EVClassMappers().size()); - assertEquals(6, mapper.getEntity2EVClassMappers().size()); - - assertEquals(1, mapper.getEVClassMappersByVertex(employeeVertexType).size()); - EVClassMapper employeeClassMapper = mapper.getEVClassMappersByVertex(employeeVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(employeeEntity).size()); - assertEquals(employeeClassMapper, mapper.getEVClassMappersByEntity(employeeEntity).get(0)); - assertEquals(employeeClassMapper.getEntity(), employeeEntity); - assertEquals(employeeClassMapper.getVertexType(), employeeVertexType); - - assertEquals(4, employeeClassMapper.getAttribute2property().size()); - assertEquals(4, employeeClassMapper.getProperty2attribute().size()); - assertEquals("id", employeeClassMapper.getAttribute2property().get("ID")); - assertEquals("name", employeeClassMapper.getAttribute2property().get("NAME")); - assertEquals("residence", employeeClassMapper.getAttribute2property().get("RESIDENCE")); - assertEquals("manager", employeeClassMapper.getAttribute2property().get("MANAGER")); - assertEquals("ID", employeeClassMapper.getProperty2attribute().get("id")); - assertEquals("NAME", employeeClassMapper.getProperty2attribute().get("name")); - assertEquals("RESIDENCE", employeeClassMapper.getProperty2attribute().get("residence")); - assertEquals("MANAGER", employeeClassMapper.getProperty2attribute().get("manager")); - - assertEquals(1, mapper.getEVClassMappersByVertex(regularEmployeeVertexType).size()); - EVClassMapper regularEmployeeClassMapper = mapper.getEVClassMappersByVertex(regularEmployeeVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(regularEmployeeEntity).size()); - assertEquals(regularEmployeeClassMapper, mapper.getEVClassMappersByEntity(regularEmployeeEntity).get(0)); - assertEquals(regularEmployeeClassMapper.getEntity(), regularEmployeeEntity); - assertEquals(regularEmployeeClassMapper.getVertexType(), regularEmployeeVertexType); - - assertEquals(2, regularEmployeeClassMapper.getAttribute2property().size()); - assertEquals(2, regularEmployeeClassMapper.getProperty2attribute().size()); - assertEquals("salary", regularEmployeeClassMapper.getAttribute2property().get("SALARY")); - assertEquals("bonus", regularEmployeeClassMapper.getAttribute2property().get("BONUS")); - assertEquals("SALARY", regularEmployeeClassMapper.getProperty2attribute().get("salary")); - assertEquals("BONUS", regularEmployeeClassMapper.getProperty2attribute().get("bonus")); - - assertEquals(1, mapper.getEVClassMappersByVertex(contractEmployeeVertexType).size()); - EVClassMapper contractEmployeeClassMapper = mapper.getEVClassMappersByVertex(contractEmployeeVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(contractEmployeeEntity).size()); - assertEquals(contractEmployeeClassMapper, mapper.getEVClassMappersByEntity(contractEmployeeEntity).get(0)); - assertEquals(contractEmployeeClassMapper.getEntity(), contractEmployeeEntity); - assertEquals(contractEmployeeClassMapper.getVertexType(), contractEmployeeVertexType); - - assertEquals(2, contractEmployeeClassMapper.getAttribute2property().size()); - assertEquals(2, contractEmployeeClassMapper.getProperty2attribute().size()); - assertEquals("payPerHour", contractEmployeeClassMapper.getAttribute2property().get("PAY_PER_HOUR")); - assertEquals("contractDuration", contractEmployeeClassMapper.getAttribute2property().get("CONTRACT_DURATION")); - assertEquals("PAY_PER_HOUR", contractEmployeeClassMapper.getProperty2attribute().get("payPerHour")); - assertEquals("CONTRACT_DURATION", contractEmployeeClassMapper.getProperty2attribute().get("contractDuration")); - - assertEquals(1, mapper.getEVClassMappersByVertex(countryVertexType).size()); - EVClassMapper countryClassMapper = mapper.getEVClassMappersByVertex(countryVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(countryEntity).size()); - assertEquals(countryClassMapper, mapper.getEVClassMappersByEntity(countryEntity).get(0)); - assertEquals(countryClassMapper.getEntity(), countryEntity); - assertEquals(countryClassMapper.getVertexType(), countryVertexType); - - assertEquals(3, countryClassMapper.getAttribute2property().size()); - assertEquals(3, countryClassMapper.getProperty2attribute().size()); - assertEquals("id", countryClassMapper.getAttribute2property().get("ID")); - assertEquals("name", countryClassMapper.getAttribute2property().get("NAME")); - assertEquals("continent", countryClassMapper.getAttribute2property().get("CONTINENT")); - assertEquals("ID", countryClassMapper.getProperty2attribute().get("id")); - assertEquals("NAME", countryClassMapper.getProperty2attribute().get("name")); - assertEquals("CONTINENT", countryClassMapper.getProperty2attribute().get("continent")); - - assertEquals(1, mapper.getEVClassMappersByVertex(managerVertexType).size()); - EVClassMapper managerClassMapper = mapper.getEVClassMappersByVertex(managerVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(managerEntity).size()); - assertEquals(managerClassMapper, mapper.getEVClassMappersByEntity(managerEntity).get(0)); - assertEquals(managerClassMapper.getEntity(), managerEntity); - assertEquals(managerClassMapper.getVertexType(), managerVertexType); - - assertEquals(2, managerClassMapper.getAttribute2property().size()); - assertEquals(2, managerClassMapper.getProperty2attribute().size()); - assertEquals("id", managerClassMapper.getAttribute2property().get("ID")); - assertEquals("name", managerClassMapper.getAttribute2property().get("NAME")); - assertEquals("ID", managerClassMapper.getProperty2attribute().get("id")); - assertEquals("NAME", managerClassMapper.getProperty2attribute().get("name")); - - assertEquals(1, mapper.getEVClassMappersByVertex(projectManagerVertexType).size()); - EVClassMapper projectManagerClassMapper = mapper.getEVClassMappersByVertex(projectManagerVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(projectManagerEntity).size()); - assertEquals(projectManagerClassMapper, mapper.getEVClassMappersByEntity(projectManagerEntity).get(0)); - assertEquals(projectManagerClassMapper.getEntity(), projectManagerEntity); - assertEquals(projectManagerClassMapper.getVertexType(), projectManagerVertexType); - - assertEquals(1, projectManagerClassMapper.getAttribute2property().size()); - assertEquals(1, projectManagerClassMapper.getProperty2attribute().size()); - assertEquals("project", projectManagerClassMapper.getAttribute2property().get("PROJECT")); - assertEquals("PROJECT", projectManagerClassMapper.getProperty2attribute().get("project")); - - // Relationships-Edges Mapping - - Iterator itRelationships = employeeEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship hasManagerRelationship = itRelationships.next(); - assertFalse(itRelationships.hasNext()); - - EdgeType hasManagerEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasManager"); - - assertEquals(1, mapper.getRelationship2edgeType().size()); - assertEquals(hasManagerEdgeType, mapper.getRelationship2edgeType().get(hasManagerRelationship)); - - assertEquals(1, mapper.getEdgeType2relationships().size()); - assertEquals(1, mapper.getEdgeType2relationships().get(hasManagerEdgeType).size()); - assertTrue(mapper.getEdgeType2relationships().get(hasManagerEdgeType).contains(hasManagerRelationship)); - - // JoinVertexes-AggregatorEdges Mapping - - assertEquals(0, mapper.getJoinVertex2aggregatorEdges().size()); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } finally { - try { - // Dropping Source DB Schema and OrientGraph - String dbDropping = "drop schema public cascade"; - st.execute(dbDropping); - connection.close(); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } - } + } + + /* + * Filtering out a table through exclude-tables (with Table per Type inheritance). + */ @Test + void filterOutThroughExcludeWithTablePerTypeInheritance() { + Connection connection = null; + Statement st = null; + + try { + Class.forName(this.driver); + connection = DriverManager.getConnection(this.jurl, this.username, this.password); + + String countryTableBuilding = + "create memory table COUNTRY(ID varchar(256) not null, NAME varchar(256), CONTINENT" + + " varchar(256), primary key (ID))"; + st = connection.createStatement(); + st.execute(countryTableBuilding); + + String residenceTableBuilding = + "create memory table RESIDENCE(ID varchar(256) not null, CITY varchar(256), COUNTRY" + + " varchar(256), primary key (ID))"; + st = connection.createStatement(); + st.execute(residenceTableBuilding); + + String managerTableBuilding = + "create memory table MANAGER(ID varchar(256) not null, NAME varchar(256), primary key" + + " (ID))"; + st.execute(managerTableBuilding); + + String projectManagerTableBuilding = + "create memory table PROJECT_MANAGER(EID varchar(256) not null, PROJECT varchar(256)," + + " primary key (EID), foreign key (EID) references MANAGER(ID))"; + st.execute(projectManagerTableBuilding); + + String employeeTableBuilding = + "create memory table EMPLOYEE (ID varchar(256) not null, NAME varchar(256), RESIDENCE" + + " varchar(256), MANAGER varchar(256), primary key (ID), foreign key (RESIDENCE)" + + " references RESIDENCE(ID), foreign key (MANAGER) references MANAGER(ID))"; + st.execute(employeeTableBuilding); + + String regularEmployeeTableBuilding = + "create memory table REGULAR_EMPLOYEE (EID varchar(256) not null, SALARY decimal(10,2)," + + " BONUS decimal(10,0), primary key (EID), foreign key (EID) references" + + " EMPLOYEE(ID))"; + st.execute(regularEmployeeTableBuilding); + + String contractEmployeeTableBuilding = + "create memory table CONTRACT_EMPLOYEE (EID varchar(256) not null, PAY_PER_HOUR" + + " decimal(10,2), CONTRACT_DURATION varchar(256), primary key (EID), foreign key" + + " (EID) references EMPLOYEE(ID))"; + st.execute(contractEmployeeTableBuilding); + + // Records Inserting + + String countryFilling = + "insert into COUNTRY (ID,NAME,CONTINENT) values (" + "('C001','Italy','Europe'))"; + st.execute(countryFilling); + + String residenceFilling = + "insert into RESIDENCE (ID,CITY,COUNTRY) values (" + + "('R001','Rome','C001')," + + "('R002','Milan','C001'))"; + st.execute(residenceFilling); + + String managerFilling = "insert into MANAGER (ID,NAME) values (" + "('M001','Bill Right'))"; + st.execute(managerFilling); + + String projectManagerFilling = + "insert into PROJECT_MANAGER (EID,PROJECT) values (" + "('M001','New World'))"; + st.execute(projectManagerFilling); + + String employeeFilling = + "insert into EMPLOYEE (ID,NAME,RESIDENCE,MANAGER) values (" + + "('E001','John Black','R001',null)," + + "('E002','Andrew Brown','R001','M001')," + + "('E003','Jack Johnson','R002',null))"; + st.execute(employeeFilling); + + String regularEmployeeFilling = + "insert into REGULAR_EMPLOYEE (EID,SALARY,BONUS) values (" + "('E002','1000.00','10'))"; + st.execute(regularEmployeeFilling); + + String contractEmployeeFilling = + "insert into CONTRACT_EMPLOYEE (EID,PAY_PER_HOUR,CONTRACT_DURATION) values (" + + "('E003','50.00','6'))"; + st.execute(contractEmployeeFilling); + + List excludedTables = new ArrayList(); + excludedTables.add("RESIDENCE"); + + this.mapper = + new Hibernate2GraphMapper( + dataSource, + FilterTableMappingTest.XML_TABLE_PER_SUBCLASS2, + null, + excludedTables, + dbQueryEngine, + dataTypeHandler, + executionStrategy, + nameResolver, + statistics); + + mapper.buildSourceDatabaseSchema(); + mapper.buildGraphModel(new JavaConventionNameResolver()); + + /* + * Testing context information + */ + + assertThat(statistics.totalNumberOfEntities).isEqualTo(6); + assertThat(statistics.builtEntities).isEqualTo(6); + assertThat(statistics.totalNumberOfRelationships).isEqualTo(4); + assertThat(statistics.builtRelationships) + .isEqualTo(4); // 3 of these are hierarchical relationships + + assertThat(statistics.totalNumberOfModelVertices).isEqualTo(6); + assertThat(statistics.builtModelVertexTypes).isEqualTo(6); + assertThat(statistics.totalNumberOfModelEdges).isEqualTo(1); + assertThat(statistics.builtModelEdgeTypes).isEqualTo(1); + + /* + * Testing built source db schema + */ + + Entity employeeEntity = mapper.getDataBaseSchema().getEntityByName("EMPLOYEE"); + Entity regularEmployeeEntity = + mapper.getDataBaseSchema().getEntityByNameIgnoreCase("REGULAR_EMPLOYEE"); + Entity contractEmployeeEntity = + mapper.getDataBaseSchema().getEntityByNameIgnoreCase("CONTRACT_EMPLOYEE"); + Entity countryEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("COUNTRY"); + Entity managerEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("MANAGER"); + Entity projectManagerEntity = + mapper.getDataBaseSchema().getEntityByNameIgnoreCase("PROJECT_MANAGER"); + Entity residenceEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("RESIDENCE"); + + // entities check + assertThat(mapper.getDataBaseSchema().getEntities().size()).isEqualTo(6); + assertThat(mapper.getDataBaseSchema().getCanonicalRelationships().size()).isEqualTo(4); + assertThat(employeeEntity).isNotNull(); + assertThat(regularEmployeeEntity).isNotNull(); + assertThat(contractEmployeeEntity).isNotNull(); + assertThat(countryEntity).isNotNull(); + assertThat(managerEntity).isNotNull(); + assertThat(residenceEntity).isNull(); + + // attributes check + assertThat(employeeEntity.getAttributes().size()).isEqualTo(4); + + assertThat(employeeEntity.getAttributeByName("ID")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(employeeEntity.getAttributeByName("ID").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("ID").getOrdinalPosition()).isEqualTo(1); + assertThat(employeeEntity.getAttributeByName("ID").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(employeeEntity.getAttributeByName("NAME")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("NAME").getName()).isEqualTo("NAME"); + assertThat(employeeEntity.getAttributeByName("NAME").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("NAME").getOrdinalPosition()).isEqualTo(2); + assertThat(employeeEntity.getAttributeByName("NAME").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(employeeEntity.getAttributeByName("RESIDENCE")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getName()).isEqualTo("RESIDENCE"); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getOrdinalPosition()).isEqualTo(3); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(employeeEntity.getAttributeByName("MANAGER")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("MANAGER").getName()).isEqualTo("MANAGER"); + assertThat(employeeEntity.getAttributeByName("MANAGER").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("MANAGER").getOrdinalPosition()).isEqualTo(4); + assertThat(employeeEntity.getAttributeByName("MANAGER").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(regularEmployeeEntity.getAttributes().size()).isEqualTo(2); + + assertThat(regularEmployeeEntity.getAttributeByName("SALARY")).isNotNull(); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getName()).isEqualTo("SALARY"); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getDataType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getOrdinalPosition()) + .isEqualTo(1); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getBelongingEntity().getName()) + .isEqualTo("REGULAR_EMPLOYEE"); + + assertThat(regularEmployeeEntity.getAttributeByName("BONUS")).isNotNull(); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getName()).isEqualTo("BONUS"); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getDataType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getOrdinalPosition()) + .isEqualTo(2); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getBelongingEntity().getName()) + .isEqualTo("REGULAR_EMPLOYEE"); + + assertThat(contractEmployeeEntity.getAttributes().size()).isEqualTo(2); + + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR")).isNotNull(); + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getName()) + .isEqualTo("PAY_PER_HOUR"); + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getDataType()) + .isEqualTo("DECIMAL"); + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getOrdinalPosition()) + .isEqualTo(1); + assertThat( + contractEmployeeEntity + .getAttributeByName("PAY_PER_HOUR") + .getBelongingEntity() + .getName()) + .isEqualTo("CONTRACT_EMPLOYEE"); + + assertThat(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION")).isNotNull(); + assertThat(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getName()) + .isEqualTo("CONTRACT_DURATION"); + assertThat(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + contractEmployeeEntity + .getAttributeByName("CONTRACT_DURATION") + .getBelongingEntity() + .getName()) + .isEqualTo("CONTRACT_EMPLOYEE"); + + assertThat(countryEntity.getAttributes().size()).isEqualTo(3); + + assertThat(countryEntity.getAttributeByName("ID")).isNotNull(); + assertThat(countryEntity.getAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(countryEntity.getAttributeByName("ID").getDataType()).isEqualTo("VARCHAR"); + assertThat(countryEntity.getAttributeByName("ID").getOrdinalPosition()).isEqualTo(1); + assertThat(countryEntity.getAttributeByName("ID").getBelongingEntity().getName()) + .isEqualTo("COUNTRY"); + + assertThat(countryEntity.getAttributeByName("NAME")).isNotNull(); + assertThat(countryEntity.getAttributeByName("NAME").getName()).isEqualTo("NAME"); + assertThat(countryEntity.getAttributeByName("NAME").getDataType()).isEqualTo("VARCHAR"); + assertThat(countryEntity.getAttributeByName("NAME").getOrdinalPosition()).isEqualTo(2); + assertThat(countryEntity.getAttributeByName("NAME").getBelongingEntity().getName()) + .isEqualTo("COUNTRY"); + + assertThat(countryEntity.getAttributeByName("CONTINENT")).isNotNull(); + assertThat(countryEntity.getAttributeByName("CONTINENT").getName()).isEqualTo("CONTINENT"); + assertThat(countryEntity.getAttributeByName("CONTINENT").getDataType()).isEqualTo("VARCHAR"); + assertThat(countryEntity.getAttributeByName("CONTINENT").getOrdinalPosition()).isEqualTo(3); + assertThat(countryEntity.getAttributeByName("CONTINENT").getBelongingEntity().getName()) + .isEqualTo("COUNTRY"); + + assertThat(managerEntity.getAttributes().size()).isEqualTo(2); + + assertThat(managerEntity.getAttributeByName("ID")).isNotNull(); + assertThat(managerEntity.getAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(managerEntity.getAttributeByName("ID").getDataType()).isEqualTo("VARCHAR"); + assertThat(managerEntity.getAttributeByName("ID").getOrdinalPosition()).isEqualTo(1); + assertThat(managerEntity.getAttributeByName("ID").getBelongingEntity().getName()) + .isEqualTo("MANAGER"); + + assertThat(managerEntity.getAttributeByName("NAME")).isNotNull(); + assertThat(managerEntity.getAttributeByName("NAME").getName()).isEqualTo("NAME"); + assertThat(managerEntity.getAttributeByName("NAME").getDataType()).isEqualTo("VARCHAR"); + assertThat(managerEntity.getAttributeByName("NAME").getOrdinalPosition()).isEqualTo(2); + assertThat(managerEntity.getAttributeByName("NAME").getBelongingEntity().getName()) + .isEqualTo("MANAGER"); + + assertThat(projectManagerEntity.getAttributes().size()).isEqualTo(1); + + assertThat(projectManagerEntity.getAttributeByName("PROJECT")).isNotNull(); + assertThat(projectManagerEntity.getAttributeByName("PROJECT").getName()).isEqualTo("PROJECT"); + assertThat(projectManagerEntity.getAttributeByName("PROJECT").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(projectManagerEntity.getAttributeByName("PROJECT").getOrdinalPosition()) + .isEqualTo(1); + assertThat(projectManagerEntity.getAttributeByName("PROJECT").getBelongingEntity().getName()) + .isEqualTo("PROJECT_MANAGER"); + + // inherited attributes check + assertThat(employeeEntity.getInheritedAttributes().size()).isEqualTo(0); + + assertThat(regularEmployeeEntity.getInheritedAttributes().size()).isEqualTo(4); + + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID")).isNotNull(); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()) + .isEqualTo(1); + assertThat( + regularEmployeeEntity + .getInheritedAttributeByName("ID") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME")).isNotNull(); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME").getName()) + .isEqualTo("NAME"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + regularEmployeeEntity + .getInheritedAttributeByName("NAME") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE")).isNotNull(); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()) + .isEqualTo("RESIDENCE"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()) + .isEqualTo(3); + assertThat( + regularEmployeeEntity + .getInheritedAttributeByName("RESIDENCE") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(regularEmployeeEntity.getInheritedAttributeByName("MANAGER")).isNotNull(); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("MANAGER").getName()) + .isEqualTo("MANAGER"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("MANAGER").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("MANAGER").getOrdinalPosition()) + .isEqualTo(4); + assertThat( + regularEmployeeEntity + .getInheritedAttributeByName("MANAGER") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(contractEmployeeEntity.getInheritedAttributes().size()).isEqualTo(4); + + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID")).isNotNull(); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID").getName()) + .isEqualTo("ID"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()) + .isEqualTo(1); + assertThat( + contractEmployeeEntity + .getInheritedAttributeByName("ID") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME")).isNotNull(); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME").getName()) + .isEqualTo("NAME"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + contractEmployeeEntity + .getInheritedAttributeByName("NAME") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE")).isNotNull(); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()) + .isEqualTo("RESIDENCE"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()) + .isEqualTo(3); + assertThat( + contractEmployeeEntity + .getInheritedAttributeByName("RESIDENCE") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(contractEmployeeEntity.getInheritedAttributeByName("MANAGER")).isNotNull(); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("MANAGER").getName()) + .isEqualTo("MANAGER"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("MANAGER").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("MANAGER").getOrdinalPosition()) + .isEqualTo(4); + assertThat( + contractEmployeeEntity + .getInheritedAttributeByName("MANAGER") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(projectManagerEntity.getInheritedAttributes().size()).isEqualTo(2); + + assertThat(projectManagerEntity.getInheritedAttributeByName("ID")).isNotNull(); + assertThat(projectManagerEntity.getInheritedAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(projectManagerEntity.getInheritedAttributeByName("ID").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(projectManagerEntity.getInheritedAttributeByName("ID").getOrdinalPosition()) + .isEqualTo(1); + assertThat( + projectManagerEntity.getInheritedAttributeByName("ID").getBelongingEntity().getName()) + .isEqualTo("MANAGER"); + + assertThat(projectManagerEntity.getInheritedAttributeByName("NAME")).isNotNull(); + assertThat(projectManagerEntity.getInheritedAttributeByName("NAME").getName()) + .isEqualTo("NAME"); + assertThat(projectManagerEntity.getInheritedAttributeByName("NAME").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(projectManagerEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + projectManagerEntity + .getInheritedAttributeByName("NAME") + .getBelongingEntity() + .getName()) + .isEqualTo("MANAGER"); + + assertThat(countryEntity.getInheritedAttributes().size()).isEqualTo(0); + assertThat(managerEntity.getInheritedAttributes().size()).isEqualTo(0); + + // primary key check + assertThat(regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()).isEqualTo(1); + assertThat(regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()) + .isEqualTo("EID"); + assertThat(regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + regularEmployeeEntity + .getPrimaryKey() + .getInvolvedAttributes() + .get(0) + .getBelongingEntity() + .getName()) + .isEqualTo("REGULAR_EMPLOYEE"); + + assertThat(contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()) + .isEqualTo(1); + assertThat(contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()) + .isEqualTo("EID"); + assertThat( + contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeEntity + .getPrimaryKey() + .getInvolvedAttributes() + .get(0) + .getBelongingEntity() + .getName()) + .isEqualTo("CONTRACT_EMPLOYEE"); + + assertThat(projectManagerEntity.getPrimaryKey().getInvolvedAttributes().size()).isEqualTo(1); + assertThat(projectManagerEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()) + .isEqualTo("EID"); + assertThat(projectManagerEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + projectManagerEntity + .getPrimaryKey() + .getInvolvedAttributes() + .get(0) + .getBelongingEntity() + .getName()) + .isEqualTo("PROJECT_MANAGER"); + + // relationship, primary and foreign key check + assertThat(regularEmployeeEntity.getOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(contractEmployeeEntity.getOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(employeeEntity.getOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(projectManagerEntity.getOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(managerEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(countryEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(regularEmployeeEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(contractEmployeeEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(employeeEntity.getInCanonicalRelationships().size()).isEqualTo(2); + assertThat(projectManagerEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(managerEntity.getInCanonicalRelationships().size()).isEqualTo(2); + assertThat(countryEntity.getInCanonicalRelationships().size()).isEqualTo(0); + + assertThat(regularEmployeeEntity.getForeignKeys().size()).isEqualTo(1); + assertThat(contractEmployeeEntity.getForeignKeys().size()).isEqualTo(1); + assertThat(employeeEntity.getForeignKeys().size()).isEqualTo(1); + assertThat(projectManagerEntity.getForeignKeys().size()).isEqualTo(1); + assertThat(managerEntity.getForeignKeys().size()).isEqualTo(0); + assertThat(countryEntity.getForeignKeys().size()).isEqualTo(0); + + Iterator itEmp = + employeeEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship currentEmpRel = itEmp.next(); + assertThat(currentEmpRel.getParentEntity().getName()).isEqualTo("MANAGER"); + assertThat(currentEmpRel.getForeignEntity().getName()).isEqualTo("EMPLOYEE"); + assertThat(currentEmpRel.getPrimaryKey()).isEqualTo(managerEntity.getPrimaryKey()); + assertThat(currentEmpRel.getForeignKey()).isEqualTo(employeeEntity.getForeignKeys().get(0)); + assertThat(itEmp.hasNext()).isFalse(); + + Iterator itManager = + managerEntity.getInCanonicalRelationships().iterator(); + CanonicalRelationship currentManRel = itManager.next(); + assertThat(currentManRel).isEqualTo(currentEmpRel); + + Iterator itContEmp = + contractEmployeeEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship currentContEmpRel = itContEmp.next(); + itEmp = employeeEntity.getInCanonicalRelationships().iterator(); + currentEmpRel = itEmp.next(); + assertThat(currentEmpRel).isEqualTo(currentContEmpRel); + + Iterator itRegEmp = + regularEmployeeEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship currentRegEmpRel = itRegEmp.next(); + currentEmpRel = itEmp.next(); + assertThat(currentEmpRel).isEqualTo(currentRegEmpRel); + + // inherited relationships check + assertThat(regularEmployeeEntity.getInheritedOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(contractEmployeeEntity.getInheritedOutCanonicalRelationships().size()) + .isEqualTo(1); + assertThat(employeeEntity.getInheritedOutCanonicalRelationships().size()).isEqualTo(0); + + itRegEmp = regularEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); + itContEmp = contractEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); + currentRegEmpRel = itRegEmp.next(); + currentContEmpRel = itContEmp.next(); + assertThat(currentRegEmpRel.getParentEntity().getName()).isEqualTo("MANAGER"); + assertThat(currentRegEmpRel.getForeignEntity().getName()).isEqualTo("EMPLOYEE"); + assertThat(currentContEmpRel.getParentEntity().getName()).isEqualTo("MANAGER"); + assertThat(currentContEmpRel.getForeignEntity().getName()).isEqualTo("EMPLOYEE"); + assertThat(currentRegEmpRel.getPrimaryKey()).isEqualTo(managerEntity.getPrimaryKey()); + assertThat(currentRegEmpRel.getFromColumns().size()).isEqualTo(1); + assertThat(currentRegEmpRel.getFromColumns().get(0).getName()).isEqualTo("MANAGER"); + assertThat(currentContEmpRel.getPrimaryKey()).isEqualTo(managerEntity.getPrimaryKey()); + assertThat(currentContEmpRel.getFromColumns().size()).isEqualTo(1); + assertThat(currentContEmpRel.getFromColumns().get(0).getName()).isEqualTo("MANAGER"); + assertThat(itRegEmp.hasNext()).isFalse(); + assertThat(itContEmp.hasNext()).isFalse(); + + // inheritance check + assertThat(regularEmployeeEntity.getParentEntity()).isEqualTo(employeeEntity); + assertThat(contractEmployeeEntity.getParentEntity()).isEqualTo(employeeEntity); + assertThat(employeeEntity.getParentEntity()).isNull(); + + assertThat(regularEmployeeEntity.getInheritanceLevel()).isEqualTo(1); + assertThat(contractEmployeeEntity.getInheritanceLevel()).isEqualTo(1); + assertThat(employeeEntity.getInheritanceLevel()).isEqualTo(0); + + // Hierarchical Bag check + assertThat(mapper.getDataBaseSchema().getHierarchicalBags().size()).isEqualTo(2); + + HierarchicalBag hierarchicalBag1 = mapper.getDataBaseSchema().getHierarchicalBags().get(0); + HierarchicalBag hierarchicalBag2 = mapper.getDataBaseSchema().getHierarchicalBags().get(1); + assertThat(hierarchicalBag1.getInheritancePattern()).isEqualTo("table-per-type"); + assertThat(hierarchicalBag2.getInheritancePattern()).isEqualTo("table-per-type"); + + assertThat(hierarchicalBag1.getDepth2entities().size()).isEqualTo(2); + + assertThat(hierarchicalBag1.getDepth2entities().get(0).size()).isEqualTo(1); + Iterator it = hierarchicalBag1.getDepth2entities().get(0).iterator(); + assertThat(it.next().getName()).isEqualTo("EMPLOYEE"); + assertThat(it.hasNext()).isFalse(); + + assertThat(hierarchicalBag1.getDepth2entities().get(1).size()).isEqualTo(2); + it = hierarchicalBag1.getDepth2entities().get(1).iterator(); + assertThat(it.next().getName()).isEqualTo("REGULAR_EMPLOYEE"); + assertThat(it.next().getName()).isEqualTo("CONTRACT_EMPLOYEE"); + assertThat(it.hasNext()).isFalse(); + + assertThat(employeeEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag1); + assertThat(regularEmployeeEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag1); + assertThat(contractEmployeeEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag1); + + assertThat(hierarchicalBag1.getDiscriminatorColumn()).isNotNull(); + + assertThat(hierarchicalBag2.getDepth2entities().size()).isEqualTo(2); + + assertThat(hierarchicalBag2.getDepth2entities().get(0).size()).isEqualTo(1); + it = hierarchicalBag2.getDepth2entities().get(0).iterator(); + assertThat(it.next().getName()).isEqualTo("MANAGER"); + assertThat(it.hasNext()).isFalse(); + + assertThat(hierarchicalBag2.getDepth2entities().get(1).size()).isEqualTo(1); + it = hierarchicalBag2.getDepth2entities().get(1).iterator(); + assertThat(it.next().getName()).isEqualTo("PROJECT_MANAGER"); + assertThat(it.hasNext()).isFalse(); + + assertThat(managerEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag2); + assertThat(projectManagerEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag2); + + assertThat(hierarchicalBag2.getDiscriminatorColumn()).isNotNull(); + + /* + * Testing built graph model + */ + + VertexType employeeVertexType = mapper.getGraphModel().getVertexTypeByName("Employee"); + VertexType regularEmployeeVertexType = + mapper.getGraphModel().getVertexTypeByName("RegularEmployee"); + VertexType contractEmployeeVertexType = + mapper.getGraphModel().getVertexTypeByName("ContractEmployee"); + VertexType countryVertexType = mapper.getGraphModel().getVertexTypeByName("Country"); + VertexType managerVertexType = mapper.getGraphModel().getVertexTypeByName("Manager"); + VertexType projectManagerVertexType = + mapper.getGraphModel().getVertexTypeByName("ProjectManager"); + VertexType residenceVertexType = mapper.getGraphModel().getVertexTypeByName("Residence"); + + // vertices check + assertThat(mapper.getGraphModel().getVerticesType().size()).isEqualTo(6); + assertThat(employeeVertexType).isNotNull(); + assertThat(regularEmployeeVertexType).isNotNull(); + assertThat(contractEmployeeVertexType).isNotNull(); + assertThat(countryVertexType).isNotNull(); + assertThat(managerVertexType).isNotNull(); + assertThat(projectManagerVertexType).isNotNull(); + assertThat(residenceVertexType).isNull(); + + // properties check + assertThat(employeeVertexType.getProperties().size()).isEqualTo(4); + + assertThat(employeeVertexType.getPropertyByName("id")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(employeeVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(employeeVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(employeeVertexType.getPropertyByName("name")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("name").getName()).isEqualTo("name"); + assertThat(employeeVertexType.getPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("name").getOrdinalPosition()).isEqualTo(2); + assertThat(employeeVertexType.getPropertyByName("name").isFromPrimaryKey()).isFalse(); + + assertThat(employeeVertexType.getPropertyByName("residence")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("residence").getName()) + .isEqualTo("residence"); + assertThat(employeeVertexType.getPropertyByName("residence").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("residence").getOrdinalPosition()) + .isEqualTo(3); + assertThat(employeeVertexType.getPropertyByName("residence").isFromPrimaryKey()).isFalse(); + + assertThat(employeeVertexType.getPropertyByName("manager")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("manager").getName()).isEqualTo("manager"); + assertThat(employeeVertexType.getPropertyByName("manager").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("manager").getOrdinalPosition()).isEqualTo(4); + assertThat(employeeVertexType.getPropertyByName("manager").isFromPrimaryKey()).isFalse(); + + assertThat(regularEmployeeVertexType.getProperties().size()).isEqualTo(2); + + assertThat(regularEmployeeVertexType.getPropertyByName("salary")).isNotNull(); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").getName()) + .isEqualTo("salary"); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").getOriginalType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").getOrdinalPosition()) + .isEqualTo(1); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").isFromPrimaryKey()) + .isFalse(); + + assertThat(regularEmployeeVertexType.getPropertyByName("bonus")).isNotNull(); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").getName()).isEqualTo("bonus"); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").getOriginalType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").getOrdinalPosition()) + .isEqualTo(2); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").isFromPrimaryKey()).isFalse(); + + assertThat(contractEmployeeVertexType.getProperties().size()).isEqualTo(2); + + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour")).isNotNull(); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").getName()) + .isEqualTo("payPerHour"); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").getOriginalType()) + .isEqualTo("DECIMAL"); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").getOrdinalPosition()) + .isEqualTo(1); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getPropertyByName("contractDuration")).isNotNull(); + assertThat(contractEmployeeVertexType.getPropertyByName("contractDuration").getName()) + .isEqualTo("contractDuration"); + assertThat(contractEmployeeVertexType.getPropertyByName("contractDuration").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeVertexType.getPropertyByName("contractDuration").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + contractEmployeeVertexType.getPropertyByName("contractDuration").isFromPrimaryKey()) + .isFalse(); + + assertThat(countryVertexType.getProperties().size()).isEqualTo(3); + + assertThat(countryVertexType.getPropertyByName("id")).isNotNull(); + assertThat(countryVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(countryVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(countryVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(countryVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(countryVertexType.getPropertyByName("name")).isNotNull(); + assertThat(countryVertexType.getPropertyByName("name").getName()).isEqualTo("name"); + assertThat(countryVertexType.getPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(countryVertexType.getPropertyByName("name").getOrdinalPosition()).isEqualTo(2); + assertThat(countryVertexType.getPropertyByName("name").isFromPrimaryKey()).isFalse(); + + assertThat(countryVertexType.getPropertyByName("continent")).isNotNull(); + assertThat(countryVertexType.getPropertyByName("continent").getName()).isEqualTo("continent"); + assertThat(countryVertexType.getPropertyByName("continent").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(countryVertexType.getPropertyByName("continent").getOrdinalPosition()) + .isEqualTo(3); + assertThat(countryVertexType.getPropertyByName("continent").isFromPrimaryKey()).isFalse(); + + assertThat(managerVertexType.getProperties().size()).isEqualTo(2); + + assertThat(managerVertexType.getPropertyByName("id")).isNotNull(); + assertThat(managerVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(managerVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(managerVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(managerVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(managerVertexType.getPropertyByName("name")).isNotNull(); + assertThat(managerVertexType.getPropertyByName("name").getName()).isEqualTo("name"); + assertThat(managerVertexType.getPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(managerVertexType.getPropertyByName("name").getOrdinalPosition()).isEqualTo(2); + assertThat(managerVertexType.getPropertyByName("name").isFromPrimaryKey()).isFalse(); + + assertThat(projectManagerVertexType.getProperties().size()).isEqualTo(1); + + assertThat(projectManagerVertexType.getPropertyByName("project")).isNotNull(); + assertThat(projectManagerVertexType.getPropertyByName("project").getName()) + .isEqualTo("project"); + assertThat(projectManagerVertexType.getPropertyByName("project").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(projectManagerVertexType.getPropertyByName("project").getOrdinalPosition()) + .isEqualTo(1); + assertThat(projectManagerVertexType.getPropertyByName("project").isFromPrimaryKey()) + .isFalse(); + + // inherited properties check + assertThat(employeeVertexType.getInheritedProperties().size()).isEqualTo(0); + + assertThat(regularEmployeeVertexType.getInheritedProperties().size()).isEqualTo(4); + + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id")).isNotNull(); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").getName()) + .isEqualTo("id"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()) + .isEqualTo(1); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()) + .isFalse(); + + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name")).isNotNull(); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").getName()) + .isEqualTo("name"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()) + .isEqualTo(2); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()) + .isFalse(); + + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("residence")).isNotNull(); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("residence").getName()) + .isEqualTo("residence"); + assertThat( + regularEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + regularEmployeeVertexType + .getInheritedPropertyByName("residence") + .getOrdinalPosition()) + .isEqualTo(3); + assertThat( + regularEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()) + .isFalse(); + + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("manager")).isNotNull(); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("manager").getName()) + .isEqualTo("manager"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("manager").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + regularEmployeeVertexType.getInheritedPropertyByName("manager").getOrdinalPosition()) + .isEqualTo(4); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("manager").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getInheritedProperties().size()).isEqualTo(4); + + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id")).isNotNull(); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").getName()) + .isEqualTo("id"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()) + .isEqualTo(1); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name")).isNotNull(); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").getName()) + .isEqualTo("name"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()) + .isEqualTo(2); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("residence")).isNotNull(); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("residence").getName()) + .isEqualTo("residence"); + assertThat( + contractEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeVertexType + .getInheritedPropertyByName("residence") + .getOrdinalPosition()) + .isEqualTo(3); + assertThat( + contractEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("manager")).isNotNull(); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("manager").getName()) + .isEqualTo("manager"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("manager").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeVertexType.getInheritedPropertyByName("manager").getOrdinalPosition()) + .isEqualTo(4); + assertThat( + contractEmployeeVertexType.getInheritedPropertyByName("manager").isFromPrimaryKey()) + .isFalse(); + + assertThat(projectManagerVertexType.getInheritedProperties().size()).isEqualTo(2); + + assertThat(projectManagerVertexType.getInheritedPropertyByName("id")).isNotNull(); + assertThat(projectManagerVertexType.getInheritedPropertyByName("id").getName()) + .isEqualTo("id"); + assertThat(projectManagerVertexType.getInheritedPropertyByName("id").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(projectManagerVertexType.getInheritedPropertyByName("id").getOrdinalPosition()) + .isEqualTo(1); + assertThat(projectManagerVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()) + .isFalse(); + + assertThat(projectManagerVertexType.getInheritedPropertyByName("name")).isNotNull(); + assertThat(projectManagerVertexType.getInheritedPropertyByName("name").getName()) + .isEqualTo("name"); + assertThat(projectManagerVertexType.getInheritedPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(projectManagerVertexType.getInheritedPropertyByName("name").getOrdinalPosition()) + .isEqualTo(2); + assertThat(projectManagerVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()) + .isFalse(); + + assertThat(countryVertexType.getInheritedProperties().size()).isEqualTo(0); + assertThat(managerVertexType.getInheritedProperties().size()).isEqualTo(0); + + // edges check + + assertThat(mapper.getRelationship2edgeType().size()).isEqualTo(1); + + assertThat(mapper.getGraphModel().getEdgesType().size()).isEqualTo(1); + assertThat(mapper.getGraphModel().getEdgesType().get(0).getName()).isEqualTo("HasManager"); + + assertThat(employeeVertexType.getOutEdgesType().size()).isEqualTo(1); + assertThat(employeeVertexType.getOutEdgesType().get(0).getName()).isEqualTo("HasManager"); + + assertThat(regularEmployeeVertexType.getOutEdgesType().size()).isEqualTo(1); + assertThat(regularEmployeeVertexType.getOutEdgesType().get(0).getName()) + .isEqualTo("HasManager"); + + assertThat(contractEmployeeVertexType.getOutEdgesType().size()).isEqualTo(1); + assertThat(contractEmployeeVertexType.getOutEdgesType().get(0).getName()) + .isEqualTo("HasManager"); + + /* + * Rules check + */ + + // Classes Mapping + + assertThat(mapper.getVertexType2EVClassMappers().size()).isEqualTo(6); + assertThat(mapper.getEntity2EVClassMappers().size()).isEqualTo(6); + + assertThat(mapper.getEVClassMappersByVertex(employeeVertexType).size()).isEqualTo(1); + EVClassMapper employeeClassMapper = + mapper.getEVClassMappersByVertex(employeeVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(employeeEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(employeeEntity).get(0)) + .isEqualTo(employeeClassMapper); + assertThat(employeeEntity).isEqualTo(employeeClassMapper.getEntity()); + assertThat(employeeVertexType).isEqualTo(employeeClassMapper.getVertexType()); + + assertThat(employeeClassMapper.getAttribute2property().size()).isEqualTo(4); + assertThat(employeeClassMapper.getProperty2attribute().size()).isEqualTo(4); + assertThat(employeeClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(employeeClassMapper.getAttribute2property().get("NAME")).isEqualTo("name"); + assertThat(employeeClassMapper.getAttribute2property().get("RESIDENCE")) + .isEqualTo("residence"); + assertThat(employeeClassMapper.getAttribute2property().get("MANAGER")).isEqualTo("manager"); + assertThat(employeeClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(employeeClassMapper.getProperty2attribute().get("name")).isEqualTo("NAME"); + assertThat(employeeClassMapper.getProperty2attribute().get("residence")) + .isEqualTo("RESIDENCE"); + assertThat(employeeClassMapper.getProperty2attribute().get("manager")).isEqualTo("MANAGER"); + + assertThat(mapper.getEVClassMappersByVertex(regularEmployeeVertexType).size()).isEqualTo(1); + EVClassMapper regularEmployeeClassMapper = + mapper.getEVClassMappersByVertex(regularEmployeeVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(regularEmployeeEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(regularEmployeeEntity).get(0)) + .isEqualTo(regularEmployeeClassMapper); + assertThat(regularEmployeeEntity).isEqualTo(regularEmployeeClassMapper.getEntity()); + assertThat(regularEmployeeVertexType).isEqualTo(regularEmployeeClassMapper.getVertexType()); + + assertThat(regularEmployeeClassMapper.getAttribute2property().size()).isEqualTo(2); + assertThat(regularEmployeeClassMapper.getProperty2attribute().size()).isEqualTo(2); + assertThat(regularEmployeeClassMapper.getAttribute2property().get("SALARY")) + .isEqualTo("salary"); + assertThat(regularEmployeeClassMapper.getAttribute2property().get("BONUS")) + .isEqualTo("bonus"); + assertThat(regularEmployeeClassMapper.getProperty2attribute().get("salary")) + .isEqualTo("SALARY"); + assertThat(regularEmployeeClassMapper.getProperty2attribute().get("bonus")) + .isEqualTo("BONUS"); + + assertThat(mapper.getEVClassMappersByVertex(contractEmployeeVertexType).size()).isEqualTo(1); + EVClassMapper contractEmployeeClassMapper = + mapper.getEVClassMappersByVertex(contractEmployeeVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(contractEmployeeEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(contractEmployeeEntity).get(0)) + .isEqualTo(contractEmployeeClassMapper); + assertThat(contractEmployeeEntity).isEqualTo(contractEmployeeClassMapper.getEntity()); + assertThat(contractEmployeeVertexType).isEqualTo(contractEmployeeClassMapper.getVertexType()); + + assertThat(contractEmployeeClassMapper.getAttribute2property().size()).isEqualTo(2); + assertThat(contractEmployeeClassMapper.getProperty2attribute().size()).isEqualTo(2); + assertThat(contractEmployeeClassMapper.getAttribute2property().get("PAY_PER_HOUR")) + .isEqualTo("payPerHour"); + assertThat(contractEmployeeClassMapper.getAttribute2property().get("CONTRACT_DURATION")) + .isEqualTo("contractDuration"); + assertThat(contractEmployeeClassMapper.getProperty2attribute().get("payPerHour")) + .isEqualTo("PAY_PER_HOUR"); + assertThat(contractEmployeeClassMapper.getProperty2attribute().get("contractDuration")) + .isEqualTo("CONTRACT_DURATION"); + + assertThat(mapper.getEVClassMappersByVertex(countryVertexType).size()).isEqualTo(1); + EVClassMapper countryClassMapper = mapper.getEVClassMappersByVertex(countryVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(countryEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(countryEntity).get(0)) + .isEqualTo(countryClassMapper); + assertThat(countryEntity).isEqualTo(countryClassMapper.getEntity()); + assertThat(countryVertexType).isEqualTo(countryClassMapper.getVertexType()); + + assertThat(countryClassMapper.getAttribute2property().size()).isEqualTo(3); + assertThat(countryClassMapper.getProperty2attribute().size()).isEqualTo(3); + assertThat(countryClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(countryClassMapper.getAttribute2property().get("NAME")).isEqualTo("name"); + assertThat(countryClassMapper.getAttribute2property().get("CONTINENT")) + .isEqualTo("continent"); + assertThat(countryClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(countryClassMapper.getProperty2attribute().get("name")).isEqualTo("NAME"); + assertThat(countryClassMapper.getProperty2attribute().get("continent")) + .isEqualTo("CONTINENT"); + + assertThat(mapper.getEVClassMappersByVertex(managerVertexType).size()).isEqualTo(1); + EVClassMapper managerClassMapper = mapper.getEVClassMappersByVertex(managerVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(managerEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(managerEntity).get(0)) + .isEqualTo(managerClassMapper); + assertThat(managerEntity).isEqualTo(managerClassMapper.getEntity()); + assertThat(managerVertexType).isEqualTo(managerClassMapper.getVertexType()); + + assertThat(managerClassMapper.getAttribute2property().size()).isEqualTo(2); + assertThat(managerClassMapper.getProperty2attribute().size()).isEqualTo(2); + assertThat(managerClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(managerClassMapper.getAttribute2property().get("NAME")).isEqualTo("name"); + assertThat(managerClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(managerClassMapper.getProperty2attribute().get("name")).isEqualTo("NAME"); + + assertThat(mapper.getEVClassMappersByVertex(projectManagerVertexType).size()).isEqualTo(1); + EVClassMapper projectManagerClassMapper = + mapper.getEVClassMappersByVertex(projectManagerVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(projectManagerEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(projectManagerEntity).get(0)) + .isEqualTo(projectManagerClassMapper); + assertThat(projectManagerEntity).isEqualTo(projectManagerClassMapper.getEntity()); + assertThat(projectManagerVertexType).isEqualTo(projectManagerClassMapper.getVertexType()); + + assertThat(projectManagerClassMapper.getAttribute2property().size()).isEqualTo(1); + assertThat(projectManagerClassMapper.getProperty2attribute().size()).isEqualTo(1); + assertThat(projectManagerClassMapper.getAttribute2property().get("PROJECT")) + .isEqualTo("project"); + assertThat(projectManagerClassMapper.getProperty2attribute().get("project")) + .isEqualTo("PROJECT"); + + // Relationships-Edges Mapping + + Iterator itRelationships = + employeeEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship hasManagerRelationship = itRelationships.next(); + assertThat(itRelationships.hasNext()).isFalse(); + + EdgeType hasManagerEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasManager"); + + assertThat(mapper.getRelationship2edgeType().size()).isEqualTo(1); + assertThat(mapper.getRelationship2edgeType().get(hasManagerRelationship)) + .isEqualTo(hasManagerEdgeType); + + assertThat(mapper.getEdgeType2relationships().size()).isEqualTo(1); + assertThat(mapper.getEdgeType2relationships().get(hasManagerEdgeType).size()).isEqualTo(1); + assertThat( + mapper + .getEdgeType2relationships() + .get(hasManagerEdgeType) + .contains(hasManagerRelationship)) + .isTrue(); + + // JoinVertexes-AggregatorEdges Mapping + + assertThat(mapper.getJoinVertex2aggregatorEdges().size()).isEqualTo(0); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } finally { + try { + // Dropping Source DB Schema and OrientGraph + String dbDropping = "drop schema public cascade"; + st.execute(dbDropping); + connection.close(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } } - - @Test - /* - * Filtering out a table through include-tables (with Table per Concrete Type inheritance). - */public void filterOutThroughIncludeWithTablePerConcreteTypeInheritance() { - Connection connection = null; - Statement st = null; - - try { - Class.forName(this.driver); - connection = DriverManager.getConnection(this.jurl, this.username, this.password); - - String countryTableBuilding = "create memory table COUNTRY(ID varchar(256) not null, NAME varchar(256), CONTINENT varchar(256), primary key (ID))"; - st = connection.createStatement(); - st.execute(countryTableBuilding); - - String residenceTableBuilding = - "create memory table RESIDENCE(ID varchar(256) not null, CITY varchar(256), COUNTRY varchar(256), primary key (ID))"; - st = connection.createStatement(); - st.execute(residenceTableBuilding); - - String managerTableBuilding = "create memory table MANAGER(ID varchar(256) not null, NAME varchar(256), primary key (ID))"; - st.execute(managerTableBuilding); - - String projectManagerTableBuilding = - "create memory table PROJECT_MANAGER(ID varchar(256) not null, NAME varchar(256), PROJECT varchar(256), primary key (ID))"; - st.execute(projectManagerTableBuilding); - - String employeeTableBuilding = - "create memory table EMPLOYEE (ID varchar(256) not null," + - " NAME varchar(256), RESIDENCE varchar(256), MANAGER varchar(256), primary key (ID), " + - "foreign key (RESIDENCE) references RESIDENCE(ID), foreign key (MANAGER) references MANAGER(ID))"; - st.execute(employeeTableBuilding); - - String regularEmployeeTableBuilding = - "create memory table REGULAR_EMPLOYEE (ID varchar(256) not null, " + - "NAME varchar(256), RESIDENCE varchar(256), MANAGER varchar(256)," + - "SALARY decimal(10,2), BONUS decimal(10,0), primary key (ID))"; - st.execute(regularEmployeeTableBuilding); - - String contractEmployeeTableBuilding = - "create memory table CONTRACT_EMPLOYEE (ID varchar(256) not null, " + - "NAME varchar(256), RESIDENCE varchar(256), MANAGER varchar(256)," + - "PAY_PER_HOUR decimal(10,2), CONTRACT_DURATION varchar(256), primary key (ID))"; - st.execute(contractEmployeeTableBuilding); - - // Records Inserting - - String countryFilling = "insert into COUNTRY (ID,NAME,CONTINENT) values (" + "('C001','Italy','Europe'))"; - st.execute(countryFilling); - - String residenceFilling = "insert into RESIDENCE (ID,CITY,COUNTRY) values (" + "('R001','Rome','C001')," + "('R002','Milan','C001'))"; - st.execute(residenceFilling); - - String managerFilling = "insert into MANAGER (ID,NAME) values (" + "('M001','Bill Right'))"; - st.execute(managerFilling); - - String projectManagerFilling = "insert into PROJECT_MANAGER (ID,NAME,PROJECT) values (" + "('M001','Bill Right','New World'))"; - st.execute(projectManagerFilling); - - String employeeFilling = - "insert into EMPLOYEE (ID,NAME,RESIDENCE,MANAGER) values (" + - "('E001','John Black','R001',null)," + - "('E002','Andrew Brown','R001','M001')," + - "('E003','Jack Johnson','R002',null))"; - st.execute(employeeFilling); - - String regularEmployeeFilling = - "insert into REGULAR_EMPLOYEE (ID,NAME,RESIDENCE,MANAGER,SALARY,BONUS) values (" + "('E002','Andrew Brown','R001','M001','1000.00','10'))"; - st.execute(regularEmployeeFilling); - - String contractEmployeeFilling = - "insert into CONTRACT_EMPLOYEE (ID,NAME,RESIDENCE,MANAGER,PAY_PER_HOUR,CONTRACT_DURATION) values (" + - "('E003','Jack Johnson','R002',null,'50.00','6'))"; - st.execute(contractEmployeeFilling); - - List includedTables = new ArrayList(); - includedTables.add("COUNTRY"); - includedTables.add("MANAGER"); - includedTables.add("PROJECT_MANAGER"); - includedTables.add("EMPLOYEE"); - includedTables.add("REGULAR_EMPLOYEE"); - includedTables.add("CONTRACT_EMPLOYEE"); - - this.mapper = - new Hibernate2GraphMapper( - dataSource, - FilterTableMappingTest.XML_TABLE_PER_CONCRETE_CLASS, - includedTables, - null, - dbQueryEngine, - dataTypeHandler, - executionStrategy, - nameResolver, - statistics - ); - mapper.buildSourceDatabaseSchema(); - mapper.buildGraphModel(new JavaConventionNameResolver()); - - /* - * Testing context information - */ - - assertEquals(6, statistics.totalNumberOfEntities); - assertEquals(6, statistics.builtEntities); - assertEquals(1, statistics.totalNumberOfRelationships); - assertEquals(1, statistics.builtRelationships); - - assertEquals(6, statistics.totalNumberOfModelVertices); - assertEquals(6, statistics.builtModelVertexTypes); - assertEquals(1, statistics.totalNumberOfModelEdges); - assertEquals(1, statistics.builtModelEdgeTypes); - - /* - * Testing built source db schema - */ - - Entity employeeEntity = mapper.getDataBaseSchema().getEntityByName("EMPLOYEE"); - Entity regularEmployeeEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("REGULAR_EMPLOYEE"); - Entity contractEmployeeEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("CONTRACT_EMPLOYEE"); - Entity countryEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("COUNTRY"); - Entity managerEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("MANAGER"); - Entity projectManagerEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("PROJECT_MANAGER"); - Entity residenceEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("RESIDENCE"); - - // entities check - assertEquals(6, mapper.getDataBaseSchema().getEntities().size()); - assertEquals(1, mapper.getDataBaseSchema().getCanonicalRelationships().size()); - assertNotNull(employeeEntity); - assertNotNull(regularEmployeeEntity); - assertNotNull(contractEmployeeEntity); - assertNotNull(countryEntity); - assertNotNull(managerEntity); - assertNull(residenceEntity); - - // attributes check - assertEquals(4, employeeEntity.getAttributes().size()); - - assertNotNull(employeeEntity.getAttributeByName("ID")); - assertEquals("ID", employeeEntity.getAttributeByName("ID").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("ID").getDataType()); - assertEquals(1, employeeEntity.getAttributeByName("ID").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(employeeEntity.getAttributeByName("NAME")); - assertEquals("NAME", employeeEntity.getAttributeByName("NAME").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("NAME").getDataType()); - assertEquals(2, employeeEntity.getAttributeByName("NAME").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(employeeEntity.getAttributeByName("RESIDENCE")); - assertEquals("RESIDENCE", employeeEntity.getAttributeByName("RESIDENCE").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("RESIDENCE").getDataType()); - assertEquals(3, employeeEntity.getAttributeByName("RESIDENCE").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("RESIDENCE").getBelongingEntity().getName()); - - assertNotNull(employeeEntity.getAttributeByName("MANAGER")); - assertEquals("MANAGER", employeeEntity.getAttributeByName("MANAGER").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("MANAGER").getDataType()); - assertEquals(4, employeeEntity.getAttributeByName("MANAGER").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("MANAGER").getBelongingEntity().getName()); - - assertEquals(2, regularEmployeeEntity.getAttributes().size()); - - assertNotNull(regularEmployeeEntity.getAttributeByName("SALARY")); - assertEquals("SALARY", regularEmployeeEntity.getAttributeByName("SALARY").getName()); - assertEquals("DECIMAL", regularEmployeeEntity.getAttributeByName("SALARY").getDataType()); - assertEquals(1, regularEmployeeEntity.getAttributeByName("SALARY").getOrdinalPosition()); - assertEquals("REGULAR_EMPLOYEE", regularEmployeeEntity.getAttributeByName("SALARY").getBelongingEntity().getName()); - - assertNotNull(regularEmployeeEntity.getAttributeByName("BONUS")); - assertEquals("BONUS", regularEmployeeEntity.getAttributeByName("BONUS").getName()); - assertEquals("DECIMAL", regularEmployeeEntity.getAttributeByName("BONUS").getDataType()); - assertEquals(2, regularEmployeeEntity.getAttributeByName("BONUS").getOrdinalPosition()); - assertEquals("REGULAR_EMPLOYEE", regularEmployeeEntity.getAttributeByName("BONUS").getBelongingEntity().getName()); - - assertEquals(2, contractEmployeeEntity.getAttributes().size()); - - assertNotNull(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR")); - assertEquals("PAY_PER_HOUR", contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getName()); - assertEquals("DECIMAL", contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getDataType()); - assertEquals(1, contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getOrdinalPosition()); - assertEquals("CONTRACT_EMPLOYEE", contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getBelongingEntity().getName()); - - assertNotNull(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION")); - assertEquals("CONTRACT_DURATION", contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getDataType()); - assertEquals(2, contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getOrdinalPosition()); - assertEquals("CONTRACT_EMPLOYEE", contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getBelongingEntity().getName()); - - assertEquals(3, countryEntity.getAttributes().size()); - - assertNotNull(countryEntity.getAttributeByName("ID")); - assertEquals("ID", countryEntity.getAttributeByName("ID").getName()); - assertEquals("VARCHAR", countryEntity.getAttributeByName("ID").getDataType()); - assertEquals(1, countryEntity.getAttributeByName("ID").getOrdinalPosition()); - assertEquals("COUNTRY", countryEntity.getAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(countryEntity.getAttributeByName("NAME")); - assertEquals("NAME", countryEntity.getAttributeByName("NAME").getName()); - assertEquals("VARCHAR", countryEntity.getAttributeByName("NAME").getDataType()); - assertEquals(2, countryEntity.getAttributeByName("NAME").getOrdinalPosition()); - assertEquals("COUNTRY", countryEntity.getAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(countryEntity.getAttributeByName("CONTINENT")); - assertEquals("CONTINENT", countryEntity.getAttributeByName("CONTINENT").getName()); - assertEquals("VARCHAR", countryEntity.getAttributeByName("CONTINENT").getDataType()); - assertEquals(3, countryEntity.getAttributeByName("CONTINENT").getOrdinalPosition()); - assertEquals("COUNTRY", countryEntity.getAttributeByName("CONTINENT").getBelongingEntity().getName()); - - assertEquals(2, managerEntity.getAttributes().size()); - - assertNotNull(managerEntity.getAttributeByName("ID")); - assertEquals("ID", managerEntity.getAttributeByName("ID").getName()); - assertEquals("VARCHAR", managerEntity.getAttributeByName("ID").getDataType()); - assertEquals(1, managerEntity.getAttributeByName("ID").getOrdinalPosition()); - assertEquals("MANAGER", managerEntity.getAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(managerEntity.getAttributeByName("NAME")); - assertEquals("NAME", managerEntity.getAttributeByName("NAME").getName()); - assertEquals("VARCHAR", managerEntity.getAttributeByName("NAME").getDataType()); - assertEquals(2, managerEntity.getAttributeByName("NAME").getOrdinalPosition()); - assertEquals("MANAGER", managerEntity.getAttributeByName("NAME").getBelongingEntity().getName()); - - assertEquals(1, projectManagerEntity.getAttributes().size()); - - assertNotNull(projectManagerEntity.getAttributeByName("PROJECT")); - assertEquals("PROJECT", projectManagerEntity.getAttributeByName("PROJECT").getName()); - assertEquals("VARCHAR", projectManagerEntity.getAttributeByName("PROJECT").getDataType()); - assertEquals(1, projectManagerEntity.getAttributeByName("PROJECT").getOrdinalPosition()); - assertEquals("PROJECT_MANAGER", projectManagerEntity.getAttributeByName("PROJECT").getBelongingEntity().getName()); - - // inherited attributes check - assertEquals(0, employeeEntity.getInheritedAttributes().size()); - - assertEquals(4, regularEmployeeEntity.getInheritedAttributes().size()); - - assertNotNull(regularEmployeeEntity.getInheritedAttributeByName("ID")); - assertEquals("ID", regularEmployeeEntity.getInheritedAttributeByName("ID").getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getInheritedAttributeByName("ID").getDataType()); - assertEquals(1, regularEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()); - assertEquals("EMPLOYEE", regularEmployeeEntity.getInheritedAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(regularEmployeeEntity.getInheritedAttributeByName("NAME")); - assertEquals("NAME", regularEmployeeEntity.getInheritedAttributeByName("NAME").getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()); - assertEquals(2, regularEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()); - assertEquals("EMPLOYEE", regularEmployeeEntity.getInheritedAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE")); - assertEquals("RESIDENCE", regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()); - assertEquals(3, regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()); - assertEquals("EMPLOYEE", regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getBelongingEntity().getName()); - - assertNotNull(regularEmployeeEntity.getInheritedAttributeByName("MANAGER")); - assertEquals("MANAGER", regularEmployeeEntity.getInheritedAttributeByName("MANAGER").getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getInheritedAttributeByName("MANAGER").getDataType()); - assertEquals(4, regularEmployeeEntity.getInheritedAttributeByName("MANAGER").getOrdinalPosition()); - assertEquals("EMPLOYEE", regularEmployeeEntity.getInheritedAttributeByName("MANAGER").getBelongingEntity().getName()); - - assertEquals(4, contractEmployeeEntity.getInheritedAttributes().size()); - - assertNotNull(contractEmployeeEntity.getInheritedAttributeByName("ID")); - assertEquals("ID", contractEmployeeEntity.getInheritedAttributeByName("ID").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getInheritedAttributeByName("ID").getDataType()); - assertEquals(1, contractEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()); - assertEquals("EMPLOYEE", contractEmployeeEntity.getInheritedAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(contractEmployeeEntity.getInheritedAttributeByName("NAME")); - assertEquals("NAME", contractEmployeeEntity.getInheritedAttributeByName("NAME").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()); - assertEquals(2, contractEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()); - assertEquals("EMPLOYEE", contractEmployeeEntity.getInheritedAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE")); - assertEquals("RESIDENCE", contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()); - assertEquals(3, contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()); - assertEquals("EMPLOYEE", contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getBelongingEntity().getName()); - - assertNotNull(contractEmployeeEntity.getInheritedAttributeByName("MANAGER")); - assertEquals("MANAGER", contractEmployeeEntity.getInheritedAttributeByName("MANAGER").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getInheritedAttributeByName("MANAGER").getDataType()); - assertEquals(4, contractEmployeeEntity.getInheritedAttributeByName("MANAGER").getOrdinalPosition()); - assertEquals("EMPLOYEE", contractEmployeeEntity.getInheritedAttributeByName("MANAGER").getBelongingEntity().getName()); - - assertEquals(2, projectManagerEntity.getInheritedAttributes().size()); - - assertNotNull(projectManagerEntity.getInheritedAttributeByName("ID")); - assertEquals("ID", projectManagerEntity.getInheritedAttributeByName("ID").getName()); - assertEquals("VARCHAR", projectManagerEntity.getInheritedAttributeByName("ID").getDataType()); - assertEquals(1, projectManagerEntity.getInheritedAttributeByName("ID").getOrdinalPosition()); - assertEquals("MANAGER", projectManagerEntity.getInheritedAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(projectManagerEntity.getInheritedAttributeByName("NAME")); - assertEquals("NAME", projectManagerEntity.getInheritedAttributeByName("NAME").getName()); - assertEquals("VARCHAR", projectManagerEntity.getInheritedAttributeByName("NAME").getDataType()); - assertEquals(2, projectManagerEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()); - assertEquals("MANAGER", projectManagerEntity.getInheritedAttributeByName("NAME").getBelongingEntity().getName()); - - assertEquals(0, countryEntity.getInheritedAttributes().size()); - assertEquals(0, managerEntity.getInheritedAttributes().size()); - - // primary key check - assertEquals(1, regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()); - assertEquals("ID", regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()); - assertEquals("REGULAR_EMPLOYEE", regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getBelongingEntity().getName()); - - assertEquals(1, contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()); - assertEquals("ID", contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()); - assertEquals("CONTRACT_EMPLOYEE", contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getBelongingEntity().getName()); - - assertEquals(1, projectManagerEntity.getPrimaryKey().getInvolvedAttributes().size()); - assertEquals("ID", projectManagerEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()); - assertEquals("VARCHAR", projectManagerEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()); - assertEquals("PROJECT_MANAGER", projectManagerEntity.getPrimaryKey().getInvolvedAttributes().get(0).getBelongingEntity().getName()); - - // relationship, primary and foreign key check - assertEquals(0, regularEmployeeEntity.getOutCanonicalRelationships().size()); - assertEquals(0, contractEmployeeEntity.getOutCanonicalRelationships().size()); - assertEquals(1, employeeEntity.getOutCanonicalRelationships().size()); - assertEquals(0, projectManagerEntity.getOutCanonicalRelationships().size()); - assertEquals(0, managerEntity.getOutCanonicalRelationships().size()); - assertEquals(0, countryEntity.getOutCanonicalRelationships().size()); - assertEquals(0, regularEmployeeEntity.getInCanonicalRelationships().size()); - assertEquals(0, contractEmployeeEntity.getInCanonicalRelationships().size()); - assertEquals(0, employeeEntity.getInCanonicalRelationships().size()); - assertEquals(0, projectManagerEntity.getInCanonicalRelationships().size()); - assertEquals(1, managerEntity.getInCanonicalRelationships().size()); - assertEquals(0, countryEntity.getInCanonicalRelationships().size()); - - assertEquals(0, regularEmployeeEntity.getForeignKeys().size()); - assertEquals(0, contractEmployeeEntity.getForeignKeys().size()); - assertEquals(1, employeeEntity.getForeignKeys().size()); - assertEquals(0, projectManagerEntity.getForeignKeys().size()); - assertEquals(0, managerEntity.getForeignKeys().size()); - assertEquals(0, countryEntity.getForeignKeys().size()); - - Iterator itEmp = employeeEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship currentEmpRel = itEmp.next(); - assertEquals("MANAGER", currentEmpRel.getParentEntity().getName()); - assertEquals("EMPLOYEE", currentEmpRel.getForeignEntity().getName()); - assertEquals(managerEntity.getPrimaryKey(), currentEmpRel.getPrimaryKey()); - assertEquals(employeeEntity.getForeignKeys().get(0), currentEmpRel.getForeignKey()); - assertFalse(itEmp.hasNext()); - - Iterator itManager = managerEntity.getInCanonicalRelationships().iterator(); - CanonicalRelationship currentManRel = itManager.next(); - assertEquals(currentEmpRel, currentManRel); - - // inherited relationships check - assertEquals(1, regularEmployeeEntity.getInheritedOutCanonicalRelationships().size()); - assertEquals(1, contractEmployeeEntity.getInheritedOutCanonicalRelationships().size()); - assertEquals(0, employeeEntity.getInheritedOutCanonicalRelationships().size()); - - Iterator itRegEmp = regularEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); - Iterator itContEmp = contractEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); - CanonicalRelationship currentRegEmpRel = itRegEmp.next(); - CanonicalRelationship currentContEmpRel = itContEmp.next(); - assertEquals("MANAGER", currentRegEmpRel.getParentEntity().getName()); - assertEquals("EMPLOYEE", currentRegEmpRel.getForeignEntity().getName()); - assertEquals("MANAGER", currentContEmpRel.getParentEntity().getName()); - assertEquals("EMPLOYEE", currentContEmpRel.getForeignEntity().getName()); - assertEquals(managerEntity.getPrimaryKey(), currentRegEmpRel.getPrimaryKey()); - assertEquals(1, currentRegEmpRel.getFromColumns().size()); - assertEquals("MANAGER", currentRegEmpRel.getFromColumns().get(0).getName()); - assertEquals(managerEntity.getPrimaryKey(), currentContEmpRel.getPrimaryKey()); - assertEquals(1, currentContEmpRel.getFromColumns().size()); - assertEquals("MANAGER", currentContEmpRel.getFromColumns().get(0).getName()); - assertFalse(itRegEmp.hasNext()); - assertFalse(itContEmp.hasNext()); - - // inheritance check - assertEquals(employeeEntity, regularEmployeeEntity.getParentEntity()); - assertEquals(employeeEntity, contractEmployeeEntity.getParentEntity()); - assertNull(employeeEntity.getParentEntity()); - - assertEquals(1, regularEmployeeEntity.getInheritanceLevel()); - assertEquals(1, contractEmployeeEntity.getInheritanceLevel()); - assertEquals(0, employeeEntity.getInheritanceLevel()); - - // Hierarchical Bag check - assertEquals(2, mapper.getDataBaseSchema().getHierarchicalBags().size()); - - HierarchicalBag hierarchicalBag1 = mapper.getDataBaseSchema().getHierarchicalBags().get(0); - HierarchicalBag hierarchicalBag2 = mapper.getDataBaseSchema().getHierarchicalBags().get(1); - assertEquals("table-per-concrete-type", hierarchicalBag1.getInheritancePattern()); - assertEquals("table-per-concrete-type", hierarchicalBag2.getInheritancePattern()); - - assertEquals(2, hierarchicalBag1.getDepth2entities().size()); - - assertEquals(1, hierarchicalBag1.getDepth2entities().get(0).size()); - Iterator it = hierarchicalBag1.getDepth2entities().get(0).iterator(); - assertEquals("EMPLOYEE", it.next().getName()); - assertTrue(!it.hasNext()); - - assertEquals(2, hierarchicalBag1.getDepth2entities().get(1).size()); - it = hierarchicalBag1.getDepth2entities().get(1).iterator(); - assertEquals("REGULAR_EMPLOYEE", it.next().getName()); - assertEquals("CONTRACT_EMPLOYEE", it.next().getName()); - assertTrue(!it.hasNext()); - - assertEquals(hierarchicalBag1, employeeEntity.getHierarchicalBag()); - assertEquals(hierarchicalBag1, regularEmployeeEntity.getHierarchicalBag()); - assertEquals(hierarchicalBag1, contractEmployeeEntity.getHierarchicalBag()); - - assertNull(hierarchicalBag1.getDiscriminatorColumn()); - - assertEquals(2, hierarchicalBag2.getDepth2entities().size()); - - assertEquals(1, hierarchicalBag2.getDepth2entities().get(0).size()); - it = hierarchicalBag2.getDepth2entities().get(0).iterator(); - assertEquals("MANAGER", it.next().getName()); - assertTrue(!it.hasNext()); - - assertEquals(1, hierarchicalBag2.getDepth2entities().get(1).size()); - it = hierarchicalBag2.getDepth2entities().get(1).iterator(); - assertEquals("PROJECT_MANAGER", it.next().getName()); - assertTrue(!it.hasNext()); - - assertEquals(hierarchicalBag2, managerEntity.getHierarchicalBag()); - assertEquals(hierarchicalBag2, projectManagerEntity.getHierarchicalBag()); - - assertNull(hierarchicalBag2.getDiscriminatorColumn()); - - /* - * Testing built graph model - */ - - VertexType employeeVertexType = mapper.getGraphModel().getVertexTypeByName("Employee"); - VertexType regularEmployeeVertexType = mapper.getGraphModel().getVertexTypeByName("RegularEmployee"); - VertexType contractEmployeeVertexType = mapper.getGraphModel().getVertexTypeByName("ContractEmployee"); - VertexType countryVertexType = mapper.getGraphModel().getVertexTypeByName("Country"); - VertexType managerVertexType = mapper.getGraphModel().getVertexTypeByName("Manager"); - VertexType projectManagerVertexType = mapper.getGraphModel().getVertexTypeByName("ProjectManager"); - VertexType residenceVertexType = mapper.getGraphModel().getVertexTypeByName("Residence"); - - // vertices check - assertEquals(6, mapper.getGraphModel().getVerticesType().size()); - assertNotNull(employeeVertexType); - assertNotNull(regularEmployeeVertexType); - assertNotNull(contractEmployeeVertexType); - assertNotNull(countryVertexType); - assertNotNull(managerVertexType); - assertNotNull(projectManagerVertexType); - assertNull(residenceVertexType); - - // properties check - assertEquals(4, employeeVertexType.getProperties().size()); - - assertNotNull(employeeVertexType.getPropertyByName("id")); - assertEquals("id", employeeVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, employeeVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, employeeVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(employeeVertexType.getPropertyByName("name")); - assertEquals("name", employeeVertexType.getPropertyByName("name").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("name").getOriginalType()); - assertEquals(2, employeeVertexType.getPropertyByName("name").getOrdinalPosition()); - assertEquals(false, employeeVertexType.getPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(employeeVertexType.getPropertyByName("residence")); - assertEquals("residence", employeeVertexType.getPropertyByName("residence").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("residence").getOriginalType()); - assertEquals(3, employeeVertexType.getPropertyByName("residence").getOrdinalPosition()); - assertEquals(false, employeeVertexType.getPropertyByName("residence").isFromPrimaryKey()); - - assertNotNull(employeeVertexType.getPropertyByName("manager")); - assertEquals("manager", employeeVertexType.getPropertyByName("manager").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("manager").getOriginalType()); - assertEquals(4, employeeVertexType.getPropertyByName("manager").getOrdinalPosition()); - assertEquals(false, employeeVertexType.getPropertyByName("manager").isFromPrimaryKey()); - - assertEquals(2, regularEmployeeVertexType.getProperties().size()); - - assertNotNull(regularEmployeeVertexType.getPropertyByName("salary")); - assertEquals("salary", regularEmployeeVertexType.getPropertyByName("salary").getName()); - assertEquals("DECIMAL", regularEmployeeVertexType.getPropertyByName("salary").getOriginalType()); - assertEquals(1, regularEmployeeVertexType.getPropertyByName("salary").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getPropertyByName("salary").isFromPrimaryKey()); - - assertNotNull(regularEmployeeVertexType.getPropertyByName("bonus")); - assertEquals("bonus", regularEmployeeVertexType.getPropertyByName("bonus").getName()); - assertEquals("DECIMAL", regularEmployeeVertexType.getPropertyByName("bonus").getOriginalType()); - assertEquals(2, regularEmployeeVertexType.getPropertyByName("bonus").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getPropertyByName("bonus").isFromPrimaryKey()); - - assertEquals(2, contractEmployeeVertexType.getProperties().size()); - - assertNotNull(contractEmployeeVertexType.getPropertyByName("payPerHour")); - assertEquals("payPerHour", contractEmployeeVertexType.getPropertyByName("payPerHour").getName()); - assertEquals("DECIMAL", contractEmployeeVertexType.getPropertyByName("payPerHour").getOriginalType()); - assertEquals(1, contractEmployeeVertexType.getPropertyByName("payPerHour").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getPropertyByName("payPerHour").isFromPrimaryKey()); - - assertNotNull(contractEmployeeVertexType.getPropertyByName("contractDuration")); - assertEquals("contractDuration", contractEmployeeVertexType.getPropertyByName("contractDuration").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getPropertyByName("contractDuration").getOriginalType()); - assertEquals(2, contractEmployeeVertexType.getPropertyByName("contractDuration").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getPropertyByName("contractDuration").isFromPrimaryKey()); - - assertEquals(3, countryVertexType.getProperties().size()); - - assertNotNull(countryVertexType.getPropertyByName("id")); - assertEquals("id", countryVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", countryVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, countryVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, countryVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(countryVertexType.getPropertyByName("name")); - assertEquals("name", countryVertexType.getPropertyByName("name").getName()); - assertEquals("VARCHAR", countryVertexType.getPropertyByName("name").getOriginalType()); - assertEquals(2, countryVertexType.getPropertyByName("name").getOrdinalPosition()); - assertEquals(false, countryVertexType.getPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(countryVertexType.getPropertyByName("continent")); - assertEquals("continent", countryVertexType.getPropertyByName("continent").getName()); - assertEquals("VARCHAR", countryVertexType.getPropertyByName("continent").getOriginalType()); - assertEquals(3, countryVertexType.getPropertyByName("continent").getOrdinalPosition()); - assertEquals(false, countryVertexType.getPropertyByName("continent").isFromPrimaryKey()); - - assertEquals(2, managerVertexType.getProperties().size()); - - assertNotNull(managerVertexType.getPropertyByName("id")); - assertEquals("id", managerVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", managerVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, managerVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, managerVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(managerVertexType.getPropertyByName("name")); - assertEquals("name", managerVertexType.getPropertyByName("name").getName()); - assertEquals("VARCHAR", managerVertexType.getPropertyByName("name").getOriginalType()); - assertEquals(2, managerVertexType.getPropertyByName("name").getOrdinalPosition()); - assertEquals(false, managerVertexType.getPropertyByName("name").isFromPrimaryKey()); - - assertEquals(1, projectManagerVertexType.getProperties().size()); - - assertNotNull(projectManagerVertexType.getPropertyByName("project")); - assertEquals("project", projectManagerVertexType.getPropertyByName("project").getName()); - assertEquals("VARCHAR", projectManagerVertexType.getPropertyByName("project").getOriginalType()); - assertEquals(1, projectManagerVertexType.getPropertyByName("project").getOrdinalPosition()); - assertEquals(false, projectManagerVertexType.getPropertyByName("project").isFromPrimaryKey()); - - // inherited properties check - assertEquals(0, employeeVertexType.getInheritedProperties().size()); - - assertEquals(4, regularEmployeeVertexType.getInheritedProperties().size()); - - assertNotNull(regularEmployeeVertexType.getInheritedPropertyByName("id")); - assertEquals("id", regularEmployeeVertexType.getInheritedPropertyByName("id").getName()); - assertEquals("VARCHAR", regularEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()); - assertEquals(1, regularEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()); - assertEquals(true, regularEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(regularEmployeeVertexType.getInheritedPropertyByName("name")); - assertEquals("name", regularEmployeeVertexType.getInheritedPropertyByName("name").getName()); - assertEquals("VARCHAR", regularEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()); - assertEquals(2, regularEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(regularEmployeeVertexType.getInheritedPropertyByName("residence")); - assertEquals("residence", regularEmployeeVertexType.getInheritedPropertyByName("residence").getName()); - assertEquals("VARCHAR", regularEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()); - assertEquals(3, regularEmployeeVertexType.getInheritedPropertyByName("residence").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()); - - assertNotNull(regularEmployeeVertexType.getInheritedPropertyByName("manager")); - assertEquals("manager", regularEmployeeVertexType.getInheritedPropertyByName("manager").getName()); - assertEquals("VARCHAR", regularEmployeeVertexType.getInheritedPropertyByName("manager").getOriginalType()); - assertEquals(4, regularEmployeeVertexType.getInheritedPropertyByName("manager").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getInheritedPropertyByName("manager").isFromPrimaryKey()); - - assertEquals(4, contractEmployeeVertexType.getInheritedProperties().size()); - - assertNotNull(contractEmployeeVertexType.getInheritedPropertyByName("id")); - assertEquals("id", contractEmployeeVertexType.getInheritedPropertyByName("id").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()); - assertEquals(1, contractEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()); - assertEquals(true, contractEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(contractEmployeeVertexType.getInheritedPropertyByName("name")); - assertEquals("name", contractEmployeeVertexType.getInheritedPropertyByName("name").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()); - assertEquals(2, contractEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(contractEmployeeVertexType.getInheritedPropertyByName("residence")); - assertEquals("residence", contractEmployeeVertexType.getInheritedPropertyByName("residence").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()); - assertEquals(3, contractEmployeeVertexType.getInheritedPropertyByName("residence").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()); - - assertNotNull(contractEmployeeVertexType.getInheritedPropertyByName("manager")); - assertEquals("manager", contractEmployeeVertexType.getInheritedPropertyByName("manager").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getInheritedPropertyByName("manager").getOriginalType()); - assertEquals(4, contractEmployeeVertexType.getInheritedPropertyByName("manager").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getInheritedPropertyByName("manager").isFromPrimaryKey()); - - assertEquals(2, projectManagerVertexType.getInheritedProperties().size()); - - assertNotNull(projectManagerVertexType.getInheritedPropertyByName("id")); - assertEquals("id", projectManagerVertexType.getInheritedPropertyByName("id").getName()); - assertEquals("VARCHAR", projectManagerVertexType.getInheritedPropertyByName("id").getOriginalType()); - assertEquals(1, projectManagerVertexType.getInheritedPropertyByName("id").getOrdinalPosition()); - assertEquals(true, projectManagerVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(projectManagerVertexType.getInheritedPropertyByName("name")); - assertEquals("name", projectManagerVertexType.getInheritedPropertyByName("name").getName()); - assertEquals("VARCHAR", projectManagerVertexType.getInheritedPropertyByName("name").getOriginalType()); - assertEquals(2, projectManagerVertexType.getInheritedPropertyByName("name").getOrdinalPosition()); - assertEquals(false, projectManagerVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()); - - assertEquals(0, countryVertexType.getInheritedProperties().size()); - assertEquals(0, managerVertexType.getInheritedProperties().size()); - - // edges check - - assertEquals(1, mapper.getRelationship2edgeType().size()); - - assertEquals(1, mapper.getGraphModel().getEdgesType().size()); - assertEquals("HasManager", mapper.getGraphModel().getEdgesType().get(0).getName()); - - assertEquals(1, employeeVertexType.getOutEdgesType().size()); - assertEquals("HasManager", employeeVertexType.getOutEdgesType().get(0).getName()); - - assertEquals(1, regularEmployeeVertexType.getOutEdgesType().size()); - assertEquals("HasManager", regularEmployeeVertexType.getOutEdgesType().get(0).getName()); - - assertEquals(1, contractEmployeeVertexType.getOutEdgesType().size()); - assertEquals("HasManager", contractEmployeeVertexType.getOutEdgesType().get(0).getName()); - - /* - * Rules check - */ - - // Classes Mapping - - assertEquals(6, mapper.getVertexType2EVClassMappers().size()); - assertEquals(6, mapper.getEntity2EVClassMappers().size()); - - assertEquals(1, mapper.getEVClassMappersByVertex(employeeVertexType).size()); - EVClassMapper employeeClassMapper = mapper.getEVClassMappersByVertex(employeeVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(employeeEntity).size()); - assertEquals(employeeClassMapper, mapper.getEVClassMappersByEntity(employeeEntity).get(0)); - assertEquals(employeeClassMapper.getEntity(), employeeEntity); - assertEquals(employeeClassMapper.getVertexType(), employeeVertexType); - - assertEquals(4, employeeClassMapper.getAttribute2property().size()); - assertEquals(4, employeeClassMapper.getProperty2attribute().size()); - assertEquals("id", employeeClassMapper.getAttribute2property().get("ID")); - assertEquals("name", employeeClassMapper.getAttribute2property().get("NAME")); - assertEquals("residence", employeeClassMapper.getAttribute2property().get("RESIDENCE")); - assertEquals("manager", employeeClassMapper.getAttribute2property().get("MANAGER")); - assertEquals("ID", employeeClassMapper.getProperty2attribute().get("id")); - assertEquals("NAME", employeeClassMapper.getProperty2attribute().get("name")); - assertEquals("RESIDENCE", employeeClassMapper.getProperty2attribute().get("residence")); - assertEquals("MANAGER", employeeClassMapper.getProperty2attribute().get("manager")); - - assertEquals(1, mapper.getEVClassMappersByVertex(regularEmployeeVertexType).size()); - EVClassMapper regularEmployeeClassMapper = mapper.getEVClassMappersByVertex(regularEmployeeVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(regularEmployeeEntity).size()); - assertEquals(regularEmployeeClassMapper, mapper.getEVClassMappersByEntity(regularEmployeeEntity).get(0)); - assertEquals(regularEmployeeClassMapper.getEntity(), regularEmployeeEntity); - assertEquals(regularEmployeeClassMapper.getVertexType(), regularEmployeeVertexType); - - assertEquals(2, regularEmployeeClassMapper.getAttribute2property().size()); - assertEquals(2, regularEmployeeClassMapper.getProperty2attribute().size()); - assertEquals("salary", regularEmployeeClassMapper.getAttribute2property().get("SALARY")); - assertEquals("bonus", regularEmployeeClassMapper.getAttribute2property().get("BONUS")); - assertEquals("SALARY", regularEmployeeClassMapper.getProperty2attribute().get("salary")); - assertEquals("BONUS", regularEmployeeClassMapper.getProperty2attribute().get("bonus")); - - assertEquals(1, mapper.getEVClassMappersByVertex(contractEmployeeVertexType).size()); - EVClassMapper contractEmployeeClassMapper = mapper.getEVClassMappersByVertex(contractEmployeeVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(contractEmployeeEntity).size()); - assertEquals(contractEmployeeClassMapper, mapper.getEVClassMappersByEntity(contractEmployeeEntity).get(0)); - assertEquals(contractEmployeeClassMapper.getEntity(), contractEmployeeEntity); - assertEquals(contractEmployeeClassMapper.getVertexType(), contractEmployeeVertexType); - - assertEquals(2, contractEmployeeClassMapper.getAttribute2property().size()); - assertEquals(2, contractEmployeeClassMapper.getProperty2attribute().size()); - assertEquals("payPerHour", contractEmployeeClassMapper.getAttribute2property().get("PAY_PER_HOUR")); - assertEquals("contractDuration", contractEmployeeClassMapper.getAttribute2property().get("CONTRACT_DURATION")); - assertEquals("PAY_PER_HOUR", contractEmployeeClassMapper.getProperty2attribute().get("payPerHour")); - assertEquals("CONTRACT_DURATION", contractEmployeeClassMapper.getProperty2attribute().get("contractDuration")); - - assertEquals(1, mapper.getEVClassMappersByVertex(countryVertexType).size()); - EVClassMapper countryClassMapper = mapper.getEVClassMappersByVertex(countryVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(countryEntity).size()); - assertEquals(countryClassMapper, mapper.getEVClassMappersByEntity(countryEntity).get(0)); - assertEquals(countryClassMapper.getEntity(), countryEntity); - assertEquals(countryClassMapper.getVertexType(), countryVertexType); - - assertEquals(3, countryClassMapper.getAttribute2property().size()); - assertEquals(3, countryClassMapper.getProperty2attribute().size()); - assertEquals("id", countryClassMapper.getAttribute2property().get("ID")); - assertEquals("name", countryClassMapper.getAttribute2property().get("NAME")); - assertEquals("continent", countryClassMapper.getAttribute2property().get("CONTINENT")); - assertEquals("ID", countryClassMapper.getProperty2attribute().get("id")); - assertEquals("NAME", countryClassMapper.getProperty2attribute().get("name")); - assertEquals("CONTINENT", countryClassMapper.getProperty2attribute().get("continent")); - - assertEquals(1, mapper.getEVClassMappersByVertex(managerVertexType).size()); - EVClassMapper managerClassMapper = mapper.getEVClassMappersByVertex(managerVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(managerEntity).size()); - assertEquals(managerClassMapper, mapper.getEVClassMappersByEntity(managerEntity).get(0)); - assertEquals(managerClassMapper.getEntity(), managerEntity); - assertEquals(managerClassMapper.getVertexType(), managerVertexType); - - assertEquals(2, managerClassMapper.getAttribute2property().size()); - assertEquals(2, managerClassMapper.getProperty2attribute().size()); - assertEquals("id", managerClassMapper.getAttribute2property().get("ID")); - assertEquals("name", managerClassMapper.getAttribute2property().get("NAME")); - assertEquals("ID", managerClassMapper.getProperty2attribute().get("id")); - assertEquals("NAME", managerClassMapper.getProperty2attribute().get("name")); - - assertEquals(1, mapper.getEVClassMappersByVertex(projectManagerVertexType).size()); - EVClassMapper projectManagerClassMapper = mapper.getEVClassMappersByVertex(projectManagerVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(projectManagerEntity).size()); - assertEquals(projectManagerClassMapper, mapper.getEVClassMappersByEntity(projectManagerEntity).get(0)); - assertEquals(projectManagerClassMapper.getEntity(), projectManagerEntity); - assertEquals(projectManagerClassMapper.getVertexType(), projectManagerVertexType); - - assertEquals(1, projectManagerClassMapper.getAttribute2property().size()); - assertEquals(1, projectManagerClassMapper.getProperty2attribute().size()); - assertEquals("project", projectManagerClassMapper.getAttribute2property().get("PROJECT")); - assertEquals("PROJECT", projectManagerClassMapper.getProperty2attribute().get("project")); - - // Relationships-Edges Mapping - - Iterator itRelationships = employeeEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship hasManagerRelationship = itRelationships.next(); - assertFalse(itRelationships.hasNext()); - - EdgeType hasManagerEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasManager"); - - assertEquals(1, mapper.getRelationship2edgeType().size()); - assertEquals(hasManagerEdgeType, mapper.getRelationship2edgeType().get(hasManagerRelationship)); - - assertEquals(1, mapper.getEdgeType2relationships().size()); - assertEquals(1, mapper.getEdgeType2relationships().get(hasManagerEdgeType).size()); - assertTrue(mapper.getEdgeType2relationships().get(hasManagerEdgeType).contains(hasManagerRelationship)); - - // JoinVertexes-AggregatorEdges Mapping - - assertEquals(0, mapper.getJoinVertex2aggregatorEdges().size()); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } finally { - try { - // Dropping Source DB Schema and OrientGraph - String dbDropping = "drop schema public cascade"; - st.execute(dbDropping); - connection.close(); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } - } + } + + /* + * Filtering out a table through include-tables (with Table per Concrete Type inheritance). + */ @Test + void filterOutThroughIncludeWithTablePerConcreteTypeInheritance() { + Connection connection = null; + Statement st = null; + + try { + Class.forName(this.driver); + connection = DriverManager.getConnection(this.jurl, this.username, this.password); + + String countryTableBuilding = + "create memory table COUNTRY(ID varchar(256) not null, NAME varchar(256), CONTINENT" + + " varchar(256), primary key (ID))"; + st = connection.createStatement(); + st.execute(countryTableBuilding); + + String residenceTableBuilding = + "create memory table RESIDENCE(ID varchar(256) not null, CITY varchar(256), COUNTRY" + + " varchar(256), primary key (ID))"; + st = connection.createStatement(); + st.execute(residenceTableBuilding); + + String managerTableBuilding = + "create memory table MANAGER(ID varchar(256) not null, NAME varchar(256), primary key" + + " (ID))"; + st.execute(managerTableBuilding); + + String projectManagerTableBuilding = + "create memory table PROJECT_MANAGER(ID varchar(256) not null, NAME varchar(256), PROJECT" + + " varchar(256), primary key (ID))"; + st.execute(projectManagerTableBuilding); + + String employeeTableBuilding = + "create memory table EMPLOYEE (ID varchar(256) not null, NAME varchar(256), RESIDENCE" + + " varchar(256), MANAGER varchar(256), primary key (ID), foreign key (RESIDENCE)" + + " references RESIDENCE(ID), foreign key (MANAGER) references MANAGER(ID))"; + st.execute(employeeTableBuilding); + + String regularEmployeeTableBuilding = + "create memory table REGULAR_EMPLOYEE (ID varchar(256) not null, " + + "NAME varchar(256), RESIDENCE varchar(256), MANAGER varchar(256)," + + "SALARY decimal(10,2), BONUS decimal(10,0), primary key (ID))"; + st.execute(regularEmployeeTableBuilding); + + String contractEmployeeTableBuilding = + "create memory table CONTRACT_EMPLOYEE (ID varchar(256) not null, " + + "NAME varchar(256), RESIDENCE varchar(256), MANAGER varchar(256)," + + "PAY_PER_HOUR decimal(10,2), CONTRACT_DURATION varchar(256), primary key (ID))"; + st.execute(contractEmployeeTableBuilding); + + // Records Inserting + + String countryFilling = + "insert into COUNTRY (ID,NAME,CONTINENT) values (" + "('C001','Italy','Europe'))"; + st.execute(countryFilling); + + String residenceFilling = + "insert into RESIDENCE (ID,CITY,COUNTRY) values (" + + "('R001','Rome','C001')," + + "('R002','Milan','C001'))"; + st.execute(residenceFilling); + + String managerFilling = "insert into MANAGER (ID,NAME) values (" + "('M001','Bill Right'))"; + st.execute(managerFilling); + + String projectManagerFilling = + "insert into PROJECT_MANAGER (ID,NAME,PROJECT) values (" + + "('M001','Bill Right','New World'))"; + st.execute(projectManagerFilling); + + String employeeFilling = + "insert into EMPLOYEE (ID,NAME,RESIDENCE,MANAGER) values (" + + "('E001','John Black','R001',null)," + + "('E002','Andrew Brown','R001','M001')," + + "('E003','Jack Johnson','R002',null))"; + st.execute(employeeFilling); + + String regularEmployeeFilling = + "insert into REGULAR_EMPLOYEE (ID,NAME,RESIDENCE,MANAGER,SALARY,BONUS) values (" + + "('E002','Andrew Brown','R001','M001','1000.00','10'))"; + st.execute(regularEmployeeFilling); + + String contractEmployeeFilling = + "insert into CONTRACT_EMPLOYEE (ID,NAME,RESIDENCE,MANAGER,PAY_PER_HOUR,CONTRACT_DURATION)" + + " values (('E003','Jack Johnson','R002',null,'50.00','6'))"; + st.execute(contractEmployeeFilling); + + List includedTables = new ArrayList(); + includedTables.add("COUNTRY"); + includedTables.add("MANAGER"); + includedTables.add("PROJECT_MANAGER"); + includedTables.add("EMPLOYEE"); + includedTables.add("REGULAR_EMPLOYEE"); + includedTables.add("CONTRACT_EMPLOYEE"); + + this.mapper = + new Hibernate2GraphMapper( + dataSource, + FilterTableMappingTest.XML_TABLE_PER_CONCRETE_CLASS, + includedTables, + null, + dbQueryEngine, + dataTypeHandler, + executionStrategy, + nameResolver, + statistics); + mapper.buildSourceDatabaseSchema(); + mapper.buildGraphModel(new JavaConventionNameResolver()); + + /* + * Testing context information + */ + + assertThat(statistics.totalNumberOfEntities).isEqualTo(6); + assertThat(statistics.builtEntities).isEqualTo(6); + assertThat(statistics.totalNumberOfRelationships).isEqualTo(1); + assertThat(statistics.builtRelationships).isEqualTo(1); + + assertThat(statistics.totalNumberOfModelVertices).isEqualTo(6); + assertThat(statistics.builtModelVertexTypes).isEqualTo(6); + assertThat(statistics.totalNumberOfModelEdges).isEqualTo(1); + assertThat(statistics.builtModelEdgeTypes).isEqualTo(1); + + /* + * Testing built source db schema + */ + + Entity employeeEntity = mapper.getDataBaseSchema().getEntityByName("EMPLOYEE"); + Entity regularEmployeeEntity = + mapper.getDataBaseSchema().getEntityByNameIgnoreCase("REGULAR_EMPLOYEE"); + Entity contractEmployeeEntity = + mapper.getDataBaseSchema().getEntityByNameIgnoreCase("CONTRACT_EMPLOYEE"); + Entity countryEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("COUNTRY"); + Entity managerEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("MANAGER"); + Entity projectManagerEntity = + mapper.getDataBaseSchema().getEntityByNameIgnoreCase("PROJECT_MANAGER"); + Entity residenceEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("RESIDENCE"); + + // entities check + assertThat(mapper.getDataBaseSchema().getEntities().size()).isEqualTo(6); + assertThat(mapper.getDataBaseSchema().getCanonicalRelationships().size()).isEqualTo(1); + assertThat(employeeEntity).isNotNull(); + assertThat(regularEmployeeEntity).isNotNull(); + assertThat(contractEmployeeEntity).isNotNull(); + assertThat(countryEntity).isNotNull(); + assertThat(managerEntity).isNotNull(); + assertThat(residenceEntity).isNull(); + + // attributes check + assertThat(employeeEntity.getAttributes().size()).isEqualTo(4); + + assertThat(employeeEntity.getAttributeByName("ID")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(employeeEntity.getAttributeByName("ID").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("ID").getOrdinalPosition()).isEqualTo(1); + assertThat(employeeEntity.getAttributeByName("ID").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(employeeEntity.getAttributeByName("NAME")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("NAME").getName()).isEqualTo("NAME"); + assertThat(employeeEntity.getAttributeByName("NAME").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("NAME").getOrdinalPosition()).isEqualTo(2); + assertThat(employeeEntity.getAttributeByName("NAME").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(employeeEntity.getAttributeByName("RESIDENCE")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getName()).isEqualTo("RESIDENCE"); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getOrdinalPosition()).isEqualTo(3); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(employeeEntity.getAttributeByName("MANAGER")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("MANAGER").getName()).isEqualTo("MANAGER"); + assertThat(employeeEntity.getAttributeByName("MANAGER").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("MANAGER").getOrdinalPosition()).isEqualTo(4); + assertThat(employeeEntity.getAttributeByName("MANAGER").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(regularEmployeeEntity.getAttributes().size()).isEqualTo(2); + + assertThat(regularEmployeeEntity.getAttributeByName("SALARY")).isNotNull(); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getName()).isEqualTo("SALARY"); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getDataType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getOrdinalPosition()) + .isEqualTo(1); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getBelongingEntity().getName()) + .isEqualTo("REGULAR_EMPLOYEE"); + + assertThat(regularEmployeeEntity.getAttributeByName("BONUS")).isNotNull(); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getName()).isEqualTo("BONUS"); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getDataType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getOrdinalPosition()) + .isEqualTo(2); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getBelongingEntity().getName()) + .isEqualTo("REGULAR_EMPLOYEE"); + + assertThat(contractEmployeeEntity.getAttributes().size()).isEqualTo(2); + + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR")).isNotNull(); + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getName()) + .isEqualTo("PAY_PER_HOUR"); + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getDataType()) + .isEqualTo("DECIMAL"); + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getOrdinalPosition()) + .isEqualTo(1); + assertThat( + contractEmployeeEntity + .getAttributeByName("PAY_PER_HOUR") + .getBelongingEntity() + .getName()) + .isEqualTo("CONTRACT_EMPLOYEE"); + + assertThat(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION")).isNotNull(); + assertThat(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getName()) + .isEqualTo("CONTRACT_DURATION"); + assertThat(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + contractEmployeeEntity + .getAttributeByName("CONTRACT_DURATION") + .getBelongingEntity() + .getName()) + .isEqualTo("CONTRACT_EMPLOYEE"); + + assertThat(countryEntity.getAttributes().size()).isEqualTo(3); + + assertThat(countryEntity.getAttributeByName("ID")).isNotNull(); + assertThat(countryEntity.getAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(countryEntity.getAttributeByName("ID").getDataType()).isEqualTo("VARCHAR"); + assertThat(countryEntity.getAttributeByName("ID").getOrdinalPosition()).isEqualTo(1); + assertThat(countryEntity.getAttributeByName("ID").getBelongingEntity().getName()) + .isEqualTo("COUNTRY"); + + assertThat(countryEntity.getAttributeByName("NAME")).isNotNull(); + assertThat(countryEntity.getAttributeByName("NAME").getName()).isEqualTo("NAME"); + assertThat(countryEntity.getAttributeByName("NAME").getDataType()).isEqualTo("VARCHAR"); + assertThat(countryEntity.getAttributeByName("NAME").getOrdinalPosition()).isEqualTo(2); + assertThat(countryEntity.getAttributeByName("NAME").getBelongingEntity().getName()) + .isEqualTo("COUNTRY"); + + assertThat(countryEntity.getAttributeByName("CONTINENT")).isNotNull(); + assertThat(countryEntity.getAttributeByName("CONTINENT").getName()).isEqualTo("CONTINENT"); + assertThat(countryEntity.getAttributeByName("CONTINENT").getDataType()).isEqualTo("VARCHAR"); + assertThat(countryEntity.getAttributeByName("CONTINENT").getOrdinalPosition()).isEqualTo(3); + assertThat(countryEntity.getAttributeByName("CONTINENT").getBelongingEntity().getName()) + .isEqualTo("COUNTRY"); + + assertThat(managerEntity.getAttributes().size()).isEqualTo(2); + + assertThat(managerEntity.getAttributeByName("ID")).isNotNull(); + assertThat(managerEntity.getAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(managerEntity.getAttributeByName("ID").getDataType()).isEqualTo("VARCHAR"); + assertThat(managerEntity.getAttributeByName("ID").getOrdinalPosition()).isEqualTo(1); + assertThat(managerEntity.getAttributeByName("ID").getBelongingEntity().getName()) + .isEqualTo("MANAGER"); + + assertThat(managerEntity.getAttributeByName("NAME")).isNotNull(); + assertThat(managerEntity.getAttributeByName("NAME").getName()).isEqualTo("NAME"); + assertThat(managerEntity.getAttributeByName("NAME").getDataType()).isEqualTo("VARCHAR"); + assertThat(managerEntity.getAttributeByName("NAME").getOrdinalPosition()).isEqualTo(2); + assertThat(managerEntity.getAttributeByName("NAME").getBelongingEntity().getName()) + .isEqualTo("MANAGER"); + + assertThat(projectManagerEntity.getAttributes().size()).isEqualTo(1); + + assertThat(projectManagerEntity.getAttributeByName("PROJECT")).isNotNull(); + assertThat(projectManagerEntity.getAttributeByName("PROJECT").getName()).isEqualTo("PROJECT"); + assertThat(projectManagerEntity.getAttributeByName("PROJECT").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(projectManagerEntity.getAttributeByName("PROJECT").getOrdinalPosition()) + .isEqualTo(1); + assertThat(projectManagerEntity.getAttributeByName("PROJECT").getBelongingEntity().getName()) + .isEqualTo("PROJECT_MANAGER"); + + // inherited attributes check + assertThat(employeeEntity.getInheritedAttributes().size()).isEqualTo(0); + + assertThat(regularEmployeeEntity.getInheritedAttributes().size()).isEqualTo(4); + + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID")).isNotNull(); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()) + .isEqualTo(1); + assertThat( + regularEmployeeEntity + .getInheritedAttributeByName("ID") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME")).isNotNull(); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME").getName()) + .isEqualTo("NAME"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + regularEmployeeEntity + .getInheritedAttributeByName("NAME") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE")).isNotNull(); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()) + .isEqualTo("RESIDENCE"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()) + .isEqualTo(3); + assertThat( + regularEmployeeEntity + .getInheritedAttributeByName("RESIDENCE") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(regularEmployeeEntity.getInheritedAttributeByName("MANAGER")).isNotNull(); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("MANAGER").getName()) + .isEqualTo("MANAGER"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("MANAGER").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("MANAGER").getOrdinalPosition()) + .isEqualTo(4); + assertThat( + regularEmployeeEntity + .getInheritedAttributeByName("MANAGER") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(contractEmployeeEntity.getInheritedAttributes().size()).isEqualTo(4); + + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID")).isNotNull(); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID").getName()) + .isEqualTo("ID"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()) + .isEqualTo(1); + assertThat( + contractEmployeeEntity + .getInheritedAttributeByName("ID") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME")).isNotNull(); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME").getName()) + .isEqualTo("NAME"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + contractEmployeeEntity + .getInheritedAttributeByName("NAME") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE")).isNotNull(); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()) + .isEqualTo("RESIDENCE"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()) + .isEqualTo(3); + assertThat( + contractEmployeeEntity + .getInheritedAttributeByName("RESIDENCE") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(contractEmployeeEntity.getInheritedAttributeByName("MANAGER")).isNotNull(); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("MANAGER").getName()) + .isEqualTo("MANAGER"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("MANAGER").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("MANAGER").getOrdinalPosition()) + .isEqualTo(4); + assertThat( + contractEmployeeEntity + .getInheritedAttributeByName("MANAGER") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(projectManagerEntity.getInheritedAttributes().size()).isEqualTo(2); + + assertThat(projectManagerEntity.getInheritedAttributeByName("ID")).isNotNull(); + assertThat(projectManagerEntity.getInheritedAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(projectManagerEntity.getInheritedAttributeByName("ID").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(projectManagerEntity.getInheritedAttributeByName("ID").getOrdinalPosition()) + .isEqualTo(1); + assertThat( + projectManagerEntity.getInheritedAttributeByName("ID").getBelongingEntity().getName()) + .isEqualTo("MANAGER"); + + assertThat(projectManagerEntity.getInheritedAttributeByName("NAME")).isNotNull(); + assertThat(projectManagerEntity.getInheritedAttributeByName("NAME").getName()) + .isEqualTo("NAME"); + assertThat(projectManagerEntity.getInheritedAttributeByName("NAME").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(projectManagerEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + projectManagerEntity + .getInheritedAttributeByName("NAME") + .getBelongingEntity() + .getName()) + .isEqualTo("MANAGER"); + + assertThat(countryEntity.getInheritedAttributes().size()).isEqualTo(0); + assertThat(managerEntity.getInheritedAttributes().size()).isEqualTo(0); + + // primary key check + assertThat(regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()).isEqualTo(1); + assertThat(regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()) + .isEqualTo("ID"); + assertThat(regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + regularEmployeeEntity + .getPrimaryKey() + .getInvolvedAttributes() + .get(0) + .getBelongingEntity() + .getName()) + .isEqualTo("REGULAR_EMPLOYEE"); + + assertThat(contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()) + .isEqualTo(1); + assertThat(contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()) + .isEqualTo("ID"); + assertThat( + contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeEntity + .getPrimaryKey() + .getInvolvedAttributes() + .get(0) + .getBelongingEntity() + .getName()) + .isEqualTo("CONTRACT_EMPLOYEE"); + + assertThat(projectManagerEntity.getPrimaryKey().getInvolvedAttributes().size()).isEqualTo(1); + assertThat(projectManagerEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()) + .isEqualTo("ID"); + assertThat(projectManagerEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + projectManagerEntity + .getPrimaryKey() + .getInvolvedAttributes() + .get(0) + .getBelongingEntity() + .getName()) + .isEqualTo("PROJECT_MANAGER"); + + // relationship, primary and foreign key check + assertThat(regularEmployeeEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(contractEmployeeEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(employeeEntity.getOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(projectManagerEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(managerEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(countryEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(regularEmployeeEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(contractEmployeeEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(employeeEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(projectManagerEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(managerEntity.getInCanonicalRelationships().size()).isEqualTo(1); + assertThat(countryEntity.getInCanonicalRelationships().size()).isEqualTo(0); + + assertThat(regularEmployeeEntity.getForeignKeys().size()).isEqualTo(0); + assertThat(contractEmployeeEntity.getForeignKeys().size()).isEqualTo(0); + assertThat(employeeEntity.getForeignKeys().size()).isEqualTo(1); + assertThat(projectManagerEntity.getForeignKeys().size()).isEqualTo(0); + assertThat(managerEntity.getForeignKeys().size()).isEqualTo(0); + assertThat(countryEntity.getForeignKeys().size()).isEqualTo(0); + + Iterator itEmp = + employeeEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship currentEmpRel = itEmp.next(); + assertThat(currentEmpRel.getParentEntity().getName()).isEqualTo("MANAGER"); + assertThat(currentEmpRel.getForeignEntity().getName()).isEqualTo("EMPLOYEE"); + assertThat(currentEmpRel.getPrimaryKey()).isEqualTo(managerEntity.getPrimaryKey()); + assertThat(currentEmpRel.getForeignKey()).isEqualTo(employeeEntity.getForeignKeys().get(0)); + assertThat(itEmp.hasNext()).isFalse(); + + Iterator itManager = + managerEntity.getInCanonicalRelationships().iterator(); + CanonicalRelationship currentManRel = itManager.next(); + assertThat(currentManRel).isEqualTo(currentEmpRel); + + // inherited relationships check + assertThat(regularEmployeeEntity.getInheritedOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(contractEmployeeEntity.getInheritedOutCanonicalRelationships().size()) + .isEqualTo(1); + assertThat(employeeEntity.getInheritedOutCanonicalRelationships().size()).isEqualTo(0); + + Iterator itRegEmp = + regularEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); + Iterator itContEmp = + contractEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); + CanonicalRelationship currentRegEmpRel = itRegEmp.next(); + CanonicalRelationship currentContEmpRel = itContEmp.next(); + assertThat(currentRegEmpRel.getParentEntity().getName()).isEqualTo("MANAGER"); + assertThat(currentRegEmpRel.getForeignEntity().getName()).isEqualTo("EMPLOYEE"); + assertThat(currentContEmpRel.getParentEntity().getName()).isEqualTo("MANAGER"); + assertThat(currentContEmpRel.getForeignEntity().getName()).isEqualTo("EMPLOYEE"); + assertThat(currentRegEmpRel.getPrimaryKey()).isEqualTo(managerEntity.getPrimaryKey()); + assertThat(currentRegEmpRel.getFromColumns().size()).isEqualTo(1); + assertThat(currentRegEmpRel.getFromColumns().get(0).getName()).isEqualTo("MANAGER"); + assertThat(currentContEmpRel.getPrimaryKey()).isEqualTo(managerEntity.getPrimaryKey()); + assertThat(currentContEmpRel.getFromColumns().size()).isEqualTo(1); + assertThat(currentContEmpRel.getFromColumns().get(0).getName()).isEqualTo("MANAGER"); + assertThat(itRegEmp.hasNext()).isFalse(); + assertThat(itContEmp.hasNext()).isFalse(); + + // inheritance check + assertThat(regularEmployeeEntity.getParentEntity()).isEqualTo(employeeEntity); + assertThat(contractEmployeeEntity.getParentEntity()).isEqualTo(employeeEntity); + assertThat(employeeEntity.getParentEntity()).isNull(); + + assertThat(regularEmployeeEntity.getInheritanceLevel()).isEqualTo(1); + assertThat(contractEmployeeEntity.getInheritanceLevel()).isEqualTo(1); + assertThat(employeeEntity.getInheritanceLevel()).isEqualTo(0); + + // Hierarchical Bag check + assertThat(mapper.getDataBaseSchema().getHierarchicalBags().size()).isEqualTo(2); + + HierarchicalBag hierarchicalBag1 = mapper.getDataBaseSchema().getHierarchicalBags().get(0); + HierarchicalBag hierarchicalBag2 = mapper.getDataBaseSchema().getHierarchicalBags().get(1); + assertThat(hierarchicalBag1.getInheritancePattern()).isEqualTo("table-per-concrete-type"); + assertThat(hierarchicalBag2.getInheritancePattern()).isEqualTo("table-per-concrete-type"); + + assertThat(hierarchicalBag1.getDepth2entities().size()).isEqualTo(2); + + assertThat(hierarchicalBag1.getDepth2entities().get(0).size()).isEqualTo(1); + Iterator it = hierarchicalBag1.getDepth2entities().get(0).iterator(); + assertThat(it.next().getName()).isEqualTo("EMPLOYEE"); + assertThat(it.hasNext()).isFalse(); + + assertThat(hierarchicalBag1.getDepth2entities().get(1).size()).isEqualTo(2); + it = hierarchicalBag1.getDepth2entities().get(1).iterator(); + assertThat(it.next().getName()).isEqualTo("REGULAR_EMPLOYEE"); + assertThat(it.next().getName()).isEqualTo("CONTRACT_EMPLOYEE"); + assertThat(it.hasNext()).isFalse(); + + assertThat(employeeEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag1); + assertThat(regularEmployeeEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag1); + assertThat(contractEmployeeEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag1); + + assertThat(hierarchicalBag1.getDiscriminatorColumn()).isNull(); + + assertThat(hierarchicalBag2.getDepth2entities().size()).isEqualTo(2); + + assertThat(hierarchicalBag2.getDepth2entities().get(0).size()).isEqualTo(1); + it = hierarchicalBag2.getDepth2entities().get(0).iterator(); + assertThat(it.next().getName()).isEqualTo("MANAGER"); + assertThat(it.hasNext()).isFalse(); + + assertThat(hierarchicalBag2.getDepth2entities().get(1).size()).isEqualTo(1); + it = hierarchicalBag2.getDepth2entities().get(1).iterator(); + assertThat(it.next().getName()).isEqualTo("PROJECT_MANAGER"); + assertThat(it.hasNext()).isFalse(); + + assertThat(managerEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag2); + assertThat(projectManagerEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag2); + + assertThat(hierarchicalBag2.getDiscriminatorColumn()).isNull(); + + /* + * Testing built graph model + */ + + VertexType employeeVertexType = mapper.getGraphModel().getVertexTypeByName("Employee"); + VertexType regularEmployeeVertexType = + mapper.getGraphModel().getVertexTypeByName("RegularEmployee"); + VertexType contractEmployeeVertexType = + mapper.getGraphModel().getVertexTypeByName("ContractEmployee"); + VertexType countryVertexType = mapper.getGraphModel().getVertexTypeByName("Country"); + VertexType managerVertexType = mapper.getGraphModel().getVertexTypeByName("Manager"); + VertexType projectManagerVertexType = + mapper.getGraphModel().getVertexTypeByName("ProjectManager"); + VertexType residenceVertexType = mapper.getGraphModel().getVertexTypeByName("Residence"); + + // vertices check + assertThat(mapper.getGraphModel().getVerticesType().size()).isEqualTo(6); + assertThat(employeeVertexType).isNotNull(); + assertThat(regularEmployeeVertexType).isNotNull(); + assertThat(contractEmployeeVertexType).isNotNull(); + assertThat(countryVertexType).isNotNull(); + assertThat(managerVertexType).isNotNull(); + assertThat(projectManagerVertexType).isNotNull(); + assertThat(residenceVertexType).isNull(); + + // properties check + assertThat(employeeVertexType.getProperties().size()).isEqualTo(4); + + assertThat(employeeVertexType.getPropertyByName("id")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(employeeVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(employeeVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(employeeVertexType.getPropertyByName("name")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("name").getName()).isEqualTo("name"); + assertThat(employeeVertexType.getPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("name").getOrdinalPosition()).isEqualTo(2); + assertThat(employeeVertexType.getPropertyByName("name").isFromPrimaryKey()).isFalse(); + + assertThat(employeeVertexType.getPropertyByName("residence")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("residence").getName()) + .isEqualTo("residence"); + assertThat(employeeVertexType.getPropertyByName("residence").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("residence").getOrdinalPosition()) + .isEqualTo(3); + assertThat(employeeVertexType.getPropertyByName("residence").isFromPrimaryKey()).isFalse(); + + assertThat(employeeVertexType.getPropertyByName("manager")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("manager").getName()).isEqualTo("manager"); + assertThat(employeeVertexType.getPropertyByName("manager").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("manager").getOrdinalPosition()).isEqualTo(4); + assertThat(employeeVertexType.getPropertyByName("manager").isFromPrimaryKey()).isFalse(); + + assertThat(regularEmployeeVertexType.getProperties().size()).isEqualTo(2); + + assertThat(regularEmployeeVertexType.getPropertyByName("salary")).isNotNull(); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").getName()) + .isEqualTo("salary"); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").getOriginalType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").getOrdinalPosition()) + .isEqualTo(1); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").isFromPrimaryKey()) + .isFalse(); + + assertThat(regularEmployeeVertexType.getPropertyByName("bonus")).isNotNull(); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").getName()).isEqualTo("bonus"); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").getOriginalType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").getOrdinalPosition()) + .isEqualTo(2); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").isFromPrimaryKey()).isFalse(); + + assertThat(contractEmployeeVertexType.getProperties().size()).isEqualTo(2); + + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour")).isNotNull(); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").getName()) + .isEqualTo("payPerHour"); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").getOriginalType()) + .isEqualTo("DECIMAL"); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").getOrdinalPosition()) + .isEqualTo(1); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getPropertyByName("contractDuration")).isNotNull(); + assertThat(contractEmployeeVertexType.getPropertyByName("contractDuration").getName()) + .isEqualTo("contractDuration"); + assertThat(contractEmployeeVertexType.getPropertyByName("contractDuration").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeVertexType.getPropertyByName("contractDuration").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + contractEmployeeVertexType.getPropertyByName("contractDuration").isFromPrimaryKey()) + .isFalse(); + + assertThat(countryVertexType.getProperties().size()).isEqualTo(3); + + assertThat(countryVertexType.getPropertyByName("id")).isNotNull(); + assertThat(countryVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(countryVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(countryVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(countryVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(countryVertexType.getPropertyByName("name")).isNotNull(); + assertThat(countryVertexType.getPropertyByName("name").getName()).isEqualTo("name"); + assertThat(countryVertexType.getPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(countryVertexType.getPropertyByName("name").getOrdinalPosition()).isEqualTo(2); + assertThat(countryVertexType.getPropertyByName("name").isFromPrimaryKey()).isFalse(); + + assertThat(countryVertexType.getPropertyByName("continent")).isNotNull(); + assertThat(countryVertexType.getPropertyByName("continent").getName()).isEqualTo("continent"); + assertThat(countryVertexType.getPropertyByName("continent").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(countryVertexType.getPropertyByName("continent").getOrdinalPosition()) + .isEqualTo(3); + assertThat(countryVertexType.getPropertyByName("continent").isFromPrimaryKey()).isFalse(); + + assertThat(managerVertexType.getProperties().size()).isEqualTo(2); + + assertThat(managerVertexType.getPropertyByName("id")).isNotNull(); + assertThat(managerVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(managerVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(managerVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(managerVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(managerVertexType.getPropertyByName("name")).isNotNull(); + assertThat(managerVertexType.getPropertyByName("name").getName()).isEqualTo("name"); + assertThat(managerVertexType.getPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(managerVertexType.getPropertyByName("name").getOrdinalPosition()).isEqualTo(2); + assertThat(managerVertexType.getPropertyByName("name").isFromPrimaryKey()).isFalse(); + + assertThat(projectManagerVertexType.getProperties().size()).isEqualTo(1); + + assertThat(projectManagerVertexType.getPropertyByName("project")).isNotNull(); + assertThat(projectManagerVertexType.getPropertyByName("project").getName()) + .isEqualTo("project"); + assertThat(projectManagerVertexType.getPropertyByName("project").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(projectManagerVertexType.getPropertyByName("project").getOrdinalPosition()) + .isEqualTo(1); + assertThat(projectManagerVertexType.getPropertyByName("project").isFromPrimaryKey()) + .isFalse(); + + // inherited properties check + assertThat(employeeVertexType.getInheritedProperties().size()).isEqualTo(0); + + assertThat(regularEmployeeVertexType.getInheritedProperties().size()).isEqualTo(4); + + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id")).isNotNull(); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").getName()) + .isEqualTo("id"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()) + .isEqualTo(1); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()) + .isTrue(); + + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name")).isNotNull(); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").getName()) + .isEqualTo("name"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()) + .isEqualTo(2); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()) + .isFalse(); + + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("residence")).isNotNull(); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("residence").getName()) + .isEqualTo("residence"); + assertThat( + regularEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + regularEmployeeVertexType + .getInheritedPropertyByName("residence") + .getOrdinalPosition()) + .isEqualTo(3); + assertThat( + regularEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()) + .isFalse(); + + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("manager")).isNotNull(); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("manager").getName()) + .isEqualTo("manager"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("manager").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + regularEmployeeVertexType.getInheritedPropertyByName("manager").getOrdinalPosition()) + .isEqualTo(4); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("manager").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getInheritedProperties().size()).isEqualTo(4); + + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id")).isNotNull(); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").getName()) + .isEqualTo("id"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()) + .isEqualTo(1); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()) + .isTrue(); + + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name")).isNotNull(); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").getName()) + .isEqualTo("name"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()) + .isEqualTo(2); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("residence")).isNotNull(); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("residence").getName()) + .isEqualTo("residence"); + assertThat( + contractEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeVertexType + .getInheritedPropertyByName("residence") + .getOrdinalPosition()) + .isEqualTo(3); + assertThat( + contractEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("manager")).isNotNull(); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("manager").getName()) + .isEqualTo("manager"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("manager").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeVertexType.getInheritedPropertyByName("manager").getOrdinalPosition()) + .isEqualTo(4); + assertThat( + contractEmployeeVertexType.getInheritedPropertyByName("manager").isFromPrimaryKey()) + .isFalse(); + + assertThat(projectManagerVertexType.getInheritedProperties().size()).isEqualTo(2); + + assertThat(projectManagerVertexType.getInheritedPropertyByName("id")).isNotNull(); + assertThat(projectManagerVertexType.getInheritedPropertyByName("id").getName()) + .isEqualTo("id"); + assertThat(projectManagerVertexType.getInheritedPropertyByName("id").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(projectManagerVertexType.getInheritedPropertyByName("id").getOrdinalPosition()) + .isEqualTo(1); + assertThat(projectManagerVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()) + .isTrue(); + + assertThat(projectManagerVertexType.getInheritedPropertyByName("name")).isNotNull(); + assertThat(projectManagerVertexType.getInheritedPropertyByName("name").getName()) + .isEqualTo("name"); + assertThat(projectManagerVertexType.getInheritedPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(projectManagerVertexType.getInheritedPropertyByName("name").getOrdinalPosition()) + .isEqualTo(2); + assertThat(projectManagerVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()) + .isFalse(); + + assertThat(countryVertexType.getInheritedProperties().size()).isEqualTo(0); + assertThat(managerVertexType.getInheritedProperties().size()).isEqualTo(0); + + // edges check + + assertThat(mapper.getRelationship2edgeType().size()).isEqualTo(1); + + assertThat(mapper.getGraphModel().getEdgesType().size()).isEqualTo(1); + assertThat(mapper.getGraphModel().getEdgesType().get(0).getName()).isEqualTo("HasManager"); + + assertThat(employeeVertexType.getOutEdgesType().size()).isEqualTo(1); + assertThat(employeeVertexType.getOutEdgesType().get(0).getName()).isEqualTo("HasManager"); + + assertThat(regularEmployeeVertexType.getOutEdgesType().size()).isEqualTo(1); + assertThat(regularEmployeeVertexType.getOutEdgesType().get(0).getName()) + .isEqualTo("HasManager"); + + assertThat(contractEmployeeVertexType.getOutEdgesType().size()).isEqualTo(1); + assertThat(contractEmployeeVertexType.getOutEdgesType().get(0).getName()) + .isEqualTo("HasManager"); + + /* + * Rules check + */ + + // Classes Mapping + + assertThat(mapper.getVertexType2EVClassMappers().size()).isEqualTo(6); + assertThat(mapper.getEntity2EVClassMappers().size()).isEqualTo(6); + + assertThat(mapper.getEVClassMappersByVertex(employeeVertexType).size()).isEqualTo(1); + EVClassMapper employeeClassMapper = + mapper.getEVClassMappersByVertex(employeeVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(employeeEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(employeeEntity).get(0)) + .isEqualTo(employeeClassMapper); + assertThat(employeeEntity).isEqualTo(employeeClassMapper.getEntity()); + assertThat(employeeVertexType).isEqualTo(employeeClassMapper.getVertexType()); + + assertThat(employeeClassMapper.getAttribute2property().size()).isEqualTo(4); + assertThat(employeeClassMapper.getProperty2attribute().size()).isEqualTo(4); + assertThat(employeeClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(employeeClassMapper.getAttribute2property().get("NAME")).isEqualTo("name"); + assertThat(employeeClassMapper.getAttribute2property().get("RESIDENCE")) + .isEqualTo("residence"); + assertThat(employeeClassMapper.getAttribute2property().get("MANAGER")).isEqualTo("manager"); + assertThat(employeeClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(employeeClassMapper.getProperty2attribute().get("name")).isEqualTo("NAME"); + assertThat(employeeClassMapper.getProperty2attribute().get("residence")) + .isEqualTo("RESIDENCE"); + assertThat(employeeClassMapper.getProperty2attribute().get("manager")).isEqualTo("MANAGER"); + + assertThat(mapper.getEVClassMappersByVertex(regularEmployeeVertexType).size()).isEqualTo(1); + EVClassMapper regularEmployeeClassMapper = + mapper.getEVClassMappersByVertex(regularEmployeeVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(regularEmployeeEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(regularEmployeeEntity).get(0)) + .isEqualTo(regularEmployeeClassMapper); + assertThat(regularEmployeeEntity).isEqualTo(regularEmployeeClassMapper.getEntity()); + assertThat(regularEmployeeVertexType).isEqualTo(regularEmployeeClassMapper.getVertexType()); + + assertThat(regularEmployeeClassMapper.getAttribute2property().size()).isEqualTo(2); + assertThat(regularEmployeeClassMapper.getProperty2attribute().size()).isEqualTo(2); + assertThat(regularEmployeeClassMapper.getAttribute2property().get("SALARY")) + .isEqualTo("salary"); + assertThat(regularEmployeeClassMapper.getAttribute2property().get("BONUS")) + .isEqualTo("bonus"); + assertThat(regularEmployeeClassMapper.getProperty2attribute().get("salary")) + .isEqualTo("SALARY"); + assertThat(regularEmployeeClassMapper.getProperty2attribute().get("bonus")) + .isEqualTo("BONUS"); + + assertThat(mapper.getEVClassMappersByVertex(contractEmployeeVertexType).size()).isEqualTo(1); + EVClassMapper contractEmployeeClassMapper = + mapper.getEVClassMappersByVertex(contractEmployeeVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(contractEmployeeEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(contractEmployeeEntity).get(0)) + .isEqualTo(contractEmployeeClassMapper); + assertThat(contractEmployeeEntity).isEqualTo(contractEmployeeClassMapper.getEntity()); + assertThat(contractEmployeeVertexType).isEqualTo(contractEmployeeClassMapper.getVertexType()); + + assertThat(contractEmployeeClassMapper.getAttribute2property().size()).isEqualTo(2); + assertThat(contractEmployeeClassMapper.getProperty2attribute().size()).isEqualTo(2); + assertThat(contractEmployeeClassMapper.getAttribute2property().get("PAY_PER_HOUR")) + .isEqualTo("payPerHour"); + assertThat(contractEmployeeClassMapper.getAttribute2property().get("CONTRACT_DURATION")) + .isEqualTo("contractDuration"); + assertThat(contractEmployeeClassMapper.getProperty2attribute().get("payPerHour")) + .isEqualTo("PAY_PER_HOUR"); + assertThat(contractEmployeeClassMapper.getProperty2attribute().get("contractDuration")) + .isEqualTo("CONTRACT_DURATION"); + + assertThat(mapper.getEVClassMappersByVertex(countryVertexType).size()).isEqualTo(1); + EVClassMapper countryClassMapper = mapper.getEVClassMappersByVertex(countryVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(countryEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(countryEntity).get(0)) + .isEqualTo(countryClassMapper); + assertThat(countryEntity).isEqualTo(countryClassMapper.getEntity()); + assertThat(countryVertexType).isEqualTo(countryClassMapper.getVertexType()); + + assertThat(countryClassMapper.getAttribute2property().size()).isEqualTo(3); + assertThat(countryClassMapper.getProperty2attribute().size()).isEqualTo(3); + assertThat(countryClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(countryClassMapper.getAttribute2property().get("NAME")).isEqualTo("name"); + assertThat(countryClassMapper.getAttribute2property().get("CONTINENT")) + .isEqualTo("continent"); + assertThat(countryClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(countryClassMapper.getProperty2attribute().get("name")).isEqualTo("NAME"); + assertThat(countryClassMapper.getProperty2attribute().get("continent")) + .isEqualTo("CONTINENT"); + + assertThat(mapper.getEVClassMappersByVertex(managerVertexType).size()).isEqualTo(1); + EVClassMapper managerClassMapper = mapper.getEVClassMappersByVertex(managerVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(managerEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(managerEntity).get(0)) + .isEqualTo(managerClassMapper); + assertThat(managerEntity).isEqualTo(managerClassMapper.getEntity()); + assertThat(managerVertexType).isEqualTo(managerClassMapper.getVertexType()); + + assertThat(managerClassMapper.getAttribute2property().size()).isEqualTo(2); + assertThat(managerClassMapper.getProperty2attribute().size()).isEqualTo(2); + assertThat(managerClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(managerClassMapper.getAttribute2property().get("NAME")).isEqualTo("name"); + assertThat(managerClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(managerClassMapper.getProperty2attribute().get("name")).isEqualTo("NAME"); + + assertThat(mapper.getEVClassMappersByVertex(projectManagerVertexType).size()).isEqualTo(1); + EVClassMapper projectManagerClassMapper = + mapper.getEVClassMappersByVertex(projectManagerVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(projectManagerEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(projectManagerEntity).get(0)) + .isEqualTo(projectManagerClassMapper); + assertThat(projectManagerEntity).isEqualTo(projectManagerClassMapper.getEntity()); + assertThat(projectManagerVertexType).isEqualTo(projectManagerClassMapper.getVertexType()); + + assertThat(projectManagerClassMapper.getAttribute2property().size()).isEqualTo(1); + assertThat(projectManagerClassMapper.getProperty2attribute().size()).isEqualTo(1); + assertThat(projectManagerClassMapper.getAttribute2property().get("PROJECT")) + .isEqualTo("project"); + assertThat(projectManagerClassMapper.getProperty2attribute().get("project")) + .isEqualTo("PROJECT"); + + // Relationships-Edges Mapping + + Iterator itRelationships = + employeeEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship hasManagerRelationship = itRelationships.next(); + assertThat(itRelationships.hasNext()).isFalse(); + + EdgeType hasManagerEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasManager"); + + assertThat(mapper.getRelationship2edgeType().size()).isEqualTo(1); + assertThat(mapper.getRelationship2edgeType().get(hasManagerRelationship)) + .isEqualTo(hasManagerEdgeType); + + assertThat(mapper.getEdgeType2relationships().size()).isEqualTo(1); + assertThat(mapper.getEdgeType2relationships().get(hasManagerEdgeType).size()).isEqualTo(1); + assertThat( + mapper + .getEdgeType2relationships() + .get(hasManagerEdgeType) + .contains(hasManagerRelationship)) + .isTrue(); + + // JoinVertexes-AggregatorEdges Mapping + + assertThat(mapper.getJoinVertex2aggregatorEdges().size()).isEqualTo(0); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } finally { + try { + // Dropping Source DB Schema and OrientGraph + String dbDropping = "drop schema public cascade"; + st.execute(dbDropping); + connection.close(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } } + } } diff --git a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/graphprovider/AbstractRDBMSGraphProvider.java b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/graphprovider/AbstractRDBMSGraphProvider.java index a364362c..4d3d5853 100644 --- a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/graphprovider/AbstractRDBMSGraphProvider.java +++ b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/graphprovider/AbstractRDBMSGraphProvider.java @@ -20,7 +20,7 @@ * #L% */ -import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import com.arcadeanalytics.data.Sprite; import com.arcadeanalytics.data.SpritePlayer; @@ -30,17 +30,18 @@ public abstract class AbstractRDBMSGraphProvider { - public long nodes; - public long edges; + public long nodes; + public long edges; - protected RDBMSGraphProvider provider; + protected RDBMSGraphProvider provider; - SpritePlayer player = new SpritePlayer() { + SpritePlayer player = + new SpritePlayer() { private int processed = 0; @Override public boolean accept(@NotNull Sprite sprite) { - return true; + return true; } @Override @@ -51,26 +52,26 @@ public void begin() {} @Override public void play(Sprite document) { - assertNotNull(document.entries()); - processed++; + assertThat(document.entries()).isNotNull(); + processed++; - if ( - document.valueOf(com.arcadeanalytics.provider.IndexConstants.ARCADE_TYPE).equals(com.arcadeanalytics.provider.IndexConstants.ARCADE_NODE_TYPE) - ) nodes++; - if ( - document.valueOf(com.arcadeanalytics.provider.IndexConstants.ARCADE_TYPE).equals(com.arcadeanalytics.provider.IndexConstants.ARCADE_EDGE_TYPE) - ) edges++; + if (document + .valueOf(com.arcadeanalytics.provider.IndexConstants.ARCADE_TYPE) + .equals(com.arcadeanalytics.provider.IndexConstants.ARCADE_NODE_TYPE)) nodes++; + if (document + .valueOf(com.arcadeanalytics.provider.IndexConstants.ARCADE_TYPE) + .equals(com.arcadeanalytics.provider.IndexConstants.ARCADE_EDGE_TYPE)) edges++; } @Override public long processed() { - return processed; + return processed; } - }; + }; - @Test - public abstract void shouldFetchAllVertexes(); + @Test + public abstract void shouldFetchAllVertexes(); - @Test - public abstract void shouldFetchAllVertexesExceptJoinTables(); + @Test + public abstract void shouldFetchAllVertexesExceptJoinTables(); } diff --git a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/graphprovider/MysqlGraphProviderTest.java b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/graphprovider/MysqlGraphProviderTest.java index b4763577..057304bf 100644 --- a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/graphprovider/MysqlGraphProviderTest.java +++ b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/graphprovider/MysqlGraphProviderTest.java @@ -23,9 +23,7 @@ import static org.assertj.core.api.Assertions.assertThat; import com.arcadeanalytics.provider.DataSourceInfo; -import com.arcadeanalytics.provider.rdbms.dataprovider.PostgreSQLDataProviderTest; import com.arcadeanalytics.provider.rdbms.dataprovider.RDBMSGraphProvider; -import org.junit.Assert; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.slf4j.Logger; @@ -35,26 +33,30 @@ public class MysqlGraphProviderTest extends AbstractRDBMSGraphProvider { - private static final Logger LOGGER = LoggerFactory.getLogger(PostgreSQLDataProviderTest.class); - private static final String driver = "com.mysql.cj.jdbc.Driver"; - private static final String username = "test"; - private static final String password = "test"; - public static MySQLContainer container = new MySQLContainer(DockerImageName.parse("arcadeanalytics/mysql-sakila").asCompatibleSubstituteFor("mysql")) - .withUsername(username) - .withPassword(password) - .withDatabaseName("sakila"); - - @BeforeAll - public static void beforeClass() throws Exception { - container.start(); - container.withDatabaseName("sakila"); - } - - @Test - public void shouldFetchAllVertexes() { - // setting the aggregationEnabled flag in the dataSource - - DataSourceInfo dataSource = new DataSourceInfo( + private static final Logger LOGGER = LoggerFactory.getLogger(MysqlGraphProviderTest.class); + private static final String driver = "com.mysql.cj.jdbc.Driver"; + private static final String username = "test"; + private static final String password = "test"; + public static MySQLContainer container = + new MySQLContainer( + DockerImageName.parse("arcadeanalytics/mysql-sakila") + .asCompatibleSubstituteFor("mysql")) + .withUsername(username) + .withPassword(password) + .withDatabaseName("sakila"); + + @BeforeAll + static void beforeClass() throws Exception { + container.start(); + container.withDatabaseName("sakila"); + } + + @Test + public void shouldFetchAllVertexes() { + // setting the aggregationEnabled flag in the dataSource + + DataSourceInfo dataSource = + new DataSourceInfo( 1L, "RDBMS_MYSQL", "testDataSource", @@ -71,22 +73,22 @@ public void shouldFetchAllVertexes() { "", 22, "", - false - ); - provider = new RDBMSGraphProvider(); + false); + provider = new RDBMSGraphProvider(); - provider.provideTo(dataSource, player); + provider.provideTo(dataSource, player); - assertThat(player.processed()).isEqualTo(47273); + assertThat(player.processed()).isEqualTo(47273); - Assert.assertEquals(47273, nodes); - Assert.assertEquals(0, edges); - } + assertThat(nodes).isEqualTo(47273); + assertThat(edges).isEqualTo(0); + } - @Test - public void shouldFetchAllVertexesExceptJoinTables() { - // setting the aggregationEnabled flag in the dataSource - DataSourceInfo dataSource = new DataSourceInfo( + @Test + public void shouldFetchAllVertexesExceptJoinTables() { + // setting the aggregationEnabled flag in the dataSource + DataSourceInfo dataSource = + new DataSourceInfo( 1L, "RDBMS_MYSQL", "testDataSource", @@ -103,16 +105,15 @@ public void shouldFetchAllVertexesExceptJoinTables() { "", 22, "", - false - ); + false); - provider = new RDBMSGraphProvider(); + provider = new RDBMSGraphProvider(); - provider.provideTo(dataSource, player); + provider.provideTo(dataSource, player); - assertThat(player.processed()).isEqualTo(47273); + assertThat(player.processed()).isEqualTo(47273); - Assert.assertEquals(40811, nodes); - Assert.assertEquals(6462, edges); - } + assertThat(nodes).isEqualTo(40811); + assertThat(edges).isEqualTo(6462); + } } diff --git a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/graphprovider/PostgreSQLGraphProviderTest.java b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/graphprovider/PostgreSQLGraphProviderTest.java index 52961f99..d88e0b6f 100644 --- a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/graphprovider/PostgreSQLGraphProviderTest.java +++ b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/graphprovider/PostgreSQLGraphProviderTest.java @@ -20,21 +20,23 @@ * #L% */ +import static org.assertj.core.api.Assertions.assertThat; + import com.arcadeanalytics.provider.DataSourceInfo; import com.arcadeanalytics.provider.rdbms.dataprovider.PostgreSQLContainerHolder; import com.arcadeanalytics.provider.rdbms.dataprovider.RDBMSGraphProvider; -import org.junit.Assert; import org.junit.jupiter.api.Test; import org.testcontainers.containers.PostgreSQLContainer; -public class PostgreSQLGraphProviderTest extends AbstractRDBMSGraphProvider { +class PostgreSQLGraphProviderTest extends AbstractRDBMSGraphProvider { - final PostgreSQLContainer container = PostgreSQLContainerHolder.container; + final PostgreSQLContainer container = PostgreSQLContainerHolder.container; - @Test - public void shouldFetchAllVertexes() { - // setting the aggregationEnabled flag in the dataSource - DataSourceInfo dataSource = new DataSourceInfo( + @Test + public void shouldFetchAllVertexes() { + // setting the aggregationEnabled flag in the dataSource + DataSourceInfo dataSource = + new DataSourceInfo( 1L, "RDBMS_POSTGRESQL", "testDataSource", @@ -51,22 +53,22 @@ public void shouldFetchAllVertexes() { "", 22, "", - false - ); + false); - provider = new RDBMSGraphProvider(); + provider = new RDBMSGraphProvider(); - provider.provideTo(dataSource, player); - Assert.assertEquals(44820, player.processed()); + provider.provideTo(dataSource, player); + assertThat(player.processed()).isEqualTo(44820); - Assert.assertEquals(44820, nodes); - Assert.assertEquals(0, edges); - } + assertThat(nodes).isEqualTo(44820); + assertThat(edges).isEqualTo(0); + } - @Test - public void shouldFetchAllVertexesExceptJoinTables() { - // setting the aggregationEnabled flag in the dataSource - DataSourceInfo dataSource = new DataSourceInfo( + @Test + public void shouldFetchAllVertexesExceptJoinTables() { + // setting the aggregationEnabled flag in the dataSource + DataSourceInfo dataSource = + new DataSourceInfo( 1L, "RDBMS_POSTGRESQL", "testDataSource", @@ -83,15 +85,14 @@ public void shouldFetchAllVertexesExceptJoinTables() { "", 22, "", - false - ); + false); - provider = new RDBMSGraphProvider(); + provider = new RDBMSGraphProvider(); - provider.provideTo(dataSource, player); - Assert.assertEquals(player.processed(), 44820); + provider.provideTo(dataSource, player); + assertThat(player.processed()).isEqualTo(44820); - Assert.assertEquals(38358, nodes); - Assert.assertEquals(6462, edges); - } + assertThat(nodes).isEqualTo(38358); + assertThat(edges).isEqualTo(6462); + } } diff --git a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/hibernate/HibernateMapperTest.java b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/hibernate/HibernateMapperTest.java index 1b293f90..131010a0 100644 --- a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/hibernate/HibernateMapperTest.java +++ b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/hibernate/HibernateMapperTest.java @@ -40,12 +40,8 @@ * #L% */ -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.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import com.arcadeanalytics.provider.DataSourceInfo; import com.arcadeanalytics.provider.rdbms.context.Statistics; @@ -68,1849 +64,2523 @@ /** * @author Gabriele Ponzi */ - -public class HibernateMapperTest { - - private static final String XML_TABLE_PER_CLASS = "src/test/resources/provider/rdbms/inheritance/hibernate/tablePerClassHierarchyInheritanceTest.xml"; - private static final String XML_TABLE_PER_SUBCLASS1 = "src/test/resources/provider/rdbms/inheritance/hibernate/tablePerSubclassInheritanceTest1.xml"; - private static final String XML_TABLE_PER_SUBCLASS2 = "src/test/resources/provider/rdbms/inheritance/hibernate/tablePerSubclassInheritanceTest2.xml"; - private static final String XML_TABLE_PER_CONCRETE_CLASS = - "src/test/resources/provider/rdbms/inheritance/hibernate/tablePerConcreteClassInheritanceTest.xml"; - private ER2GraphMapper mapper; - private DBQueryEngine dbQueryEngine; - private String driver = "org.hsqldb.jdbc.JDBCDriver"; - private String jurl = "jdbc:hsqldb:mem:mydb"; - private String username = "SA"; - private String password = ""; - private DataSourceInfo dataSource; - private String executionStrategy; - private JavaConventionNameResolver nameResolver; - private HSQLDBDataTypeHandler dataTypeHandler; - private Statistics statistics; - - @BeforeEach - public void init() { - this.dataSource = - new DataSourceInfo( - 1L, - "RDBMS_HSQL", - "testDataSource", - "desc", - "mem", - 1234, - "mydb", - username, - password, - false, - "{}", - false, - false, - "", - 22, - "", - false - ); - - dbQueryEngine = new DBQueryEngine(dataSource, 300); - executionStrategy = "not_specified"; - nameResolver = new JavaConventionNameResolver(); - dataTypeHandler = new HSQLDBDataTypeHandler(); - statistics = new Statistics(); - } - - @Test - /* - * Table per Class Hierarchy Inheritance ( tag) - * table ( http://www.javatpoint.com/hibernate-table-per-hierarchy-example-using-xml-file ) - */ - - public void TablePerClassHierarchyInheritance() { - Connection connection = null; - Statement st = null; - - try { - Class.forName(this.driver); - connection = DriverManager.getConnection(this.jurl, this.username, this.password); - - String residence = "create memory table RESIDENCE(ID varchar(256) not null, CITY varchar(256), COUNTRY varchar(256), primary key (ID))"; - st = connection.createStatement(); - st.execute(residence); - - String employeeTableBuilding = - "create memory table EMPLOYEE (ID varchar(256) not null," + - " TYPE varchar(256), NAME varchar(256), SALARY decimal(10,2), BONUS decimal(10,0), " + - "PAY_PER_HOUR decimal(10,2), CONTRACT_DURATION varchar(256), RESIDENCE varchar(256)," + - "primary key (id), foreign key (RESIDENCE) references RESIDENCE(ID))"; - st.execute(employeeTableBuilding); - - this.mapper = - new Hibernate2GraphMapper( - dataSource, - HibernateMapperTest.XML_TABLE_PER_CLASS, - null, - null, - dbQueryEngine, - dataTypeHandler, - executionStrategy, - nameResolver, - statistics - ); - - mapper.buildSourceDatabaseSchema(); - mapper.buildGraphModel(new JavaConventionNameResolver()); - - /* - * Testing context information - */ - - assertEquals(2, statistics.totalNumberOfEntities); - assertEquals(2, statistics.builtEntities); - assertEquals(1, statistics.totalNumberOfRelationships); - assertEquals(1, statistics.builtRelationships); - - assertEquals(4, statistics.totalNumberOfModelVertices); - assertEquals(4, statistics.builtModelVertexTypes); - assertEquals(1, statistics.totalNumberOfModelEdges); - assertEquals(1, statistics.builtModelEdgeTypes); - - /* - * Testing built source db schema - */ - - Entity employeeEntity = mapper.getDataBaseSchema().getEntityByName("EMPLOYEE"); - Entity regularEmployeeEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("REGULAR_EMPLOYEE"); - Entity contractEmployeeEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("CONTRACT_EMPLOYEE"); - Entity residenceEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("RESIDENCE"); - - // entities check - assertEquals(4, mapper.getDataBaseSchema().getEntities().size()); - assertEquals(1, mapper.getDataBaseSchema().getCanonicalRelationships().size()); - assertNotNull(employeeEntity); - assertNotNull(regularEmployeeEntity); - assertNotNull(contractEmployeeEntity); - assertNotNull(residenceEntity); - - // attributes check - assertEquals(3, employeeEntity.getAttributes().size()); - - assertNotNull(employeeEntity.getAttributeByName("ID")); - assertEquals("ID", employeeEntity.getAttributeByName("ID").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("ID").getDataType()); - assertEquals(1, employeeEntity.getAttributeByName("ID").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(employeeEntity.getAttributeByName("NAME")); - assertEquals("NAME", employeeEntity.getAttributeByName("NAME").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("NAME").getDataType()); - assertEquals(2, employeeEntity.getAttributeByName("NAME").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(employeeEntity.getAttributeByName("RESIDENCE")); - assertEquals("RESIDENCE", employeeEntity.getAttributeByName("RESIDENCE").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("RESIDENCE").getDataType()); - assertEquals(3, employeeEntity.getAttributeByName("RESIDENCE").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("RESIDENCE").getBelongingEntity().getName()); - - assertEquals(2, regularEmployeeEntity.getAttributes().size()); - - assertNotNull(regularEmployeeEntity.getAttributeByName("SALARY")); - assertEquals("SALARY", regularEmployeeEntity.getAttributeByName("SALARY").getName()); - assertEquals("DECIMAL", regularEmployeeEntity.getAttributeByName("SALARY").getDataType()); - assertEquals(1, regularEmployeeEntity.getAttributeByName("SALARY").getOrdinalPosition()); - assertEquals("Regular_Employee", regularEmployeeEntity.getAttributeByName("SALARY").getBelongingEntity().getName()); - - assertNotNull(regularEmployeeEntity.getAttributeByName("BONUS")); - assertEquals("BONUS", regularEmployeeEntity.getAttributeByName("BONUS").getName()); - assertEquals("DECIMAL", regularEmployeeEntity.getAttributeByName("BONUS").getDataType()); - assertEquals(2, regularEmployeeEntity.getAttributeByName("BONUS").getOrdinalPosition()); - assertEquals("Regular_Employee", regularEmployeeEntity.getAttributeByName("BONUS").getBelongingEntity().getName()); - - assertEquals(2, contractEmployeeEntity.getAttributes().size()); - - assertNotNull(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR")); - assertEquals("PAY_PER_HOUR", contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getName()); - assertEquals("DECIMAL", contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getDataType()); - assertEquals(1, contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getOrdinalPosition()); - assertEquals("Contract_Employee", contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getBelongingEntity().getName()); - - assertNotNull(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION")); - assertEquals("CONTRACT_DURATION", contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getDataType()); - assertEquals(2, contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getOrdinalPosition()); - assertEquals("Contract_Employee", contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getBelongingEntity().getName()); - - // inherited attributes check - assertEquals(0, employeeEntity.getInheritedAttributes().size()); - - assertEquals(3, regularEmployeeEntity.getInheritedAttributes().size()); - - assertNotNull(regularEmployeeEntity.getInheritedAttributeByName("ID")); - assertEquals("ID", regularEmployeeEntity.getInheritedAttributeByName("ID").getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getInheritedAttributeByName("ID").getDataType()); - assertEquals(1, regularEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()); - assertEquals("EMPLOYEE", regularEmployeeEntity.getInheritedAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(regularEmployeeEntity.getInheritedAttributeByName("NAME")); - assertEquals("NAME", regularEmployeeEntity.getInheritedAttributeByName("NAME").getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()); - assertEquals(2, regularEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()); - assertEquals("EMPLOYEE", regularEmployeeEntity.getInheritedAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE")); - assertEquals("RESIDENCE", regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()); - assertEquals(3, regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()); - assertEquals("EMPLOYEE", regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getBelongingEntity().getName()); - - assertEquals(3, contractEmployeeEntity.getInheritedAttributes().size()); - - assertNotNull(contractEmployeeEntity.getInheritedAttributeByName("ID")); - assertEquals("ID", contractEmployeeEntity.getInheritedAttributeByName("ID").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getInheritedAttributeByName("ID").getDataType()); - assertEquals(1, contractEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()); - assertEquals("EMPLOYEE", contractEmployeeEntity.getInheritedAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(contractEmployeeEntity.getInheritedAttributeByName("NAME")); - assertEquals("NAME", contractEmployeeEntity.getInheritedAttributeByName("NAME").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()); - assertEquals(2, contractEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()); - assertEquals("EMPLOYEE", contractEmployeeEntity.getInheritedAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE")); - assertEquals("RESIDENCE", contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()); - assertEquals(3, contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()); - assertEquals("EMPLOYEE", contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getBelongingEntity().getName()); - - // primary key check - assertEquals(1, regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()); - assertEquals("ID", regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()); - assertEquals("EMPLOYEE", regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getBelongingEntity().getName()); - - assertEquals(1, contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()); - assertEquals("ID", contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()); - assertEquals("EMPLOYEE", contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getBelongingEntity().getName()); - - // relationship, primary and foreign key check - assertEquals(0, regularEmployeeEntity.getOutCanonicalRelationships().size()); - assertEquals(0, contractEmployeeEntity.getOutCanonicalRelationships().size()); - assertEquals(1, employeeEntity.getOutCanonicalRelationships().size()); - assertEquals(0, residenceEntity.getOutCanonicalRelationships().size()); - assertEquals(0, regularEmployeeEntity.getInCanonicalRelationships().size()); - assertEquals(0, contractEmployeeEntity.getInCanonicalRelationships().size()); - assertEquals(0, employeeEntity.getInCanonicalRelationships().size()); - assertEquals(1, residenceEntity.getInCanonicalRelationships().size()); - - assertEquals(0, regularEmployeeEntity.getForeignKeys().size()); - assertEquals(0, contractEmployeeEntity.getForeignKeys().size()); - assertEquals(1, employeeEntity.getForeignKeys().size()); - assertEquals(0, residenceEntity.getForeignKeys().size()); - - Iterator itEmp = employeeEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship currentEmpRel = itEmp.next(); - assertEquals("RESIDENCE", currentEmpRel.getParentEntity().getName()); - assertEquals("EMPLOYEE", currentEmpRel.getForeignEntity().getName()); - assertEquals(residenceEntity.getPrimaryKey(), currentEmpRel.getPrimaryKey()); - assertEquals(employeeEntity.getForeignKeys().get(0), currentEmpRel.getForeignKey()); - assertFalse(itEmp.hasNext()); - - Iterator itRes = residenceEntity.getInCanonicalRelationships().iterator(); - CanonicalRelationship currentResRel = itRes.next(); - assertEquals(currentEmpRel, currentResRel); - - // inherited relationships check - assertEquals(1, regularEmployeeEntity.getInheritedOutCanonicalRelationships().size()); - assertEquals(1, contractEmployeeEntity.getInheritedOutCanonicalRelationships().size()); - assertEquals(0, employeeEntity.getInheritedOutCanonicalRelationships().size()); - assertEquals(0, residenceEntity.getInheritedOutCanonicalRelationships().size()); - - Iterator itRegEmp = regularEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); - Iterator itContEmp = contractEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); - CanonicalRelationship currentRegEmpRel = itRegEmp.next(); - CanonicalRelationship currentContEmpRel = itContEmp.next(); - assertEquals("RESIDENCE", currentRegEmpRel.getParentEntity().getName()); - assertEquals("EMPLOYEE", currentRegEmpRel.getForeignEntity().getName()); - assertEquals("RESIDENCE", currentContEmpRel.getParentEntity().getName()); - assertEquals("EMPLOYEE", currentContEmpRel.getForeignEntity().getName()); - assertEquals(residenceEntity.getPrimaryKey(), currentRegEmpRel.getPrimaryKey()); - assertEquals(1, currentRegEmpRel.getFromColumns().size()); - assertEquals("RESIDENCE", currentRegEmpRel.getFromColumns().get(0).getName()); - assertEquals(residenceEntity.getPrimaryKey(), currentContEmpRel.getPrimaryKey()); - assertEquals(1, currentContEmpRel.getFromColumns().size()); - assertEquals("RESIDENCE", currentContEmpRel.getFromColumns().get(0).getName()); - assertFalse(itRegEmp.hasNext()); - assertFalse(itContEmp.hasNext()); - - // inheritance check - assertEquals(employeeEntity, regularEmployeeEntity.getParentEntity()); - assertEquals(employeeEntity, contractEmployeeEntity.getParentEntity()); - assertNull(employeeEntity.getParentEntity()); - assertNull(residenceEntity.getParentEntity()); - - assertEquals(1, regularEmployeeEntity.getInheritanceLevel()); - assertEquals(1, contractEmployeeEntity.getInheritanceLevel()); - assertEquals(0, employeeEntity.getInheritanceLevel()); - assertEquals(0, residenceEntity.getInheritanceLevel()); - - // Hierarchical Bag check - assertEquals(1, mapper.getDataBaseSchema().getHierarchicalBags().size()); - HierarchicalBag hierarchicalBag = mapper.getDataBaseSchema().getHierarchicalBags().get(0); - assertEquals("table-per-hierarchy", hierarchicalBag.getInheritancePattern()); - - assertEquals(2, hierarchicalBag.getDepth2entities().size()); - - assertEquals(1, hierarchicalBag.getDepth2entities().get(0).size()); - Iterator it = hierarchicalBag.getDepth2entities().get(0).iterator(); - assertEquals("EMPLOYEE", it.next().getName()); - assertTrue(!it.hasNext()); - - assertEquals(2, hierarchicalBag.getDepth2entities().get(1).size()); - it = hierarchicalBag.getDepth2entities().get(1).iterator(); - assertEquals("Regular_Employee", it.next().getName()); - assertEquals("Contract_Employee", it.next().getName()); - assertTrue(!it.hasNext()); - - assertEquals(hierarchicalBag, employeeEntity.getHierarchicalBag()); - assertEquals(hierarchicalBag, regularEmployeeEntity.getHierarchicalBag()); - assertEquals(hierarchicalBag, contractEmployeeEntity.getHierarchicalBag()); - - assertNotNull(hierarchicalBag.getDiscriminatorColumn()); - assertEquals("TYPE", hierarchicalBag.getDiscriminatorColumn()); - - assertEquals(3, hierarchicalBag.getEntityName2discriminatorValue().size()); - assertEquals("emp", hierarchicalBag.getEntityName2discriminatorValue().get("EMPLOYEE")); - assertEquals("reg_emp", hierarchicalBag.getEntityName2discriminatorValue().get("Regular_Employee")); - assertEquals("cont_emp", hierarchicalBag.getEntityName2discriminatorValue().get("Contract_Employee")); - - /* - * Testing built graph model - */ - - VertexType employeeVertexType = mapper.getGraphModel().getVertexTypeByName("Employee"); - VertexType regularEmployeeVertexType = mapper.getGraphModel().getVertexTypeByName("RegularEmployee"); - VertexType contractEmployeeVertexType = mapper.getGraphModel().getVertexTypeByName("ContractEmployee"); - VertexType residenceVertexType = mapper.getGraphModel().getVertexTypeByName("Residence"); - - // vertices check - assertEquals(4, mapper.getGraphModel().getVerticesType().size()); - assertNotNull(employeeVertexType); - assertNotNull(regularEmployeeVertexType); - assertNotNull(contractEmployeeVertexType); - assertNotNull(residenceVertexType); - - // properties check - assertEquals(3, employeeVertexType.getProperties().size()); - - assertNotNull(employeeVertexType.getPropertyByName("id")); - assertEquals("id", employeeVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, employeeVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, employeeVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(employeeVertexType.getPropertyByName("name")); - assertEquals("name", employeeVertexType.getPropertyByName("name").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("name").getOriginalType()); - assertEquals(2, employeeVertexType.getPropertyByName("name").getOrdinalPosition()); - assertEquals(false, employeeVertexType.getPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(employeeVertexType.getPropertyByName("residence")); - assertEquals("residence", employeeVertexType.getPropertyByName("residence").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("residence").getOriginalType()); - assertEquals(3, employeeVertexType.getPropertyByName("residence").getOrdinalPosition()); - assertEquals(false, employeeVertexType.getPropertyByName("residence").isFromPrimaryKey()); - - assertEquals(2, regularEmployeeVertexType.getProperties().size()); - - assertNotNull(regularEmployeeVertexType.getPropertyByName("salary")); - assertEquals("salary", regularEmployeeVertexType.getPropertyByName("salary").getName()); - assertEquals("DECIMAL", regularEmployeeVertexType.getPropertyByName("salary").getOriginalType()); - assertEquals(1, regularEmployeeVertexType.getPropertyByName("salary").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getPropertyByName("salary").isFromPrimaryKey()); - - assertNotNull(regularEmployeeVertexType.getPropertyByName("bonus")); - assertEquals("bonus", regularEmployeeVertexType.getPropertyByName("bonus").getName()); - assertEquals("DECIMAL", regularEmployeeVertexType.getPropertyByName("bonus").getOriginalType()); - assertEquals(2, regularEmployeeVertexType.getPropertyByName("bonus").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getPropertyByName("bonus").isFromPrimaryKey()); - - assertEquals(2, contractEmployeeVertexType.getProperties().size()); - - assertNotNull(contractEmployeeVertexType.getPropertyByName("payPerHour")); - assertEquals("payPerHour", contractEmployeeVertexType.getPropertyByName("payPerHour").getName()); - assertEquals("DECIMAL", contractEmployeeVertexType.getPropertyByName("payPerHour").getOriginalType()); - assertEquals(1, contractEmployeeVertexType.getPropertyByName("payPerHour").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getPropertyByName("payPerHour").isFromPrimaryKey()); - - assertNotNull(contractEmployeeVertexType.getPropertyByName("contractDuration")); - assertEquals("contractDuration", contractEmployeeVertexType.getPropertyByName("contractDuration").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getPropertyByName("contractDuration").getOriginalType()); - assertEquals(2, contractEmployeeVertexType.getPropertyByName("contractDuration").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getPropertyByName("contractDuration").isFromPrimaryKey()); - - assertEquals(3, residenceVertexType.getProperties().size()); - - assertNotNull(residenceVertexType.getPropertyByName("id")); - assertEquals("id", residenceVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", residenceVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, residenceVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, residenceVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(residenceVertexType.getPropertyByName("city")); - assertEquals("city", residenceVertexType.getPropertyByName("city").getName()); - assertEquals("VARCHAR", residenceVertexType.getPropertyByName("city").getOriginalType()); - assertEquals(2, residenceVertexType.getPropertyByName("city").getOrdinalPosition()); - assertEquals(false, residenceVertexType.getPropertyByName("city").isFromPrimaryKey()); - - assertNotNull(residenceVertexType.getPropertyByName("country")); - assertEquals("country", residenceVertexType.getPropertyByName("country").getName()); - assertEquals("VARCHAR", residenceVertexType.getPropertyByName("country").getOriginalType()); - assertEquals(3, residenceVertexType.getPropertyByName("country").getOrdinalPosition()); - assertEquals(false, residenceVertexType.getPropertyByName("country").isFromPrimaryKey()); - - // inherited properties check - assertEquals(0, employeeVertexType.getInheritedProperties().size()); - - assertEquals(3, regularEmployeeVertexType.getInheritedProperties().size()); - - assertNotNull(regularEmployeeVertexType.getInheritedPropertyByName("id")); - assertEquals("id", regularEmployeeVertexType.getInheritedPropertyByName("id").getName()); - assertEquals("VARCHAR", regularEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()); - assertEquals(1, regularEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()); - assertEquals(true, regularEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(regularEmployeeVertexType.getInheritedPropertyByName("name")); - assertEquals("name", regularEmployeeVertexType.getInheritedPropertyByName("name").getName()); - assertEquals("VARCHAR", regularEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()); - assertEquals(2, regularEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(regularEmployeeVertexType.getInheritedPropertyByName("residence")); - assertEquals("residence", regularEmployeeVertexType.getInheritedPropertyByName("residence").getName()); - assertEquals("VARCHAR", regularEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()); - assertEquals(3, regularEmployeeVertexType.getInheritedPropertyByName("residence").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()); - - assertEquals(3, contractEmployeeVertexType.getInheritedProperties().size()); - - assertNotNull(contractEmployeeVertexType.getInheritedPropertyByName("id")); - assertEquals("id", contractEmployeeVertexType.getInheritedPropertyByName("id").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()); - assertEquals(1, contractEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()); - assertEquals(true, contractEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(contractEmployeeVertexType.getInheritedPropertyByName("name")); - assertEquals("name", contractEmployeeVertexType.getInheritedPropertyByName("name").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()); - assertEquals(2, contractEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(contractEmployeeVertexType.getInheritedPropertyByName("residence")); - assertEquals("residence", contractEmployeeVertexType.getInheritedPropertyByName("residence").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()); - assertEquals(3, contractEmployeeVertexType.getInheritedPropertyByName("residence").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()); - - assertEquals(0, residenceVertexType.getInheritedProperties().size()); - - // edges check - - assertEquals(1, mapper.getRelationship2edgeType().size()); - - assertEquals(1, mapper.getGraphModel().getEdgesType().size()); - assertEquals("HasResidence", mapper.getGraphModel().getEdgesType().get(0).getName()); - - assertEquals(1, employeeVertexType.getOutEdgesType().size()); - assertEquals("HasResidence", employeeVertexType.getOutEdgesType().get(0).getName()); - - assertEquals(1, regularEmployeeVertexType.getOutEdgesType().size()); - assertEquals("HasResidence", regularEmployeeVertexType.getOutEdgesType().get(0).getName()); - - assertEquals(1, contractEmployeeVertexType.getOutEdgesType().size()); - assertEquals("HasResidence", contractEmployeeVertexType.getOutEdgesType().get(0).getName()); - - // inheritance check - assertEquals(employeeVertexType, regularEmployeeVertexType.getParentType()); - assertEquals(employeeVertexType, contractEmployeeVertexType.getParentType()); - assertNull(employeeVertexType.getParentType()); - - assertEquals(1, regularEmployeeVertexType.getInheritanceLevel()); - assertEquals(1, contractEmployeeVertexType.getInheritanceLevel()); - assertEquals(0, employeeVertexType.getInheritanceLevel()); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } finally { - try { - // Dropping Source DB Schema and OrientGraph - String dbDropping = "drop schema public cascade"; - st.execute(dbDropping); - connection.close(); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } - } +class HibernateMapperTest { + + private static final String XML_TABLE_PER_CLASS = + "src/test/resources/provider/rdbms/inheritance/hibernate/tablePerClassHierarchyInheritanceTest.xml"; + private static final String XML_TABLE_PER_SUBCLASS1 = + "src/test/resources/provider/rdbms/inheritance/hibernate/tablePerSubclassInheritanceTest1.xml"; + private static final String XML_TABLE_PER_SUBCLASS2 = + "src/test/resources/provider/rdbms/inheritance/hibernate/tablePerSubclassInheritanceTest2.xml"; + private static final String XML_TABLE_PER_CONCRETE_CLASS = + "src/test/resources/provider/rdbms/inheritance/hibernate/tablePerConcreteClassInheritanceTest.xml"; + private ER2GraphMapper mapper; + private DBQueryEngine dbQueryEngine; + private String driver = "org.hsqldb.jdbc.JDBCDriver"; + private String jurl = "jdbc:hsqldb:mem:mydb"; + private String username = "SA"; + private String password = ""; + private DataSourceInfo dataSource; + private String executionStrategy; + private JavaConventionNameResolver nameResolver; + private HSQLDBDataTypeHandler dataTypeHandler; + private Statistics statistics; + + @BeforeEach + void init() { + this.dataSource = + new DataSourceInfo( + 1L, + "RDBMS_HSQL", + "testDataSource", + "desc", + "mem", + 1234, + "mydb", + username, + password, + false, + "{}", + false, + false, + "", + 22, + "", + false); + + dbQueryEngine = new DBQueryEngine(dataSource, 300); + executionStrategy = "not_specified"; + nameResolver = new JavaConventionNameResolver(); + dataTypeHandler = new HSQLDBDataTypeHandler(); + statistics = new Statistics(); + } + + /* + * Table per Class Hierarchy Inheritance ( tag) + * table ( http://www.javatpoint.com/hibernate-table-per-hierarchy-example-using-xml-file ) + */ + + @Test + void TablePerClassHierarchyInheritance() { + Connection connection = null; + Statement st = null; + + try { + Class.forName(this.driver); + connection = DriverManager.getConnection(this.jurl, this.username, this.password); + + String residence = + "create memory table RESIDENCE(ID varchar(256) not null, CITY varchar(256), COUNTRY" + + " varchar(256), primary key (ID))"; + st = connection.createStatement(); + st.execute(residence); + + String employeeTableBuilding = + "create memory table EMPLOYEE (ID varchar(256) not null, TYPE varchar(256), NAME" + + " varchar(256), SALARY decimal(10,2), BONUS decimal(10,0), PAY_PER_HOUR" + + " decimal(10,2), CONTRACT_DURATION varchar(256), RESIDENCE varchar(256),primary key" + + " (id), foreign key (RESIDENCE) references RESIDENCE(ID))"; + st.execute(employeeTableBuilding); + + this.mapper = + new Hibernate2GraphMapper( + dataSource, + HibernateMapperTest.XML_TABLE_PER_CLASS, + null, + null, + dbQueryEngine, + dataTypeHandler, + executionStrategy, + nameResolver, + statistics); + + mapper.buildSourceDatabaseSchema(); + mapper.buildGraphModel(new JavaConventionNameResolver()); + + /* + * Testing context information + */ + + assertThat(statistics.totalNumberOfEntities).isEqualTo(2); + assertThat(statistics.builtEntities).isEqualTo(2); + assertThat(statistics.totalNumberOfRelationships).isEqualTo(1); + assertThat(statistics.builtRelationships).isEqualTo(1); + + assertThat(statistics.totalNumberOfModelVertices).isEqualTo(4); + assertThat(statistics.builtModelVertexTypes).isEqualTo(4); + assertThat(statistics.totalNumberOfModelEdges).isEqualTo(1); + assertThat(statistics.builtModelEdgeTypes).isEqualTo(1); + + /* + * Testing built source db schema + */ + + Entity employeeEntity = mapper.getDataBaseSchema().getEntityByName("EMPLOYEE"); + Entity regularEmployeeEntity = + mapper.getDataBaseSchema().getEntityByNameIgnoreCase("REGULAR_EMPLOYEE"); + Entity contractEmployeeEntity = + mapper.getDataBaseSchema().getEntityByNameIgnoreCase("CONTRACT_EMPLOYEE"); + Entity residenceEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("RESIDENCE"); + + // entities check + assertThat(mapper.getDataBaseSchema().getEntities().size()).isEqualTo(4); + assertThat(mapper.getDataBaseSchema().getCanonicalRelationships().size()).isEqualTo(1); + assertThat(employeeEntity).isNotNull(); + assertThat(regularEmployeeEntity).isNotNull(); + assertThat(contractEmployeeEntity).isNotNull(); + assertThat(residenceEntity).isNotNull(); + + // attributes check + assertThat(employeeEntity.getAttributes().size()).isEqualTo(3); + + assertThat(employeeEntity.getAttributeByName("ID")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(employeeEntity.getAttributeByName("ID").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("ID").getOrdinalPosition()).isEqualTo(1); + assertThat(employeeEntity.getAttributeByName("ID").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(employeeEntity.getAttributeByName("NAME")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("NAME").getName()).isEqualTo("NAME"); + assertThat(employeeEntity.getAttributeByName("NAME").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("NAME").getOrdinalPosition()).isEqualTo(2); + assertThat(employeeEntity.getAttributeByName("NAME").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(employeeEntity.getAttributeByName("RESIDENCE")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getName()).isEqualTo("RESIDENCE"); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getOrdinalPosition()).isEqualTo(3); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(regularEmployeeEntity.getAttributes().size()).isEqualTo(2); + + assertThat(regularEmployeeEntity.getAttributeByName("SALARY")).isNotNull(); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getName()).isEqualTo("SALARY"); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getDataType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getOrdinalPosition()) + .isEqualTo(1); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getBelongingEntity().getName()) + .isEqualTo("Regular_Employee"); + + assertThat(regularEmployeeEntity.getAttributeByName("BONUS")).isNotNull(); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getName()).isEqualTo("BONUS"); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getDataType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getOrdinalPosition()) + .isEqualTo(2); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getBelongingEntity().getName()) + .isEqualTo("Regular_Employee"); + + assertThat(contractEmployeeEntity.getAttributes().size()).isEqualTo(2); + + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR")).isNotNull(); + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getName()) + .isEqualTo("PAY_PER_HOUR"); + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getDataType()) + .isEqualTo("DECIMAL"); + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getOrdinalPosition()) + .isEqualTo(1); + assertThat( + contractEmployeeEntity + .getAttributeByName("PAY_PER_HOUR") + .getBelongingEntity() + .getName()) + .isEqualTo("Contract_Employee"); + + assertThat(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION")).isNotNull(); + assertThat(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getName()) + .isEqualTo("CONTRACT_DURATION"); + assertThat(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + contractEmployeeEntity + .getAttributeByName("CONTRACT_DURATION") + .getBelongingEntity() + .getName()) + .isEqualTo("Contract_Employee"); + + // inherited attributes check + assertThat(employeeEntity.getInheritedAttributes().size()).isEqualTo(0); + + assertThat(regularEmployeeEntity.getInheritedAttributes().size()).isEqualTo(3); + + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID")).isNotNull(); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()) + .isEqualTo(1); + assertThat( + regularEmployeeEntity + .getInheritedAttributeByName("ID") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME")).isNotNull(); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME").getName()) + .isEqualTo("NAME"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + regularEmployeeEntity + .getInheritedAttributeByName("NAME") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE")).isNotNull(); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()) + .isEqualTo("RESIDENCE"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()) + .isEqualTo(3); + assertThat( + regularEmployeeEntity + .getInheritedAttributeByName("RESIDENCE") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(contractEmployeeEntity.getInheritedAttributes().size()).isEqualTo(3); + + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID")).isNotNull(); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID").getName()) + .isEqualTo("ID"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()) + .isEqualTo(1); + assertThat( + contractEmployeeEntity + .getInheritedAttributeByName("ID") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME")).isNotNull(); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME").getName()) + .isEqualTo("NAME"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + contractEmployeeEntity + .getInheritedAttributeByName("NAME") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE")).isNotNull(); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()) + .isEqualTo("RESIDENCE"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()) + .isEqualTo(3); + assertThat( + contractEmployeeEntity + .getInheritedAttributeByName("RESIDENCE") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + // primary key check + assertThat(regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()).isEqualTo(1); + assertThat(regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()) + .isEqualTo("ID"); + assertThat(regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + regularEmployeeEntity + .getPrimaryKey() + .getInvolvedAttributes() + .get(0) + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()) + .isEqualTo(1); + assertThat(contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()) + .isEqualTo("ID"); + assertThat( + contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeEntity + .getPrimaryKey() + .getInvolvedAttributes() + .get(0) + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + // relationship, primary and foreign key check + assertThat(regularEmployeeEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(contractEmployeeEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(employeeEntity.getOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(residenceEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(regularEmployeeEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(contractEmployeeEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(employeeEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(residenceEntity.getInCanonicalRelationships().size()).isEqualTo(1); + + assertThat(regularEmployeeEntity.getForeignKeys().size()).isEqualTo(0); + assertThat(contractEmployeeEntity.getForeignKeys().size()).isEqualTo(0); + assertThat(employeeEntity.getForeignKeys().size()).isEqualTo(1); + assertThat(residenceEntity.getForeignKeys().size()).isEqualTo(0); + + Iterator itEmp = + employeeEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship currentEmpRel = itEmp.next(); + assertThat(currentEmpRel.getParentEntity().getName()).isEqualTo("RESIDENCE"); + assertThat(currentEmpRel.getForeignEntity().getName()).isEqualTo("EMPLOYEE"); + assertThat(currentEmpRel.getPrimaryKey()).isEqualTo(residenceEntity.getPrimaryKey()); + assertThat(currentEmpRel.getForeignKey()).isEqualTo(employeeEntity.getForeignKeys().get(0)); + assertThat(itEmp.hasNext()).isFalse(); + + Iterator itRes = + residenceEntity.getInCanonicalRelationships().iterator(); + CanonicalRelationship currentResRel = itRes.next(); + assertThat(currentResRel).isEqualTo(currentEmpRel); + + // inherited relationships check + assertThat(regularEmployeeEntity.getInheritedOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(contractEmployeeEntity.getInheritedOutCanonicalRelationships().size()) + .isEqualTo(1); + assertThat(employeeEntity.getInheritedOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(residenceEntity.getInheritedOutCanonicalRelationships().size()).isEqualTo(0); + + Iterator itRegEmp = + regularEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); + Iterator itContEmp = + contractEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); + CanonicalRelationship currentRegEmpRel = itRegEmp.next(); + CanonicalRelationship currentContEmpRel = itContEmp.next(); + assertThat(currentRegEmpRel.getParentEntity().getName()).isEqualTo("RESIDENCE"); + assertThat(currentRegEmpRel.getForeignEntity().getName()).isEqualTo("EMPLOYEE"); + assertThat(currentContEmpRel.getParentEntity().getName()).isEqualTo("RESIDENCE"); + assertThat(currentContEmpRel.getForeignEntity().getName()).isEqualTo("EMPLOYEE"); + assertThat(currentRegEmpRel.getPrimaryKey()).isEqualTo(residenceEntity.getPrimaryKey()); + assertThat(currentRegEmpRel.getFromColumns().size()).isEqualTo(1); + assertThat(currentRegEmpRel.getFromColumns().get(0).getName()).isEqualTo("RESIDENCE"); + assertThat(currentContEmpRel.getPrimaryKey()).isEqualTo(residenceEntity.getPrimaryKey()); + assertThat(currentContEmpRel.getFromColumns().size()).isEqualTo(1); + assertThat(currentContEmpRel.getFromColumns().get(0).getName()).isEqualTo("RESIDENCE"); + assertThat(itRegEmp.hasNext()).isFalse(); + assertThat(itContEmp.hasNext()).isFalse(); + + // inheritance check + assertThat(regularEmployeeEntity.getParentEntity()).isEqualTo(employeeEntity); + assertThat(contractEmployeeEntity.getParentEntity()).isEqualTo(employeeEntity); + assertThat(employeeEntity.getParentEntity()).isNull(); + assertThat(residenceEntity.getParentEntity()).isNull(); + + assertThat(regularEmployeeEntity.getInheritanceLevel()).isEqualTo(1); + assertThat(contractEmployeeEntity.getInheritanceLevel()).isEqualTo(1); + assertThat(employeeEntity.getInheritanceLevel()).isEqualTo(0); + assertThat(residenceEntity.getInheritanceLevel()).isEqualTo(0); + + // Hierarchical Bag check + assertThat(mapper.getDataBaseSchema().getHierarchicalBags().size()).isEqualTo(1); + HierarchicalBag hierarchicalBag = mapper.getDataBaseSchema().getHierarchicalBags().get(0); + assertThat(hierarchicalBag.getInheritancePattern()).isEqualTo("table-per-hierarchy"); + + assertThat(hierarchicalBag.getDepth2entities().size()).isEqualTo(2); + + assertThat(hierarchicalBag.getDepth2entities().get(0).size()).isEqualTo(1); + Iterator it = hierarchicalBag.getDepth2entities().get(0).iterator(); + assertThat(it.next().getName()).isEqualTo("EMPLOYEE"); + assertThat(it.hasNext()).isFalse(); + + assertThat(hierarchicalBag.getDepth2entities().get(1).size()).isEqualTo(2); + it = hierarchicalBag.getDepth2entities().get(1).iterator(); + assertThat(it.next().getName()).isEqualTo("Regular_Employee"); + assertThat(it.next().getName()).isEqualTo("Contract_Employee"); + assertThat(it.hasNext()).isFalse(); + + assertThat(employeeEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag); + assertThat(regularEmployeeEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag); + assertThat(contractEmployeeEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag); + + assertThat(hierarchicalBag.getDiscriminatorColumn()).isNotNull(); + assertThat(hierarchicalBag.getDiscriminatorColumn()).isEqualTo("TYPE"); + + assertThat(hierarchicalBag.getEntityName2discriminatorValue().size()).isEqualTo(3); + assertThat(hierarchicalBag.getEntityName2discriminatorValue().get("EMPLOYEE")) + .isEqualTo("emp"); + assertThat(hierarchicalBag.getEntityName2discriminatorValue().get("Regular_Employee")) + .isEqualTo("reg_emp"); + assertThat(hierarchicalBag.getEntityName2discriminatorValue().get("Contract_Employee")) + .isEqualTo("cont_emp"); + + /* + * Testing built graph model + */ + + VertexType employeeVertexType = mapper.getGraphModel().getVertexTypeByName("Employee"); + VertexType regularEmployeeVertexType = + mapper.getGraphModel().getVertexTypeByName("RegularEmployee"); + VertexType contractEmployeeVertexType = + mapper.getGraphModel().getVertexTypeByName("ContractEmployee"); + VertexType residenceVertexType = mapper.getGraphModel().getVertexTypeByName("Residence"); + + // vertices check + assertThat(mapper.getGraphModel().getVerticesType().size()).isEqualTo(4); + assertThat(employeeVertexType).isNotNull(); + assertThat(regularEmployeeVertexType).isNotNull(); + assertThat(contractEmployeeVertexType).isNotNull(); + assertThat(residenceVertexType).isNotNull(); + + // properties check + assertThat(employeeVertexType.getProperties().size()).isEqualTo(3); + + assertThat(employeeVertexType.getPropertyByName("id")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(employeeVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(employeeVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(employeeVertexType.getPropertyByName("name")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("name").getName()).isEqualTo("name"); + assertThat(employeeVertexType.getPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("name").getOrdinalPosition()).isEqualTo(2); + assertThat(employeeVertexType.getPropertyByName("name").isFromPrimaryKey()).isFalse(); + + assertThat(employeeVertexType.getPropertyByName("residence")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("residence").getName()) + .isEqualTo("residence"); + assertThat(employeeVertexType.getPropertyByName("residence").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("residence").getOrdinalPosition()) + .isEqualTo(3); + assertThat(employeeVertexType.getPropertyByName("residence").isFromPrimaryKey()).isFalse(); + + assertThat(regularEmployeeVertexType.getProperties().size()).isEqualTo(2); + + assertThat(regularEmployeeVertexType.getPropertyByName("salary")).isNotNull(); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").getName()) + .isEqualTo("salary"); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").getOriginalType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").getOrdinalPosition()) + .isEqualTo(1); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").isFromPrimaryKey()) + .isFalse(); + + assertThat(regularEmployeeVertexType.getPropertyByName("bonus")).isNotNull(); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").getName()).isEqualTo("bonus"); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").getOriginalType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").getOrdinalPosition()) + .isEqualTo(2); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").isFromPrimaryKey()).isFalse(); + + assertThat(contractEmployeeVertexType.getProperties().size()).isEqualTo(2); + + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour")).isNotNull(); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").getName()) + .isEqualTo("payPerHour"); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").getOriginalType()) + .isEqualTo("DECIMAL"); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").getOrdinalPosition()) + .isEqualTo(1); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getPropertyByName("contractDuration")).isNotNull(); + assertThat(contractEmployeeVertexType.getPropertyByName("contractDuration").getName()) + .isEqualTo("contractDuration"); + assertThat(contractEmployeeVertexType.getPropertyByName("contractDuration").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeVertexType.getPropertyByName("contractDuration").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + contractEmployeeVertexType.getPropertyByName("contractDuration").isFromPrimaryKey()) + .isFalse(); + + assertThat(residenceVertexType.getProperties().size()).isEqualTo(3); + + assertThat(residenceVertexType.getPropertyByName("id")).isNotNull(); + assertThat(residenceVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(residenceVertexType.getPropertyByName("id").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(residenceVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(residenceVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(residenceVertexType.getPropertyByName("city")).isNotNull(); + assertThat(residenceVertexType.getPropertyByName("city").getName()).isEqualTo("city"); + assertThat(residenceVertexType.getPropertyByName("city").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(residenceVertexType.getPropertyByName("city").getOrdinalPosition()).isEqualTo(2); + assertThat(residenceVertexType.getPropertyByName("city").isFromPrimaryKey()).isFalse(); + + assertThat(residenceVertexType.getPropertyByName("country")).isNotNull(); + assertThat(residenceVertexType.getPropertyByName("country").getName()).isEqualTo("country"); + assertThat(residenceVertexType.getPropertyByName("country").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(residenceVertexType.getPropertyByName("country").getOrdinalPosition()) + .isEqualTo(3); + assertThat(residenceVertexType.getPropertyByName("country").isFromPrimaryKey()).isFalse(); + + // inherited properties check + assertThat(employeeVertexType.getInheritedProperties().size()).isEqualTo(0); + + assertThat(regularEmployeeVertexType.getInheritedProperties().size()).isEqualTo(3); + + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id")).isNotNull(); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").getName()) + .isEqualTo("id"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()) + .isEqualTo(1); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()) + .isTrue(); + + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name")).isNotNull(); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").getName()) + .isEqualTo("name"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()) + .isEqualTo(2); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()) + .isFalse(); + + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("residence")).isNotNull(); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("residence").getName()) + .isEqualTo("residence"); + assertThat( + regularEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + regularEmployeeVertexType + .getInheritedPropertyByName("residence") + .getOrdinalPosition()) + .isEqualTo(3); + assertThat( + regularEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getInheritedProperties().size()).isEqualTo(3); + + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id")).isNotNull(); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").getName()) + .isEqualTo("id"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()) + .isEqualTo(1); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()) + .isTrue(); + + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name")).isNotNull(); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").getName()) + .isEqualTo("name"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()) + .isEqualTo(2); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("residence")).isNotNull(); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("residence").getName()) + .isEqualTo("residence"); + assertThat( + contractEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeVertexType + .getInheritedPropertyByName("residence") + .getOrdinalPosition()) + .isEqualTo(3); + assertThat( + contractEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()) + .isFalse(); + + assertThat(residenceVertexType.getInheritedProperties().size()).isEqualTo(0); + + // edges check + + assertThat(mapper.getRelationship2edgeType().size()).isEqualTo(1); + + assertThat(mapper.getGraphModel().getEdgesType().size()).isEqualTo(1); + assertThat(mapper.getGraphModel().getEdgesType().get(0).getName()).isEqualTo("HasResidence"); + + assertThat(employeeVertexType.getOutEdgesType().size()).isEqualTo(1); + assertThat(employeeVertexType.getOutEdgesType().get(0).getName()).isEqualTo("HasResidence"); + + assertThat(regularEmployeeVertexType.getOutEdgesType().size()).isEqualTo(1); + assertThat(regularEmployeeVertexType.getOutEdgesType().get(0).getName()) + .isEqualTo("HasResidence"); + + assertThat(contractEmployeeVertexType.getOutEdgesType().size()).isEqualTo(1); + assertThat(contractEmployeeVertexType.getOutEdgesType().get(0).getName()) + .isEqualTo("HasResidence"); + + // inheritance check + assertThat(regularEmployeeVertexType.getParentType()).isEqualTo(employeeVertexType); + assertThat(contractEmployeeVertexType.getParentType()).isEqualTo(employeeVertexType); + assertThat(employeeVertexType.getParentType()).isNull(); + + assertThat(regularEmployeeVertexType.getInheritanceLevel()).isEqualTo(1); + assertThat(contractEmployeeVertexType.getInheritanceLevel()).isEqualTo(1); + assertThat(employeeVertexType.getInheritanceLevel()).isEqualTo(0); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } finally { + try { + // Dropping Source DB Schema and OrientGraph + String dbDropping = "drop schema public cascade"; + st.execute(dbDropping); + connection.close(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } } - - @Test - /* - * Table per Subclass Inheritance ( tag) - * 3 tables, one parent and 2 childs ( http://www.javatpoint.com/table-per-subclass ) - */ - - public void TablePerSubclassInheritanceSyntax1() { - Connection connection = null; - Statement st = null; - - try { - Class.forName("org.hsqldb.jdbc.JDBCDriver"); - connection = DriverManager.getConnection(this.jurl, this.username, this.password); - - String residence = "create memory table RESIDENCE(ID varchar(256) not null, CITY varchar(256), COUNTRY varchar(256), primary key (ID))"; - st = connection.createStatement(); - st.execute(residence); - - String employeeTableBuilding = - "create memory table EMPLOYEE (ID varchar(256) not null," + - " NAME varchar(256), RESIDENCE varchar(256), primary key (ID), foreign key (RESIDENCE) references RESIDENCE(ID))"; - st.execute(employeeTableBuilding); - - String regularEmployeeTableBuilding = - "create memory table REGULAR_EMPLOYEE (EID varchar(256) not null, " + - "SALARY decimal(10,2), BONUS decimal(10,0), primary key (EID), foreign key (EID) references EMPLOYEE(ID))"; - st.execute(regularEmployeeTableBuilding); - - String contractEmployeeTableBuilding = - "create memory table CONTRACT_EMPLOYEE (EID varchar(256) not null, " + - "PAY_PER_HOUR decimal(10,2), CONTRACT_DURATION varchar(256), primary key (EID), foreign key (EID) references EMPLOYEE(ID))"; - st.execute(contractEmployeeTableBuilding); - - this.mapper = - new Hibernate2GraphMapper( - dataSource, - HibernateMapperTest.XML_TABLE_PER_SUBCLASS1, - null, - null, - dbQueryEngine, - dataTypeHandler, - executionStrategy, - nameResolver, - statistics - ); - - mapper.buildSourceDatabaseSchema(); - mapper.buildGraphModel(new JavaConventionNameResolver()); - - /* - * Testing context information - */ - - assertEquals(4, statistics.totalNumberOfEntities); - assertEquals(4, statistics.builtEntities); - assertEquals(3, statistics.totalNumberOfRelationships); - assertEquals(3, statistics.builtRelationships); - - assertEquals(4, statistics.totalNumberOfModelVertices); - assertEquals(4, statistics.builtModelVertexTypes); - assertEquals(1, statistics.totalNumberOfModelEdges); - assertEquals(1, statistics.builtModelEdgeTypes); - - /* - * Testing built source db schema - */ - - Entity employeeEntity = mapper.getDataBaseSchema().getEntityByName("EMPLOYEE"); - Entity regularEmployeeEntity = mapper.getDataBaseSchema().getEntityByName("REGULAR_EMPLOYEE"); - Entity contractEmployeeEntity = mapper.getDataBaseSchema().getEntityByName("CONTRACT_EMPLOYEE"); - Entity residenceEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("RESIDENCE"); - - // entities check - assertEquals(4, mapper.getDataBaseSchema().getEntities().size()); - assertEquals(3, mapper.getDataBaseSchema().getCanonicalRelationships().size()); - assertNotNull(employeeEntity); - assertNotNull(regularEmployeeEntity); - assertNotNull(contractEmployeeEntity); - assertNotNull(residenceEntity); - - // attributes check - assertEquals(3, employeeEntity.getAttributes().size()); - - assertNotNull(employeeEntity.getAttributeByName("ID")); - assertEquals("ID", employeeEntity.getAttributeByName("ID").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("ID").getDataType()); - assertEquals(1, employeeEntity.getAttributeByName("ID").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(employeeEntity.getAttributeByName("NAME")); - assertEquals("NAME", employeeEntity.getAttributeByName("NAME").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("NAME").getDataType()); - assertEquals(2, employeeEntity.getAttributeByName("NAME").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(employeeEntity.getAttributeByName("RESIDENCE")); - assertEquals("RESIDENCE", employeeEntity.getAttributeByName("RESIDENCE").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("RESIDENCE").getDataType()); - assertEquals(3, employeeEntity.getAttributeByName("RESIDENCE").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("RESIDENCE").getBelongingEntity().getName()); - - assertEquals(2, regularEmployeeEntity.getAttributes().size()); - - assertNotNull(regularEmployeeEntity.getAttributeByName("SALARY")); - assertEquals("SALARY", regularEmployeeEntity.getAttributeByName("SALARY").getName()); - assertEquals("DECIMAL", regularEmployeeEntity.getAttributeByName("SALARY").getDataType()); - assertEquals(1, regularEmployeeEntity.getAttributeByName("SALARY").getOrdinalPosition()); - assertEquals("REGULAR_EMPLOYEE", regularEmployeeEntity.getAttributeByName("SALARY").getBelongingEntity().getName()); - - assertNotNull(regularEmployeeEntity.getAttributeByName("BONUS")); - assertEquals("BONUS", regularEmployeeEntity.getAttributeByName("BONUS").getName()); - assertEquals("DECIMAL", regularEmployeeEntity.getAttributeByName("BONUS").getDataType()); - assertEquals(2, regularEmployeeEntity.getAttributeByName("BONUS").getOrdinalPosition()); - assertEquals("REGULAR_EMPLOYEE", regularEmployeeEntity.getAttributeByName("BONUS").getBelongingEntity().getName()); - - assertEquals(2, contractEmployeeEntity.getAttributes().size()); - - assertNotNull(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR")); - assertEquals("PAY_PER_HOUR", contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getName()); - assertEquals("DECIMAL", contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getDataType()); - assertEquals(1, contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getOrdinalPosition()); - assertEquals("CONTRACT_EMPLOYEE", contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getBelongingEntity().getName()); - - assertNotNull(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION")); - assertEquals("CONTRACT_DURATION", contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getDataType()); - assertEquals(2, contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getOrdinalPosition()); - assertEquals("CONTRACT_EMPLOYEE", contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getBelongingEntity().getName()); - - // inherited attributes check - assertEquals(0, employeeEntity.getInheritedAttributes().size()); - - assertEquals(3, regularEmployeeEntity.getInheritedAttributes().size()); - - assertNotNull(regularEmployeeEntity.getInheritedAttributeByName("ID")); - assertEquals("ID", regularEmployeeEntity.getInheritedAttributeByName("ID").getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getInheritedAttributeByName("ID").getDataType()); - assertEquals(1, regularEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()); - assertEquals("EMPLOYEE", regularEmployeeEntity.getInheritedAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(regularEmployeeEntity.getInheritedAttributeByName("NAME")); - assertEquals("NAME", regularEmployeeEntity.getInheritedAttributeByName("NAME").getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()); - assertEquals(2, regularEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()); - assertEquals("EMPLOYEE", regularEmployeeEntity.getInheritedAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE")); - assertEquals("RESIDENCE", regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()); - assertEquals(3, regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()); - assertEquals("EMPLOYEE", regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getBelongingEntity().getName()); - - assertEquals(3, contractEmployeeEntity.getInheritedAttributes().size()); - - assertNotNull(contractEmployeeEntity.getInheritedAttributeByName("ID")); - assertEquals("ID", contractEmployeeEntity.getInheritedAttributeByName("ID").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getInheritedAttributeByName("ID").getDataType()); - assertEquals(1, contractEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()); - assertEquals("EMPLOYEE", contractEmployeeEntity.getInheritedAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(contractEmployeeEntity.getInheritedAttributeByName("NAME")); - assertEquals("NAME", contractEmployeeEntity.getInheritedAttributeByName("NAME").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()); - assertEquals(2, contractEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()); - assertEquals("EMPLOYEE", contractEmployeeEntity.getInheritedAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE")); - assertEquals("RESIDENCE", contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()); - assertEquals(3, contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()); - assertEquals("EMPLOYEE", contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getBelongingEntity().getName()); - - // primary key check - assertEquals(1, regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()); - assertEquals("EID", regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()); - assertEquals("REGULAR_EMPLOYEE", regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getBelongingEntity().getName()); - - assertEquals(1, contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()); - assertEquals("EID", contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()); - assertEquals("CONTRACT_EMPLOYEE", contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getBelongingEntity().getName()); - - // relationship, primary and foreign key check - assertEquals(1, regularEmployeeEntity.getOutCanonicalRelationships().size()); - assertEquals(1, contractEmployeeEntity.getOutCanonicalRelationships().size()); - assertEquals(1, employeeEntity.getOutCanonicalRelationships().size()); - assertEquals(0, residenceEntity.getOutCanonicalRelationships().size()); - assertEquals(0, regularEmployeeEntity.getInCanonicalRelationships().size()); - assertEquals(0, contractEmployeeEntity.getInCanonicalRelationships().size()); - assertEquals(2, employeeEntity.getInCanonicalRelationships().size()); - assertEquals(1, residenceEntity.getInCanonicalRelationships().size()); - - assertEquals(1, regularEmployeeEntity.getForeignKeys().size()); - assertEquals(1, contractEmployeeEntity.getForeignKeys().size()); - assertEquals(1, employeeEntity.getForeignKeys().size()); - assertEquals(0, residenceEntity.getForeignKeys().size()); - - Iterator itEmp = employeeEntity.getOutCanonicalRelationships().iterator(); - Iterator itRegEmp = regularEmployeeEntity.getOutCanonicalRelationships().iterator(); - Iterator itContEmp = contractEmployeeEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship currentEmpRel = itEmp.next(); - CanonicalRelationship currentRegEmpRel = itRegEmp.next(); - CanonicalRelationship currentContEmpRel = itContEmp.next(); - assertEquals("RESIDENCE", currentEmpRel.getParentEntity().getName()); - assertEquals("EMPLOYEE", currentEmpRel.getForeignEntity().getName()); - assertEquals("EMPLOYEE", currentRegEmpRel.getParentEntity().getName()); - assertEquals("REGULAR_EMPLOYEE", currentRegEmpRel.getForeignEntity().getName()); - assertEquals("EMPLOYEE", currentContEmpRel.getParentEntity().getName()); - assertEquals("CONTRACT_EMPLOYEE", currentContEmpRel.getForeignEntity().getName()); - assertEquals(residenceEntity.getPrimaryKey(), currentEmpRel.getPrimaryKey()); - assertEquals(employeeEntity.getForeignKeys().get(0), currentEmpRel.getForeignKey()); - assertEquals(employeeEntity.getPrimaryKey(), currentRegEmpRel.getPrimaryKey()); - assertEquals(regularEmployeeEntity.getForeignKeys().get(0), currentRegEmpRel.getForeignKey()); - assertEquals(employeeEntity.getPrimaryKey(), currentContEmpRel.getPrimaryKey()); - assertEquals(contractEmployeeEntity.getForeignKeys().get(0), currentContEmpRel.getForeignKey()); - assertFalse(itEmp.hasNext()); - assertFalse(itRegEmp.hasNext()); - assertFalse(itContEmp.hasNext()); - - Iterator itRes = residenceEntity.getInCanonicalRelationships().iterator(); - CanonicalRelationship currentResRel = itRes.next(); - assertEquals(currentEmpRel, currentResRel); - - itEmp = employeeEntity.getInCanonicalRelationships().iterator(); - currentEmpRel = itEmp.next(); - assertEquals(currentEmpRel, currentContEmpRel); - - currentEmpRel = itEmp.next(); - assertEquals(currentEmpRel, currentRegEmpRel); - - // inherited relationships check - assertEquals(1, regularEmployeeEntity.getInheritedOutCanonicalRelationships().size()); - assertEquals(1, contractEmployeeEntity.getInheritedOutCanonicalRelationships().size()); - assertEquals(0, employeeEntity.getInheritedOutCanonicalRelationships().size()); - assertEquals(0, residenceEntity.getInheritedOutCanonicalRelationships().size()); - - itRegEmp = regularEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); - itContEmp = contractEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); - currentRegEmpRel = itRegEmp.next(); - currentContEmpRel = itContEmp.next(); - assertEquals("RESIDENCE", currentRegEmpRel.getParentEntity().getName()); - assertEquals("EMPLOYEE", currentRegEmpRel.getForeignEntity().getName()); - assertEquals("RESIDENCE", currentContEmpRel.getParentEntity().getName()); - assertEquals("EMPLOYEE", currentContEmpRel.getForeignEntity().getName()); - assertEquals(residenceEntity.getPrimaryKey(), currentRegEmpRel.getPrimaryKey()); - assertEquals(1, currentRegEmpRel.getFromColumns().size()); - assertEquals("RESIDENCE", currentRegEmpRel.getFromColumns().get(0).getName()); - assertEquals(residenceEntity.getPrimaryKey(), currentContEmpRel.getPrimaryKey()); - assertEquals(1, currentContEmpRel.getFromColumns().size()); - assertEquals("RESIDENCE", currentContEmpRel.getFromColumns().get(0).getName()); - assertFalse(itRegEmp.hasNext()); - assertFalse(itContEmp.hasNext()); - - assertEquals(1, currentRegEmpRel.getFromColumns().size()); - assertEquals("RESIDENCE", currentRegEmpRel.getFromColumns().get(0).getName()); - - // inheritance check - assertEquals(employeeEntity, regularEmployeeEntity.getParentEntity()); - assertEquals(employeeEntity, contractEmployeeEntity.getParentEntity()); - assertNull(employeeEntity.getParentEntity()); - assertNull(residenceEntity.getParentEntity()); - - assertEquals(1, regularEmployeeEntity.getInheritanceLevel()); - assertEquals(1, contractEmployeeEntity.getInheritanceLevel()); - assertEquals(0, employeeEntity.getInheritanceLevel()); - assertEquals(0, residenceEntity.getInheritanceLevel()); - - // Hierarchical Bag check - assertEquals(1, mapper.getDataBaseSchema().getHierarchicalBags().size()); - HierarchicalBag hierarchicalBag = mapper.getDataBaseSchema().getHierarchicalBags().get(0); - assertEquals("table-per-type", hierarchicalBag.getInheritancePattern()); - - assertEquals(2, hierarchicalBag.getDepth2entities().size()); - - assertEquals(1, hierarchicalBag.getDepth2entities().get(0).size()); - Iterator it = hierarchicalBag.getDepth2entities().get(0).iterator(); - assertEquals("EMPLOYEE", it.next().getName()); - assertTrue(!it.hasNext()); - - assertEquals(2, hierarchicalBag.getDepth2entities().get(1).size()); - it = hierarchicalBag.getDepth2entities().get(1).iterator(); - assertEquals("REGULAR_EMPLOYEE", it.next().getName()); - assertEquals("CONTRACT_EMPLOYEE", it.next().getName()); - assertTrue(!it.hasNext()); - - assertEquals(hierarchicalBag, employeeEntity.getHierarchicalBag()); - assertEquals(hierarchicalBag, regularEmployeeEntity.getHierarchicalBag()); - assertEquals(hierarchicalBag, contractEmployeeEntity.getHierarchicalBag()); - - assertNull(hierarchicalBag.getDiscriminatorColumn()); - - /* - * Testing built graph model - */ - - VertexType employeeVertexType = mapper.getGraphModel().getVertexTypeByName("Employee"); - VertexType regularEmployeeVertexType = mapper.getGraphModel().getVertexTypeByName("RegularEmployee"); - VertexType contractEmployeeVertexType = mapper.getGraphModel().getVertexTypeByName("ContractEmployee"); - VertexType residenceVertexType = mapper.getGraphModel().getVertexTypeByName("Residence"); - - // vertices check - assertEquals(4, mapper.getGraphModel().getVerticesType().size()); - assertNotNull(employeeVertexType); - assertNotNull(regularEmployeeVertexType); - assertNotNull(contractEmployeeVertexType); - assertNotNull(residenceVertexType); - - // properties check - assertEquals(3, employeeVertexType.getProperties().size()); - - assertNotNull(employeeVertexType.getPropertyByName("id")); - assertEquals("id", employeeVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, employeeVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, employeeVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(employeeVertexType.getPropertyByName("name")); - assertEquals("name", employeeVertexType.getPropertyByName("name").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("name").getOriginalType()); - assertEquals(2, employeeVertexType.getPropertyByName("name").getOrdinalPosition()); - assertEquals(false, employeeVertexType.getPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(employeeVertexType.getPropertyByName("residence")); - assertEquals("residence", employeeVertexType.getPropertyByName("residence").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("residence").getOriginalType()); - assertEquals(3, employeeVertexType.getPropertyByName("residence").getOrdinalPosition()); - assertEquals(false, employeeVertexType.getPropertyByName("residence").isFromPrimaryKey()); - - assertEquals(2, regularEmployeeVertexType.getProperties().size()); - - assertNotNull(regularEmployeeVertexType.getPropertyByName("salary")); - assertEquals("salary", regularEmployeeVertexType.getPropertyByName("salary").getName()); - assertEquals("DECIMAL", regularEmployeeVertexType.getPropertyByName("salary").getOriginalType()); - assertEquals(1, regularEmployeeVertexType.getPropertyByName("salary").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getPropertyByName("salary").isFromPrimaryKey()); - - assertNotNull(regularEmployeeVertexType.getPropertyByName("bonus")); - assertEquals("bonus", regularEmployeeVertexType.getPropertyByName("bonus").getName()); - assertEquals("DECIMAL", regularEmployeeVertexType.getPropertyByName("bonus").getOriginalType()); - assertEquals(2, regularEmployeeVertexType.getPropertyByName("bonus").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getPropertyByName("bonus").isFromPrimaryKey()); - - assertEquals(2, contractEmployeeVertexType.getProperties().size()); - - assertNotNull(contractEmployeeVertexType.getPropertyByName("payPerHour")); - assertEquals("payPerHour", contractEmployeeVertexType.getPropertyByName("payPerHour").getName()); - assertEquals("DECIMAL", contractEmployeeVertexType.getPropertyByName("payPerHour").getOriginalType()); - assertEquals(1, contractEmployeeVertexType.getPropertyByName("payPerHour").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getPropertyByName("payPerHour").isFromPrimaryKey()); - - assertNotNull(contractEmployeeVertexType.getPropertyByName("contractDuration")); - assertEquals("contractDuration", contractEmployeeVertexType.getPropertyByName("contractDuration").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getPropertyByName("contractDuration").getOriginalType()); - assertEquals(2, contractEmployeeVertexType.getPropertyByName("contractDuration").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getPropertyByName("contractDuration").isFromPrimaryKey()); - - assertEquals(3, residenceVertexType.getProperties().size()); - - assertNotNull(residenceVertexType.getPropertyByName("id")); - assertEquals("id", residenceVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", residenceVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, residenceVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, residenceVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(residenceVertexType.getPropertyByName("city")); - assertEquals("city", residenceVertexType.getPropertyByName("city").getName()); - assertEquals("VARCHAR", residenceVertexType.getPropertyByName("city").getOriginalType()); - assertEquals(2, residenceVertexType.getPropertyByName("city").getOrdinalPosition()); - assertEquals(false, residenceVertexType.getPropertyByName("city").isFromPrimaryKey()); - - assertNotNull(residenceVertexType.getPropertyByName("country")); - assertEquals("country", residenceVertexType.getPropertyByName("country").getName()); - assertEquals("VARCHAR", residenceVertexType.getPropertyByName("country").getOriginalType()); - assertEquals(3, residenceVertexType.getPropertyByName("country").getOrdinalPosition()); - assertEquals(false, residenceVertexType.getPropertyByName("country").isFromPrimaryKey()); - - // inherited properties check - assertEquals(0, employeeVertexType.getInheritedProperties().size()); - - assertEquals(3, regularEmployeeVertexType.getInheritedProperties().size()); - - assertNotNull(regularEmployeeVertexType.getInheritedPropertyByName("id")); - assertEquals("id", regularEmployeeVertexType.getInheritedPropertyByName("id").getName()); - assertEquals("VARCHAR", regularEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()); - assertEquals(1, regularEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(regularEmployeeVertexType.getInheritedPropertyByName("name")); - assertEquals("name", regularEmployeeVertexType.getInheritedPropertyByName("name").getName()); - assertEquals("VARCHAR", regularEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()); - assertEquals(2, regularEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(regularEmployeeVertexType.getInheritedPropertyByName("residence")); - assertEquals("residence", regularEmployeeVertexType.getInheritedPropertyByName("residence").getName()); - assertEquals("VARCHAR", regularEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()); - assertEquals(3, regularEmployeeVertexType.getInheritedPropertyByName("residence").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()); - - assertEquals(3, contractEmployeeVertexType.getInheritedProperties().size()); - - assertNotNull(contractEmployeeVertexType.getInheritedPropertyByName("id")); - assertEquals("id", contractEmployeeVertexType.getInheritedPropertyByName("id").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()); - assertEquals(1, contractEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(contractEmployeeVertexType.getInheritedPropertyByName("name")); - assertEquals("name", contractEmployeeVertexType.getInheritedPropertyByName("name").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()); - assertEquals(2, contractEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(contractEmployeeVertexType.getInheritedPropertyByName("residence")); - assertEquals("residence", contractEmployeeVertexType.getInheritedPropertyByName("residence").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()); - assertEquals(3, contractEmployeeVertexType.getInheritedPropertyByName("residence").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()); - - assertEquals(0, residenceVertexType.getInheritedProperties().size()); - - // edges check - - assertEquals(1, mapper.getRelationship2edgeType().size()); - - assertEquals(1, mapper.getGraphModel().getEdgesType().size()); - assertEquals("HasResidence", mapper.getGraphModel().getEdgesType().get(0).getName()); - - assertEquals(1, employeeVertexType.getOutEdgesType().size()); - assertEquals("HasResidence", employeeVertexType.getOutEdgesType().get(0).getName()); - - assertEquals(1, regularEmployeeVertexType.getOutEdgesType().size()); - assertEquals("HasResidence", regularEmployeeVertexType.getOutEdgesType().get(0).getName()); - - assertEquals(1, contractEmployeeVertexType.getOutEdgesType().size()); - assertEquals("HasResidence", contractEmployeeVertexType.getOutEdgesType().get(0).getName()); - - // inheritance check - assertEquals(employeeVertexType, regularEmployeeVertexType.getParentType()); - assertEquals(employeeVertexType, contractEmployeeVertexType.getParentType()); - assertNull(employeeVertexType.getParentType()); - - assertEquals(1, regularEmployeeVertexType.getInheritanceLevel()); - assertEquals(1, contractEmployeeVertexType.getInheritanceLevel()); - assertEquals(0, employeeVertexType.getInheritanceLevel()); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } finally { - try { - // Dropping Source DB Schema and OrientGraph - String dbDropping = "drop schema public cascade"; - st.execute(dbDropping); - connection.close(); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } - } + } + + /* + * Table per Subclass Inheritance ( tag) + * 3 tables, one parent and 2 childs ( http://www.javatpoint.com/table-per-subclass ) + */ + + @Test + void TablePerSubclassInheritanceSyntax1() { + Connection connection = null; + Statement st = null; + + try { + Class.forName("org.hsqldb.jdbc.JDBCDriver"); + connection = DriverManager.getConnection(this.jurl, this.username, this.password); + + String residence = + "create memory table RESIDENCE(ID varchar(256) not null, CITY varchar(256), COUNTRY" + + " varchar(256), primary key (ID))"; + st = connection.createStatement(); + st.execute(residence); + + String employeeTableBuilding = + "create memory table EMPLOYEE (ID varchar(256) not null, NAME varchar(256), RESIDENCE" + + " varchar(256), primary key (ID), foreign key (RESIDENCE) references" + + " RESIDENCE(ID))"; + st.execute(employeeTableBuilding); + + String regularEmployeeTableBuilding = + "create memory table REGULAR_EMPLOYEE (EID varchar(256) not null, SALARY decimal(10,2)," + + " BONUS decimal(10,0), primary key (EID), foreign key (EID) references" + + " EMPLOYEE(ID))"; + st.execute(regularEmployeeTableBuilding); + + String contractEmployeeTableBuilding = + "create memory table CONTRACT_EMPLOYEE (EID varchar(256) not null, PAY_PER_HOUR" + + " decimal(10,2), CONTRACT_DURATION varchar(256), primary key (EID), foreign key" + + " (EID) references EMPLOYEE(ID))"; + st.execute(contractEmployeeTableBuilding); + + this.mapper = + new Hibernate2GraphMapper( + dataSource, + HibernateMapperTest.XML_TABLE_PER_SUBCLASS1, + null, + null, + dbQueryEngine, + dataTypeHandler, + executionStrategy, + nameResolver, + statistics); + + mapper.buildSourceDatabaseSchema(); + mapper.buildGraphModel(new JavaConventionNameResolver()); + + /* + * Testing context information + */ + + assertThat(statistics.totalNumberOfEntities).isEqualTo(4); + assertThat(statistics.builtEntities).isEqualTo(4); + assertThat(statistics.totalNumberOfRelationships).isEqualTo(3); + assertThat(statistics.builtRelationships).isEqualTo(3); + + assertThat(statistics.totalNumberOfModelVertices).isEqualTo(4); + assertThat(statistics.builtModelVertexTypes).isEqualTo(4); + assertThat(statistics.totalNumberOfModelEdges).isEqualTo(1); + assertThat(statistics.builtModelEdgeTypes).isEqualTo(1); + + /* + * Testing built source db schema + */ + + Entity employeeEntity = mapper.getDataBaseSchema().getEntityByName("EMPLOYEE"); + Entity regularEmployeeEntity = mapper.getDataBaseSchema().getEntityByName("REGULAR_EMPLOYEE"); + Entity contractEmployeeEntity = + mapper.getDataBaseSchema().getEntityByName("CONTRACT_EMPLOYEE"); + Entity residenceEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("RESIDENCE"); + + // entities check + assertThat(mapper.getDataBaseSchema().getEntities().size()).isEqualTo(4); + assertThat(mapper.getDataBaseSchema().getCanonicalRelationships().size()).isEqualTo(3); + assertThat(employeeEntity).isNotNull(); + assertThat(regularEmployeeEntity).isNotNull(); + assertThat(contractEmployeeEntity).isNotNull(); + assertThat(residenceEntity).isNotNull(); + + // attributes check + assertThat(employeeEntity.getAttributes().size()).isEqualTo(3); + + assertThat(employeeEntity.getAttributeByName("ID")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(employeeEntity.getAttributeByName("ID").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("ID").getOrdinalPosition()).isEqualTo(1); + assertThat(employeeEntity.getAttributeByName("ID").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(employeeEntity.getAttributeByName("NAME")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("NAME").getName()).isEqualTo("NAME"); + assertThat(employeeEntity.getAttributeByName("NAME").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("NAME").getOrdinalPosition()).isEqualTo(2); + assertThat(employeeEntity.getAttributeByName("NAME").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(employeeEntity.getAttributeByName("RESIDENCE")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getName()).isEqualTo("RESIDENCE"); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getOrdinalPosition()).isEqualTo(3); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(regularEmployeeEntity.getAttributes().size()).isEqualTo(2); + + assertThat(regularEmployeeEntity.getAttributeByName("SALARY")).isNotNull(); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getName()).isEqualTo("SALARY"); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getDataType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getOrdinalPosition()) + .isEqualTo(1); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getBelongingEntity().getName()) + .isEqualTo("REGULAR_EMPLOYEE"); + + assertThat(regularEmployeeEntity.getAttributeByName("BONUS")).isNotNull(); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getName()).isEqualTo("BONUS"); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getDataType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getOrdinalPosition()) + .isEqualTo(2); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getBelongingEntity().getName()) + .isEqualTo("REGULAR_EMPLOYEE"); + + assertThat(contractEmployeeEntity.getAttributes().size()).isEqualTo(2); + + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR")).isNotNull(); + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getName()) + .isEqualTo("PAY_PER_HOUR"); + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getDataType()) + .isEqualTo("DECIMAL"); + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getOrdinalPosition()) + .isEqualTo(1); + assertThat( + contractEmployeeEntity + .getAttributeByName("PAY_PER_HOUR") + .getBelongingEntity() + .getName()) + .isEqualTo("CONTRACT_EMPLOYEE"); + + assertThat(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION")).isNotNull(); + assertThat(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getName()) + .isEqualTo("CONTRACT_DURATION"); + assertThat(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + contractEmployeeEntity + .getAttributeByName("CONTRACT_DURATION") + .getBelongingEntity() + .getName()) + .isEqualTo("CONTRACT_EMPLOYEE"); + + // inherited attributes check + assertThat(employeeEntity.getInheritedAttributes().size()).isEqualTo(0); + + assertThat(regularEmployeeEntity.getInheritedAttributes().size()).isEqualTo(3); + + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID")).isNotNull(); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()) + .isEqualTo(1); + assertThat( + regularEmployeeEntity + .getInheritedAttributeByName("ID") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME")).isNotNull(); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME").getName()) + .isEqualTo("NAME"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + regularEmployeeEntity + .getInheritedAttributeByName("NAME") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE")).isNotNull(); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()) + .isEqualTo("RESIDENCE"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()) + .isEqualTo(3); + assertThat( + regularEmployeeEntity + .getInheritedAttributeByName("RESIDENCE") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(contractEmployeeEntity.getInheritedAttributes().size()).isEqualTo(3); + + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID")).isNotNull(); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID").getName()) + .isEqualTo("ID"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()) + .isEqualTo(1); + assertThat( + contractEmployeeEntity + .getInheritedAttributeByName("ID") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME")).isNotNull(); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME").getName()) + .isEqualTo("NAME"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + contractEmployeeEntity + .getInheritedAttributeByName("NAME") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE")).isNotNull(); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()) + .isEqualTo("RESIDENCE"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()) + .isEqualTo(3); + assertThat( + contractEmployeeEntity + .getInheritedAttributeByName("RESIDENCE") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + // primary key check + assertThat(regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()).isEqualTo(1); + assertThat(regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()) + .isEqualTo("EID"); + assertThat(regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + regularEmployeeEntity + .getPrimaryKey() + .getInvolvedAttributes() + .get(0) + .getBelongingEntity() + .getName()) + .isEqualTo("REGULAR_EMPLOYEE"); + + assertThat(contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()) + .isEqualTo(1); + assertThat(contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()) + .isEqualTo("EID"); + assertThat( + contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeEntity + .getPrimaryKey() + .getInvolvedAttributes() + .get(0) + .getBelongingEntity() + .getName()) + .isEqualTo("CONTRACT_EMPLOYEE"); + + // relationship, primary and foreign key check + assertThat(regularEmployeeEntity.getOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(contractEmployeeEntity.getOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(employeeEntity.getOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(residenceEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(regularEmployeeEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(contractEmployeeEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(employeeEntity.getInCanonicalRelationships().size()).isEqualTo(2); + assertThat(residenceEntity.getInCanonicalRelationships().size()).isEqualTo(1); + + assertThat(regularEmployeeEntity.getForeignKeys().size()).isEqualTo(1); + assertThat(contractEmployeeEntity.getForeignKeys().size()).isEqualTo(1); + assertThat(employeeEntity.getForeignKeys().size()).isEqualTo(1); + assertThat(residenceEntity.getForeignKeys().size()).isEqualTo(0); + + Iterator itEmp = + employeeEntity.getOutCanonicalRelationships().iterator(); + Iterator itRegEmp = + regularEmployeeEntity.getOutCanonicalRelationships().iterator(); + Iterator itContEmp = + contractEmployeeEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship currentEmpRel = itEmp.next(); + CanonicalRelationship currentRegEmpRel = itRegEmp.next(); + CanonicalRelationship currentContEmpRel = itContEmp.next(); + assertThat(currentEmpRel.getParentEntity().getName()).isEqualTo("RESIDENCE"); + assertThat(currentEmpRel.getForeignEntity().getName()).isEqualTo("EMPLOYEE"); + assertThat(currentRegEmpRel.getParentEntity().getName()).isEqualTo("EMPLOYEE"); + assertThat(currentRegEmpRel.getForeignEntity().getName()).isEqualTo("REGULAR_EMPLOYEE"); + assertThat(currentContEmpRel.getParentEntity().getName()).isEqualTo("EMPLOYEE"); + assertThat(currentContEmpRel.getForeignEntity().getName()).isEqualTo("CONTRACT_EMPLOYEE"); + assertThat(currentEmpRel.getPrimaryKey()).isEqualTo(residenceEntity.getPrimaryKey()); + assertThat(currentEmpRel.getForeignKey()).isEqualTo(employeeEntity.getForeignKeys().get(0)); + assertThat(currentRegEmpRel.getPrimaryKey()).isEqualTo(employeeEntity.getPrimaryKey()); + assertThat(currentRegEmpRel.getForeignKey()) + .isEqualTo(regularEmployeeEntity.getForeignKeys().get(0)); + assertThat(currentContEmpRel.getPrimaryKey()).isEqualTo(employeeEntity.getPrimaryKey()); + assertThat(currentContEmpRel.getForeignKey()) + .isEqualTo(contractEmployeeEntity.getForeignKeys().get(0)); + assertThat(itEmp.hasNext()).isFalse(); + assertThat(itRegEmp.hasNext()).isFalse(); + assertThat(itContEmp.hasNext()).isFalse(); + + Iterator itRes = + residenceEntity.getInCanonicalRelationships().iterator(); + CanonicalRelationship currentResRel = itRes.next(); + assertThat(currentResRel).isEqualTo(currentEmpRel); + + itEmp = employeeEntity.getInCanonicalRelationships().iterator(); + currentEmpRel = itEmp.next(); + assertThat(currentContEmpRel).isEqualTo(currentEmpRel); + + currentEmpRel = itEmp.next(); + assertThat(currentRegEmpRel).isEqualTo(currentEmpRel); + + // inherited relationships check + assertThat(regularEmployeeEntity.getInheritedOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(contractEmployeeEntity.getInheritedOutCanonicalRelationships().size()) + .isEqualTo(1); + assertThat(employeeEntity.getInheritedOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(residenceEntity.getInheritedOutCanonicalRelationships().size()).isEqualTo(0); + + itRegEmp = regularEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); + itContEmp = contractEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); + currentRegEmpRel = itRegEmp.next(); + currentContEmpRel = itContEmp.next(); + assertThat(currentRegEmpRel.getParentEntity().getName()).isEqualTo("RESIDENCE"); + assertThat(currentRegEmpRel.getForeignEntity().getName()).isEqualTo("EMPLOYEE"); + assertThat(currentContEmpRel.getParentEntity().getName()).isEqualTo("RESIDENCE"); + assertThat(currentContEmpRel.getForeignEntity().getName()).isEqualTo("EMPLOYEE"); + assertThat(currentRegEmpRel.getPrimaryKey()).isEqualTo(residenceEntity.getPrimaryKey()); + assertThat(currentRegEmpRel.getFromColumns().size()).isEqualTo(1); + assertThat(currentRegEmpRel.getFromColumns().get(0).getName()).isEqualTo("RESIDENCE"); + assertThat(currentContEmpRel.getPrimaryKey()).isEqualTo(residenceEntity.getPrimaryKey()); + assertThat(currentContEmpRel.getFromColumns().size()).isEqualTo(1); + assertThat(currentContEmpRel.getFromColumns().get(0).getName()).isEqualTo("RESIDENCE"); + assertThat(itRegEmp.hasNext()).isFalse(); + assertThat(itContEmp.hasNext()).isFalse(); + + assertThat(currentRegEmpRel.getFromColumns().size()).isEqualTo(1); + assertThat(currentRegEmpRel.getFromColumns().get(0).getName()).isEqualTo("RESIDENCE"); + + // inheritance check + assertThat(regularEmployeeEntity.getParentEntity()).isEqualTo(employeeEntity); + assertThat(contractEmployeeEntity.getParentEntity()).isEqualTo(employeeEntity); + assertThat(employeeEntity.getParentEntity()).isNull(); + assertThat(residenceEntity.getParentEntity()).isNull(); + + assertThat(regularEmployeeEntity.getInheritanceLevel()).isEqualTo(1); + assertThat(contractEmployeeEntity.getInheritanceLevel()).isEqualTo(1); + assertThat(employeeEntity.getInheritanceLevel()).isEqualTo(0); + assertThat(residenceEntity.getInheritanceLevel()).isEqualTo(0); + + // Hierarchical Bag check + assertThat(mapper.getDataBaseSchema().getHierarchicalBags().size()).isEqualTo(1); + HierarchicalBag hierarchicalBag = mapper.getDataBaseSchema().getHierarchicalBags().get(0); + assertThat(hierarchicalBag.getInheritancePattern()).isEqualTo("table-per-type"); + + assertThat(hierarchicalBag.getDepth2entities().size()).isEqualTo(2); + + assertThat(hierarchicalBag.getDepth2entities().get(0).size()).isEqualTo(1); + Iterator it = hierarchicalBag.getDepth2entities().get(0).iterator(); + assertThat(it.next().getName()).isEqualTo("EMPLOYEE"); + assertThat(it.hasNext()).isFalse(); + + assertThat(hierarchicalBag.getDepth2entities().get(1).size()).isEqualTo(2); + it = hierarchicalBag.getDepth2entities().get(1).iterator(); + assertThat(it.next().getName()).isEqualTo("REGULAR_EMPLOYEE"); + assertThat(it.next().getName()).isEqualTo("CONTRACT_EMPLOYEE"); + assertThat(it.hasNext()).isFalse(); + + assertThat(employeeEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag); + assertThat(regularEmployeeEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag); + assertThat(contractEmployeeEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag); + + assertThat(hierarchicalBag.getDiscriminatorColumn()).isNull(); + + /* + * Testing built graph model + */ + + VertexType employeeVertexType = mapper.getGraphModel().getVertexTypeByName("Employee"); + VertexType regularEmployeeVertexType = + mapper.getGraphModel().getVertexTypeByName("RegularEmployee"); + VertexType contractEmployeeVertexType = + mapper.getGraphModel().getVertexTypeByName("ContractEmployee"); + VertexType residenceVertexType = mapper.getGraphModel().getVertexTypeByName("Residence"); + + // vertices check + assertThat(mapper.getGraphModel().getVerticesType().size()).isEqualTo(4); + assertThat(employeeVertexType).isNotNull(); + assertThat(regularEmployeeVertexType).isNotNull(); + assertThat(contractEmployeeVertexType).isNotNull(); + assertThat(residenceVertexType).isNotNull(); + + // properties check + assertThat(employeeVertexType.getProperties().size()).isEqualTo(3); + + assertThat(employeeVertexType.getPropertyByName("id")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(employeeVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(employeeVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(employeeVertexType.getPropertyByName("name")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("name").getName()).isEqualTo("name"); + assertThat(employeeVertexType.getPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("name").getOrdinalPosition()).isEqualTo(2); + assertThat(employeeVertexType.getPropertyByName("name").isFromPrimaryKey()).isFalse(); + + assertThat(employeeVertexType.getPropertyByName("residence")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("residence").getName()) + .isEqualTo("residence"); + assertThat(employeeVertexType.getPropertyByName("residence").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("residence").getOrdinalPosition()) + .isEqualTo(3); + assertThat(employeeVertexType.getPropertyByName("residence").isFromPrimaryKey()).isFalse(); + + assertThat(regularEmployeeVertexType.getProperties().size()).isEqualTo(2); + + assertThat(regularEmployeeVertexType.getPropertyByName("salary")).isNotNull(); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").getName()) + .isEqualTo("salary"); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").getOriginalType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").getOrdinalPosition()) + .isEqualTo(1); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").isFromPrimaryKey()) + .isFalse(); + + assertThat(regularEmployeeVertexType.getPropertyByName("bonus")).isNotNull(); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").getName()).isEqualTo("bonus"); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").getOriginalType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").getOrdinalPosition()) + .isEqualTo(2); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").isFromPrimaryKey()).isFalse(); + + assertThat(contractEmployeeVertexType.getProperties().size()).isEqualTo(2); + + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour")).isNotNull(); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").getName()) + .isEqualTo("payPerHour"); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").getOriginalType()) + .isEqualTo("DECIMAL"); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").getOrdinalPosition()) + .isEqualTo(1); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getPropertyByName("contractDuration")).isNotNull(); + assertThat(contractEmployeeVertexType.getPropertyByName("contractDuration").getName()) + .isEqualTo("contractDuration"); + assertThat(contractEmployeeVertexType.getPropertyByName("contractDuration").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeVertexType.getPropertyByName("contractDuration").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + contractEmployeeVertexType.getPropertyByName("contractDuration").isFromPrimaryKey()) + .isFalse(); + + assertThat(residenceVertexType.getProperties().size()).isEqualTo(3); + + assertThat(residenceVertexType.getPropertyByName("id")).isNotNull(); + assertThat(residenceVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(residenceVertexType.getPropertyByName("id").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(residenceVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(residenceVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(residenceVertexType.getPropertyByName("city")).isNotNull(); + assertThat(residenceVertexType.getPropertyByName("city").getName()).isEqualTo("city"); + assertThat(residenceVertexType.getPropertyByName("city").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(residenceVertexType.getPropertyByName("city").getOrdinalPosition()).isEqualTo(2); + assertThat(residenceVertexType.getPropertyByName("city").isFromPrimaryKey()).isFalse(); + + assertThat(residenceVertexType.getPropertyByName("country")).isNotNull(); + assertThat(residenceVertexType.getPropertyByName("country").getName()).isEqualTo("country"); + assertThat(residenceVertexType.getPropertyByName("country").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(residenceVertexType.getPropertyByName("country").getOrdinalPosition()) + .isEqualTo(3); + assertThat(residenceVertexType.getPropertyByName("country").isFromPrimaryKey()).isFalse(); + + // inherited properties check + assertThat(employeeVertexType.getInheritedProperties().size()).isEqualTo(0); + + assertThat(regularEmployeeVertexType.getInheritedProperties().size()).isEqualTo(3); + + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id")).isNotNull(); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").getName()) + .isEqualTo("id"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()) + .isEqualTo(1); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()) + .isFalse(); + + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name")).isNotNull(); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").getName()) + .isEqualTo("name"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()) + .isEqualTo(2); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()) + .isFalse(); + + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("residence")).isNotNull(); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("residence").getName()) + .isEqualTo("residence"); + assertThat( + regularEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + regularEmployeeVertexType + .getInheritedPropertyByName("residence") + .getOrdinalPosition()) + .isEqualTo(3); + assertThat( + regularEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getInheritedProperties().size()).isEqualTo(3); + + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id")).isNotNull(); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").getName()) + .isEqualTo("id"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()) + .isEqualTo(1); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name")).isNotNull(); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").getName()) + .isEqualTo("name"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()) + .isEqualTo(2); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("residence")).isNotNull(); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("residence").getName()) + .isEqualTo("residence"); + assertThat( + contractEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeVertexType + .getInheritedPropertyByName("residence") + .getOrdinalPosition()) + .isEqualTo(3); + assertThat( + contractEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()) + .isFalse(); + + assertThat(residenceVertexType.getInheritedProperties().size()).isEqualTo(0); + + // edges check + + assertThat(mapper.getRelationship2edgeType().size()).isEqualTo(1); + + assertThat(mapper.getGraphModel().getEdgesType().size()).isEqualTo(1); + assertThat(mapper.getGraphModel().getEdgesType().get(0).getName()).isEqualTo("HasResidence"); + + assertThat(employeeVertexType.getOutEdgesType().size()).isEqualTo(1); + assertThat(employeeVertexType.getOutEdgesType().get(0).getName()).isEqualTo("HasResidence"); + + assertThat(regularEmployeeVertexType.getOutEdgesType().size()).isEqualTo(1); + assertThat(regularEmployeeVertexType.getOutEdgesType().get(0).getName()) + .isEqualTo("HasResidence"); + + assertThat(contractEmployeeVertexType.getOutEdgesType().size()).isEqualTo(1); + assertThat(contractEmployeeVertexType.getOutEdgesType().get(0).getName()) + .isEqualTo("HasResidence"); + + // inheritance check + assertThat(regularEmployeeVertexType.getParentType()).isEqualTo(employeeVertexType); + assertThat(contractEmployeeVertexType.getParentType()).isEqualTo(employeeVertexType); + assertThat(employeeVertexType.getParentType()).isNull(); + + assertThat(regularEmployeeVertexType.getInheritanceLevel()).isEqualTo(1); + assertThat(contractEmployeeVertexType.getInheritanceLevel()).isEqualTo(1); + assertThat(employeeVertexType.getInheritanceLevel()).isEqualTo(0); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } finally { + try { + // Dropping Source DB Schema and OrientGraph + String dbDropping = "drop schema public cascade"; + st.execute(dbDropping); + connection.close(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } } - - @Test - /* - * Table per Subclass Inheritance ( tags) - * 3 tables, one parent and 2 children ( http://www.javatpoint.com/table-per-subclass ) - */ - - public void TablePerSubclassInheritanceSyntax2() { - Connection connection = null; - Statement st = null; - - try { - Class.forName("org.hsqldb.jdbc.JDBCDriver"); - connection = DriverManager.getConnection(this.jurl, this.username, this.password); - - String residence = "create memory table RESIDENCE(ID varchar(256) not null, CITY varchar(256), COUNTRY varchar(256), primary key (ID))"; - st = connection.createStatement(); - st.execute(residence); - - String employeeTableBuilding = - "create memory table EMPLOYEE (ID varchar(256) not null," + - " NAME varchar(256), RESIDENCE varchar(256), primary key (ID), foreign key (RESIDENCE) references RESIDENCE(ID))"; - st.execute(employeeTableBuilding); - - String regularEmployeeTableBuilding = - "create memory table REGULAR_EMPLOYEE (EID varchar(256) not null, " + - "SALARY decimal(10,2), BONUS decimal(10,0), primary key (EID), foreign key (EID) references EMPLOYEE(ID))"; - st.execute(regularEmployeeTableBuilding); - - String contractEmployeeTableBuilding = - "create memory table CONTRACT_EMPLOYEE (EID varchar(256) not null, " + - "PAY_PER_HOUR decimal(10,2), CONTRACT_DURATION varchar(256), primary key (EID), foreign key (EID) references EMPLOYEE(ID))"; - st.execute(contractEmployeeTableBuilding); - - this.mapper = - new Hibernate2GraphMapper( - dataSource, - HibernateMapperTest.XML_TABLE_PER_SUBCLASS2, - null, - null, - dbQueryEngine, - dataTypeHandler, - executionStrategy, - nameResolver, - statistics - ); - - mapper.buildSourceDatabaseSchema(); - mapper.buildGraphModel(new JavaConventionNameResolver()); - - /* - * Testing context information - */ - - assertEquals(4, statistics.totalNumberOfEntities); - assertEquals(4, statistics.builtEntities); - assertEquals(3, statistics.totalNumberOfRelationships); - assertEquals(3, statistics.builtRelationships); - - assertEquals(4, statistics.totalNumberOfModelVertices); - assertEquals(4, statistics.builtModelVertexTypes); - assertEquals(1, statistics.totalNumberOfModelEdges); - assertEquals(1, statistics.builtModelEdgeTypes); - - /* - * Testing built source db schema - */ - - Entity employeeEntity = mapper.getDataBaseSchema().getEntityByName("EMPLOYEE"); - Entity regularEmployeeEntity = mapper.getDataBaseSchema().getEntityByName("REGULAR_EMPLOYEE"); - Entity contractEmployeeEntity = mapper.getDataBaseSchema().getEntityByName("CONTRACT_EMPLOYEE"); - Entity residenceEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("RESIDENCE"); - - // entities check - assertEquals(4, mapper.getDataBaseSchema().getEntities().size()); - assertEquals(3, mapper.getDataBaseSchema().getCanonicalRelationships().size()); - assertNotNull(employeeEntity); - assertNotNull(regularEmployeeEntity); - assertNotNull(contractEmployeeEntity); - assertNotNull(residenceEntity); - - // attributes check - assertEquals(3, employeeEntity.getAttributes().size()); - - assertNotNull(employeeEntity.getAttributeByName("ID")); - assertEquals("ID", employeeEntity.getAttributeByName("ID").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("ID").getDataType()); - assertEquals(1, employeeEntity.getAttributeByName("ID").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(employeeEntity.getAttributeByName("NAME")); - assertEquals("NAME", employeeEntity.getAttributeByName("NAME").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("NAME").getDataType()); - assertEquals(2, employeeEntity.getAttributeByName("NAME").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(employeeEntity.getAttributeByName("RESIDENCE")); - assertEquals("RESIDENCE", employeeEntity.getAttributeByName("RESIDENCE").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("RESIDENCE").getDataType()); - assertEquals(3, employeeEntity.getAttributeByName("RESIDENCE").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("RESIDENCE").getBelongingEntity().getName()); - - assertEquals(2, regularEmployeeEntity.getAttributes().size()); - - assertNotNull(regularEmployeeEntity.getAttributeByName("SALARY")); - assertEquals("SALARY", regularEmployeeEntity.getAttributeByName("SALARY").getName()); - assertEquals("DECIMAL", regularEmployeeEntity.getAttributeByName("SALARY").getDataType()); - assertEquals(1, regularEmployeeEntity.getAttributeByName("SALARY").getOrdinalPosition()); - assertEquals("REGULAR_EMPLOYEE", regularEmployeeEntity.getAttributeByName("SALARY").getBelongingEntity().getName()); - - assertNotNull(regularEmployeeEntity.getAttributeByName("BONUS")); - assertEquals("BONUS", regularEmployeeEntity.getAttributeByName("BONUS").getName()); - assertEquals("DECIMAL", regularEmployeeEntity.getAttributeByName("BONUS").getDataType()); - assertEquals(2, regularEmployeeEntity.getAttributeByName("BONUS").getOrdinalPosition()); - assertEquals("REGULAR_EMPLOYEE", regularEmployeeEntity.getAttributeByName("BONUS").getBelongingEntity().getName()); - - assertEquals(2, contractEmployeeEntity.getAttributes().size()); - - assertNotNull(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR")); - assertEquals("PAY_PER_HOUR", contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getName()); - assertEquals("DECIMAL", contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getDataType()); - assertEquals(1, contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getOrdinalPosition()); - assertEquals("CONTRACT_EMPLOYEE", contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getBelongingEntity().getName()); - - assertNotNull(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION")); - assertEquals("CONTRACT_DURATION", contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getDataType()); - assertEquals(2, contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getOrdinalPosition()); - assertEquals("CONTRACT_EMPLOYEE", contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getBelongingEntity().getName()); - - // inherited attributes check - assertEquals(0, employeeEntity.getInheritedAttributes().size()); - - assertEquals(3, regularEmployeeEntity.getInheritedAttributes().size()); - - assertNotNull(regularEmployeeEntity.getInheritedAttributeByName("ID")); - assertEquals("ID", regularEmployeeEntity.getInheritedAttributeByName("ID").getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getInheritedAttributeByName("ID").getDataType()); - assertEquals(1, regularEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()); - assertEquals("EMPLOYEE", regularEmployeeEntity.getInheritedAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(regularEmployeeEntity.getInheritedAttributeByName("NAME")); - assertEquals("NAME", regularEmployeeEntity.getInheritedAttributeByName("NAME").getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()); - assertEquals(2, regularEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()); - assertEquals("EMPLOYEE", regularEmployeeEntity.getInheritedAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE")); - assertEquals("RESIDENCE", regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()); - assertEquals(3, regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()); - assertEquals("EMPLOYEE", regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getBelongingEntity().getName()); - - assertEquals(3, contractEmployeeEntity.getInheritedAttributes().size()); - - assertNotNull(contractEmployeeEntity.getInheritedAttributeByName("ID")); - assertEquals("ID", contractEmployeeEntity.getInheritedAttributeByName("ID").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getInheritedAttributeByName("ID").getDataType()); - assertEquals(1, contractEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()); - assertEquals("EMPLOYEE", contractEmployeeEntity.getInheritedAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(contractEmployeeEntity.getInheritedAttributeByName("NAME")); - assertEquals("NAME", contractEmployeeEntity.getInheritedAttributeByName("NAME").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()); - assertEquals(2, contractEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()); - assertEquals("EMPLOYEE", contractEmployeeEntity.getInheritedAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE")); - assertEquals("RESIDENCE", contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()); - assertEquals(3, contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()); - assertEquals("EMPLOYEE", contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getBelongingEntity().getName()); - - // primary key check - assertEquals(1, regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()); - assertEquals("EID", regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()); - assertEquals("REGULAR_EMPLOYEE", regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getBelongingEntity().getName()); - - assertEquals(1, contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()); - assertEquals("EID", contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()); - assertEquals("CONTRACT_EMPLOYEE", contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getBelongingEntity().getName()); - - // relationship, primary and foreign key check - assertEquals(1, regularEmployeeEntity.getOutCanonicalRelationships().size()); - assertEquals(1, contractEmployeeEntity.getOutCanonicalRelationships().size()); - assertEquals(1, employeeEntity.getOutCanonicalRelationships().size()); - assertEquals(0, residenceEntity.getOutCanonicalRelationships().size()); - assertEquals(0, regularEmployeeEntity.getInCanonicalRelationships().size()); - assertEquals(0, contractEmployeeEntity.getInCanonicalRelationships().size()); - assertEquals(2, employeeEntity.getInCanonicalRelationships().size()); - assertEquals(1, residenceEntity.getInCanonicalRelationships().size()); - - assertEquals(1, regularEmployeeEntity.getForeignKeys().size()); - assertEquals(1, contractEmployeeEntity.getForeignKeys().size()); - assertEquals(1, employeeEntity.getForeignKeys().size()); - assertEquals(0, residenceEntity.getForeignKeys().size()); - - Iterator itEmp = employeeEntity.getOutCanonicalRelationships().iterator(); - Iterator itRegEmp = regularEmployeeEntity.getOutCanonicalRelationships().iterator(); - Iterator itContEmp = contractEmployeeEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship currentEmpRel = itEmp.next(); - CanonicalRelationship currentRegEmpRel = itRegEmp.next(); - CanonicalRelationship currentContEmpRel = itContEmp.next(); - assertEquals("RESIDENCE", currentEmpRel.getParentEntity().getName()); - assertEquals("EMPLOYEE", currentEmpRel.getForeignEntity().getName()); - assertEquals("EMPLOYEE", currentRegEmpRel.getParentEntity().getName()); - assertEquals("REGULAR_EMPLOYEE", currentRegEmpRel.getForeignEntity().getName()); - assertEquals("EMPLOYEE", currentContEmpRel.getParentEntity().getName()); - assertEquals("CONTRACT_EMPLOYEE", currentContEmpRel.getForeignEntity().getName()); - assertEquals(residenceEntity.getPrimaryKey(), currentEmpRel.getPrimaryKey()); - assertEquals(employeeEntity.getForeignKeys().get(0), currentEmpRel.getForeignKey()); - assertEquals(employeeEntity.getPrimaryKey(), currentRegEmpRel.getPrimaryKey()); - assertEquals(regularEmployeeEntity.getForeignKeys().get(0), currentRegEmpRel.getForeignKey()); - assertEquals(employeeEntity.getPrimaryKey(), currentContEmpRel.getPrimaryKey()); - assertEquals(contractEmployeeEntity.getForeignKeys().get(0), currentContEmpRel.getForeignKey()); - assertFalse(itEmp.hasNext()); - assertFalse(itRegEmp.hasNext()); - assertFalse(itContEmp.hasNext()); - - Iterator itRes = residenceEntity.getInCanonicalRelationships().iterator(); - CanonicalRelationship currentResRel = itRes.next(); - assertEquals(currentEmpRel, currentResRel); - - itEmp = employeeEntity.getInCanonicalRelationships().iterator(); - currentEmpRel = itEmp.next(); - assertEquals(currentEmpRel, currentContEmpRel); - - currentEmpRel = itEmp.next(); - assertEquals(currentEmpRel, currentRegEmpRel); - - // inherited relationships check - assertEquals(1, regularEmployeeEntity.getInheritedOutCanonicalRelationships().size()); - assertEquals(1, contractEmployeeEntity.getInheritedOutCanonicalRelationships().size()); - assertEquals(0, employeeEntity.getInheritedOutCanonicalRelationships().size()); - assertEquals(0, residenceEntity.getInheritedOutCanonicalRelationships().size()); - - itRegEmp = regularEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); - itContEmp = contractEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); - currentRegEmpRel = itRegEmp.next(); - currentContEmpRel = itContEmp.next(); - assertEquals("RESIDENCE", currentRegEmpRel.getParentEntity().getName()); - assertEquals("EMPLOYEE", currentRegEmpRel.getForeignEntity().getName()); - assertEquals("RESIDENCE", currentContEmpRel.getParentEntity().getName()); - assertEquals("EMPLOYEE", currentContEmpRel.getForeignEntity().getName()); - assertEquals(residenceEntity.getPrimaryKey(), currentRegEmpRel.getPrimaryKey()); - assertEquals(1, currentRegEmpRel.getFromColumns().size()); - assertEquals("RESIDENCE", currentRegEmpRel.getFromColumns().get(0).getName()); - assertEquals(residenceEntity.getPrimaryKey(), currentContEmpRel.getPrimaryKey()); - assertEquals(1, currentContEmpRel.getFromColumns().size()); - assertEquals("RESIDENCE", currentContEmpRel.getFromColumns().get(0).getName()); - assertFalse(itRegEmp.hasNext()); - assertFalse(itContEmp.hasNext()); - - // inheritance check - assertEquals(employeeEntity, regularEmployeeEntity.getParentEntity()); - assertEquals(employeeEntity, contractEmployeeEntity.getParentEntity()); - assertNull(employeeEntity.getParentEntity()); - assertNull(residenceEntity.getParentEntity()); - - assertEquals(1, regularEmployeeEntity.getInheritanceLevel()); - assertEquals(1, contractEmployeeEntity.getInheritanceLevel()); - assertEquals(0, employeeEntity.getInheritanceLevel()); - assertEquals(0, residenceEntity.getInheritanceLevel()); - - // Hierarchical Bag check - assertEquals(1, mapper.getDataBaseSchema().getHierarchicalBags().size()); - HierarchicalBag hierarchicalBag = mapper.getDataBaseSchema().getHierarchicalBags().get(0); - assertEquals("table-per-type", hierarchicalBag.getInheritancePattern()); - - assertEquals(2, hierarchicalBag.getDepth2entities().size()); - - assertEquals(1, hierarchicalBag.getDepth2entities().get(0).size()); - Iterator it = hierarchicalBag.getDepth2entities().get(0).iterator(); - assertEquals("EMPLOYEE", it.next().getName()); - assertTrue(!it.hasNext()); - - assertEquals(2, hierarchicalBag.getDepth2entities().get(1).size()); - it = hierarchicalBag.getDepth2entities().get(1).iterator(); - assertEquals("REGULAR_EMPLOYEE", it.next().getName()); - assertEquals("CONTRACT_EMPLOYEE", it.next().getName()); - assertTrue(!it.hasNext()); - - assertEquals(hierarchicalBag, employeeEntity.getHierarchicalBag()); - assertEquals(hierarchicalBag, regularEmployeeEntity.getHierarchicalBag()); - assertEquals(hierarchicalBag, contractEmployeeEntity.getHierarchicalBag()); - - assertNotNull(hierarchicalBag.getDiscriminatorColumn()); - assertEquals("employee_type", hierarchicalBag.getDiscriminatorColumn()); - - /* - * Testing built graph model - */ - - VertexType employeeVertexType = mapper.getGraphModel().getVertexTypeByName("Employee"); - VertexType regularEmployeeVertexType = mapper.getGraphModel().getVertexTypeByName("RegularEmployee"); - VertexType contractEmployeeVertexType = mapper.getGraphModel().getVertexTypeByName("ContractEmployee"); - VertexType residenceVertexType = mapper.getGraphModel().getVertexTypeByName("Residence"); - - // vertices check - assertEquals(4, mapper.getGraphModel().getVerticesType().size()); - assertNotNull(employeeVertexType); - assertNotNull(regularEmployeeVertexType); - assertNotNull(contractEmployeeVertexType); - assertNotNull(residenceVertexType); - - // properties check - assertEquals(3, employeeVertexType.getProperties().size()); - - assertNotNull(employeeVertexType.getPropertyByName("id")); - assertEquals("id", employeeVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, employeeVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, employeeVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(employeeVertexType.getPropertyByName("name")); - assertEquals("name", employeeVertexType.getPropertyByName("name").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("name").getOriginalType()); - assertEquals(2, employeeVertexType.getPropertyByName("name").getOrdinalPosition()); - assertEquals(false, employeeVertexType.getPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(employeeVertexType.getPropertyByName("residence")); - assertEquals("residence", employeeVertexType.getPropertyByName("residence").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("residence").getOriginalType()); - assertEquals(3, employeeVertexType.getPropertyByName("residence").getOrdinalPosition()); - assertEquals(false, employeeVertexType.getPropertyByName("residence").isFromPrimaryKey()); - - assertEquals(2, regularEmployeeVertexType.getProperties().size()); - - assertNotNull(regularEmployeeVertexType.getPropertyByName("salary")); - assertEquals("salary", regularEmployeeVertexType.getPropertyByName("salary").getName()); - assertEquals("DECIMAL", regularEmployeeVertexType.getPropertyByName("salary").getOriginalType()); - assertEquals(1, regularEmployeeVertexType.getPropertyByName("salary").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getPropertyByName("salary").isFromPrimaryKey()); - - assertNotNull(regularEmployeeVertexType.getPropertyByName("bonus")); - assertEquals("bonus", regularEmployeeVertexType.getPropertyByName("bonus").getName()); - assertEquals("DECIMAL", regularEmployeeVertexType.getPropertyByName("bonus").getOriginalType()); - assertEquals(2, regularEmployeeVertexType.getPropertyByName("bonus").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getPropertyByName("bonus").isFromPrimaryKey()); - - assertEquals(2, contractEmployeeVertexType.getProperties().size()); - - assertNotNull(contractEmployeeVertexType.getPropertyByName("payPerHour")); - assertEquals("payPerHour", contractEmployeeVertexType.getPropertyByName("payPerHour").getName()); - assertEquals("DECIMAL", contractEmployeeVertexType.getPropertyByName("payPerHour").getOriginalType()); - assertEquals(1, contractEmployeeVertexType.getPropertyByName("payPerHour").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getPropertyByName("payPerHour").isFromPrimaryKey()); - - assertNotNull(contractEmployeeVertexType.getPropertyByName("contractDuration")); - assertEquals("contractDuration", contractEmployeeVertexType.getPropertyByName("contractDuration").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getPropertyByName("contractDuration").getOriginalType()); - assertEquals(2, contractEmployeeVertexType.getPropertyByName("contractDuration").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getPropertyByName("contractDuration").isFromPrimaryKey()); - - assertEquals(3, residenceVertexType.getProperties().size()); - - assertNotNull(residenceVertexType.getPropertyByName("id")); - assertEquals("id", residenceVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", residenceVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, residenceVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, residenceVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(residenceVertexType.getPropertyByName("city")); - assertEquals("city", residenceVertexType.getPropertyByName("city").getName()); - assertEquals("VARCHAR", residenceVertexType.getPropertyByName("city").getOriginalType()); - assertEquals(2, residenceVertexType.getPropertyByName("city").getOrdinalPosition()); - assertEquals(false, residenceVertexType.getPropertyByName("city").isFromPrimaryKey()); - - assertNotNull(residenceVertexType.getPropertyByName("country")); - assertEquals("country", residenceVertexType.getPropertyByName("country").getName()); - assertEquals("VARCHAR", residenceVertexType.getPropertyByName("country").getOriginalType()); - assertEquals(3, residenceVertexType.getPropertyByName("country").getOrdinalPosition()); - assertEquals(false, residenceVertexType.getPropertyByName("country").isFromPrimaryKey()); - - // inherited properties check - assertEquals(0, employeeVertexType.getInheritedProperties().size()); - - assertEquals(3, regularEmployeeVertexType.getInheritedProperties().size()); - - assertNotNull(regularEmployeeVertexType.getInheritedPropertyByName("id")); - assertEquals("id", regularEmployeeVertexType.getInheritedPropertyByName("id").getName()); - assertEquals("VARCHAR", regularEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()); - assertEquals(1, regularEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(regularEmployeeVertexType.getInheritedPropertyByName("name")); - assertEquals("name", regularEmployeeVertexType.getInheritedPropertyByName("name").getName()); - assertEquals("VARCHAR", regularEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()); - assertEquals(2, regularEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(regularEmployeeVertexType.getInheritedPropertyByName("residence")); - assertEquals("residence", regularEmployeeVertexType.getInheritedPropertyByName("residence").getName()); - assertEquals("VARCHAR", regularEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()); - assertEquals(3, regularEmployeeVertexType.getInheritedPropertyByName("residence").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()); - - assertEquals(3, contractEmployeeVertexType.getInheritedProperties().size()); - - assertNotNull(contractEmployeeVertexType.getInheritedPropertyByName("id")); - assertEquals("id", contractEmployeeVertexType.getInheritedPropertyByName("id").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()); - assertEquals(1, contractEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(contractEmployeeVertexType.getInheritedPropertyByName("name")); - assertEquals("name", contractEmployeeVertexType.getInheritedPropertyByName("name").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()); - assertEquals(2, contractEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(contractEmployeeVertexType.getInheritedPropertyByName("residence")); - assertEquals("residence", contractEmployeeVertexType.getInheritedPropertyByName("residence").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()); - assertEquals(3, contractEmployeeVertexType.getInheritedPropertyByName("residence").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()); - - assertEquals(0, residenceVertexType.getInheritedProperties().size()); - - // edges check - - assertEquals(1, mapper.getRelationship2edgeType().size()); - - assertEquals(1, mapper.getGraphModel().getEdgesType().size()); - assertEquals("HasResidence", mapper.getGraphModel().getEdgesType().get(0).getName()); - - assertEquals(1, employeeVertexType.getOutEdgesType().size()); - assertEquals("HasResidence", employeeVertexType.getOutEdgesType().get(0).getName()); - - assertEquals(1, regularEmployeeVertexType.getOutEdgesType().size()); - assertEquals("HasResidence", regularEmployeeVertexType.getOutEdgesType().get(0).getName()); - - assertEquals(1, contractEmployeeVertexType.getOutEdgesType().size()); - assertEquals("HasResidence", contractEmployeeVertexType.getOutEdgesType().get(0).getName()); - - // inheritance check - assertEquals(employeeVertexType, regularEmployeeVertexType.getParentType()); - assertEquals(employeeVertexType, contractEmployeeVertexType.getParentType()); - assertNull(employeeVertexType.getParentType()); - - assertEquals(1, regularEmployeeVertexType.getInheritanceLevel()); - assertEquals(1, contractEmployeeVertexType.getInheritanceLevel()); - assertEquals(0, employeeVertexType.getInheritanceLevel()); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } finally { - try { - // Dropping Source DB Schema and OrientGraph - String dbDropping = "drop schema public cascade"; - st.execute(dbDropping); - connection.close(); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } - } + } + + /* + * Table per Subclass Inheritance ( tags) + * 3 tables, one parent and 2 children ( http://www.javatpoint.com/table-per-subclass ) + */ + + @Test + void TablePerSubclassInheritanceSyntax2() { + Connection connection = null; + Statement st = null; + + try { + Class.forName("org.hsqldb.jdbc.JDBCDriver"); + connection = DriverManager.getConnection(this.jurl, this.username, this.password); + + String residence = + "create memory table RESIDENCE(ID varchar(256) not null, CITY varchar(256), COUNTRY" + + " varchar(256), primary key (ID))"; + st = connection.createStatement(); + st.execute(residence); + + String employeeTableBuilding = + "create memory table EMPLOYEE (ID varchar(256) not null, NAME varchar(256), RESIDENCE" + + " varchar(256), primary key (ID), foreign key (RESIDENCE) references" + + " RESIDENCE(ID))"; + st.execute(employeeTableBuilding); + + String regularEmployeeTableBuilding = + "create memory table REGULAR_EMPLOYEE (EID varchar(256) not null, SALARY decimal(10,2)," + + " BONUS decimal(10,0), primary key (EID), foreign key (EID) references" + + " EMPLOYEE(ID))"; + st.execute(regularEmployeeTableBuilding); + + String contractEmployeeTableBuilding = + "create memory table CONTRACT_EMPLOYEE (EID varchar(256) not null, PAY_PER_HOUR" + + " decimal(10,2), CONTRACT_DURATION varchar(256), primary key (EID), foreign key" + + " (EID) references EMPLOYEE(ID))"; + st.execute(contractEmployeeTableBuilding); + + this.mapper = + new Hibernate2GraphMapper( + dataSource, + HibernateMapperTest.XML_TABLE_PER_SUBCLASS2, + null, + null, + dbQueryEngine, + dataTypeHandler, + executionStrategy, + nameResolver, + statistics); + + mapper.buildSourceDatabaseSchema(); + mapper.buildGraphModel(new JavaConventionNameResolver()); + + /* + * Testing context information + */ + + assertThat(statistics.totalNumberOfEntities).isEqualTo(4); + assertThat(statistics.builtEntities).isEqualTo(4); + assertThat(statistics.totalNumberOfRelationships).isEqualTo(3); + assertThat(statistics.builtRelationships).isEqualTo(3); + + assertThat(statistics.totalNumberOfModelVertices).isEqualTo(4); + assertThat(statistics.builtModelVertexTypes).isEqualTo(4); + assertThat(statistics.totalNumberOfModelEdges).isEqualTo(1); + assertThat(statistics.builtModelEdgeTypes).isEqualTo(1); + + /* + * Testing built source db schema + */ + + Entity employeeEntity = mapper.getDataBaseSchema().getEntityByName("EMPLOYEE"); + Entity regularEmployeeEntity = mapper.getDataBaseSchema().getEntityByName("REGULAR_EMPLOYEE"); + Entity contractEmployeeEntity = + mapper.getDataBaseSchema().getEntityByName("CONTRACT_EMPLOYEE"); + Entity residenceEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("RESIDENCE"); + + // entities check + assertThat(mapper.getDataBaseSchema().getEntities().size()).isEqualTo(4); + assertThat(mapper.getDataBaseSchema().getCanonicalRelationships().size()).isEqualTo(3); + assertThat(employeeEntity).isNotNull(); + assertThat(regularEmployeeEntity).isNotNull(); + assertThat(contractEmployeeEntity).isNotNull(); + assertThat(residenceEntity).isNotNull(); + + // attributes check + assertThat(employeeEntity.getAttributes().size()).isEqualTo(3); + + assertThat(employeeEntity.getAttributeByName("ID")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(employeeEntity.getAttributeByName("ID").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("ID").getOrdinalPosition()).isEqualTo(1); + assertThat(employeeEntity.getAttributeByName("ID").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(employeeEntity.getAttributeByName("NAME")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("NAME").getName()).isEqualTo("NAME"); + assertThat(employeeEntity.getAttributeByName("NAME").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("NAME").getOrdinalPosition()).isEqualTo(2); + assertThat(employeeEntity.getAttributeByName("NAME").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(employeeEntity.getAttributeByName("RESIDENCE")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getName()).isEqualTo("RESIDENCE"); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getOrdinalPosition()).isEqualTo(3); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(regularEmployeeEntity.getAttributes().size()).isEqualTo(2); + + assertThat(regularEmployeeEntity.getAttributeByName("SALARY")).isNotNull(); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getName()).isEqualTo("SALARY"); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getDataType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getOrdinalPosition()) + .isEqualTo(1); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getBelongingEntity().getName()) + .isEqualTo("REGULAR_EMPLOYEE"); + + assertThat(regularEmployeeEntity.getAttributeByName("BONUS")).isNotNull(); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getName()).isEqualTo("BONUS"); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getDataType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getOrdinalPosition()) + .isEqualTo(2); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getBelongingEntity().getName()) + .isEqualTo("REGULAR_EMPLOYEE"); + + assertThat(contractEmployeeEntity.getAttributes().size()).isEqualTo(2); + + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR")).isNotNull(); + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getName()) + .isEqualTo("PAY_PER_HOUR"); + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getDataType()) + .isEqualTo("DECIMAL"); + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getOrdinalPosition()) + .isEqualTo(1); + assertThat( + contractEmployeeEntity + .getAttributeByName("PAY_PER_HOUR") + .getBelongingEntity() + .getName()) + .isEqualTo("CONTRACT_EMPLOYEE"); + + assertThat(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION")).isNotNull(); + assertThat(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getName()) + .isEqualTo("CONTRACT_DURATION"); + assertThat(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + contractEmployeeEntity + .getAttributeByName("CONTRACT_DURATION") + .getBelongingEntity() + .getName()) + .isEqualTo("CONTRACT_EMPLOYEE"); + + // inherited attributes check + assertThat(employeeEntity.getInheritedAttributes().size()).isEqualTo(0); + + assertThat(regularEmployeeEntity.getInheritedAttributes().size()).isEqualTo(3); + + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID")).isNotNull(); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()) + .isEqualTo(1); + assertThat( + regularEmployeeEntity + .getInheritedAttributeByName("ID") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME")).isNotNull(); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME").getName()) + .isEqualTo("NAME"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + regularEmployeeEntity + .getInheritedAttributeByName("NAME") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE")).isNotNull(); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()) + .isEqualTo("RESIDENCE"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()) + .isEqualTo(3); + assertThat( + regularEmployeeEntity + .getInheritedAttributeByName("RESIDENCE") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(contractEmployeeEntity.getInheritedAttributes().size()).isEqualTo(3); + + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID")).isNotNull(); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID").getName()) + .isEqualTo("ID"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()) + .isEqualTo(1); + assertThat( + contractEmployeeEntity + .getInheritedAttributeByName("ID") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME")).isNotNull(); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME").getName()) + .isEqualTo("NAME"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + contractEmployeeEntity + .getInheritedAttributeByName("NAME") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE")).isNotNull(); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()) + .isEqualTo("RESIDENCE"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()) + .isEqualTo(3); + assertThat( + contractEmployeeEntity + .getInheritedAttributeByName("RESIDENCE") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + // primary key check + assertThat(regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()).isEqualTo(1); + assertThat(regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()) + .isEqualTo("EID"); + assertThat(regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + regularEmployeeEntity + .getPrimaryKey() + .getInvolvedAttributes() + .get(0) + .getBelongingEntity() + .getName()) + .isEqualTo("REGULAR_EMPLOYEE"); + + assertThat(contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()) + .isEqualTo(1); + assertThat(contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()) + .isEqualTo("EID"); + assertThat( + contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeEntity + .getPrimaryKey() + .getInvolvedAttributes() + .get(0) + .getBelongingEntity() + .getName()) + .isEqualTo("CONTRACT_EMPLOYEE"); + + // relationship, primary and foreign key check + assertThat(regularEmployeeEntity.getOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(contractEmployeeEntity.getOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(employeeEntity.getOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(residenceEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(regularEmployeeEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(contractEmployeeEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(employeeEntity.getInCanonicalRelationships().size()).isEqualTo(2); + assertThat(residenceEntity.getInCanonicalRelationships().size()).isEqualTo(1); + + assertThat(regularEmployeeEntity.getForeignKeys().size()).isEqualTo(1); + assertThat(contractEmployeeEntity.getForeignKeys().size()).isEqualTo(1); + assertThat(employeeEntity.getForeignKeys().size()).isEqualTo(1); + assertThat(residenceEntity.getForeignKeys().size()).isEqualTo(0); + + Iterator itEmp = + employeeEntity.getOutCanonicalRelationships().iterator(); + Iterator itRegEmp = + regularEmployeeEntity.getOutCanonicalRelationships().iterator(); + Iterator itContEmp = + contractEmployeeEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship currentEmpRel = itEmp.next(); + CanonicalRelationship currentRegEmpRel = itRegEmp.next(); + CanonicalRelationship currentContEmpRel = itContEmp.next(); + assertThat(currentEmpRel.getParentEntity().getName()).isEqualTo("RESIDENCE"); + assertThat(currentEmpRel.getForeignEntity().getName()).isEqualTo("EMPLOYEE"); + assertThat(currentRegEmpRel.getParentEntity().getName()).isEqualTo("EMPLOYEE"); + assertThat(currentRegEmpRel.getForeignEntity().getName()).isEqualTo("REGULAR_EMPLOYEE"); + assertThat(currentContEmpRel.getParentEntity().getName()).isEqualTo("EMPLOYEE"); + assertThat(currentContEmpRel.getForeignEntity().getName()).isEqualTo("CONTRACT_EMPLOYEE"); + assertThat(currentEmpRel.getPrimaryKey()).isEqualTo(residenceEntity.getPrimaryKey()); + assertThat(currentEmpRel.getForeignKey()).isEqualTo(employeeEntity.getForeignKeys().get(0)); + assertThat(currentRegEmpRel.getPrimaryKey()).isEqualTo(employeeEntity.getPrimaryKey()); + assertThat(currentRegEmpRel.getForeignKey()) + .isEqualTo(regularEmployeeEntity.getForeignKeys().get(0)); + assertThat(currentContEmpRel.getPrimaryKey()).isEqualTo(employeeEntity.getPrimaryKey()); + assertThat(currentContEmpRel.getForeignKey()) + .isEqualTo(contractEmployeeEntity.getForeignKeys().get(0)); + assertThat(itEmp.hasNext()).isFalse(); + assertThat(itRegEmp.hasNext()).isFalse(); + assertThat(itContEmp.hasNext()).isFalse(); + + Iterator itRes = + residenceEntity.getInCanonicalRelationships().iterator(); + CanonicalRelationship currentResRel = itRes.next(); + assertThat(currentResRel).isEqualTo(currentEmpRel); + + itEmp = employeeEntity.getInCanonicalRelationships().iterator(); + currentEmpRel = itEmp.next(); + assertThat(currentContEmpRel).isEqualTo(currentEmpRel); + + currentEmpRel = itEmp.next(); + assertThat(currentRegEmpRel).isEqualTo(currentEmpRel); + + // inherited relationships check + assertThat(regularEmployeeEntity.getInheritedOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(contractEmployeeEntity.getInheritedOutCanonicalRelationships().size()) + .isEqualTo(1); + assertThat(employeeEntity.getInheritedOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(residenceEntity.getInheritedOutCanonicalRelationships().size()).isEqualTo(0); + + itRegEmp = regularEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); + itContEmp = contractEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); + currentRegEmpRel = itRegEmp.next(); + currentContEmpRel = itContEmp.next(); + assertThat(currentRegEmpRel.getParentEntity().getName()).isEqualTo("RESIDENCE"); + assertThat(currentRegEmpRel.getForeignEntity().getName()).isEqualTo("EMPLOYEE"); + assertThat(currentContEmpRel.getParentEntity().getName()).isEqualTo("RESIDENCE"); + assertThat(currentContEmpRel.getForeignEntity().getName()).isEqualTo("EMPLOYEE"); + assertThat(currentRegEmpRel.getPrimaryKey()).isEqualTo(residenceEntity.getPrimaryKey()); + assertThat(currentRegEmpRel.getFromColumns().size()).isEqualTo(1); + assertThat(currentRegEmpRel.getFromColumns().get(0).getName()).isEqualTo("RESIDENCE"); + assertThat(currentContEmpRel.getPrimaryKey()).isEqualTo(residenceEntity.getPrimaryKey()); + assertThat(currentContEmpRel.getFromColumns().size()).isEqualTo(1); + assertThat(currentContEmpRel.getFromColumns().get(0).getName()).isEqualTo("RESIDENCE"); + assertThat(itRegEmp.hasNext()).isFalse(); + assertThat(itContEmp.hasNext()).isFalse(); + + // inheritance check + assertThat(regularEmployeeEntity.getParentEntity()).isEqualTo(employeeEntity); + assertThat(contractEmployeeEntity.getParentEntity()).isEqualTo(employeeEntity); + assertThat(employeeEntity.getParentEntity()).isNull(); + assertThat(residenceEntity.getParentEntity()).isNull(); + + assertThat(regularEmployeeEntity.getInheritanceLevel()).isEqualTo(1); + assertThat(contractEmployeeEntity.getInheritanceLevel()).isEqualTo(1); + assertThat(employeeEntity.getInheritanceLevel()).isEqualTo(0); + assertThat(residenceEntity.getInheritanceLevel()).isEqualTo(0); + + // Hierarchical Bag check + assertThat(mapper.getDataBaseSchema().getHierarchicalBags().size()).isEqualTo(1); + HierarchicalBag hierarchicalBag = mapper.getDataBaseSchema().getHierarchicalBags().get(0); + assertThat(hierarchicalBag.getInheritancePattern()).isEqualTo("table-per-type"); + + assertThat(hierarchicalBag.getDepth2entities().size()).isEqualTo(2); + + assertThat(hierarchicalBag.getDepth2entities().get(0).size()).isEqualTo(1); + Iterator it = hierarchicalBag.getDepth2entities().get(0).iterator(); + assertThat(it.next().getName()).isEqualTo("EMPLOYEE"); + assertThat(it.hasNext()).isFalse(); + + assertThat(hierarchicalBag.getDepth2entities().get(1).size()).isEqualTo(2); + it = hierarchicalBag.getDepth2entities().get(1).iterator(); + assertThat(it.next().getName()).isEqualTo("REGULAR_EMPLOYEE"); + assertThat(it.next().getName()).isEqualTo("CONTRACT_EMPLOYEE"); + assertThat(it.hasNext()).isFalse(); + + assertThat(employeeEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag); + assertThat(regularEmployeeEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag); + assertThat(contractEmployeeEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag); + + assertThat(hierarchicalBag.getDiscriminatorColumn()).isNotNull(); + assertThat(hierarchicalBag.getDiscriminatorColumn()).isEqualTo("employee_type"); + + /* + * Testing built graph model + */ + + VertexType employeeVertexType = mapper.getGraphModel().getVertexTypeByName("Employee"); + VertexType regularEmployeeVertexType = + mapper.getGraphModel().getVertexTypeByName("RegularEmployee"); + VertexType contractEmployeeVertexType = + mapper.getGraphModel().getVertexTypeByName("ContractEmployee"); + VertexType residenceVertexType = mapper.getGraphModel().getVertexTypeByName("Residence"); + + // vertices check + assertThat(mapper.getGraphModel().getVerticesType().size()).isEqualTo(4); + assertThat(employeeVertexType).isNotNull(); + assertThat(regularEmployeeVertexType).isNotNull(); + assertThat(contractEmployeeVertexType).isNotNull(); + assertThat(residenceVertexType).isNotNull(); + + // properties check + assertThat(employeeVertexType.getProperties().size()).isEqualTo(3); + + assertThat(employeeVertexType.getPropertyByName("id")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(employeeVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(employeeVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(employeeVertexType.getPropertyByName("name")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("name").getName()).isEqualTo("name"); + assertThat(employeeVertexType.getPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("name").getOrdinalPosition()).isEqualTo(2); + assertThat(employeeVertexType.getPropertyByName("name").isFromPrimaryKey()).isFalse(); + + assertThat(employeeVertexType.getPropertyByName("residence")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("residence").getName()) + .isEqualTo("residence"); + assertThat(employeeVertexType.getPropertyByName("residence").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("residence").getOrdinalPosition()) + .isEqualTo(3); + assertThat(employeeVertexType.getPropertyByName("residence").isFromPrimaryKey()).isFalse(); + + assertThat(regularEmployeeVertexType.getProperties().size()).isEqualTo(2); + + assertThat(regularEmployeeVertexType.getPropertyByName("salary")).isNotNull(); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").getName()) + .isEqualTo("salary"); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").getOriginalType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").getOrdinalPosition()) + .isEqualTo(1); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").isFromPrimaryKey()) + .isFalse(); + + assertThat(regularEmployeeVertexType.getPropertyByName("bonus")).isNotNull(); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").getName()).isEqualTo("bonus"); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").getOriginalType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").getOrdinalPosition()) + .isEqualTo(2); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").isFromPrimaryKey()).isFalse(); + + assertThat(contractEmployeeVertexType.getProperties().size()).isEqualTo(2); + + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour")).isNotNull(); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").getName()) + .isEqualTo("payPerHour"); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").getOriginalType()) + .isEqualTo("DECIMAL"); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").getOrdinalPosition()) + .isEqualTo(1); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getPropertyByName("contractDuration")).isNotNull(); + assertThat(contractEmployeeVertexType.getPropertyByName("contractDuration").getName()) + .isEqualTo("contractDuration"); + assertThat(contractEmployeeVertexType.getPropertyByName("contractDuration").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeVertexType.getPropertyByName("contractDuration").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + contractEmployeeVertexType.getPropertyByName("contractDuration").isFromPrimaryKey()) + .isFalse(); + + assertThat(residenceVertexType.getProperties().size()).isEqualTo(3); + + assertThat(residenceVertexType.getPropertyByName("id")).isNotNull(); + assertThat(residenceVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(residenceVertexType.getPropertyByName("id").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(residenceVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(residenceVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(residenceVertexType.getPropertyByName("city")).isNotNull(); + assertThat(residenceVertexType.getPropertyByName("city").getName()).isEqualTo("city"); + assertThat(residenceVertexType.getPropertyByName("city").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(residenceVertexType.getPropertyByName("city").getOrdinalPosition()).isEqualTo(2); + assertThat(residenceVertexType.getPropertyByName("city").isFromPrimaryKey()).isFalse(); + + assertThat(residenceVertexType.getPropertyByName("country")).isNotNull(); + assertThat(residenceVertexType.getPropertyByName("country").getName()).isEqualTo("country"); + assertThat(residenceVertexType.getPropertyByName("country").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(residenceVertexType.getPropertyByName("country").getOrdinalPosition()) + .isEqualTo(3); + assertThat(residenceVertexType.getPropertyByName("country").isFromPrimaryKey()).isFalse(); + + // inherited properties check + assertThat(employeeVertexType.getInheritedProperties().size()).isEqualTo(0); + + assertThat(regularEmployeeVertexType.getInheritedProperties().size()).isEqualTo(3); + + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id")).isNotNull(); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").getName()) + .isEqualTo("id"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()) + .isEqualTo(1); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()) + .isFalse(); + + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name")).isNotNull(); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").getName()) + .isEqualTo("name"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()) + .isEqualTo(2); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()) + .isFalse(); + + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("residence")).isNotNull(); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("residence").getName()) + .isEqualTo("residence"); + assertThat( + regularEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + regularEmployeeVertexType + .getInheritedPropertyByName("residence") + .getOrdinalPosition()) + .isEqualTo(3); + assertThat( + regularEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getInheritedProperties().size()).isEqualTo(3); + + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id")).isNotNull(); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").getName()) + .isEqualTo("id"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()) + .isEqualTo(1); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name")).isNotNull(); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").getName()) + .isEqualTo("name"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()) + .isEqualTo(2); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("residence")).isNotNull(); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("residence").getName()) + .isEqualTo("residence"); + assertThat( + contractEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeVertexType + .getInheritedPropertyByName("residence") + .getOrdinalPosition()) + .isEqualTo(3); + assertThat( + contractEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()) + .isFalse(); + + assertThat(residenceVertexType.getInheritedProperties().size()).isEqualTo(0); + + // edges check + + assertThat(mapper.getRelationship2edgeType().size()).isEqualTo(1); + + assertThat(mapper.getGraphModel().getEdgesType().size()).isEqualTo(1); + assertThat(mapper.getGraphModel().getEdgesType().get(0).getName()).isEqualTo("HasResidence"); + + assertThat(employeeVertexType.getOutEdgesType().size()).isEqualTo(1); + assertThat(employeeVertexType.getOutEdgesType().get(0).getName()).isEqualTo("HasResidence"); + + assertThat(regularEmployeeVertexType.getOutEdgesType().size()).isEqualTo(1); + assertThat(regularEmployeeVertexType.getOutEdgesType().get(0).getName()) + .isEqualTo("HasResidence"); + + assertThat(contractEmployeeVertexType.getOutEdgesType().size()).isEqualTo(1); + assertThat(contractEmployeeVertexType.getOutEdgesType().get(0).getName()) + .isEqualTo("HasResidence"); + + // inheritance check + assertThat(regularEmployeeVertexType.getParentType()).isEqualTo(employeeVertexType); + assertThat(contractEmployeeVertexType.getParentType()).isEqualTo(employeeVertexType); + assertThat(employeeVertexType.getParentType()).isNull(); + + assertThat(regularEmployeeVertexType.getInheritanceLevel()).isEqualTo(1); + assertThat(contractEmployeeVertexType.getInheritanceLevel()).isEqualTo(1); + assertThat(employeeVertexType.getInheritanceLevel()).isEqualTo(0); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } finally { + try { + // Dropping Source DB Schema and OrientGraph + String dbDropping = "drop schema public cascade"; + st.execute(dbDropping); + connection.close(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } } - - @Test - /* - * Table per Concrete Class Inheritance ( tag) - * 3 tables, one parent and 2 childs ( http://www.javatpoint.com/table-per-concrete-class ) - */ - - public void TablePerConcreteClassInheritance() { - Connection connection = null; - Statement st = null; - - try { - Class.forName("org.hsqldb.jdbc.JDBCDriver"); - connection = DriverManager.getConnection(this.jurl, this.username, this.password); - - String residence = "create memory table RESIDENCE(ID varchar(256) not null, CITY varchar(256), COUNTRY varchar(256), primary key (ID))"; - st = connection.createStatement(); - st.execute(residence); - - String employeeTableBuilding = - "create memory table EMPLOYEE (ID varchar(256) not null," + - " NAME varchar(256), RESIDENCE varchar(256), primary key (ID), foreign key (RESIDENCE) references RESIDENCE(ID))"; - st.execute(employeeTableBuilding); - - String regularEmployeeTableBuilding = - "create memory table REGULAR_EMPLOYEE (ID varchar(256) not null, " + - "NAME varchar(256), RESIDENCE varchar(256), SALARY decimal(10,2), BONUS decimal(10,0), primary key (ID))"; - st.execute(regularEmployeeTableBuilding); - - String contractEmployeeTableBuilding = - "create memory table CONTRACT_EMPLOYEE (ID varchar(256) not null, " + - "NAME varchar(256), RESIDENCE varchar(256), PAY_PER_HOUR decimal(10,2), CONTRACT_DURATION varchar(256), primary key (ID))"; - st.execute(contractEmployeeTableBuilding); - - this.mapper = - new Hibernate2GraphMapper( - dataSource, - HibernateMapperTest.XML_TABLE_PER_CONCRETE_CLASS, - null, - null, - dbQueryEngine, - dataTypeHandler, - executionStrategy, - nameResolver, - statistics - ); - - mapper.buildSourceDatabaseSchema(); - mapper.buildGraphModel(new JavaConventionNameResolver()); - - /* - * Testing context information - */ - - assertEquals(4, statistics.totalNumberOfEntities); - assertEquals(4, statistics.builtEntities); - assertEquals(1, statistics.totalNumberOfRelationships); - assertEquals(1, statistics.builtRelationships); - - assertEquals(4, statistics.totalNumberOfModelVertices); - assertEquals(4, statistics.builtModelVertexTypes); - assertEquals(1, statistics.totalNumberOfModelEdges); - assertEquals(1, statistics.builtModelEdgeTypes); - - /* - * Testing built source db schema - */ - - Entity employeeEntity = mapper.getDataBaseSchema().getEntityByName("EMPLOYEE"); - Entity regularEmployeeEntity = mapper.getDataBaseSchema().getEntityByName("REGULAR_EMPLOYEE"); - Entity contractEmployeeEntity = mapper.getDataBaseSchema().getEntityByName("CONTRACT_EMPLOYEE"); - Entity residenceEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("RESIDENCE"); - - // entities check - assertEquals(4, mapper.getDataBaseSchema().getEntities().size()); - assertEquals(1, mapper.getDataBaseSchema().getCanonicalRelationships().size()); - assertNotNull(employeeEntity); - assertNotNull(regularEmployeeEntity); - assertNotNull(contractEmployeeEntity); - assertNotNull(residenceEntity); - - // attributes check - assertEquals(3, employeeEntity.getAttributes().size()); - - assertNotNull(employeeEntity.getAttributeByName("ID")); - assertEquals("ID", employeeEntity.getAttributeByName("ID").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("ID").getDataType()); - assertEquals(1, employeeEntity.getAttributeByName("ID").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(employeeEntity.getAttributeByName("NAME")); - assertEquals("NAME", employeeEntity.getAttributeByName("NAME").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("NAME").getDataType()); - assertEquals(2, employeeEntity.getAttributeByName("NAME").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(employeeEntity.getAttributeByName("RESIDENCE")); - assertEquals("RESIDENCE", employeeEntity.getAttributeByName("RESIDENCE").getName()); - assertEquals("VARCHAR", employeeEntity.getAttributeByName("RESIDENCE").getDataType()); - assertEquals(3, employeeEntity.getAttributeByName("RESIDENCE").getOrdinalPosition()); - assertEquals("EMPLOYEE", employeeEntity.getAttributeByName("RESIDENCE").getBelongingEntity().getName()); - - assertEquals(2, regularEmployeeEntity.getAttributes().size()); - - assertNotNull(regularEmployeeEntity.getAttributeByName("SALARY")); - assertEquals("SALARY", regularEmployeeEntity.getAttributeByName("SALARY").getName()); - assertEquals("DECIMAL", regularEmployeeEntity.getAttributeByName("SALARY").getDataType()); - assertEquals(1, regularEmployeeEntity.getAttributeByName("SALARY").getOrdinalPosition()); - assertEquals("REGULAR_EMPLOYEE", regularEmployeeEntity.getAttributeByName("SALARY").getBelongingEntity().getName()); - - assertNotNull(regularEmployeeEntity.getAttributeByName("BONUS")); - assertEquals("BONUS", regularEmployeeEntity.getAttributeByName("BONUS").getName()); - assertEquals("DECIMAL", regularEmployeeEntity.getAttributeByName("BONUS").getDataType()); - assertEquals(2, regularEmployeeEntity.getAttributeByName("BONUS").getOrdinalPosition()); - assertEquals("REGULAR_EMPLOYEE", regularEmployeeEntity.getAttributeByName("BONUS").getBelongingEntity().getName()); - - assertEquals(2, contractEmployeeEntity.getAttributes().size()); - - assertNotNull(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR")); - assertEquals("PAY_PER_HOUR", contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getName()); - assertEquals("DECIMAL", contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getDataType()); - assertEquals(1, contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getOrdinalPosition()); - assertEquals("CONTRACT_EMPLOYEE", contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getBelongingEntity().getName()); - - assertNotNull(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION")); - assertEquals("CONTRACT_DURATION", contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getDataType()); - assertEquals(2, contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getOrdinalPosition()); - assertEquals("CONTRACT_EMPLOYEE", contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getBelongingEntity().getName()); - - // inherited attributes check - assertEquals(0, employeeEntity.getInheritedAttributes().size()); - - assertEquals(3, regularEmployeeEntity.getInheritedAttributes().size()); - - assertNotNull(regularEmployeeEntity.getInheritedAttributeByName("ID")); - assertEquals("ID", regularEmployeeEntity.getInheritedAttributeByName("ID").getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getInheritedAttributeByName("ID").getDataType()); - assertEquals(1, regularEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()); - assertEquals("EMPLOYEE", regularEmployeeEntity.getInheritedAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(regularEmployeeEntity.getInheritedAttributeByName("NAME")); - assertEquals("NAME", regularEmployeeEntity.getInheritedAttributeByName("NAME").getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()); - assertEquals(2, regularEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()); - assertEquals("EMPLOYEE", regularEmployeeEntity.getInheritedAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE")); - assertEquals("RESIDENCE", regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()); - assertEquals(3, regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()); - assertEquals("EMPLOYEE", regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getBelongingEntity().getName()); - - assertEquals(3, contractEmployeeEntity.getInheritedAttributes().size()); - - assertNotNull(contractEmployeeEntity.getInheritedAttributeByName("ID")); - assertEquals("ID", contractEmployeeEntity.getInheritedAttributeByName("ID").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getInheritedAttributeByName("ID").getDataType()); - assertEquals(1, contractEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()); - assertEquals("EMPLOYEE", contractEmployeeEntity.getInheritedAttributeByName("ID").getBelongingEntity().getName()); - - assertNotNull(contractEmployeeEntity.getInheritedAttributeByName("NAME")); - assertEquals("NAME", contractEmployeeEntity.getInheritedAttributeByName("NAME").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()); - assertEquals(2, contractEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()); - assertEquals("EMPLOYEE", contractEmployeeEntity.getInheritedAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE")); - assertEquals("RESIDENCE", contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()); - assertEquals(3, contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()); - assertEquals("EMPLOYEE", contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getBelongingEntity().getName()); - - // primary key check (not "inherited") - assertEquals(1, regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()); - assertEquals("ID", regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()); - assertEquals("VARCHAR", regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()); - assertEquals("REGULAR_EMPLOYEE", regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getBelongingEntity().getName()); - - assertEquals(1, contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()); - assertEquals("ID", contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()); - assertEquals("VARCHAR", contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()); - assertEquals("CONTRACT_EMPLOYEE", contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getBelongingEntity().getName()); - - // relationship, primary and foreign key check - assertEquals(0, regularEmployeeEntity.getOutCanonicalRelationships().size()); - assertEquals(0, contractEmployeeEntity.getOutCanonicalRelationships().size()); - assertEquals(1, employeeEntity.getOutCanonicalRelationships().size()); - assertEquals(0, residenceEntity.getOutCanonicalRelationships().size()); - assertEquals(0, regularEmployeeEntity.getInCanonicalRelationships().size()); - assertEquals(0, contractEmployeeEntity.getInCanonicalRelationships().size()); - assertEquals(0, employeeEntity.getInCanonicalRelationships().size()); - assertEquals(1, residenceEntity.getInCanonicalRelationships().size()); - - assertEquals(0, regularEmployeeEntity.getForeignKeys().size()); - assertEquals(0, contractEmployeeEntity.getForeignKeys().size()); - assertEquals(1, employeeEntity.getForeignKeys().size()); - assertEquals(0, residenceEntity.getForeignKeys().size()); - - Iterator itEmp = employeeEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship currentEmpRel = itEmp.next(); - assertEquals("RESIDENCE", currentEmpRel.getParentEntity().getName()); - assertEquals("EMPLOYEE", currentEmpRel.getForeignEntity().getName()); - assertEquals(residenceEntity.getPrimaryKey(), currentEmpRel.getPrimaryKey()); - assertEquals(employeeEntity.getForeignKeys().get(0), currentEmpRel.getForeignKey()); - assertFalse(itEmp.hasNext()); - - Iterator itRes = residenceEntity.getInCanonicalRelationships().iterator(); - CanonicalRelationship currentResRel = itRes.next(); - assertEquals(currentEmpRel, currentResRel); - - // inherited relationships check - assertEquals(1, regularEmployeeEntity.getInheritedOutCanonicalRelationships().size()); - assertEquals(1, contractEmployeeEntity.getInheritedOutCanonicalRelationships().size()); - assertEquals(0, employeeEntity.getInheritedOutCanonicalRelationships().size()); - assertEquals(0, residenceEntity.getInheritedOutCanonicalRelationships().size()); - - Iterator itRegEmp = regularEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); - Iterator itContEmp = contractEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); - CanonicalRelationship currentRegEmpRel = itRegEmp.next(); - CanonicalRelationship currentContEmpRel = itContEmp.next(); - assertEquals("RESIDENCE", currentRegEmpRel.getParentEntity().getName()); - assertEquals("EMPLOYEE", currentRegEmpRel.getForeignEntity().getName()); - assertEquals("RESIDENCE", currentContEmpRel.getParentEntity().getName()); - assertEquals("EMPLOYEE", currentContEmpRel.getForeignEntity().getName()); - assertEquals(residenceEntity.getPrimaryKey(), currentRegEmpRel.getPrimaryKey()); - assertEquals(1, currentRegEmpRel.getFromColumns().size()); - assertEquals("RESIDENCE", currentRegEmpRel.getFromColumns().get(0).getName()); - assertEquals(residenceEntity.getPrimaryKey(), currentContEmpRel.getPrimaryKey()); - assertEquals(1, currentContEmpRel.getFromColumns().size()); - assertEquals("RESIDENCE", currentContEmpRel.getFromColumns().get(0).getName()); - assertFalse(itRegEmp.hasNext()); - assertFalse(itContEmp.hasNext()); - - // inheritance check - assertEquals(employeeEntity, regularEmployeeEntity.getParentEntity()); - assertEquals(employeeEntity, contractEmployeeEntity.getParentEntity()); - assertNull(employeeEntity.getParentEntity()); - assertNull(residenceEntity.getParentEntity()); - - assertEquals(1, regularEmployeeEntity.getInheritanceLevel()); - assertEquals(1, contractEmployeeEntity.getInheritanceLevel()); - assertEquals(0, employeeEntity.getInheritanceLevel()); - assertEquals(0, residenceEntity.getInheritanceLevel()); - - // Hierarchical Bag check - assertEquals(1, mapper.getDataBaseSchema().getHierarchicalBags().size()); - HierarchicalBag hierarchicalBag = mapper.getDataBaseSchema().getHierarchicalBags().get(0); - assertEquals("table-per-concrete-type", hierarchicalBag.getInheritancePattern()); - - assertEquals(2, hierarchicalBag.getDepth2entities().size()); - - assertEquals(1, hierarchicalBag.getDepth2entities().get(0).size()); - Iterator it = hierarchicalBag.getDepth2entities().get(0).iterator(); - assertEquals("EMPLOYEE", it.next().getName()); - assertTrue(!it.hasNext()); - - assertEquals(2, hierarchicalBag.getDepth2entities().get(1).size()); - it = hierarchicalBag.getDepth2entities().get(1).iterator(); - assertEquals("REGULAR_EMPLOYEE", it.next().getName()); - assertEquals("CONTRACT_EMPLOYEE", it.next().getName()); - assertTrue(!it.hasNext()); - - assertEquals(hierarchicalBag, employeeEntity.getHierarchicalBag()); - assertEquals(hierarchicalBag, regularEmployeeEntity.getHierarchicalBag()); - assertEquals(hierarchicalBag, contractEmployeeEntity.getHierarchicalBag()); - - assertNull(hierarchicalBag.getDiscriminatorColumn()); - - /* - * Testing built graph model - */ - - VertexType employeeVertexType = mapper.getGraphModel().getVertexTypeByName("Employee"); - VertexType regularEmployeeVertexType = mapper.getGraphModel().getVertexTypeByName("RegularEmployee"); - VertexType contractEmployeeVertexType = mapper.getGraphModel().getVertexTypeByName("ContractEmployee"); - VertexType residenceVertexType = mapper.getGraphModel().getVertexTypeByName("Residence"); - - // vertices check - assertEquals(4, mapper.getGraphModel().getVerticesType().size()); - assertNotNull(employeeVertexType); - assertNotNull(regularEmployeeVertexType); - assertNotNull(contractEmployeeVertexType); - assertNotNull(residenceVertexType); - - // properties check - assertEquals(3, employeeVertexType.getProperties().size()); - - assertNotNull(employeeVertexType.getPropertyByName("id")); - assertEquals("id", employeeVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, employeeVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, employeeVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(employeeVertexType.getPropertyByName("name")); - assertEquals("name", employeeVertexType.getPropertyByName("name").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("name").getOriginalType()); - assertEquals(2, employeeVertexType.getPropertyByName("name").getOrdinalPosition()); - assertEquals(false, employeeVertexType.getPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(employeeVertexType.getPropertyByName("residence")); - assertEquals("residence", employeeVertexType.getPropertyByName("residence").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("residence").getOriginalType()); - assertEquals(3, employeeVertexType.getPropertyByName("residence").getOrdinalPosition()); - assertEquals(false, employeeVertexType.getPropertyByName("residence").isFromPrimaryKey()); - - assertEquals(2, regularEmployeeVertexType.getProperties().size()); - - assertNotNull(regularEmployeeVertexType.getPropertyByName("salary")); - assertEquals("salary", regularEmployeeVertexType.getPropertyByName("salary").getName()); - assertEquals("DECIMAL", regularEmployeeVertexType.getPropertyByName("salary").getOriginalType()); - assertEquals(1, regularEmployeeVertexType.getPropertyByName("salary").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getPropertyByName("salary").isFromPrimaryKey()); - - assertNotNull(regularEmployeeVertexType.getPropertyByName("bonus")); - assertEquals("bonus", regularEmployeeVertexType.getPropertyByName("bonus").getName()); - assertEquals("DECIMAL", regularEmployeeVertexType.getPropertyByName("bonus").getOriginalType()); - assertEquals(2, regularEmployeeVertexType.getPropertyByName("bonus").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getPropertyByName("bonus").isFromPrimaryKey()); - - assertEquals(2, contractEmployeeVertexType.getProperties().size()); - - assertNotNull(contractEmployeeVertexType.getPropertyByName("payPerHour")); - assertEquals("payPerHour", contractEmployeeVertexType.getPropertyByName("payPerHour").getName()); - assertEquals("DECIMAL", contractEmployeeVertexType.getPropertyByName("payPerHour").getOriginalType()); - assertEquals(1, contractEmployeeVertexType.getPropertyByName("payPerHour").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getPropertyByName("payPerHour").isFromPrimaryKey()); - - assertNotNull(contractEmployeeVertexType.getPropertyByName("contractDuration")); - assertEquals("contractDuration", contractEmployeeVertexType.getPropertyByName("contractDuration").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getPropertyByName("contractDuration").getOriginalType()); - assertEquals(2, contractEmployeeVertexType.getPropertyByName("contractDuration").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getPropertyByName("contractDuration").isFromPrimaryKey()); - - assertEquals(3, residenceVertexType.getProperties().size()); - - assertNotNull(residenceVertexType.getPropertyByName("id")); - assertEquals("id", residenceVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", residenceVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, residenceVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, residenceVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(residenceVertexType.getPropertyByName("city")); - assertEquals("city", residenceVertexType.getPropertyByName("city").getName()); - assertEquals("VARCHAR", residenceVertexType.getPropertyByName("city").getOriginalType()); - assertEquals(2, residenceVertexType.getPropertyByName("city").getOrdinalPosition()); - assertEquals(false, residenceVertexType.getPropertyByName("city").isFromPrimaryKey()); - - assertNotNull(residenceVertexType.getPropertyByName("country")); - assertEquals("country", residenceVertexType.getPropertyByName("country").getName()); - assertEquals("VARCHAR", residenceVertexType.getPropertyByName("country").getOriginalType()); - assertEquals(3, residenceVertexType.getPropertyByName("country").getOrdinalPosition()); - assertEquals(false, residenceVertexType.getPropertyByName("country").isFromPrimaryKey()); - - // inherited properties check - assertEquals(0, employeeVertexType.getInheritedProperties().size()); - - assertEquals(3, regularEmployeeVertexType.getInheritedProperties().size()); - - assertNotNull(regularEmployeeVertexType.getInheritedPropertyByName("id")); - assertEquals("id", regularEmployeeVertexType.getInheritedPropertyByName("id").getName()); - assertEquals("VARCHAR", regularEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()); - assertEquals(1, regularEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()); - assertEquals(true, regularEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(regularEmployeeVertexType.getInheritedPropertyByName("name")); - assertEquals("name", regularEmployeeVertexType.getInheritedPropertyByName("name").getName()); - assertEquals("VARCHAR", regularEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()); - assertEquals(2, regularEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(regularEmployeeVertexType.getInheritedPropertyByName("residence")); - assertEquals("residence", regularEmployeeVertexType.getInheritedPropertyByName("residence").getName()); - assertEquals("VARCHAR", regularEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()); - assertEquals(3, regularEmployeeVertexType.getInheritedPropertyByName("residence").getOrdinalPosition()); - assertEquals(false, regularEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()); - - assertEquals(3, contractEmployeeVertexType.getInheritedProperties().size()); - - assertNotNull(contractEmployeeVertexType.getInheritedPropertyByName("id")); - assertEquals("id", contractEmployeeVertexType.getInheritedPropertyByName("id").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()); - assertEquals(1, contractEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()); - assertEquals(true, contractEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(contractEmployeeVertexType.getInheritedPropertyByName("name")); - assertEquals("name", contractEmployeeVertexType.getInheritedPropertyByName("name").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()); - assertEquals(2, contractEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(contractEmployeeVertexType.getInheritedPropertyByName("residence")); - assertEquals("residence", contractEmployeeVertexType.getInheritedPropertyByName("residence").getName()); - assertEquals("VARCHAR", contractEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()); - assertEquals(3, contractEmployeeVertexType.getInheritedPropertyByName("residence").getOrdinalPosition()); - assertEquals(false, contractEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()); - - assertEquals(0, residenceVertexType.getInheritedProperties().size()); - - // edges check - - assertEquals(1, mapper.getRelationship2edgeType().size()); - - assertEquals(1, mapper.getGraphModel().getEdgesType().size()); - assertEquals("HasResidence", mapper.getGraphModel().getEdgesType().get(0).getName()); - - assertEquals(1, employeeVertexType.getOutEdgesType().size()); - assertEquals("HasResidence", employeeVertexType.getOutEdgesType().get(0).getName()); - - assertEquals(1, regularEmployeeVertexType.getOutEdgesType().size()); - assertEquals("HasResidence", regularEmployeeVertexType.getOutEdgesType().get(0).getName()); - - assertEquals(1, contractEmployeeVertexType.getOutEdgesType().size()); - assertEquals("HasResidence", contractEmployeeVertexType.getOutEdgesType().get(0).getName()); - - // inheritance check - assertEquals(employeeVertexType, regularEmployeeVertexType.getParentType()); - assertEquals(employeeVertexType, contractEmployeeVertexType.getParentType()); - assertNull(employeeVertexType.getParentType()); - - assertEquals(1, regularEmployeeVertexType.getInheritanceLevel()); - assertEquals(1, contractEmployeeVertexType.getInheritanceLevel()); - assertEquals(0, employeeVertexType.getInheritanceLevel()); - } catch (Exception e) { - e.printStackTrace(); - fail(e); - } finally { - try { - // Dropping Source DB Schema and OrientGraph - String dbDropping = "drop schema public cascade"; - st.execute(dbDropping); - connection.close(); - } catch (Exception e) { - e.printStackTrace(); - fail(e); - } - } + } + + /* + * Table per Concrete Class Inheritance ( tag) + * 3 tables, one parent and 2 childs ( http://www.javatpoint.com/table-per-concrete-class ) + */ + + @Test + void TablePerConcreteClassInheritance() { + Connection connection = null; + Statement st = null; + + try { + Class.forName("org.hsqldb.jdbc.JDBCDriver"); + connection = DriverManager.getConnection(this.jurl, this.username, this.password); + + String residence = + "create memory table RESIDENCE(ID varchar(256) not null, CITY varchar(256), COUNTRY" + + " varchar(256), primary key (ID))"; + st = connection.createStatement(); + st.execute(residence); + + String employeeTableBuilding = + "create memory table EMPLOYEE (ID varchar(256) not null, NAME varchar(256), RESIDENCE" + + " varchar(256), primary key (ID), foreign key (RESIDENCE) references" + + " RESIDENCE(ID))"; + st.execute(employeeTableBuilding); + + String regularEmployeeTableBuilding = + "create memory table REGULAR_EMPLOYEE (ID varchar(256) not null, NAME varchar(256)," + + " RESIDENCE varchar(256), SALARY decimal(10,2), BONUS decimal(10,0), primary key" + + " (ID))"; + st.execute(regularEmployeeTableBuilding); + + String contractEmployeeTableBuilding = + "create memory table CONTRACT_EMPLOYEE (ID varchar(256) not null, NAME varchar(256)," + + " RESIDENCE varchar(256), PAY_PER_HOUR decimal(10,2), CONTRACT_DURATION" + + " varchar(256), primary key (ID))"; + st.execute(contractEmployeeTableBuilding); + + this.mapper = + new Hibernate2GraphMapper( + dataSource, + HibernateMapperTest.XML_TABLE_PER_CONCRETE_CLASS, + null, + null, + dbQueryEngine, + dataTypeHandler, + executionStrategy, + nameResolver, + statistics); + + mapper.buildSourceDatabaseSchema(); + mapper.buildGraphModel(new JavaConventionNameResolver()); + + /* + * Testing context information + */ + + assertThat(statistics.totalNumberOfEntities).isEqualTo(4); + assertThat(statistics.builtEntities).isEqualTo(4); + assertThat(statistics.totalNumberOfRelationships).isEqualTo(1); + assertThat(statistics.builtRelationships).isEqualTo(1); + + assertThat(statistics.totalNumberOfModelVertices).isEqualTo(4); + assertThat(statistics.builtModelVertexTypes).isEqualTo(4); + assertThat(statistics.totalNumberOfModelEdges).isEqualTo(1); + assertThat(statistics.builtModelEdgeTypes).isEqualTo(1); + + /* + * Testing built source db schema + */ + + Entity employeeEntity = mapper.getDataBaseSchema().getEntityByName("EMPLOYEE"); + Entity regularEmployeeEntity = mapper.getDataBaseSchema().getEntityByName("REGULAR_EMPLOYEE"); + Entity contractEmployeeEntity = + mapper.getDataBaseSchema().getEntityByName("CONTRACT_EMPLOYEE"); + Entity residenceEntity = mapper.getDataBaseSchema().getEntityByNameIgnoreCase("RESIDENCE"); + + // entities check + assertThat(mapper.getDataBaseSchema().getEntities().size()).isEqualTo(4); + assertThat(mapper.getDataBaseSchema().getCanonicalRelationships().size()).isEqualTo(1); + assertThat(employeeEntity).isNotNull(); + assertThat(regularEmployeeEntity).isNotNull(); + assertThat(contractEmployeeEntity).isNotNull(); + assertThat(residenceEntity).isNotNull(); + + // attributes check + assertThat(employeeEntity.getAttributes().size()).isEqualTo(3); + + assertThat(employeeEntity.getAttributeByName("ID")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(employeeEntity.getAttributeByName("ID").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("ID").getOrdinalPosition()).isEqualTo(1); + assertThat(employeeEntity.getAttributeByName("ID").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(employeeEntity.getAttributeByName("NAME")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("NAME").getName()).isEqualTo("NAME"); + assertThat(employeeEntity.getAttributeByName("NAME").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("NAME").getOrdinalPosition()).isEqualTo(2); + assertThat(employeeEntity.getAttributeByName("NAME").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(employeeEntity.getAttributeByName("RESIDENCE")).isNotNull(); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getName()).isEqualTo("RESIDENCE"); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getDataType()).isEqualTo("VARCHAR"); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getOrdinalPosition()).isEqualTo(3); + assertThat(employeeEntity.getAttributeByName("RESIDENCE").getBelongingEntity().getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(regularEmployeeEntity.getAttributes().size()).isEqualTo(2); + + assertThat(regularEmployeeEntity.getAttributeByName("SALARY")).isNotNull(); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getName()).isEqualTo("SALARY"); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getDataType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getOrdinalPosition()) + .isEqualTo(1); + assertThat(regularEmployeeEntity.getAttributeByName("SALARY").getBelongingEntity().getName()) + .isEqualTo("REGULAR_EMPLOYEE"); + + assertThat(regularEmployeeEntity.getAttributeByName("BONUS")).isNotNull(); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getName()).isEqualTo("BONUS"); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getDataType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getOrdinalPosition()) + .isEqualTo(2); + assertThat(regularEmployeeEntity.getAttributeByName("BONUS").getBelongingEntity().getName()) + .isEqualTo("REGULAR_EMPLOYEE"); + + assertThat(contractEmployeeEntity.getAttributes().size()).isEqualTo(2); + + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR")).isNotNull(); + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getName()) + .isEqualTo("PAY_PER_HOUR"); + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getDataType()) + .isEqualTo("DECIMAL"); + assertThat(contractEmployeeEntity.getAttributeByName("PAY_PER_HOUR").getOrdinalPosition()) + .isEqualTo(1); + assertThat( + contractEmployeeEntity + .getAttributeByName("PAY_PER_HOUR") + .getBelongingEntity() + .getName()) + .isEqualTo("CONTRACT_EMPLOYEE"); + + assertThat(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION")).isNotNull(); + assertThat(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getName()) + .isEqualTo("CONTRACT_DURATION"); + assertThat(contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeEntity.getAttributeByName("CONTRACT_DURATION").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + contractEmployeeEntity + .getAttributeByName("CONTRACT_DURATION") + .getBelongingEntity() + .getName()) + .isEqualTo("CONTRACT_EMPLOYEE"); + + // inherited attributes check + assertThat(employeeEntity.getInheritedAttributes().size()).isEqualTo(0); + + assertThat(regularEmployeeEntity.getInheritedAttributes().size()).isEqualTo(3); + + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID")).isNotNull(); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID").getName()).isEqualTo("ID"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()) + .isEqualTo(1); + assertThat( + regularEmployeeEntity + .getInheritedAttributeByName("ID") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME")).isNotNull(); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME").getName()) + .isEqualTo("NAME"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + regularEmployeeEntity + .getInheritedAttributeByName("NAME") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE")).isNotNull(); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()) + .isEqualTo("RESIDENCE"); + assertThat(regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + regularEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()) + .isEqualTo(3); + assertThat( + regularEmployeeEntity + .getInheritedAttributeByName("RESIDENCE") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(contractEmployeeEntity.getInheritedAttributes().size()).isEqualTo(3); + + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID")).isNotNull(); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID").getName()) + .isEqualTo("ID"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("ID").getOrdinalPosition()) + .isEqualTo(1); + assertThat( + contractEmployeeEntity + .getInheritedAttributeByName("ID") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME")).isNotNull(); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME").getName()) + .isEqualTo("NAME"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("NAME").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + contractEmployeeEntity + .getInheritedAttributeByName("NAME") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + assertThat(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE")).isNotNull(); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getName()) + .isEqualTo("RESIDENCE"); + assertThat(contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeEntity.getInheritedAttributeByName("RESIDENCE").getOrdinalPosition()) + .isEqualTo(3); + assertThat( + contractEmployeeEntity + .getInheritedAttributeByName("RESIDENCE") + .getBelongingEntity() + .getName()) + .isEqualTo("EMPLOYEE"); + + // primary key check (not "inherited") + assertThat(regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()).isEqualTo(1); + assertThat(regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()) + .isEqualTo("ID"); + assertThat(regularEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + regularEmployeeEntity + .getPrimaryKey() + .getInvolvedAttributes() + .get(0) + .getBelongingEntity() + .getName()) + .isEqualTo("REGULAR_EMPLOYEE"); + + assertThat(contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().size()) + .isEqualTo(1); + assertThat(contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()) + .isEqualTo("ID"); + assertThat( + contractEmployeeEntity.getPrimaryKey().getInvolvedAttributes().get(0).getDataType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeEntity + .getPrimaryKey() + .getInvolvedAttributes() + .get(0) + .getBelongingEntity() + .getName()) + .isEqualTo("CONTRACT_EMPLOYEE"); + + // relationship, primary and foreign key check + assertThat(regularEmployeeEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(contractEmployeeEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(employeeEntity.getOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(residenceEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(regularEmployeeEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(contractEmployeeEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(employeeEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(residenceEntity.getInCanonicalRelationships().size()).isEqualTo(1); + + assertThat(regularEmployeeEntity.getForeignKeys().size()).isEqualTo(0); + assertThat(contractEmployeeEntity.getForeignKeys().size()).isEqualTo(0); + assertThat(employeeEntity.getForeignKeys().size()).isEqualTo(1); + assertThat(residenceEntity.getForeignKeys().size()).isEqualTo(0); + + Iterator itEmp = + employeeEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship currentEmpRel = itEmp.next(); + assertThat(currentEmpRel.getParentEntity().getName()).isEqualTo("RESIDENCE"); + assertThat(currentEmpRel.getForeignEntity().getName()).isEqualTo("EMPLOYEE"); + assertThat(currentEmpRel.getPrimaryKey()).isEqualTo(residenceEntity.getPrimaryKey()); + assertThat(currentEmpRel.getForeignKey()).isEqualTo(employeeEntity.getForeignKeys().get(0)); + assertThat(itEmp.hasNext()).isFalse(); + + Iterator itRes = + residenceEntity.getInCanonicalRelationships().iterator(); + CanonicalRelationship currentResRel = itRes.next(); + assertThat(currentResRel).isEqualTo(currentEmpRel); + + // inherited relationships check + assertThat(regularEmployeeEntity.getInheritedOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(contractEmployeeEntity.getInheritedOutCanonicalRelationships().size()) + .isEqualTo(1); + assertThat(employeeEntity.getInheritedOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(residenceEntity.getInheritedOutCanonicalRelationships().size()).isEqualTo(0); + + Iterator itRegEmp = + regularEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); + Iterator itContEmp = + contractEmployeeEntity.getInheritedOutCanonicalRelationships().iterator(); + CanonicalRelationship currentRegEmpRel = itRegEmp.next(); + CanonicalRelationship currentContEmpRel = itContEmp.next(); + assertThat(currentRegEmpRel.getParentEntity().getName()).isEqualTo("RESIDENCE"); + assertThat(currentRegEmpRel.getForeignEntity().getName()).isEqualTo("EMPLOYEE"); + assertThat(currentContEmpRel.getParentEntity().getName()).isEqualTo("RESIDENCE"); + assertThat(currentContEmpRel.getForeignEntity().getName()).isEqualTo("EMPLOYEE"); + assertThat(currentRegEmpRel.getPrimaryKey()).isEqualTo(residenceEntity.getPrimaryKey()); + assertThat(currentRegEmpRel.getFromColumns().size()).isEqualTo(1); + assertThat(currentRegEmpRel.getFromColumns().get(0).getName()).isEqualTo("RESIDENCE"); + assertThat(currentContEmpRel.getPrimaryKey()).isEqualTo(residenceEntity.getPrimaryKey()); + assertThat(currentContEmpRel.getFromColumns().size()).isEqualTo(1); + assertThat(currentContEmpRel.getFromColumns().get(0).getName()).isEqualTo("RESIDENCE"); + assertThat(itRegEmp.hasNext()).isFalse(); + assertThat(itContEmp.hasNext()).isFalse(); + + // inheritance check + assertThat(regularEmployeeEntity.getParentEntity()).isEqualTo(employeeEntity); + assertThat(contractEmployeeEntity.getParentEntity()).isEqualTo(employeeEntity); + assertThat(employeeEntity.getParentEntity()).isNull(); + assertThat(residenceEntity.getParentEntity()).isNull(); + + assertThat(regularEmployeeEntity.getInheritanceLevel()).isEqualTo(1); + assertThat(contractEmployeeEntity.getInheritanceLevel()).isEqualTo(1); + assertThat(employeeEntity.getInheritanceLevel()).isEqualTo(0); + assertThat(residenceEntity.getInheritanceLevel()).isEqualTo(0); + + // Hierarchical Bag check + assertThat(mapper.getDataBaseSchema().getHierarchicalBags().size()).isEqualTo(1); + HierarchicalBag hierarchicalBag = mapper.getDataBaseSchema().getHierarchicalBags().get(0); + assertThat(hierarchicalBag.getInheritancePattern()).isEqualTo("table-per-concrete-type"); + + assertThat(hierarchicalBag.getDepth2entities().size()).isEqualTo(2); + + assertThat(hierarchicalBag.getDepth2entities().get(0).size()).isEqualTo(1); + Iterator it = hierarchicalBag.getDepth2entities().get(0).iterator(); + assertThat(it.next().getName()).isEqualTo("EMPLOYEE"); + assertThat(it.hasNext()).isFalse(); + + assertThat(hierarchicalBag.getDepth2entities().get(1).size()).isEqualTo(2); + it = hierarchicalBag.getDepth2entities().get(1).iterator(); + assertThat(it.next().getName()).isEqualTo("REGULAR_EMPLOYEE"); + assertThat(it.next().getName()).isEqualTo("CONTRACT_EMPLOYEE"); + assertThat(it.hasNext()).isFalse(); + + assertThat(employeeEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag); + assertThat(regularEmployeeEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag); + assertThat(contractEmployeeEntity.getHierarchicalBag()).isEqualTo(hierarchicalBag); + + assertThat(hierarchicalBag.getDiscriminatorColumn()).isNull(); + + /* + * Testing built graph model + */ + + VertexType employeeVertexType = mapper.getGraphModel().getVertexTypeByName("Employee"); + VertexType regularEmployeeVertexType = + mapper.getGraphModel().getVertexTypeByName("RegularEmployee"); + VertexType contractEmployeeVertexType = + mapper.getGraphModel().getVertexTypeByName("ContractEmployee"); + VertexType residenceVertexType = mapper.getGraphModel().getVertexTypeByName("Residence"); + + // vertices check + assertThat(mapper.getGraphModel().getVerticesType().size()).isEqualTo(4); + assertThat(employeeVertexType).isNotNull(); + assertThat(regularEmployeeVertexType).isNotNull(); + assertThat(contractEmployeeVertexType).isNotNull(); + assertThat(residenceVertexType).isNotNull(); + + // properties check + assertThat(employeeVertexType.getProperties().size()).isEqualTo(3); + + assertThat(employeeVertexType.getPropertyByName("id")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(employeeVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(employeeVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(employeeVertexType.getPropertyByName("name")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("name").getName()).isEqualTo("name"); + assertThat(employeeVertexType.getPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("name").getOrdinalPosition()).isEqualTo(2); + assertThat(employeeVertexType.getPropertyByName("name").isFromPrimaryKey()).isFalse(); + + assertThat(employeeVertexType.getPropertyByName("residence")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("residence").getName()) + .isEqualTo("residence"); + assertThat(employeeVertexType.getPropertyByName("residence").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("residence").getOrdinalPosition()) + .isEqualTo(3); + assertThat(employeeVertexType.getPropertyByName("residence").isFromPrimaryKey()).isFalse(); + + assertThat(regularEmployeeVertexType.getProperties().size()).isEqualTo(2); + + assertThat(regularEmployeeVertexType.getPropertyByName("salary")).isNotNull(); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").getName()) + .isEqualTo("salary"); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").getOriginalType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").getOrdinalPosition()) + .isEqualTo(1); + assertThat(regularEmployeeVertexType.getPropertyByName("salary").isFromPrimaryKey()) + .isFalse(); + + assertThat(regularEmployeeVertexType.getPropertyByName("bonus")).isNotNull(); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").getName()).isEqualTo("bonus"); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").getOriginalType()) + .isEqualTo("DECIMAL"); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").getOrdinalPosition()) + .isEqualTo(2); + assertThat(regularEmployeeVertexType.getPropertyByName("bonus").isFromPrimaryKey()).isFalse(); + + assertThat(contractEmployeeVertexType.getProperties().size()).isEqualTo(2); + + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour")).isNotNull(); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").getName()) + .isEqualTo("payPerHour"); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").getOriginalType()) + .isEqualTo("DECIMAL"); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").getOrdinalPosition()) + .isEqualTo(1); + assertThat(contractEmployeeVertexType.getPropertyByName("payPerHour").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getPropertyByName("contractDuration")).isNotNull(); + assertThat(contractEmployeeVertexType.getPropertyByName("contractDuration").getName()) + .isEqualTo("contractDuration"); + assertThat(contractEmployeeVertexType.getPropertyByName("contractDuration").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeVertexType.getPropertyByName("contractDuration").getOrdinalPosition()) + .isEqualTo(2); + assertThat( + contractEmployeeVertexType.getPropertyByName("contractDuration").isFromPrimaryKey()) + .isFalse(); + + assertThat(residenceVertexType.getProperties().size()).isEqualTo(3); + + assertThat(residenceVertexType.getPropertyByName("id")).isNotNull(); + assertThat(residenceVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(residenceVertexType.getPropertyByName("id").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(residenceVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(residenceVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(residenceVertexType.getPropertyByName("city")).isNotNull(); + assertThat(residenceVertexType.getPropertyByName("city").getName()).isEqualTo("city"); + assertThat(residenceVertexType.getPropertyByName("city").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(residenceVertexType.getPropertyByName("city").getOrdinalPosition()).isEqualTo(2); + assertThat(residenceVertexType.getPropertyByName("city").isFromPrimaryKey()).isFalse(); + + assertThat(residenceVertexType.getPropertyByName("country")).isNotNull(); + assertThat(residenceVertexType.getPropertyByName("country").getName()).isEqualTo("country"); + assertThat(residenceVertexType.getPropertyByName("country").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(residenceVertexType.getPropertyByName("country").getOrdinalPosition()) + .isEqualTo(3); + assertThat(residenceVertexType.getPropertyByName("country").isFromPrimaryKey()).isFalse(); + + // inherited properties check + assertThat(employeeVertexType.getInheritedProperties().size()).isEqualTo(0); + + assertThat(regularEmployeeVertexType.getInheritedProperties().size()).isEqualTo(3); + + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id")).isNotNull(); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").getName()) + .isEqualTo("id"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()) + .isEqualTo(1); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()) + .isTrue(); + + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name")).isNotNull(); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").getName()) + .isEqualTo("name"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()) + .isEqualTo(2); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()) + .isFalse(); + + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("residence")).isNotNull(); + assertThat(regularEmployeeVertexType.getInheritedPropertyByName("residence").getName()) + .isEqualTo("residence"); + assertThat( + regularEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + regularEmployeeVertexType + .getInheritedPropertyByName("residence") + .getOrdinalPosition()) + .isEqualTo(3); + assertThat( + regularEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getInheritedProperties().size()).isEqualTo(3); + + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id")).isNotNull(); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").getName()) + .isEqualTo("id"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").getOrdinalPosition()) + .isEqualTo(1); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("id").isFromPrimaryKey()) + .isTrue(); + + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name")).isNotNull(); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").getName()) + .isEqualTo("name"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").getOrdinalPosition()) + .isEqualTo(2); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("name").isFromPrimaryKey()) + .isFalse(); + + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("residence")).isNotNull(); + assertThat(contractEmployeeVertexType.getInheritedPropertyByName("residence").getName()) + .isEqualTo("residence"); + assertThat( + contractEmployeeVertexType.getInheritedPropertyByName("residence").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat( + contractEmployeeVertexType + .getInheritedPropertyByName("residence") + .getOrdinalPosition()) + .isEqualTo(3); + assertThat( + contractEmployeeVertexType.getInheritedPropertyByName("residence").isFromPrimaryKey()) + .isFalse(); + + assertThat(residenceVertexType.getInheritedProperties().size()).isEqualTo(0); + + // edges check + + assertThat(mapper.getRelationship2edgeType().size()).isEqualTo(1); + + assertThat(mapper.getGraphModel().getEdgesType().size()).isEqualTo(1); + assertThat(mapper.getGraphModel().getEdgesType().get(0).getName()).isEqualTo("HasResidence"); + + assertThat(employeeVertexType.getOutEdgesType().size()).isEqualTo(1); + assertThat(employeeVertexType.getOutEdgesType().get(0).getName()).isEqualTo("HasResidence"); + + assertThat(regularEmployeeVertexType.getOutEdgesType().size()).isEqualTo(1); + assertThat(regularEmployeeVertexType.getOutEdgesType().get(0).getName()) + .isEqualTo("HasResidence"); + + assertThat(contractEmployeeVertexType.getOutEdgesType().size()).isEqualTo(1); + assertThat(contractEmployeeVertexType.getOutEdgesType().get(0).getName()) + .isEqualTo("HasResidence"); + + // inheritance check + assertThat(regularEmployeeVertexType.getParentType()).isEqualTo(employeeVertexType); + assertThat(contractEmployeeVertexType.getParentType()).isEqualTo(employeeVertexType); + assertThat(employeeVertexType.getParentType()).isNull(); + + assertThat(regularEmployeeVertexType.getInheritanceLevel()).isEqualTo(1); + assertThat(contractEmployeeVertexType.getInheritanceLevel()).isEqualTo(1); + assertThat(employeeVertexType.getInheritanceLevel()).isEqualTo(0); + } catch (Exception e) { + e.printStackTrace(); + fail("", e); + } finally { + try { + // Dropping Source DB Schema and OrientGraph + String dbDropping = "drop schema public cascade"; + st.execute(dbDropping); + connection.close(); + } catch (Exception e) { + e.printStackTrace(); + fail("", e); + } } + } } diff --git a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/jointableaggregation/AggregationStrategyTest.java b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/jointableaggregation/AggregationStrategyTest.java index 083f4448..c3bac78c 100644 --- a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/jointableaggregation/AggregationStrategyTest.java +++ b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/jointableaggregation/AggregationStrategyTest.java @@ -40,12 +40,8 @@ * #L% */ -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.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import com.arcadeanalytics.provider.DataSourceInfo; import com.arcadeanalytics.provider.rdbms.context.Statistics; @@ -70,447 +66,563 @@ /** * @author Gabriele Ponzi */ - -public class AggregationStrategyTest { - - private DBQueryEngine dbQueryEngine; - private String driver = "org.hsqldb.jdbc.JDBCDriver"; - private String jurl = "jdbc:hsqldb:mem:mydb"; - private String username = "SA"; - private String password = ""; - private DataSourceInfo dataSource; - - private NameResolver nameResolver; - private DBMSDataTypeHandler dataTypeHandler; - private String executionStrategy; - private Statistics statistics; - - @BeforeEach - public void init() { - this.dataSource = - new DataSourceInfo( - 1L, - "RDBMS_HSQL", - "testDataSource", - "desc", - "mem", - 1234, - "mydb", - username, - password, - false, - "{}", - false, - false, - "", - 22, - "", - false - ); - dbQueryEngine = new DBQueryEngine(dataSource, 300); - executionStrategy = "not_specified"; - nameResolver = new JavaConventionNameResolver(); - dataTypeHandler = new HSQLDBDataTypeHandler(); - statistics = new Statistics(); - } - - @Test - /* - * Aggregation Strategy Test: executing mapping - */public void performMappingWithAggregationStrategy() { - Connection connection = null; - Statement st = null; - - try { - Class.forName(this.driver); - connection = DriverManager.getConnection(this.jurl, this.username, this.password); - - // Tables Building - - String employeeTableBuilding = - "create memory table EMPLOYEE (ID varchar(256) not null," + - " FIRST_NAME varchar(256) not null, LAST_NAME varchar(256) not null, primary key (ID))"; - st = connection.createStatement(); - st.execute(employeeTableBuilding); - - String departmentTableBuilding = "create memory table DEPARTMENT (ID varchar(256) not null, NAME varchar(256)," + " primary key (ID))"; - st.execute(departmentTableBuilding); - - String dept2empTableBuilding = - "create memory table DEPT_EMP (DEPT_ID varchar(256) not null, EMP_ID varchar(256), HIRING_YEAR varchar(256)," + - " primary key (DEPT_ID,EMP_ID), foreign key (EMP_ID) references EMPLOYEE(ID), foreign key (DEPT_ID) references DEPARTMENT(ID))"; - st.execute(dept2empTableBuilding); - - String dept2managerTableBuilding = - "create memory table DEPT_MANAGER (DEPT_ID varchar(256) not null, EMP_ID varchar(256)," + - " primary key (DEPT_ID,EMP_ID), foreign key (EMP_ID) references EMPLOYEE(ID), foreign key (DEPT_ID) references DEPARTMENT(ID))"; - st.execute(dept2managerTableBuilding); - - String branchTableBuilding = - "create memory table BRANCH(BRANCH_ID varchar(256) not null, LOCATION varchar(256)," + - "DEPT varchar(256) not null, primary key (BRANCH_ID), foreign key (DEPT) references DEPARTMENT(ID))"; - st.execute(branchTableBuilding); - - ER2GraphMapper mapper = new ER2GraphMapper(dataSource, null, null, dbQueryEngine, dataTypeHandler, executionStrategy, nameResolver, statistics); - mapper.buildSourceDatabaseSchema(); - mapper.buildGraphModel(new JavaConventionNameResolver()); - - /* - * Testing context information - */ - - assertEquals(5, statistics.totalNumberOfModelVertices); - assertEquals(5, statistics.builtModelVertexTypes); - assertEquals(2, statistics.totalNumberOfModelEdges); - assertEquals(2, statistics.builtModelEdgeTypes); - - /* - * Testing built graph model - */ - VertexType employeeVertexType = mapper.getGraphModel().getVertexTypeByName("Employee"); - VertexType departmentVertexType = mapper.getGraphModel().getVertexTypeByName("Department"); - VertexType deptEmpVertexType = mapper.getGraphModel().getVertexTypeByName("DeptEmp"); - VertexType deptManagerVertexType = mapper.getGraphModel().getVertexTypeByName("DeptManager"); - VertexType branchVertexType = mapper.getGraphModel().getVertexTypeByName("Branch"); - EdgeType deptEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasDept"); - EdgeType empEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasEmp"); - - // vertices check - assertEquals(5, mapper.getGraphModel().getVerticesType().size()); - assertNotNull(employeeVertexType); - assertNotNull(departmentVertexType); - assertNotNull(deptEmpVertexType); - assertNotNull(deptManagerVertexType); - assertNotNull(branchVertexType); - - // edges check - assertEquals(2, mapper.getGraphModel().getEdgesType().size()); - assertNotNull(deptEdgeType); - assertNotNull(empEdgeType); - assertEquals(3, deptEdgeType.getNumberRelationshipsRepresented()); - assertEquals(2, empEdgeType.getNumberRelationshipsRepresented()); - - /* - * Rules check - */ - - // Classes Mapping - - assertEquals(5, mapper.getVertexType2EVClassMappers().size()); - assertEquals(5, mapper.getEntity2EVClassMappers().size()); - - Entity employeeEntity = mapper.getDataBaseSchema().getEntityByName("EMPLOYEE"); - assertEquals(1, mapper.getEVClassMappersByVertex(employeeVertexType).size()); - EVClassMapper employeeClassMapper = mapper.getEVClassMappersByVertex(employeeVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(employeeEntity).size()); - assertEquals(employeeClassMapper, mapper.getEVClassMappersByEntity(employeeEntity).get(0)); - assertEquals(employeeClassMapper.getEntity(), employeeEntity); - assertEquals(employeeClassMapper.getVertexType(), employeeVertexType); - - assertEquals(3, employeeClassMapper.getAttribute2property().size()); - assertEquals(3, employeeClassMapper.getProperty2attribute().size()); - assertEquals("id", employeeClassMapper.getAttribute2property().get("ID")); - assertEquals("firstName", employeeClassMapper.getAttribute2property().get("FIRST_NAME")); - assertEquals("lastName", employeeClassMapper.getAttribute2property().get("LAST_NAME")); - assertEquals("ID", employeeClassMapper.getProperty2attribute().get("id")); - assertEquals("FIRST_NAME", employeeClassMapper.getProperty2attribute().get("firstName")); - assertEquals("LAST_NAME", employeeClassMapper.getProperty2attribute().get("lastName")); - - Entity departmentEntity = mapper.getDataBaseSchema().getEntityByName("DEPARTMENT"); - assertEquals(1, mapper.getEVClassMappersByVertex(departmentVertexType).size()); - EVClassMapper departmentClassMapper = mapper.getEVClassMappersByVertex(departmentVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(departmentEntity).size()); - assertEquals(departmentClassMapper, mapper.getEVClassMappersByEntity(departmentEntity).get(0)); - assertEquals(departmentClassMapper.getEntity(), departmentEntity); - assertEquals(departmentClassMapper.getVertexType(), departmentVertexType); - - assertEquals(2, departmentClassMapper.getAttribute2property().size()); - assertEquals(2, departmentClassMapper.getProperty2attribute().size()); - assertEquals("id", departmentClassMapper.getAttribute2property().get("ID")); - assertEquals("name", departmentClassMapper.getAttribute2property().get("NAME")); - assertEquals("ID", departmentClassMapper.getProperty2attribute().get("id")); - assertEquals("NAME", departmentClassMapper.getProperty2attribute().get("name")); - - Entity branchEntity = mapper.getDataBaseSchema().getEntityByName("BRANCH"); - assertEquals(1, mapper.getEVClassMappersByVertex(branchVertexType).size()); - EVClassMapper branchClassMapper = mapper.getEVClassMappersByVertex(branchVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(branchEntity).size()); - assertEquals(branchClassMapper, mapper.getEVClassMappersByEntity(branchEntity).get(0)); - assertEquals(branchClassMapper.getEntity(), branchEntity); - assertEquals(branchClassMapper.getVertexType(), branchVertexType); - - assertEquals(3, branchClassMapper.getAttribute2property().size()); - assertEquals(3, branchClassMapper.getProperty2attribute().size()); - assertEquals("branchId", branchClassMapper.getAttribute2property().get("BRANCH_ID")); - assertEquals("location", branchClassMapper.getAttribute2property().get("LOCATION")); - assertEquals("dept", branchClassMapper.getAttribute2property().get("DEPT")); - assertEquals("BRANCH_ID", branchClassMapper.getProperty2attribute().get("branchId")); - assertEquals("LOCATION", branchClassMapper.getProperty2attribute().get("location")); - assertEquals("DEPT", branchClassMapper.getProperty2attribute().get("dept")); - - Entity deptEmpEntity = mapper.getDataBaseSchema().getEntityByName("DEPT_EMP"); - assertEquals(1, mapper.getEVClassMappersByVertex(deptEmpVertexType).size()); - EVClassMapper deptEmpClassMapper = mapper.getEVClassMappersByVertex(deptEmpVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(deptEmpEntity).size()); - assertEquals(deptEmpClassMapper, mapper.getEVClassMappersByEntity(deptEmpEntity).get(0)); - assertEquals(deptEmpClassMapper.getEntity(), deptEmpEntity); - assertEquals(deptEmpClassMapper.getVertexType(), deptEmpVertexType); - - assertEquals(3, deptEmpClassMapper.getAttribute2property().size()); - assertEquals(3, deptEmpClassMapper.getProperty2attribute().size()); - assertEquals("deptId", deptEmpClassMapper.getAttribute2property().get("DEPT_ID")); - assertEquals("empId", deptEmpClassMapper.getAttribute2property().get("EMP_ID")); - assertEquals("hiringYear", deptEmpClassMapper.getAttribute2property().get("HIRING_YEAR")); - assertEquals("DEPT_ID", deptEmpClassMapper.getProperty2attribute().get("deptId")); - assertEquals("EMP_ID", deptEmpClassMapper.getProperty2attribute().get("empId")); - assertEquals("HIRING_YEAR", deptEmpClassMapper.getProperty2attribute().get("hiringYear")); - - Entity deptMgrEntity = mapper.getDataBaseSchema().getEntityByName("DEPT_MANAGER"); - assertEquals(1, mapper.getEVClassMappersByVertex(deptManagerVertexType).size()); - EVClassMapper deptManagerClassMapper = mapper.getEVClassMappersByVertex(deptManagerVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(deptMgrEntity).size()); - assertEquals(deptManagerClassMapper, mapper.getEVClassMappersByEntity(deptMgrEntity).get(0)); - assertEquals(deptManagerClassMapper.getEntity(), deptMgrEntity); - assertEquals(deptManagerClassMapper.getVertexType(), deptManagerVertexType); - - assertEquals(2, deptManagerClassMapper.getAttribute2property().size()); - assertEquals(2, deptManagerClassMapper.getProperty2attribute().size()); - assertEquals("deptId", deptManagerClassMapper.getAttribute2property().get("DEPT_ID")); - assertEquals("empId", deptManagerClassMapper.getAttribute2property().get("EMP_ID")); - assertEquals("DEPT_ID", deptManagerClassMapper.getProperty2attribute().get("deptId")); - assertEquals("EMP_ID", deptManagerClassMapper.getProperty2attribute().get("empId")); - - // Relationships-Edges Mapping - - Iterator it = deptEmpEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship hasDepartmentRelationship1 = it.next(); - CanonicalRelationship hasEmployeeRelationship1 = it.next(); - assertFalse(it.hasNext()); - - it = deptMgrEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship hasDepartmentRelationship2 = it.next(); - CanonicalRelationship hasEmployeeRelationship2 = it.next(); - assertFalse(it.hasNext()); - - it = branchEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship hasDepartmentRelationship3 = it.next(); - assertFalse(it.hasNext()); - - assertEquals(5, mapper.getRelationship2edgeType().size()); - assertEquals(deptEdgeType, mapper.getRelationship2edgeType().get(hasDepartmentRelationship1)); - assertEquals(deptEdgeType, mapper.getRelationship2edgeType().get(hasDepartmentRelationship2)); - assertEquals(deptEdgeType, mapper.getRelationship2edgeType().get(hasDepartmentRelationship3)); - assertEquals(empEdgeType, mapper.getRelationship2edgeType().get(hasEmployeeRelationship1)); - assertEquals(empEdgeType, mapper.getRelationship2edgeType().get(hasEmployeeRelationship2)); - - assertEquals(2, mapper.getEdgeType2relationships().size()); - assertEquals(3, mapper.getEdgeType2relationships().get(deptEdgeType).size()); - assertTrue(mapper.getEdgeType2relationships().get(deptEdgeType).contains(hasDepartmentRelationship1)); - assertTrue(mapper.getEdgeType2relationships().get(deptEdgeType).contains(hasDepartmentRelationship2)); - assertTrue(mapper.getEdgeType2relationships().get(deptEdgeType).contains(hasDepartmentRelationship3)); - assertEquals(2, mapper.getEdgeType2relationships().get(empEdgeType).size()); - assertTrue(mapper.getEdgeType2relationships().get(empEdgeType).contains(hasEmployeeRelationship1)); - assertTrue(mapper.getEdgeType2relationships().get(empEdgeType).contains(hasEmployeeRelationship2)); - - assertEquals(0, mapper.getJoinVertex2aggregatorEdges().size()); - - /* - * Aggregation of join tables - */ - mapper.performMany2ManyAggregation(); - - /* - * Testing context information - */ - - assertEquals(3, statistics.totalNumberOfModelVertices); - assertEquals(3, statistics.builtModelVertexTypes); - assertEquals(3, statistics.totalNumberOfModelEdges); - assertEquals(3, statistics.builtModelEdgeTypes); - - /* - * Testing built graph model - */ - - employeeVertexType = mapper.getGraphModel().getVertexTypeByName("Employee"); - departmentVertexType = mapper.getGraphModel().getVertexTypeByName("Department"); - branchVertexType = mapper.getGraphModel().getVertexTypeByName("Branch"); - deptEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasDept"); - EdgeType deptEmpEdgeType = mapper.getGraphModel().getEdgeTypeByName("DeptEmp"); - EdgeType deptManagerEdgeType = mapper.getGraphModel().getEdgeTypeByName("DeptManager"); - - // vertices check - assertEquals(3, mapper.getGraphModel().getVerticesType().size()); - assertNotNull(employeeVertexType); - assertNotNull(departmentVertexType); - assertNull(mapper.getGraphModel().getVertexTypeByName("DeptEmp")); - assertNull(mapper.getGraphModel().getVertexTypeByName("DeptManager")); - assertNotNull(branchVertexType); - - // edges check - assertEquals(3, mapper.getGraphModel().getEdgesType().size()); - assertNotNull(deptEdgeType); - assertNotNull(deptEmpEdgeType); - assertNotNull(deptManagerEdgeType); - assertNull(mapper.getGraphModel().getEdgeTypeByName("HasEmp")); - assertEquals(1, deptEdgeType.getNumberRelationshipsRepresented()); - assertEquals(1, deptEmpEdgeType.getNumberRelationshipsRepresented()); - assertEquals(1, deptManagerEdgeType.getNumberRelationshipsRepresented()); - - assertNotNull(deptEmpEdgeType.getPropertyByName("hiringYear")); - assertTrue(deptEmpEdgeType.getPropertyByName("hiringYear").getOriginalType().equals("VARCHAR")); - - /* - * Rules check - */ - - // Classes Mapping - - assertEquals(5, mapper.getVertexType2EVClassMappers().size()); - assertEquals(5, mapper.getEntity2EVClassMappers().size()); - - employeeEntity = mapper.getDataBaseSchema().getEntityByName("EMPLOYEE"); - assertEquals(1, mapper.getEVClassMappersByVertex(employeeVertexType).size()); - employeeClassMapper = mapper.getEVClassMappersByVertex(employeeVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(employeeEntity).size()); - assertEquals(employeeClassMapper, mapper.getEVClassMappersByEntity(employeeEntity).get(0)); - assertEquals(employeeClassMapper.getEntity(), employeeEntity); - assertEquals(employeeClassMapper.getVertexType(), employeeVertexType); - - assertEquals(3, employeeClassMapper.getAttribute2property().size()); - assertEquals(3, employeeClassMapper.getProperty2attribute().size()); - assertEquals("id", employeeClassMapper.getAttribute2property().get("ID")); - assertEquals("firstName", employeeClassMapper.getAttribute2property().get("FIRST_NAME")); - assertEquals("lastName", employeeClassMapper.getAttribute2property().get("LAST_NAME")); - assertEquals("ID", employeeClassMapper.getProperty2attribute().get("id")); - assertEquals("FIRST_NAME", employeeClassMapper.getProperty2attribute().get("firstName")); - assertEquals("LAST_NAME", employeeClassMapper.getProperty2attribute().get("lastName")); - - departmentEntity = mapper.getDataBaseSchema().getEntityByName("DEPARTMENT"); - assertEquals(1, mapper.getEVClassMappersByVertex(departmentVertexType).size()); - departmentClassMapper = mapper.getEVClassMappersByVertex(departmentVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(departmentEntity).size()); - assertEquals(departmentClassMapper, mapper.getEVClassMappersByEntity(departmentEntity).get(0)); - assertEquals(departmentClassMapper.getEntity(), departmentEntity); - assertEquals(departmentClassMapper.getVertexType(), departmentVertexType); - - assertEquals(2, departmentClassMapper.getAttribute2property().size()); - assertEquals(2, departmentClassMapper.getProperty2attribute().size()); - assertEquals("id", departmentClassMapper.getAttribute2property().get("ID")); - assertEquals("name", departmentClassMapper.getAttribute2property().get("NAME")); - assertEquals("ID", departmentClassMapper.getProperty2attribute().get("id")); - assertEquals("NAME", departmentClassMapper.getProperty2attribute().get("name")); - - branchEntity = mapper.getDataBaseSchema().getEntityByName("BRANCH"); - assertEquals(1, mapper.getEVClassMappersByVertex(branchVertexType).size()); - branchClassMapper = mapper.getEVClassMappersByVertex(branchVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(branchEntity).size()); - assertEquals(branchClassMapper, mapper.getEVClassMappersByEntity(branchEntity).get(0)); - assertEquals(branchClassMapper.getEntity(), branchEntity); - assertEquals(branchClassMapper.getVertexType(), branchVertexType); - - assertEquals(3, branchClassMapper.getAttribute2property().size()); - assertEquals(3, branchClassMapper.getProperty2attribute().size()); - assertEquals("branchId", branchClassMapper.getAttribute2property().get("BRANCH_ID")); - assertEquals("location", branchClassMapper.getAttribute2property().get("LOCATION")); - assertEquals("dept", branchClassMapper.getAttribute2property().get("DEPT")); - assertEquals("BRANCH_ID", branchClassMapper.getProperty2attribute().get("branchId")); - assertEquals("LOCATION", branchClassMapper.getProperty2attribute().get("location")); - assertEquals("DEPT", branchClassMapper.getProperty2attribute().get("dept")); - - deptEmpEntity = mapper.getDataBaseSchema().getEntityByName("DEPT_EMP"); - assertEquals(1, mapper.getEVClassMappersByVertex(deptEmpVertexType).size()); - deptEmpClassMapper = mapper.getEVClassMappersByVertex(deptEmpVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(deptEmpEntity).size()); - assertEquals(deptEmpClassMapper, mapper.getEVClassMappersByEntity(deptEmpEntity).get(0)); - assertEquals(deptEmpClassMapper.getEntity(), deptEmpEntity); - assertEquals(deptEmpClassMapper.getVertexType(), deptEmpVertexType); - - assertEquals(3, deptEmpClassMapper.getAttribute2property().size()); - assertEquals(3, deptEmpClassMapper.getProperty2attribute().size()); - assertEquals("deptId", deptEmpClassMapper.getAttribute2property().get("DEPT_ID")); - assertEquals("empId", deptEmpClassMapper.getAttribute2property().get("EMP_ID")); - assertEquals("hiringYear", deptEmpClassMapper.getAttribute2property().get("HIRING_YEAR")); - assertEquals("DEPT_ID", deptEmpClassMapper.getProperty2attribute().get("deptId")); - assertEquals("EMP_ID", deptEmpClassMapper.getProperty2attribute().get("empId")); - assertEquals("HIRING_YEAR", deptEmpClassMapper.getProperty2attribute().get("hiringYear")); - - deptMgrEntity = mapper.getDataBaseSchema().getEntityByName("DEPT_MANAGER"); - assertEquals(1, mapper.getEVClassMappersByVertex(deptManagerVertexType).size()); - deptManagerClassMapper = mapper.getEVClassMappersByVertex(deptManagerVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(deptMgrEntity).size()); - assertEquals(deptManagerClassMapper, mapper.getEVClassMappersByEntity(deptMgrEntity).get(0)); - assertEquals(deptManagerClassMapper.getEntity(), deptMgrEntity); - assertEquals(deptManagerClassMapper.getVertexType(), deptManagerVertexType); - - assertEquals(2, deptManagerClassMapper.getAttribute2property().size()); - assertEquals(2, deptManagerClassMapper.getProperty2attribute().size()); - assertEquals("deptId", deptManagerClassMapper.getAttribute2property().get("DEPT_ID")); - assertEquals("empId", deptManagerClassMapper.getAttribute2property().get("EMP_ID")); - assertEquals("DEPT_ID", deptManagerClassMapper.getProperty2attribute().get("deptId")); - assertEquals("EMP_ID", deptManagerClassMapper.getProperty2attribute().get("empId")); - - // Relationships-Edges Mapping - - it = deptEmpEntity.getOutCanonicalRelationships().iterator(); - hasDepartmentRelationship1 = it.next(); - hasEmployeeRelationship1 = it.next(); - assertFalse(it.hasNext()); - - it = deptMgrEntity.getOutCanonicalRelationships().iterator(); - hasDepartmentRelationship2 = it.next(); - hasEmployeeRelationship2 = it.next(); - assertFalse(it.hasNext()); - - it = branchEntity.getOutCanonicalRelationships().iterator(); - hasDepartmentRelationship3 = it.next(); - assertFalse(it.hasNext()); - - // fetching empEdgeType from the rules as was deleted from the graph model during the aggregation - assertEquals("HasEmp", empEdgeType.getName()); - assertEquals(employeeVertexType, empEdgeType.getInVertexType()); - assertEquals(0, empEdgeType.getAllProperties().size()); - - assertEquals(5, mapper.getRelationship2edgeType().size()); - assertEquals(deptEdgeType, mapper.getRelationship2edgeType().get(hasDepartmentRelationship1)); - assertEquals(deptEdgeType, mapper.getRelationship2edgeType().get(hasDepartmentRelationship2)); - assertEquals(deptEdgeType, mapper.getRelationship2edgeType().get(hasDepartmentRelationship3)); - assertEquals(empEdgeType, mapper.getRelationship2edgeType().get(hasEmployeeRelationship1)); - assertEquals(empEdgeType, mapper.getRelationship2edgeType().get(hasEmployeeRelationship2)); - - assertEquals(2, mapper.getEdgeType2relationships().size()); - assertEquals(3, mapper.getEdgeType2relationships().get(deptEdgeType).size()); - assertTrue(mapper.getEdgeType2relationships().get(deptEdgeType).contains(hasDepartmentRelationship1)); - assertTrue(mapper.getEdgeType2relationships().get(deptEdgeType).contains(hasDepartmentRelationship2)); - assertTrue(mapper.getEdgeType2relationships().get(deptEdgeType).contains(hasDepartmentRelationship3)); - assertEquals(2, mapper.getEdgeType2relationships().get(empEdgeType).size()); - assertTrue(mapper.getEdgeType2relationships().get(empEdgeType).contains(hasEmployeeRelationship1)); - assertTrue(mapper.getEdgeType2relationships().get(empEdgeType).contains(hasEmployeeRelationship2)); - - // JoinVertexes-AggregatorEdges Mapping - - assertEquals(2, mapper.getJoinVertex2aggregatorEdges().size()); - assertTrue(mapper.getJoinVertex2aggregatorEdges().containsKey(deptManagerVertexType)); - assertTrue(mapper.getJoinVertex2aggregatorEdges().containsKey(deptEmpVertexType)); - assertEquals(deptManagerEdgeType, mapper.getJoinVertex2aggregatorEdges().get(deptManagerVertexType).getEdgeType()); - assertEquals("Department", mapper.getJoinVertex2aggregatorEdges().get(deptManagerVertexType).getOutVertexClassName()); - assertEquals("Employee", mapper.getJoinVertex2aggregatorEdges().get(deptManagerVertexType).getInVertexClassName()); - assertEquals(deptEmpEdgeType, mapper.getJoinVertex2aggregatorEdges().get(deptEmpVertexType).getEdgeType()); - assertEquals("Department", mapper.getJoinVertex2aggregatorEdges().get(deptEmpVertexType).getOutVertexClassName()); - assertEquals("Employee", mapper.getJoinVertex2aggregatorEdges().get(deptEmpVertexType).getInVertexClassName()); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } finally { - try { - // Dropping Source DB Schema and OrientGraph - String dbDropping = "drop schema public cascade"; - st.execute(dbDropping); - connection.close(); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } - } +class AggregationStrategyTest { + + private DBQueryEngine dbQueryEngine; + private String driver = "org.hsqldb.jdbc.JDBCDriver"; + private String jurl = "jdbc:hsqldb:mem:mydb"; + private String username = "SA"; + private String password = ""; + private DataSourceInfo dataSource; + + private NameResolver nameResolver; + private DBMSDataTypeHandler dataTypeHandler; + private String executionStrategy; + private Statistics statistics; + + @BeforeEach + void init() { + this.dataSource = + new DataSourceInfo( + 1L, + "RDBMS_HSQL", + "testDataSource", + "desc", + "mem", + 1234, + "mydb", + username, + password, + false, + "{}", + false, + false, + "", + 22, + "", + false); + dbQueryEngine = new DBQueryEngine(dataSource, 300); + executionStrategy = "not_specified"; + nameResolver = new JavaConventionNameResolver(); + dataTypeHandler = new HSQLDBDataTypeHandler(); + statistics = new Statistics(); + } + + /* + * Aggregation Strategy Test: executing mapping + */ @Test + void performMappingWithAggregationStrategy() { + Connection connection = null; + Statement st = null; + + try { + Class.forName(this.driver); + connection = DriverManager.getConnection(this.jurl, this.username, this.password); + + // Tables Building + + String employeeTableBuilding = + "create memory table EMPLOYEE (ID varchar(256) not null, FIRST_NAME varchar(256) not" + + " null, LAST_NAME varchar(256) not null, primary key (ID))"; + st = connection.createStatement(); + st.execute(employeeTableBuilding); + + String departmentTableBuilding = + "create memory table DEPARTMENT (ID varchar(256) not null, NAME varchar(256)," + + " primary key (ID))"; + st.execute(departmentTableBuilding); + + String dept2empTableBuilding = + "create memory table DEPT_EMP (DEPT_ID varchar(256) not null, EMP_ID varchar(256)," + + " HIRING_YEAR varchar(256), primary key (DEPT_ID,EMP_ID), foreign key (EMP_ID)" + + " references EMPLOYEE(ID), foreign key (DEPT_ID) references DEPARTMENT(ID))"; + st.execute(dept2empTableBuilding); + + String dept2managerTableBuilding = + "create memory table DEPT_MANAGER (DEPT_ID varchar(256) not null, EMP_ID varchar(256)," + + " primary key (DEPT_ID,EMP_ID), foreign key (EMP_ID) references EMPLOYEE(ID)," + + " foreign key (DEPT_ID) references DEPARTMENT(ID))"; + st.execute(dept2managerTableBuilding); + + String branchTableBuilding = + "create memory table BRANCH(BRANCH_ID varchar(256) not null, LOCATION varchar(256),DEPT" + + " varchar(256) not null, primary key (BRANCH_ID), foreign key (DEPT) references" + + " DEPARTMENT(ID))"; + st.execute(branchTableBuilding); + + ER2GraphMapper mapper = + new ER2GraphMapper( + dataSource, + null, + null, + dbQueryEngine, + dataTypeHandler, + executionStrategy, + nameResolver, + statistics); + mapper.buildSourceDatabaseSchema(); + mapper.buildGraphModel(new JavaConventionNameResolver()); + + /* + * Testing context information + */ + + assertThat(statistics.totalNumberOfModelVertices).isEqualTo(5); + assertThat(statistics.builtModelVertexTypes).isEqualTo(5); + assertThat(statistics.totalNumberOfModelEdges).isEqualTo(2); + assertThat(statistics.builtModelEdgeTypes).isEqualTo(2); + + /* + * Testing built graph model + */ + VertexType employeeVertexType = mapper.getGraphModel().getVertexTypeByName("Employee"); + VertexType departmentVertexType = mapper.getGraphModel().getVertexTypeByName("Department"); + VertexType deptEmpVertexType = mapper.getGraphModel().getVertexTypeByName("DeptEmp"); + VertexType deptManagerVertexType = mapper.getGraphModel().getVertexTypeByName("DeptManager"); + VertexType branchVertexType = mapper.getGraphModel().getVertexTypeByName("Branch"); + EdgeType deptEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasDept"); + EdgeType empEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasEmp"); + + // vertices check + assertThat(mapper.getGraphModel().getVerticesType().size()).isEqualTo(5); + assertThat(employeeVertexType).isNotNull(); + assertThat(departmentVertexType).isNotNull(); + assertThat(deptEmpVertexType).isNotNull(); + assertThat(deptManagerVertexType).isNotNull(); + assertThat(branchVertexType).isNotNull(); + + // edges check + assertThat(mapper.getGraphModel().getEdgesType().size()).isEqualTo(2); + assertThat(deptEdgeType).isNotNull(); + assertThat(empEdgeType).isNotNull(); + assertThat(deptEdgeType.getNumberRelationshipsRepresented()).isEqualTo(3); + assertThat(empEdgeType.getNumberRelationshipsRepresented()).isEqualTo(2); + + /* + * Rules check + */ + + // Classes Mapping + + assertThat(mapper.getVertexType2EVClassMappers().size()).isEqualTo(5); + assertThat(mapper.getEntity2EVClassMappers().size()).isEqualTo(5); + + Entity employeeEntity = mapper.getDataBaseSchema().getEntityByName("EMPLOYEE"); + assertThat(mapper.getEVClassMappersByVertex(employeeVertexType).size()).isEqualTo(1); + EVClassMapper employeeClassMapper = + mapper.getEVClassMappersByVertex(employeeVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(employeeEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(employeeEntity).get(0)) + .isEqualTo(employeeClassMapper); + assertThat(employeeEntity).isEqualTo(employeeClassMapper.getEntity()); + assertThat(employeeVertexType).isEqualTo(employeeClassMapper.getVertexType()); + + assertThat(employeeClassMapper.getAttribute2property().size()).isEqualTo(3); + assertThat(employeeClassMapper.getProperty2attribute().size()).isEqualTo(3); + assertThat(employeeClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(employeeClassMapper.getAttribute2property().get("FIRST_NAME")) + .isEqualTo("firstName"); + assertThat(employeeClassMapper.getAttribute2property().get("LAST_NAME")) + .isEqualTo("lastName"); + assertThat(employeeClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(employeeClassMapper.getProperty2attribute().get("firstName")) + .isEqualTo("FIRST_NAME"); + assertThat(employeeClassMapper.getProperty2attribute().get("lastName")) + .isEqualTo("LAST_NAME"); + + Entity departmentEntity = mapper.getDataBaseSchema().getEntityByName("DEPARTMENT"); + assertThat(mapper.getEVClassMappersByVertex(departmentVertexType).size()).isEqualTo(1); + EVClassMapper departmentClassMapper = + mapper.getEVClassMappersByVertex(departmentVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(departmentEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(departmentEntity).get(0)) + .isEqualTo(departmentClassMapper); + assertThat(departmentEntity).isEqualTo(departmentClassMapper.getEntity()); + assertThat(departmentVertexType).isEqualTo(departmentClassMapper.getVertexType()); + + assertThat(departmentClassMapper.getAttribute2property().size()).isEqualTo(2); + assertThat(departmentClassMapper.getProperty2attribute().size()).isEqualTo(2); + assertThat(departmentClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(departmentClassMapper.getAttribute2property().get("NAME")).isEqualTo("name"); + assertThat(departmentClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(departmentClassMapper.getProperty2attribute().get("name")).isEqualTo("NAME"); + + Entity branchEntity = mapper.getDataBaseSchema().getEntityByName("BRANCH"); + assertThat(mapper.getEVClassMappersByVertex(branchVertexType).size()).isEqualTo(1); + EVClassMapper branchClassMapper = mapper.getEVClassMappersByVertex(branchVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(branchEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(branchEntity).get(0)) + .isEqualTo(branchClassMapper); + assertThat(branchEntity).isEqualTo(branchClassMapper.getEntity()); + assertThat(branchVertexType).isEqualTo(branchClassMapper.getVertexType()); + + assertThat(branchClassMapper.getAttribute2property().size()).isEqualTo(3); + assertThat(branchClassMapper.getProperty2attribute().size()).isEqualTo(3); + assertThat(branchClassMapper.getAttribute2property().get("BRANCH_ID")).isEqualTo("branchId"); + assertThat(branchClassMapper.getAttribute2property().get("LOCATION")).isEqualTo("location"); + assertThat(branchClassMapper.getAttribute2property().get("DEPT")).isEqualTo("dept"); + assertThat(branchClassMapper.getProperty2attribute().get("branchId")).isEqualTo("BRANCH_ID"); + assertThat(branchClassMapper.getProperty2attribute().get("location")).isEqualTo("LOCATION"); + assertThat(branchClassMapper.getProperty2attribute().get("dept")).isEqualTo("DEPT"); + + Entity deptEmpEntity = mapper.getDataBaseSchema().getEntityByName("DEPT_EMP"); + assertThat(mapper.getEVClassMappersByVertex(deptEmpVertexType).size()).isEqualTo(1); + EVClassMapper deptEmpClassMapper = mapper.getEVClassMappersByVertex(deptEmpVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(deptEmpEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(deptEmpEntity).get(0)) + .isEqualTo(deptEmpClassMapper); + assertThat(deptEmpEntity).isEqualTo(deptEmpClassMapper.getEntity()); + assertThat(deptEmpVertexType).isEqualTo(deptEmpClassMapper.getVertexType()); + + assertThat(deptEmpClassMapper.getAttribute2property().size()).isEqualTo(3); + assertThat(deptEmpClassMapper.getProperty2attribute().size()).isEqualTo(3); + assertThat(deptEmpClassMapper.getAttribute2property().get("DEPT_ID")).isEqualTo("deptId"); + assertThat(deptEmpClassMapper.getAttribute2property().get("EMP_ID")).isEqualTo("empId"); + assertThat(deptEmpClassMapper.getAttribute2property().get("HIRING_YEAR")) + .isEqualTo("hiringYear"); + assertThat(deptEmpClassMapper.getProperty2attribute().get("deptId")).isEqualTo("DEPT_ID"); + assertThat(deptEmpClassMapper.getProperty2attribute().get("empId")).isEqualTo("EMP_ID"); + assertThat(deptEmpClassMapper.getProperty2attribute().get("hiringYear")) + .isEqualTo("HIRING_YEAR"); + + Entity deptMgrEntity = mapper.getDataBaseSchema().getEntityByName("DEPT_MANAGER"); + assertThat(mapper.getEVClassMappersByVertex(deptManagerVertexType).size()).isEqualTo(1); + EVClassMapper deptManagerClassMapper = + mapper.getEVClassMappersByVertex(deptManagerVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(deptMgrEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(deptMgrEntity).get(0)) + .isEqualTo(deptManagerClassMapper); + assertThat(deptMgrEntity).isEqualTo(deptManagerClassMapper.getEntity()); + assertThat(deptManagerVertexType).isEqualTo(deptManagerClassMapper.getVertexType()); + + assertThat(deptManagerClassMapper.getAttribute2property().size()).isEqualTo(2); + assertThat(deptManagerClassMapper.getProperty2attribute().size()).isEqualTo(2); + assertThat(deptManagerClassMapper.getAttribute2property().get("DEPT_ID")).isEqualTo("deptId"); + assertThat(deptManagerClassMapper.getAttribute2property().get("EMP_ID")).isEqualTo("empId"); + assertThat(deptManagerClassMapper.getProperty2attribute().get("deptId")).isEqualTo("DEPT_ID"); + assertThat(deptManagerClassMapper.getProperty2attribute().get("empId")).isEqualTo("EMP_ID"); + + // Relationships-Edges Mapping + + Iterator it = deptEmpEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship hasDepartmentRelationship1 = it.next(); + CanonicalRelationship hasEmployeeRelationship1 = it.next(); + assertThat(it.hasNext()).isFalse(); + + it = deptMgrEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship hasDepartmentRelationship2 = it.next(); + CanonicalRelationship hasEmployeeRelationship2 = it.next(); + assertThat(it.hasNext()).isFalse(); + + it = branchEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship hasDepartmentRelationship3 = it.next(); + assertThat(it.hasNext()).isFalse(); + + assertThat(mapper.getRelationship2edgeType().size()).isEqualTo(5); + assertThat(mapper.getRelationship2edgeType().get(hasDepartmentRelationship1)) + .isEqualTo(deptEdgeType); + assertThat(mapper.getRelationship2edgeType().get(hasDepartmentRelationship2)) + .isEqualTo(deptEdgeType); + assertThat(mapper.getRelationship2edgeType().get(hasDepartmentRelationship3)) + .isEqualTo(deptEdgeType); + assertThat(mapper.getRelationship2edgeType().get(hasEmployeeRelationship1)) + .isEqualTo(empEdgeType); + assertThat(mapper.getRelationship2edgeType().get(hasEmployeeRelationship2)) + .isEqualTo(empEdgeType); + + assertThat(mapper.getEdgeType2relationships().size()).isEqualTo(2); + assertThat(mapper.getEdgeType2relationships().get(deptEdgeType).size()).isEqualTo(3); + assertThat( + mapper + .getEdgeType2relationships() + .get(deptEdgeType) + .contains(hasDepartmentRelationship1)) + .isTrue(); + assertThat( + mapper + .getEdgeType2relationships() + .get(deptEdgeType) + .contains(hasDepartmentRelationship2)) + .isTrue(); + assertThat( + mapper + .getEdgeType2relationships() + .get(deptEdgeType) + .contains(hasDepartmentRelationship3)) + .isTrue(); + assertThat(mapper.getEdgeType2relationships().get(empEdgeType).size()).isEqualTo(2); + assertThat( + mapper + .getEdgeType2relationships() + .get(empEdgeType) + .contains(hasEmployeeRelationship1)) + .isTrue(); + assertThat( + mapper + .getEdgeType2relationships() + .get(empEdgeType) + .contains(hasEmployeeRelationship2)) + .isTrue(); + + assertThat(mapper.getJoinVertex2aggregatorEdges().size()).isEqualTo(0); + + /* + * Aggregation of join tables + */ + mapper.performMany2ManyAggregation(); + + /* + * Testing context information + */ + + assertThat(statistics.totalNumberOfModelVertices).isEqualTo(3); + assertThat(statistics.builtModelVertexTypes).isEqualTo(3); + assertThat(statistics.totalNumberOfModelEdges).isEqualTo(3); + assertThat(statistics.builtModelEdgeTypes).isEqualTo(3); + + /* + * Testing built graph model + */ + + employeeVertexType = mapper.getGraphModel().getVertexTypeByName("Employee"); + departmentVertexType = mapper.getGraphModel().getVertexTypeByName("Department"); + branchVertexType = mapper.getGraphModel().getVertexTypeByName("Branch"); + deptEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasDept"); + EdgeType deptEmpEdgeType = mapper.getGraphModel().getEdgeTypeByName("DeptEmp"); + EdgeType deptManagerEdgeType = mapper.getGraphModel().getEdgeTypeByName("DeptManager"); + + // vertices check + assertThat(mapper.getGraphModel().getVerticesType().size()).isEqualTo(3); + assertThat(employeeVertexType).isNotNull(); + assertThat(departmentVertexType).isNotNull(); + assertThat(mapper.getGraphModel().getVertexTypeByName("DeptEmp")).isNull(); + assertThat(mapper.getGraphModel().getVertexTypeByName("DeptManager")).isNull(); + assertThat(branchVertexType).isNotNull(); + + // edges check + assertThat(mapper.getGraphModel().getEdgesType().size()).isEqualTo(3); + assertThat(deptEdgeType).isNotNull(); + assertThat(deptEmpEdgeType).isNotNull(); + assertThat(deptManagerEdgeType).isNotNull(); + assertThat(mapper.getGraphModel().getEdgeTypeByName("HasEmp")).isNull(); + assertThat(deptEdgeType.getNumberRelationshipsRepresented()).isEqualTo(1); + assertThat(deptEmpEdgeType.getNumberRelationshipsRepresented()).isEqualTo(1); + assertThat(deptManagerEdgeType.getNumberRelationshipsRepresented()).isEqualTo(1); + + assertThat(deptEmpEdgeType.getPropertyByName("hiringYear")).isNotNull(); + assertThat(deptEmpEdgeType.getPropertyByName("hiringYear").getOriginalType()) + .isEqualTo("VARCHAR"); + + /* + * Rules check + */ + + // Classes Mapping + + assertThat(mapper.getVertexType2EVClassMappers().size()).isEqualTo(5); + assertThat(mapper.getEntity2EVClassMappers().size()).isEqualTo(5); + + employeeEntity = mapper.getDataBaseSchema().getEntityByName("EMPLOYEE"); + assertThat(mapper.getEVClassMappersByVertex(employeeVertexType).size()).isEqualTo(1); + employeeClassMapper = mapper.getEVClassMappersByVertex(employeeVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(employeeEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(employeeEntity).get(0)) + .isEqualTo(employeeClassMapper); + assertThat(employeeEntity).isEqualTo(employeeClassMapper.getEntity()); + assertThat(employeeVertexType).isEqualTo(employeeClassMapper.getVertexType()); + + assertThat(employeeClassMapper.getAttribute2property().size()).isEqualTo(3); + assertThat(employeeClassMapper.getProperty2attribute().size()).isEqualTo(3); + assertThat(employeeClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(employeeClassMapper.getAttribute2property().get("FIRST_NAME")) + .isEqualTo("firstName"); + assertThat(employeeClassMapper.getAttribute2property().get("LAST_NAME")) + .isEqualTo("lastName"); + assertThat(employeeClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(employeeClassMapper.getProperty2attribute().get("firstName")) + .isEqualTo("FIRST_NAME"); + assertThat(employeeClassMapper.getProperty2attribute().get("lastName")) + .isEqualTo("LAST_NAME"); + + departmentEntity = mapper.getDataBaseSchema().getEntityByName("DEPARTMENT"); + assertThat(mapper.getEVClassMappersByVertex(departmentVertexType).size()).isEqualTo(1); + departmentClassMapper = mapper.getEVClassMappersByVertex(departmentVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(departmentEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(departmentEntity).get(0)) + .isEqualTo(departmentClassMapper); + assertThat(departmentEntity).isEqualTo(departmentClassMapper.getEntity()); + assertThat(departmentVertexType).isEqualTo(departmentClassMapper.getVertexType()); + + assertThat(departmentClassMapper.getAttribute2property().size()).isEqualTo(2); + assertThat(departmentClassMapper.getProperty2attribute().size()).isEqualTo(2); + assertThat(departmentClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(departmentClassMapper.getAttribute2property().get("NAME")).isEqualTo("name"); + assertThat(departmentClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(departmentClassMapper.getProperty2attribute().get("name")).isEqualTo("NAME"); + + branchEntity = mapper.getDataBaseSchema().getEntityByName("BRANCH"); + assertThat(mapper.getEVClassMappersByVertex(branchVertexType).size()).isEqualTo(1); + branchClassMapper = mapper.getEVClassMappersByVertex(branchVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(branchEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(branchEntity).get(0)) + .isEqualTo(branchClassMapper); + assertThat(branchEntity).isEqualTo(branchClassMapper.getEntity()); + assertThat(branchVertexType).isEqualTo(branchClassMapper.getVertexType()); + + assertThat(branchClassMapper.getAttribute2property().size()).isEqualTo(3); + assertThat(branchClassMapper.getProperty2attribute().size()).isEqualTo(3); + assertThat(branchClassMapper.getAttribute2property().get("BRANCH_ID")).isEqualTo("branchId"); + assertThat(branchClassMapper.getAttribute2property().get("LOCATION")).isEqualTo("location"); + assertThat(branchClassMapper.getAttribute2property().get("DEPT")).isEqualTo("dept"); + assertThat(branchClassMapper.getProperty2attribute().get("branchId")).isEqualTo("BRANCH_ID"); + assertThat(branchClassMapper.getProperty2attribute().get("location")).isEqualTo("LOCATION"); + assertThat(branchClassMapper.getProperty2attribute().get("dept")).isEqualTo("DEPT"); + + deptEmpEntity = mapper.getDataBaseSchema().getEntityByName("DEPT_EMP"); + assertThat(mapper.getEVClassMappersByVertex(deptEmpVertexType).size()).isEqualTo(1); + deptEmpClassMapper = mapper.getEVClassMappersByVertex(deptEmpVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(deptEmpEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(deptEmpEntity).get(0)) + .isEqualTo(deptEmpClassMapper); + assertThat(deptEmpEntity).isEqualTo(deptEmpClassMapper.getEntity()); + assertThat(deptEmpVertexType).isEqualTo(deptEmpClassMapper.getVertexType()); + + assertThat(deptEmpClassMapper.getAttribute2property().size()).isEqualTo(3); + assertThat(deptEmpClassMapper.getProperty2attribute().size()).isEqualTo(3); + assertThat(deptEmpClassMapper.getAttribute2property().get("DEPT_ID")).isEqualTo("deptId"); + assertThat(deptEmpClassMapper.getAttribute2property().get("EMP_ID")).isEqualTo("empId"); + assertThat(deptEmpClassMapper.getAttribute2property().get("HIRING_YEAR")) + .isEqualTo("hiringYear"); + assertThat(deptEmpClassMapper.getProperty2attribute().get("deptId")).isEqualTo("DEPT_ID"); + assertThat(deptEmpClassMapper.getProperty2attribute().get("empId")).isEqualTo("EMP_ID"); + assertThat(deptEmpClassMapper.getProperty2attribute().get("hiringYear")) + .isEqualTo("HIRING_YEAR"); + + deptMgrEntity = mapper.getDataBaseSchema().getEntityByName("DEPT_MANAGER"); + assertThat(mapper.getEVClassMappersByVertex(deptManagerVertexType).size()).isEqualTo(1); + deptManagerClassMapper = mapper.getEVClassMappersByVertex(deptManagerVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(deptMgrEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(deptMgrEntity).get(0)) + .isEqualTo(deptManagerClassMapper); + assertThat(deptMgrEntity).isEqualTo(deptManagerClassMapper.getEntity()); + assertThat(deptManagerVertexType).isEqualTo(deptManagerClassMapper.getVertexType()); + + assertThat(deptManagerClassMapper.getAttribute2property().size()).isEqualTo(2); + assertThat(deptManagerClassMapper.getProperty2attribute().size()).isEqualTo(2); + assertThat(deptManagerClassMapper.getAttribute2property().get("DEPT_ID")).isEqualTo("deptId"); + assertThat(deptManagerClassMapper.getAttribute2property().get("EMP_ID")).isEqualTo("empId"); + assertThat(deptManagerClassMapper.getProperty2attribute().get("deptId")).isEqualTo("DEPT_ID"); + assertThat(deptManagerClassMapper.getProperty2attribute().get("empId")).isEqualTo("EMP_ID"); + + // Relationships-Edges Mapping + + it = deptEmpEntity.getOutCanonicalRelationships().iterator(); + hasDepartmentRelationship1 = it.next(); + hasEmployeeRelationship1 = it.next(); + assertThat(it.hasNext()).isFalse(); + + it = deptMgrEntity.getOutCanonicalRelationships().iterator(); + hasDepartmentRelationship2 = it.next(); + hasEmployeeRelationship2 = it.next(); + assertThat(it.hasNext()).isFalse(); + + it = branchEntity.getOutCanonicalRelationships().iterator(); + hasDepartmentRelationship3 = it.next(); + assertThat(it.hasNext()).isFalse(); + + // fetching empEdgeType from the rules as was deleted from the graph model during the + // aggregation + assertThat(empEdgeType.getName()).isEqualTo("HasEmp"); + assertThat(empEdgeType.getInVertexType()).isEqualTo(employeeVertexType); + assertThat(empEdgeType.getAllProperties().size()).isEqualTo(0); + + assertThat(mapper.getRelationship2edgeType().size()).isEqualTo(5); + assertThat(mapper.getRelationship2edgeType().get(hasDepartmentRelationship1)) + .isEqualTo(deptEdgeType); + assertThat(mapper.getRelationship2edgeType().get(hasDepartmentRelationship2)) + .isEqualTo(deptEdgeType); + assertThat(mapper.getRelationship2edgeType().get(hasDepartmentRelationship3)) + .isEqualTo(deptEdgeType); + assertThat(mapper.getRelationship2edgeType().get(hasEmployeeRelationship1)) + .isEqualTo(empEdgeType); + assertThat(mapper.getRelationship2edgeType().get(hasEmployeeRelationship2)) + .isEqualTo(empEdgeType); + + assertThat(mapper.getEdgeType2relationships().size()).isEqualTo(2); + assertThat(mapper.getEdgeType2relationships().get(deptEdgeType).size()).isEqualTo(3); + assertThat( + mapper + .getEdgeType2relationships() + .get(deptEdgeType) + .contains(hasDepartmentRelationship1)) + .isTrue(); + assertThat( + mapper + .getEdgeType2relationships() + .get(deptEdgeType) + .contains(hasDepartmentRelationship2)) + .isTrue(); + assertThat( + mapper + .getEdgeType2relationships() + .get(deptEdgeType) + .contains(hasDepartmentRelationship3)) + .isTrue(); + assertThat(mapper.getEdgeType2relationships().get(empEdgeType).size()).isEqualTo(2); + assertThat( + mapper + .getEdgeType2relationships() + .get(empEdgeType) + .contains(hasEmployeeRelationship1)) + .isTrue(); + assertThat( + mapper + .getEdgeType2relationships() + .get(empEdgeType) + .contains(hasEmployeeRelationship2)) + .isTrue(); + + // JoinVertexes-AggregatorEdges Mapping + + assertThat(mapper.getJoinVertex2aggregatorEdges().size()).isEqualTo(2); + assertThat(mapper.getJoinVertex2aggregatorEdges().containsKey(deptManagerVertexType)) + .isTrue(); + assertThat(mapper.getJoinVertex2aggregatorEdges().containsKey(deptEmpVertexType)).isTrue(); + assertThat(mapper.getJoinVertex2aggregatorEdges().get(deptManagerVertexType).getEdgeType()) + .isEqualTo(deptManagerEdgeType); + assertThat( + mapper + .getJoinVertex2aggregatorEdges() + .get(deptManagerVertexType) + .getOutVertexClassName()) + .isEqualTo("Department"); + assertThat( + mapper + .getJoinVertex2aggregatorEdges() + .get(deptManagerVertexType) + .getInVertexClassName()) + .isEqualTo("Employee"); + assertThat(mapper.getJoinVertex2aggregatorEdges().get(deptEmpVertexType).getEdgeType()) + .isEqualTo(deptEmpEdgeType); + assertThat( + mapper.getJoinVertex2aggregatorEdges().get(deptEmpVertexType).getOutVertexClassName()) + .isEqualTo("Department"); + assertThat( + mapper.getJoinVertex2aggregatorEdges().get(deptEmpVertexType).getInVertexClassName()) + .isEqualTo("Employee"); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } finally { + try { + // Dropping Source DB Schema and OrientGraph + String dbDropping = "drop schema public cascade"; + st.execute(dbDropping); + connection.close(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } } + } } diff --git a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/mapper/GraphModelBuildingTest.java b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/mapper/GraphModelBuildingTest.java index a35ed40b..d855dfc0 100644 --- a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/mapper/GraphModelBuildingTest.java +++ b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/mapper/GraphModelBuildingTest.java @@ -40,11 +40,8 @@ * #L% */ -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.junit.jupiter.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import com.arcadeanalytics.provider.DataSourceInfo; import com.arcadeanalytics.provider.rdbms.context.Statistics; @@ -68,1272 +65,1425 @@ /** * @author Gabriele Ponzi */ - -public class GraphModelBuildingTest { - - private ER2GraphMapper mapper; - private DBQueryEngine dbQueryEngine; - private String driver = "org.hsqldb.jdbc.JDBCDriver"; - private String jurl = "jdbc:hsqldb:mem:mydb"; - private String username = "SA"; - private String password = ""; - private DataSourceInfo dataSource; - private Statistics statistics; - private String executionStrategy; - private NameResolver nameResolver; - private HSQLDBDataTypeHandler dataTypeHandler; - - @BeforeEach - public void init() { - this.dataSource = - new DataSourceInfo( - 1L, - "RDBMS_HSQL", - "testDataSource", - "desc", - "mem", - 1234, - "mydb", - username, - password, - false, - "{}", - false, - false, - "", - 22, - "", - false - ); - - statistics = new Statistics(); - - dbQueryEngine = new DBQueryEngine(dataSource, 300); - executionStrategy = "not_specified"; - nameResolver = new JavaConventionNameResolver(); - dataTypeHandler = new HSQLDBDataTypeHandler(); - } - - @Test - /* - * Two tables Foreign and Parent with a simple primary key imported from the parent table. - */ - - public void buildGraphModelFromTwoTablesWithOneSimplePK() { - Connection connection = null; - Statement st = null; - - try { - Class.forName(this.driver); - connection = DriverManager.getConnection(this.jurl, this.username, this.password); - - String parentTableBuilding = - "create memory table BOOK_AUTHOR (ID varchar(256) not null," + " NAME varchar(256) not null, AGE integer not null, primary key (ID))"; - st = connection.createStatement(); - st.execute(parentTableBuilding); - - String foreignTableBuilding = - "create memory table BOOK (ID varchar(256) not null, TITLE varchar(256)," + - " AUTHOR_ID varchar(256) not null, primary key (ID), foreign key (AUTHOR_ID) references BOOK_AUTHOR(ID))"; - st.execute(foreignTableBuilding); - - mapper = new ER2GraphMapper(dataSource, null, null, dbQueryEngine, dataTypeHandler, executionStrategy, nameResolver, statistics); - mapper.buildSourceDatabaseSchema(); - mapper.buildGraphModel(new JavaConventionNameResolver()); - - /* - * Testing context information - */ - - assertEquals(2, statistics.totalNumberOfModelVertices); - assertEquals(2, statistics.builtModelVertexTypes); - assertEquals(1, statistics.totalNumberOfModelEdges); - assertEquals(1, statistics.builtModelEdgeTypes); - - /* - * Testing built graph model - */ - VertexType authorVertexType = mapper.getGraphModel().getVertexTypeByName("BookAuthor"); - VertexType bookVertexType = mapper.getGraphModel().getVertexTypeByName("Book"); - EdgeType authorEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasAuthor"); - - // vertices check - assertEquals(2, mapper.getGraphModel().getVerticesType().size()); - assertNotNull(authorVertexType); - assertNotNull(bookVertexType); - - // properties check - assertEquals(3, authorVertexType.getProperties().size()); - - assertNotNull(authorVertexType.getPropertyByName("id")); - assertEquals("id", authorVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", authorVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, authorVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, authorVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(authorVertexType.getPropertyByName("name")); - assertEquals("name", authorVertexType.getPropertyByName("name").getName()); - assertEquals("VARCHAR", authorVertexType.getPropertyByName("name").getOriginalType()); - assertEquals(2, authorVertexType.getPropertyByName("name").getOrdinalPosition()); - assertEquals(false, authorVertexType.getPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(authorVertexType.getPropertyByName("age")); - assertEquals("age", authorVertexType.getPropertyByName("age").getName()); - assertEquals("INTEGER", authorVertexType.getPropertyByName("age").getOriginalType()); - assertEquals(3, authorVertexType.getPropertyByName("age").getOrdinalPosition()); - assertEquals(false, authorVertexType.getPropertyByName("age").isFromPrimaryKey()); - - assertEquals(3, bookVertexType.getProperties().size()); - - assertNotNull(bookVertexType.getPropertyByName("id")); - assertEquals("id", bookVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", bookVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, bookVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, bookVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(bookVertexType.getPropertyByName("title")); - assertEquals("title", bookVertexType.getPropertyByName("title").getName()); - assertEquals("VARCHAR", bookVertexType.getPropertyByName("title").getOriginalType()); - assertEquals(2, bookVertexType.getPropertyByName("title").getOrdinalPosition()); - assertEquals(false, bookVertexType.getPropertyByName("title").isFromPrimaryKey()); - - assertNotNull(bookVertexType.getPropertyByName("authorId")); - assertEquals("authorId", bookVertexType.getPropertyByName("authorId").getName()); - assertEquals("VARCHAR", bookVertexType.getPropertyByName("authorId").getOriginalType()); - assertEquals(3, bookVertexType.getPropertyByName("authorId").getOrdinalPosition()); - assertEquals(false, bookVertexType.getPropertyByName("authorId").isFromPrimaryKey()); - - // edges check - assertEquals(1, mapper.getGraphModel().getEdgesType().size()); - assertNotNull(authorEdgeType); - - assertEquals("HasAuthor", authorEdgeType.getName()); - assertEquals(0, authorEdgeType.getProperties().size()); - assertEquals("BookAuthor", authorEdgeType.getInVertexType().getName()); - assertEquals(1, authorEdgeType.getNumberRelationshipsRepresented()); - - /* - * Rules check - */ - - // Classes Mapping - - assertEquals(2, mapper.getVertexType2EVClassMappers().size()); - assertEquals(2, mapper.getEntity2EVClassMappers().size()); - - Entity bookEntity = mapper.getDataBaseSchema().getEntityByName("BOOK"); - assertEquals(1, mapper.getEVClassMappersByVertex(bookVertexType).size()); - EVClassMapper bookClassMapper = mapper.getEVClassMappersByVertex(bookVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(bookEntity).size()); - assertEquals(bookClassMapper, mapper.getEVClassMappersByEntity(bookEntity).get(0)); - assertEquals(bookClassMapper.getEntity(), bookEntity); - assertEquals(bookClassMapper.getVertexType(), bookVertexType); - - assertEquals(3, bookClassMapper.getAttribute2property().size()); - assertEquals(3, bookClassMapper.getProperty2attribute().size()); - assertEquals("id", bookClassMapper.getAttribute2property().get("ID")); - assertEquals("title", bookClassMapper.getAttribute2property().get("TITLE")); - assertEquals("authorId", bookClassMapper.getAttribute2property().get("AUTHOR_ID")); - assertEquals("ID", bookClassMapper.getProperty2attribute().get("id")); - assertEquals("TITLE", bookClassMapper.getProperty2attribute().get("title")); - assertEquals("AUTHOR_ID", bookClassMapper.getProperty2attribute().get("authorId")); - - Entity bookAuthorEntity = mapper.getDataBaseSchema().getEntityByName("BOOK_AUTHOR"); - assertEquals(1, mapper.getEVClassMappersByVertex(authorVertexType).size()); - EVClassMapper bookAuthorClassMapper = mapper.getEVClassMappersByVertex(authorVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(bookAuthorEntity).size()); - assertEquals(bookAuthorClassMapper, mapper.getEVClassMappersByEntity(bookAuthorEntity).get(0)); - assertEquals(bookAuthorClassMapper.getEntity(), bookAuthorEntity); - assertEquals(bookAuthorClassMapper.getVertexType(), authorVertexType); - - assertEquals(3, bookAuthorClassMapper.getAttribute2property().size()); - assertEquals(3, bookAuthorClassMapper.getProperty2attribute().size()); - assertEquals("id", bookAuthorClassMapper.getAttribute2property().get("ID")); - assertEquals("name", bookAuthorClassMapper.getAttribute2property().get("NAME")); - assertEquals("age", bookAuthorClassMapper.getAttribute2property().get("AGE")); - assertEquals("ID", bookAuthorClassMapper.getProperty2attribute().get("id")); - assertEquals("NAME", bookAuthorClassMapper.getProperty2attribute().get("name")); - assertEquals("AGE", bookAuthorClassMapper.getProperty2attribute().get("age")); - - // Relationships-Edges Mapping - - Iterator it = bookEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship hasAuthorRelationship = it.next(); - assertFalse(it.hasNext()); - - assertEquals(1, mapper.getRelationship2edgeType().size()); - assertEquals(authorEdgeType, mapper.getRelationship2edgeType().get(hasAuthorRelationship)); - - assertEquals(1, mapper.getEdgeType2relationships().size()); - assertEquals(1, mapper.getEdgeType2relationships().get(authorEdgeType).size()); - assertTrue(mapper.getEdgeType2relationships().get(authorEdgeType).contains(hasAuthorRelationship)); - - // JoinVertexes-AggregatorEdges Mapping - - assertEquals(0, mapper.getJoinVertex2aggregatorEdges().size()); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } finally { - try { - // Dropping Source DB Schema and OrientGraph - String dbDropping = "drop schema public cascade"; - st.execute(dbDropping); - connection.close(); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } - } +class GraphModelBuildingTest { + + private ER2GraphMapper mapper; + private DBQueryEngine dbQueryEngine; + private String driver = "org.hsqldb.jdbc.JDBCDriver"; + private String jurl = "jdbc:hsqldb:mem:mydb"; + private String username = "SA"; + private String password = ""; + private DataSourceInfo dataSource; + private Statistics statistics; + private String executionStrategy; + private NameResolver nameResolver; + private HSQLDBDataTypeHandler dataTypeHandler; + + @BeforeEach + void init() { + this.dataSource = + new DataSourceInfo( + 1L, + "RDBMS_HSQL", + "testDataSource", + "desc", + "mem", + 1234, + "mydb", + username, + password, + false, + "{}", + false, + false, + "", + 22, + "", + false); + + statistics = new Statistics(); + + dbQueryEngine = new DBQueryEngine(dataSource, 300); + executionStrategy = "not_specified"; + nameResolver = new JavaConventionNameResolver(); + dataTypeHandler = new HSQLDBDataTypeHandler(); + } + + /* + * Two tables Foreign and Parent with a simple primary key imported from the parent table. + */ + + @Test + void buildGraphModelFromTwoTablesWithOneSimplePK() { + Connection connection = null; + Statement st = null; + + try { + Class.forName(this.driver); + connection = DriverManager.getConnection(this.jurl, this.username, this.password); + + String parentTableBuilding = + "create memory table BOOK_AUTHOR (ID varchar(256) not null," + + " NAME varchar(256) not null, AGE integer not null, primary key (ID))"; + st = connection.createStatement(); + st.execute(parentTableBuilding); + + String foreignTableBuilding = + "create memory table BOOK (ID varchar(256) not null, TITLE varchar(256), AUTHOR_ID" + + " varchar(256) not null, primary key (ID), foreign key (AUTHOR_ID) references" + + " BOOK_AUTHOR(ID))"; + st.execute(foreignTableBuilding); + + mapper = + new ER2GraphMapper( + dataSource, + null, + null, + dbQueryEngine, + dataTypeHandler, + executionStrategy, + nameResolver, + statistics); + mapper.buildSourceDatabaseSchema(); + mapper.buildGraphModel(new JavaConventionNameResolver()); + + /* + * Testing context information + */ + + assertThat(statistics.totalNumberOfModelVertices).isEqualTo(2); + assertThat(statistics.builtModelVertexTypes).isEqualTo(2); + assertThat(statistics.totalNumberOfModelEdges).isEqualTo(1); + assertThat(statistics.builtModelEdgeTypes).isEqualTo(1); + + /* + * Testing built graph model + */ + VertexType authorVertexType = mapper.getGraphModel().getVertexTypeByName("BookAuthor"); + VertexType bookVertexType = mapper.getGraphModel().getVertexTypeByName("Book"); + EdgeType authorEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasAuthor"); + + // vertices check + assertThat(mapper.getGraphModel().getVerticesType().size()).isEqualTo(2); + assertThat(authorVertexType).isNotNull(); + assertThat(bookVertexType).isNotNull(); + + // properties check + assertThat(authorVertexType.getProperties().size()).isEqualTo(3); + + assertThat(authorVertexType.getPropertyByName("id")).isNotNull(); + assertThat(authorVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(authorVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(authorVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(authorVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(authorVertexType.getPropertyByName("name")).isNotNull(); + assertThat(authorVertexType.getPropertyByName("name").getName()).isEqualTo("name"); + assertThat(authorVertexType.getPropertyByName("name").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(authorVertexType.getPropertyByName("name").getOrdinalPosition()).isEqualTo(2); + assertThat(authorVertexType.getPropertyByName("name").isFromPrimaryKey()).isFalse(); + + assertThat(authorVertexType.getPropertyByName("age")).isNotNull(); + assertThat(authorVertexType.getPropertyByName("age").getName()).isEqualTo("age"); + assertThat(authorVertexType.getPropertyByName("age").getOriginalType()).isEqualTo("INTEGER"); + assertThat(authorVertexType.getPropertyByName("age").getOrdinalPosition()).isEqualTo(3); + assertThat(authorVertexType.getPropertyByName("age").isFromPrimaryKey()).isFalse(); + + assertThat(bookVertexType.getProperties().size()).isEqualTo(3); + + assertThat(bookVertexType.getPropertyByName("id")).isNotNull(); + assertThat(bookVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(bookVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(bookVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(bookVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(bookVertexType.getPropertyByName("title")).isNotNull(); + assertThat(bookVertexType.getPropertyByName("title").getName()).isEqualTo("title"); + assertThat(bookVertexType.getPropertyByName("title").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(bookVertexType.getPropertyByName("title").getOrdinalPosition()).isEqualTo(2); + assertThat(bookVertexType.getPropertyByName("title").isFromPrimaryKey()).isFalse(); + + assertThat(bookVertexType.getPropertyByName("authorId")).isNotNull(); + assertThat(bookVertexType.getPropertyByName("authorId").getName()).isEqualTo("authorId"); + assertThat(bookVertexType.getPropertyByName("authorId").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(bookVertexType.getPropertyByName("authorId").getOrdinalPosition()).isEqualTo(3); + assertThat(bookVertexType.getPropertyByName("authorId").isFromPrimaryKey()).isFalse(); + + // edges check + assertThat(mapper.getGraphModel().getEdgesType().size()).isEqualTo(1); + assertThat(authorEdgeType).isNotNull(); + + assertThat(authorEdgeType.getName()).isEqualTo("HasAuthor"); + assertThat(authorEdgeType.getProperties().size()).isEqualTo(0); + assertThat(authorEdgeType.getInVertexType().getName()).isEqualTo("BookAuthor"); + assertThat(authorEdgeType.getNumberRelationshipsRepresented()).isEqualTo(1); + + /* + * Rules check + */ + + // Classes Mapping + + assertThat(mapper.getVertexType2EVClassMappers().size()).isEqualTo(2); + assertThat(mapper.getEntity2EVClassMappers().size()).isEqualTo(2); + + Entity bookEntity = mapper.getDataBaseSchema().getEntityByName("BOOK"); + assertThat(mapper.getEVClassMappersByVertex(bookVertexType).size()).isEqualTo(1); + EVClassMapper bookClassMapper = mapper.getEVClassMappersByVertex(bookVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(bookEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(bookEntity).get(0)).isEqualTo(bookClassMapper); + assertThat(bookEntity).isEqualTo(bookClassMapper.getEntity()); + assertThat(bookVertexType).isEqualTo(bookClassMapper.getVertexType()); + + assertThat(bookClassMapper.getAttribute2property().size()).isEqualTo(3); + assertThat(bookClassMapper.getProperty2attribute().size()).isEqualTo(3); + assertThat(bookClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(bookClassMapper.getAttribute2property().get("TITLE")).isEqualTo("title"); + assertThat(bookClassMapper.getAttribute2property().get("AUTHOR_ID")).isEqualTo("authorId"); + assertThat(bookClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(bookClassMapper.getProperty2attribute().get("title")).isEqualTo("TITLE"); + assertThat(bookClassMapper.getProperty2attribute().get("authorId")).isEqualTo("AUTHOR_ID"); + + Entity bookAuthorEntity = mapper.getDataBaseSchema().getEntityByName("BOOK_AUTHOR"); + assertThat(mapper.getEVClassMappersByVertex(authorVertexType).size()).isEqualTo(1); + EVClassMapper bookAuthorClassMapper = + mapper.getEVClassMappersByVertex(authorVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(bookAuthorEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(bookAuthorEntity).get(0)) + .isEqualTo(bookAuthorClassMapper); + assertThat(bookAuthorEntity).isEqualTo(bookAuthorClassMapper.getEntity()); + assertThat(authorVertexType).isEqualTo(bookAuthorClassMapper.getVertexType()); + + assertThat(bookAuthorClassMapper.getAttribute2property().size()).isEqualTo(3); + assertThat(bookAuthorClassMapper.getProperty2attribute().size()).isEqualTo(3); + assertThat(bookAuthorClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(bookAuthorClassMapper.getAttribute2property().get("NAME")).isEqualTo("name"); + assertThat(bookAuthorClassMapper.getAttribute2property().get("AGE")).isEqualTo("age"); + assertThat(bookAuthorClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(bookAuthorClassMapper.getProperty2attribute().get("name")).isEqualTo("NAME"); + assertThat(bookAuthorClassMapper.getProperty2attribute().get("age")).isEqualTo("AGE"); + + // Relationships-Edges Mapping + + Iterator it = bookEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship hasAuthorRelationship = it.next(); + assertThat(it.hasNext()).isFalse(); + + assertThat(mapper.getRelationship2edgeType().size()).isEqualTo(1); + assertThat(mapper.getRelationship2edgeType().get(hasAuthorRelationship)) + .isEqualTo(authorEdgeType); + + assertThat(mapper.getEdgeType2relationships().size()).isEqualTo(1); + assertThat(mapper.getEdgeType2relationships().get(authorEdgeType).size()).isEqualTo(1); + assertThat( + mapper + .getEdgeType2relationships() + .get(authorEdgeType) + .contains(hasAuthorRelationship)) + .isTrue(); + + // JoinVertexes-AggregatorEdges Mapping + + assertThat(mapper.getJoinVertex2aggregatorEdges().size()).isEqualTo(0); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } finally { + try { + // Dropping Source DB Schema and OrientGraph + String dbDropping = "drop schema public cascade"; + st.execute(dbDropping); + connection.close(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } } - - @Test - /* - * Three tables and two relationships with two different simple primary keys imported . - */ - - public void buildGraphModelFromThreeTablesWithTwoSimplePK() { - Connection connection = null; - Statement st = null; - - try { - Class.forName(this.driver); - connection = DriverManager.getConnection(this.jurl, this.username, this.password); - - String authorTableBuilding = - "create memory table AUTHOR (ID varchar(256) not null," + " NAME varchar(256) not null, AGE integer not null, primary key (ID))"; - st = connection.createStatement(); - st.execute(authorTableBuilding); - - String bookTableBuilding = - "create memory table BOOK (ID varchar(256) not null, TITLE varchar(256)," + - " AUTHOR_ID varchar(256) not null, primary key (ID), foreign key (AUTHOR_ID) references AUTHOR(ID))"; - st.execute(bookTableBuilding); - - String itemTableBuilding = - "create memory table ITEM (ID varchar(256) not null, BOOK_ID varchar(256)," + - " PRICE varchar(256) not null, primary key (ID), foreign key (BOOK_ID) references BOOK(ID))"; - st.execute(itemTableBuilding); - - this.mapper = new ER2GraphMapper(dataSource, null, null, dbQueryEngine, dataTypeHandler, executionStrategy, nameResolver, statistics); - mapper.buildSourceDatabaseSchema(); - mapper.buildGraphModel(new JavaConventionNameResolver()); - - /* - * Testing context information - */ - - assertEquals(3, statistics.totalNumberOfModelVertices); - assertEquals(3, statistics.builtModelVertexTypes); - assertEquals(2, statistics.totalNumberOfModelEdges); - assertEquals(2, statistics.builtModelEdgeTypes); - - /* - * Testing built graph model - */ - VertexType authorVertexType = mapper.getGraphModel().getVertexTypeByName("Author"); - VertexType bookVertexType = mapper.getGraphModel().getVertexTypeByName("Book"); - VertexType itemVertexType = mapper.getGraphModel().getVertexTypeByName("Item"); - EdgeType authorEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasAuthor"); - EdgeType bookEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasBook"); - - // vertices check - assertEquals(3, mapper.getGraphModel().getVerticesType().size()); - assertNotNull(authorVertexType); - assertNotNull(bookVertexType); - - // properties check - assertEquals(3, authorVertexType.getProperties().size()); - - assertNotNull(authorVertexType.getPropertyByName("id")); - assertEquals("id", authorVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", authorVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, authorVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, authorVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(authorVertexType.getPropertyByName("name")); - assertEquals("name", authorVertexType.getPropertyByName("name").getName()); - assertEquals("VARCHAR", authorVertexType.getPropertyByName("name").getOriginalType()); - assertEquals(2, authorVertexType.getPropertyByName("name").getOrdinalPosition()); - assertEquals(false, authorVertexType.getPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(authorVertexType.getPropertyByName("age")); - assertEquals("age", authorVertexType.getPropertyByName("age").getName()); - assertEquals("INTEGER", authorVertexType.getPropertyByName("age").getOriginalType()); - assertEquals(3, authorVertexType.getPropertyByName("age").getOrdinalPosition()); - assertEquals(false, authorVertexType.getPropertyByName("age").isFromPrimaryKey()); - - assertEquals(3, bookVertexType.getProperties().size()); - - assertNotNull(bookVertexType.getPropertyByName("id")); - assertEquals("id", bookVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", bookVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, bookVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, bookVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(bookVertexType.getPropertyByName("title")); - assertEquals("title", bookVertexType.getPropertyByName("title").getName()); - assertEquals("VARCHAR", bookVertexType.getPropertyByName("title").getOriginalType()); - assertEquals(2, bookVertexType.getPropertyByName("title").getOrdinalPosition()); - assertEquals(false, bookVertexType.getPropertyByName("title").isFromPrimaryKey()); - - assertNotNull(bookVertexType.getPropertyByName("authorId")); - assertEquals("authorId", bookVertexType.getPropertyByName("authorId").getName()); - assertEquals("VARCHAR", bookVertexType.getPropertyByName("authorId").getOriginalType()); - assertEquals(3, bookVertexType.getPropertyByName("authorId").getOrdinalPosition()); - assertEquals(false, bookVertexType.getPropertyByName("authorId").isFromPrimaryKey()); - - assertEquals(3, itemVertexType.getProperties().size()); - - assertNotNull(itemVertexType.getPropertyByName("id")); - assertEquals("id", itemVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", itemVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, itemVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, itemVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(itemVertexType.getPropertyByName("bookId")); - assertEquals("bookId", itemVertexType.getPropertyByName("bookId").getName()); - assertEquals("VARCHAR", itemVertexType.getPropertyByName("bookId").getOriginalType()); - assertEquals(2, itemVertexType.getPropertyByName("bookId").getOrdinalPosition()); - assertEquals(false, itemVertexType.getPropertyByName("bookId").isFromPrimaryKey()); - - assertNotNull(itemVertexType.getPropertyByName("price")); - assertEquals("price", itemVertexType.getPropertyByName("price").getName()); - assertEquals("VARCHAR", itemVertexType.getPropertyByName("price").getOriginalType()); - assertEquals(3, itemVertexType.getPropertyByName("price").getOrdinalPosition()); - assertEquals(false, itemVertexType.getPropertyByName("price").isFromPrimaryKey()); - - // edges check - assertEquals(2, mapper.getGraphModel().getEdgesType().size()); - assertNotNull(authorEdgeType); - assertNotNull(bookEdgeType); - - assertEquals("HasAuthor", authorEdgeType.getName()); - assertEquals(0, authorEdgeType.getProperties().size()); - assertEquals("Author", authorEdgeType.getInVertexType().getName()); - assertEquals(1, authorEdgeType.getNumberRelationshipsRepresented()); - - assertEquals("HasBook", bookEdgeType.getName()); - assertEquals(0, bookEdgeType.getProperties().size()); - assertEquals("Book", bookEdgeType.getInVertexType().getName()); - assertEquals(1, bookEdgeType.getNumberRelationshipsRepresented()); - - /* - * Rules check - */ - - // Classes Mapping - - assertEquals(3, mapper.getVertexType2EVClassMappers().size()); - assertEquals(3, mapper.getEntity2EVClassMappers().size()); - - Entity bookEntity = mapper.getDataBaseSchema().getEntityByName("BOOK"); - assertEquals(1, mapper.getEVClassMappersByVertex(bookVertexType).size()); - EVClassMapper bookClassMapper = mapper.getEVClassMappersByVertex(bookVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(bookEntity).size()); - assertEquals(bookClassMapper, mapper.getEVClassMappersByEntity(bookEntity).get(0)); - assertEquals(bookClassMapper.getEntity(), bookEntity); - assertEquals(bookClassMapper.getVertexType(), bookVertexType); - - assertEquals(3, bookClassMapper.getAttribute2property().size()); - assertEquals(3, bookClassMapper.getProperty2attribute().size()); - assertEquals("id", bookClassMapper.getAttribute2property().get("ID")); - assertEquals("title", bookClassMapper.getAttribute2property().get("TITLE")); - assertEquals("authorId", bookClassMapper.getAttribute2property().get("AUTHOR_ID")); - assertEquals("ID", bookClassMapper.getProperty2attribute().get("id")); - assertEquals("TITLE", bookClassMapper.getProperty2attribute().get("title")); - assertEquals("AUTHOR_ID", bookClassMapper.getProperty2attribute().get("authorId")); - - Entity authorEntity = mapper.getDataBaseSchema().getEntityByName("AUTHOR"); - assertEquals(1, mapper.getEVClassMappersByVertex(authorVertexType).size()); - EVClassMapper authorClassMapper = mapper.getEVClassMappersByVertex(authorVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(authorEntity).size()); - assertEquals(authorClassMapper, mapper.getEVClassMappersByEntity(authorEntity).get(0)); - assertEquals(authorClassMapper.getEntity(), authorEntity); - assertEquals(authorClassMapper.getVertexType(), authorVertexType); - - assertEquals(3, authorClassMapper.getAttribute2property().size()); - assertEquals(3, authorClassMapper.getProperty2attribute().size()); - assertEquals("id", authorClassMapper.getAttribute2property().get("ID")); - assertEquals("name", authorClassMapper.getAttribute2property().get("NAME")); - assertEquals("age", authorClassMapper.getAttribute2property().get("AGE")); - assertEquals("ID", authorClassMapper.getProperty2attribute().get("id")); - assertEquals("NAME", authorClassMapper.getProperty2attribute().get("name")); - assertEquals("AGE", authorClassMapper.getProperty2attribute().get("age")); - - Entity itemEntity = mapper.getDataBaseSchema().getEntityByName("ITEM"); - assertEquals(1, mapper.getEVClassMappersByVertex(itemVertexType).size()); - EVClassMapper itemClassMapper = mapper.getEVClassMappersByVertex(itemVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(itemEntity).size()); - assertEquals(itemClassMapper, mapper.getEVClassMappersByEntity(itemEntity).get(0)); - assertEquals(itemClassMapper.getEntity(), itemEntity); - assertEquals(itemClassMapper.getVertexType(), itemVertexType); - - assertEquals(3, itemClassMapper.getAttribute2property().size()); - assertEquals(3, itemClassMapper.getProperty2attribute().size()); - assertEquals("id", itemClassMapper.getAttribute2property().get("ID")); - assertEquals("bookId", itemClassMapper.getAttribute2property().get("BOOK_ID")); - assertEquals("price", itemClassMapper.getAttribute2property().get("PRICE")); - assertEquals("ID", itemClassMapper.getProperty2attribute().get("id")); - assertEquals("BOOK_ID", itemClassMapper.getProperty2attribute().get("bookId")); - assertEquals("PRICE", itemClassMapper.getProperty2attribute().get("price")); - - // Relationships-Edges Mapping - - Iterator it = bookEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship hasAuthorRelationship = it.next(); - assertFalse(it.hasNext()); - it = itemEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship hasBookRelationship = it.next(); - assertFalse(it.hasNext()); - - assertEquals(2, mapper.getRelationship2edgeType().size()); - assertEquals(authorEdgeType, mapper.getRelationship2edgeType().get(hasAuthorRelationship)); - assertEquals(bookEdgeType, mapper.getRelationship2edgeType().get(hasBookRelationship)); - - assertEquals(2, mapper.getEdgeType2relationships().size()); - assertEquals(1, mapper.getEdgeType2relationships().get(authorEdgeType).size()); - assertTrue(mapper.getEdgeType2relationships().get(authorEdgeType).contains(hasAuthorRelationship)); - assertEquals(1, mapper.getEdgeType2relationships().get(bookEdgeType).size()); - assertTrue(mapper.getEdgeType2relationships().get(bookEdgeType).contains(hasBookRelationship)); - - // JoinVertexes-AggregatorEdges Mapping - - assertEquals(0, mapper.getJoinVertex2aggregatorEdges().size()); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } finally { - try { - // Dropping Source DB Schema and OrientGraph - String dbDropping = "drop schema public cascade"; - st.execute(dbDropping); - connection.close(); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } - } + } + + /* + * Three tables and two relationships with two different simple primary keys imported . + */ + + @Test + void buildGraphModelFromThreeTablesWithTwoSimplePK() { + Connection connection = null; + Statement st = null; + + try { + Class.forName(this.driver); + connection = DriverManager.getConnection(this.jurl, this.username, this.password); + + String authorTableBuilding = + "create memory table AUTHOR (ID varchar(256) not null," + + " NAME varchar(256) not null, AGE integer not null, primary key (ID))"; + st = connection.createStatement(); + st.execute(authorTableBuilding); + + String bookTableBuilding = + "create memory table BOOK (ID varchar(256) not null, TITLE varchar(256), AUTHOR_ID" + + " varchar(256) not null, primary key (ID), foreign key (AUTHOR_ID) references" + + " AUTHOR(ID))"; + st.execute(bookTableBuilding); + + String itemTableBuilding = + "create memory table ITEM (ID varchar(256) not null, BOOK_ID varchar(256), PRICE" + + " varchar(256) not null, primary key (ID), foreign key (BOOK_ID) references" + + " BOOK(ID))"; + st.execute(itemTableBuilding); + + this.mapper = + new ER2GraphMapper( + dataSource, + null, + null, + dbQueryEngine, + dataTypeHandler, + executionStrategy, + nameResolver, + statistics); + mapper.buildSourceDatabaseSchema(); + mapper.buildGraphModel(new JavaConventionNameResolver()); + + /* + * Testing context information + */ + + assertThat(statistics.totalNumberOfModelVertices).isEqualTo(3); + assertThat(statistics.builtModelVertexTypes).isEqualTo(3); + assertThat(statistics.totalNumberOfModelEdges).isEqualTo(2); + assertThat(statistics.builtModelEdgeTypes).isEqualTo(2); + + /* + * Testing built graph model + */ + VertexType authorVertexType = mapper.getGraphModel().getVertexTypeByName("Author"); + VertexType bookVertexType = mapper.getGraphModel().getVertexTypeByName("Book"); + VertexType itemVertexType = mapper.getGraphModel().getVertexTypeByName("Item"); + EdgeType authorEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasAuthor"); + EdgeType bookEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasBook"); + + // vertices check + assertThat(mapper.getGraphModel().getVerticesType().size()).isEqualTo(3); + assertThat(authorVertexType).isNotNull(); + assertThat(bookVertexType).isNotNull(); + + // properties check + assertThat(authorVertexType.getProperties().size()).isEqualTo(3); + + assertThat(authorVertexType.getPropertyByName("id")).isNotNull(); + assertThat(authorVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(authorVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(authorVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(authorVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(authorVertexType.getPropertyByName("name")).isNotNull(); + assertThat(authorVertexType.getPropertyByName("name").getName()).isEqualTo("name"); + assertThat(authorVertexType.getPropertyByName("name").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(authorVertexType.getPropertyByName("name").getOrdinalPosition()).isEqualTo(2); + assertThat(authorVertexType.getPropertyByName("name").isFromPrimaryKey()).isFalse(); + + assertThat(authorVertexType.getPropertyByName("age")).isNotNull(); + assertThat(authorVertexType.getPropertyByName("age").getName()).isEqualTo("age"); + assertThat(authorVertexType.getPropertyByName("age").getOriginalType()).isEqualTo("INTEGER"); + assertThat(authorVertexType.getPropertyByName("age").getOrdinalPosition()).isEqualTo(3); + assertThat(authorVertexType.getPropertyByName("age").isFromPrimaryKey()).isFalse(); + + assertThat(bookVertexType.getProperties().size()).isEqualTo(3); + + assertThat(bookVertexType.getPropertyByName("id")).isNotNull(); + assertThat(bookVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(bookVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(bookVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(bookVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(bookVertexType.getPropertyByName("title")).isNotNull(); + assertThat(bookVertexType.getPropertyByName("title").getName()).isEqualTo("title"); + assertThat(bookVertexType.getPropertyByName("title").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(bookVertexType.getPropertyByName("title").getOrdinalPosition()).isEqualTo(2); + assertThat(bookVertexType.getPropertyByName("title").isFromPrimaryKey()).isFalse(); + + assertThat(bookVertexType.getPropertyByName("authorId")).isNotNull(); + assertThat(bookVertexType.getPropertyByName("authorId").getName()).isEqualTo("authorId"); + assertThat(bookVertexType.getPropertyByName("authorId").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(bookVertexType.getPropertyByName("authorId").getOrdinalPosition()).isEqualTo(3); + assertThat(bookVertexType.getPropertyByName("authorId").isFromPrimaryKey()).isFalse(); + + assertThat(itemVertexType.getProperties().size()).isEqualTo(3); + + assertThat(itemVertexType.getPropertyByName("id")).isNotNull(); + assertThat(itemVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(itemVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(itemVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(itemVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(itemVertexType.getPropertyByName("bookId")).isNotNull(); + assertThat(itemVertexType.getPropertyByName("bookId").getName()).isEqualTo("bookId"); + assertThat(itemVertexType.getPropertyByName("bookId").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(itemVertexType.getPropertyByName("bookId").getOrdinalPosition()).isEqualTo(2); + assertThat(itemVertexType.getPropertyByName("bookId").isFromPrimaryKey()).isFalse(); + + assertThat(itemVertexType.getPropertyByName("price")).isNotNull(); + assertThat(itemVertexType.getPropertyByName("price").getName()).isEqualTo("price"); + assertThat(itemVertexType.getPropertyByName("price").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(itemVertexType.getPropertyByName("price").getOrdinalPosition()).isEqualTo(3); + assertThat(itemVertexType.getPropertyByName("price").isFromPrimaryKey()).isFalse(); + + // edges check + assertThat(mapper.getGraphModel().getEdgesType().size()).isEqualTo(2); + assertThat(authorEdgeType).isNotNull(); + assertThat(bookEdgeType).isNotNull(); + + assertThat(authorEdgeType.getName()).isEqualTo("HasAuthor"); + assertThat(authorEdgeType.getProperties().size()).isEqualTo(0); + assertThat(authorEdgeType.getInVertexType().getName()).isEqualTo("Author"); + assertThat(authorEdgeType.getNumberRelationshipsRepresented()).isEqualTo(1); + + assertThat(bookEdgeType.getName()).isEqualTo("HasBook"); + assertThat(bookEdgeType.getProperties().size()).isEqualTo(0); + assertThat(bookEdgeType.getInVertexType().getName()).isEqualTo("Book"); + assertThat(bookEdgeType.getNumberRelationshipsRepresented()).isEqualTo(1); + + /* + * Rules check + */ + + // Classes Mapping + + assertThat(mapper.getVertexType2EVClassMappers().size()).isEqualTo(3); + assertThat(mapper.getEntity2EVClassMappers().size()).isEqualTo(3); + + Entity bookEntity = mapper.getDataBaseSchema().getEntityByName("BOOK"); + assertThat(mapper.getEVClassMappersByVertex(bookVertexType).size()).isEqualTo(1); + EVClassMapper bookClassMapper = mapper.getEVClassMappersByVertex(bookVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(bookEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(bookEntity).get(0)).isEqualTo(bookClassMapper); + assertThat(bookEntity).isEqualTo(bookClassMapper.getEntity()); + assertThat(bookVertexType).isEqualTo(bookClassMapper.getVertexType()); + + assertThat(bookClassMapper.getAttribute2property().size()).isEqualTo(3); + assertThat(bookClassMapper.getProperty2attribute().size()).isEqualTo(3); + assertThat(bookClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(bookClassMapper.getAttribute2property().get("TITLE")).isEqualTo("title"); + assertThat(bookClassMapper.getAttribute2property().get("AUTHOR_ID")).isEqualTo("authorId"); + assertThat(bookClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(bookClassMapper.getProperty2attribute().get("title")).isEqualTo("TITLE"); + assertThat(bookClassMapper.getProperty2attribute().get("authorId")).isEqualTo("AUTHOR_ID"); + + Entity authorEntity = mapper.getDataBaseSchema().getEntityByName("AUTHOR"); + assertThat(mapper.getEVClassMappersByVertex(authorVertexType).size()).isEqualTo(1); + EVClassMapper authorClassMapper = mapper.getEVClassMappersByVertex(authorVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(authorEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(authorEntity).get(0)) + .isEqualTo(authorClassMapper); + assertThat(authorEntity).isEqualTo(authorClassMapper.getEntity()); + assertThat(authorVertexType).isEqualTo(authorClassMapper.getVertexType()); + + assertThat(authorClassMapper.getAttribute2property().size()).isEqualTo(3); + assertThat(authorClassMapper.getProperty2attribute().size()).isEqualTo(3); + assertThat(authorClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(authorClassMapper.getAttribute2property().get("NAME")).isEqualTo("name"); + assertThat(authorClassMapper.getAttribute2property().get("AGE")).isEqualTo("age"); + assertThat(authorClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(authorClassMapper.getProperty2attribute().get("name")).isEqualTo("NAME"); + assertThat(authorClassMapper.getProperty2attribute().get("age")).isEqualTo("AGE"); + + Entity itemEntity = mapper.getDataBaseSchema().getEntityByName("ITEM"); + assertThat(mapper.getEVClassMappersByVertex(itemVertexType).size()).isEqualTo(1); + EVClassMapper itemClassMapper = mapper.getEVClassMappersByVertex(itemVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(itemEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(itemEntity).get(0)).isEqualTo(itemClassMapper); + assertThat(itemEntity).isEqualTo(itemClassMapper.getEntity()); + assertThat(itemVertexType).isEqualTo(itemClassMapper.getVertexType()); + + assertThat(itemClassMapper.getAttribute2property().size()).isEqualTo(3); + assertThat(itemClassMapper.getProperty2attribute().size()).isEqualTo(3); + assertThat(itemClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(itemClassMapper.getAttribute2property().get("BOOK_ID")).isEqualTo("bookId"); + assertThat(itemClassMapper.getAttribute2property().get("PRICE")).isEqualTo("price"); + assertThat(itemClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(itemClassMapper.getProperty2attribute().get("bookId")).isEqualTo("BOOK_ID"); + assertThat(itemClassMapper.getProperty2attribute().get("price")).isEqualTo("PRICE"); + + // Relationships-Edges Mapping + + Iterator it = bookEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship hasAuthorRelationship = it.next(); + assertThat(it.hasNext()).isFalse(); + it = itemEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship hasBookRelationship = it.next(); + assertThat(it.hasNext()).isFalse(); + + assertThat(mapper.getRelationship2edgeType().size()).isEqualTo(2); + assertThat(mapper.getRelationship2edgeType().get(hasAuthorRelationship)) + .isEqualTo(authorEdgeType); + assertThat(mapper.getRelationship2edgeType().get(hasBookRelationship)) + .isEqualTo(bookEdgeType); + + assertThat(mapper.getEdgeType2relationships().size()).isEqualTo(2); + assertThat(mapper.getEdgeType2relationships().get(authorEdgeType).size()).isEqualTo(1); + assertThat( + mapper + .getEdgeType2relationships() + .get(authorEdgeType) + .contains(hasAuthorRelationship)) + .isTrue(); + assertThat(mapper.getEdgeType2relationships().get(bookEdgeType).size()).isEqualTo(1); + assertThat(mapper.getEdgeType2relationships().get(bookEdgeType).contains(hasBookRelationship)) + .isTrue(); + + // JoinVertexes-AggregatorEdges Mapping + + assertThat(mapper.getJoinVertex2aggregatorEdges().size()).isEqualTo(0); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } finally { + try { + // Dropping Source DB Schema and OrientGraph + String dbDropping = "drop schema public cascade"; + st.execute(dbDropping); + connection.close(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } } - - @Test - /* - * Three tables and two relationships with a simple primary keys twice imported. - */ - - public void buildGraphModelFromThreeTablesWithOneSimplePKImportedTwice() { - Connection connection = null; - Statement st = null; - - try { - Class.forName(this.driver); - connection = DriverManager.getConnection(this.jurl, this.username, this.password); - - String authorTableBuilding = - "create memory table AUTHOR (ID varchar(256) not null," + " NAME varchar(256) not null, AGE integer not null, primary key (ID))"; - st = connection.createStatement(); - st.execute(authorTableBuilding); - - String bookTableBuilding = - "create memory table BOOK (ID varchar(256) not null, TITLE varchar(256)," + - " AUTHOR_ID varchar(256) not null, primary key (ID), foreign key (AUTHOR_ID) references AUTHOR(ID))"; - st.execute(bookTableBuilding); - - String articleTableBuilding = - "create memory table ARTICLE (ID varchar(256) not null, TITLE varchar(256)," + - " DATE date, AUTHOR_ID varchar(256) not null, primary key (ID), foreign key (AUTHOR_ID) references AUTHOR(ID))"; - st.execute(articleTableBuilding); - - this.mapper = new ER2GraphMapper(dataSource, null, null, dbQueryEngine, dataTypeHandler, executionStrategy, nameResolver, statistics); - mapper.buildSourceDatabaseSchema(); - mapper.buildGraphModel(new JavaConventionNameResolver()); - - /* - * Testing context information - */ - - assertEquals(3, statistics.totalNumberOfModelVertices); - assertEquals(3, statistics.builtModelVertexTypes); - assertEquals(1, statistics.totalNumberOfModelEdges); - assertEquals(1, statistics.builtModelEdgeTypes); - - /* - * Testing built graph model - */ - VertexType authorVertexType = mapper.getGraphModel().getVertexTypeByName("Author"); - VertexType bookVertexType = mapper.getGraphModel().getVertexTypeByName("Book"); - VertexType articleVertexType = mapper.getGraphModel().getVertexTypeByName("Article"); - EdgeType authorEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasAuthor"); - - // vertices check - assertEquals(3, mapper.getGraphModel().getVerticesType().size()); - assertNotNull(authorVertexType); - assertNotNull(bookVertexType); - - // properties check - assertEquals(3, authorVertexType.getProperties().size()); - - assertNotNull(authorVertexType.getPropertyByName("id")); - assertEquals("id", authorVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", authorVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, authorVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, authorVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(authorVertexType.getPropertyByName("name")); - assertEquals("name", authorVertexType.getPropertyByName("name").getName()); - assertEquals("VARCHAR", authorVertexType.getPropertyByName("name").getOriginalType()); - assertEquals(2, authorVertexType.getPropertyByName("name").getOrdinalPosition()); - assertEquals(false, authorVertexType.getPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(authorVertexType.getPropertyByName("age")); - assertEquals("age", authorVertexType.getPropertyByName("age").getName()); - assertEquals("INTEGER", authorVertexType.getPropertyByName("age").getOriginalType()); - assertEquals(3, authorVertexType.getPropertyByName("age").getOrdinalPosition()); - assertEquals(false, authorVertexType.getPropertyByName("age").isFromPrimaryKey()); - - assertEquals(3, bookVertexType.getProperties().size()); - - assertNotNull(bookVertexType.getPropertyByName("id")); - assertEquals("id", bookVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", bookVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, bookVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, bookVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(bookVertexType.getPropertyByName("title")); - assertEquals("title", bookVertexType.getPropertyByName("title").getName()); - assertEquals("VARCHAR", bookVertexType.getPropertyByName("title").getOriginalType()); - assertEquals(2, bookVertexType.getPropertyByName("title").getOrdinalPosition()); - assertEquals(false, bookVertexType.getPropertyByName("title").isFromPrimaryKey()); - - assertNotNull(bookVertexType.getPropertyByName("authorId")); - assertEquals("authorId", bookVertexType.getPropertyByName("authorId").getName()); - assertEquals("VARCHAR", bookVertexType.getPropertyByName("authorId").getOriginalType()); - assertEquals(3, bookVertexType.getPropertyByName("authorId").getOrdinalPosition()); - assertEquals(false, bookVertexType.getPropertyByName("authorId").isFromPrimaryKey()); - - assertEquals(4, articleVertexType.getProperties().size()); - - assertNotNull(articleVertexType.getPropertyByName("id")); - assertEquals("id", articleVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", articleVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, articleVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, articleVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(articleVertexType.getPropertyByName("title")); - assertEquals("title", articleVertexType.getPropertyByName("title").getName()); - assertEquals("VARCHAR", articleVertexType.getPropertyByName("title").getOriginalType()); - assertEquals(2, articleVertexType.getPropertyByName("title").getOrdinalPosition()); - assertEquals(false, articleVertexType.getPropertyByName("title").isFromPrimaryKey()); - - assertNotNull(articleVertexType.getPropertyByName("date")); - assertEquals("date", articleVertexType.getPropertyByName("date").getName()); - assertEquals("DATE", articleVertexType.getPropertyByName("date").getOriginalType()); - assertEquals(3, articleVertexType.getPropertyByName("date").getOrdinalPosition()); - assertEquals(false, articleVertexType.getPropertyByName("date").isFromPrimaryKey()); - - assertNotNull(articleVertexType.getPropertyByName("authorId")); - assertEquals("authorId", articleVertexType.getPropertyByName("authorId").getName()); - assertEquals("VARCHAR", articleVertexType.getPropertyByName("authorId").getOriginalType()); - assertEquals(4, articleVertexType.getPropertyByName("authorId").getOrdinalPosition()); - assertEquals(false, articleVertexType.getPropertyByName("authorId").isFromPrimaryKey()); - - // edges check - assertEquals(1, mapper.getGraphModel().getEdgesType().size()); - assertNotNull(authorEdgeType); - - assertEquals("HasAuthor", authorEdgeType.getName()); - assertEquals(0, authorEdgeType.getProperties().size()); - assertEquals("Author", authorEdgeType.getInVertexType().getName()); - assertEquals(2, authorEdgeType.getNumberRelationshipsRepresented()); - - /* - * Rules check - */ - - // Classes Mapping - - assertEquals(3, mapper.getVertexType2EVClassMappers().size()); - assertEquals(3, mapper.getEntity2EVClassMappers().size()); - - Entity bookEntity = mapper.getDataBaseSchema().getEntityByName("BOOK"); - assertEquals(1, mapper.getEVClassMappersByVertex(bookVertexType).size()); - EVClassMapper bookClassMapper = mapper.getEVClassMappersByVertex(bookVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(bookEntity).size()); - assertEquals(bookClassMapper, mapper.getEVClassMappersByEntity(bookEntity).get(0)); - assertEquals(bookClassMapper.getEntity(), bookEntity); - assertEquals(bookClassMapper.getVertexType(), bookVertexType); - - assertEquals(3, bookClassMapper.getAttribute2property().size()); - assertEquals(3, bookClassMapper.getProperty2attribute().size()); - assertEquals("id", bookClassMapper.getAttribute2property().get("ID")); - assertEquals("title", bookClassMapper.getAttribute2property().get("TITLE")); - assertEquals("authorId", bookClassMapper.getAttribute2property().get("AUTHOR_ID")); - assertEquals("ID", bookClassMapper.getProperty2attribute().get("id")); - assertEquals("TITLE", bookClassMapper.getProperty2attribute().get("title")); - assertEquals("AUTHOR_ID", bookClassMapper.getProperty2attribute().get("authorId")); - - Entity authorEntity = mapper.getDataBaseSchema().getEntityByName("AUTHOR"); - assertEquals(1, mapper.getEVClassMappersByVertex(authorVertexType).size()); - EVClassMapper authorClassMapper = mapper.getEVClassMappersByVertex(authorVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(authorEntity).size()); - assertEquals(authorClassMapper, mapper.getEVClassMappersByEntity(authorEntity).get(0)); - assertEquals(authorClassMapper.getEntity(), authorEntity); - assertEquals(authorClassMapper.getVertexType(), authorVertexType); - - assertEquals(3, authorClassMapper.getAttribute2property().size()); - assertEquals(3, authorClassMapper.getProperty2attribute().size()); - assertEquals("id", authorClassMapper.getAttribute2property().get("ID")); - assertEquals("name", authorClassMapper.getAttribute2property().get("NAME")); - assertEquals("age", authorClassMapper.getAttribute2property().get("AGE")); - assertEquals("ID", authorClassMapper.getProperty2attribute().get("id")); - assertEquals("NAME", authorClassMapper.getProperty2attribute().get("name")); - assertEquals("AGE", authorClassMapper.getProperty2attribute().get("age")); - - Entity articleEntity = mapper.getDataBaseSchema().getEntityByName("ARTICLE"); - assertEquals(1, mapper.getEVClassMappersByVertex(articleVertexType).size()); - EVClassMapper articleClassMapper = mapper.getEVClassMappersByVertex(articleVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(articleEntity).size()); - assertEquals(articleClassMapper, mapper.getEVClassMappersByEntity(articleEntity).get(0)); - assertEquals(articleClassMapper.getEntity(), articleEntity); - assertEquals(articleClassMapper.getVertexType(), articleVertexType); - - assertEquals(4, articleClassMapper.getAttribute2property().size()); - assertEquals(4, articleClassMapper.getProperty2attribute().size()); - assertEquals("id", articleClassMapper.getAttribute2property().get("ID")); - assertEquals("title", articleClassMapper.getAttribute2property().get("TITLE")); - assertEquals("date", articleClassMapper.getAttribute2property().get("DATE")); - assertEquals("authorId", articleClassMapper.getAttribute2property().get("AUTHOR_ID")); - assertEquals("ID", articleClassMapper.getProperty2attribute().get("id")); - assertEquals("TITLE", articleClassMapper.getProperty2attribute().get("title")); - assertEquals("DATE", articleClassMapper.getProperty2attribute().get("date")); - assertEquals("AUTHOR_ID", articleClassMapper.getProperty2attribute().get("authorId")); - - // Relationships-Edges Mapping - - Iterator it = bookEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship hasAuthorRelationship1 = it.next(); - assertFalse(it.hasNext()); - it = articleEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship hasAuthorRelationship2 = it.next(); - assertFalse(it.hasNext()); - - assertEquals(2, mapper.getRelationship2edgeType().size()); - assertEquals(authorEdgeType, mapper.getRelationship2edgeType().get(hasAuthorRelationship1)); - assertEquals(authorEdgeType, mapper.getRelationship2edgeType().get(hasAuthorRelationship2)); - - assertEquals(1, mapper.getEdgeType2relationships().size()); - assertEquals(2, mapper.getEdgeType2relationships().get(authorEdgeType).size()); - assertTrue(mapper.getEdgeType2relationships().get(authorEdgeType).contains(hasAuthorRelationship1)); - assertTrue(mapper.getEdgeType2relationships().get(authorEdgeType).contains(hasAuthorRelationship2)); - - // JoinVertexes-AggregatorEdges Mapping - - assertEquals(0, mapper.getJoinVertex2aggregatorEdges().size()); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } finally { - try { - // Dropping Source DB Schema and OrientGraph - String dbDropping = "drop schema public cascade"; - st.execute(dbDropping); - connection.close(); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } - } + } + + /* + * Three tables and two relationships with a simple primary keys twice imported. + */ + + @Test + void buildGraphModelFromThreeTablesWithOneSimplePKImportedTwice() { + Connection connection = null; + Statement st = null; + + try { + Class.forName(this.driver); + connection = DriverManager.getConnection(this.jurl, this.username, this.password); + + String authorTableBuilding = + "create memory table AUTHOR (ID varchar(256) not null," + + " NAME varchar(256) not null, AGE integer not null, primary key (ID))"; + st = connection.createStatement(); + st.execute(authorTableBuilding); + + String bookTableBuilding = + "create memory table BOOK (ID varchar(256) not null, TITLE varchar(256), AUTHOR_ID" + + " varchar(256) not null, primary key (ID), foreign key (AUTHOR_ID) references" + + " AUTHOR(ID))"; + st.execute(bookTableBuilding); + + String articleTableBuilding = + "create memory table ARTICLE (ID varchar(256) not null, TITLE varchar(256), DATE date," + + " AUTHOR_ID varchar(256) not null, primary key (ID), foreign key (AUTHOR_ID)" + + " references AUTHOR(ID))"; + st.execute(articleTableBuilding); + + this.mapper = + new ER2GraphMapper( + dataSource, + null, + null, + dbQueryEngine, + dataTypeHandler, + executionStrategy, + nameResolver, + statistics); + mapper.buildSourceDatabaseSchema(); + mapper.buildGraphModel(new JavaConventionNameResolver()); + + /* + * Testing context information + */ + + assertThat(statistics.totalNumberOfModelVertices).isEqualTo(3); + assertThat(statistics.builtModelVertexTypes).isEqualTo(3); + assertThat(statistics.totalNumberOfModelEdges).isEqualTo(1); + assertThat(statistics.builtModelEdgeTypes).isEqualTo(1); + + /* + * Testing built graph model + */ + VertexType authorVertexType = mapper.getGraphModel().getVertexTypeByName("Author"); + VertexType bookVertexType = mapper.getGraphModel().getVertexTypeByName("Book"); + VertexType articleVertexType = mapper.getGraphModel().getVertexTypeByName("Article"); + EdgeType authorEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasAuthor"); + + // vertices check + assertThat(mapper.getGraphModel().getVerticesType().size()).isEqualTo(3); + assertThat(authorVertexType).isNotNull(); + assertThat(bookVertexType).isNotNull(); + + // properties check + assertThat(authorVertexType.getProperties().size()).isEqualTo(3); + + assertThat(authorVertexType.getPropertyByName("id")).isNotNull(); + assertThat(authorVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(authorVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(authorVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(authorVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(authorVertexType.getPropertyByName("name")).isNotNull(); + assertThat(authorVertexType.getPropertyByName("name").getName()).isEqualTo("name"); + assertThat(authorVertexType.getPropertyByName("name").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(authorVertexType.getPropertyByName("name").getOrdinalPosition()).isEqualTo(2); + assertThat(authorVertexType.getPropertyByName("name").isFromPrimaryKey()).isFalse(); + + assertThat(authorVertexType.getPropertyByName("age")).isNotNull(); + assertThat(authorVertexType.getPropertyByName("age").getName()).isEqualTo("age"); + assertThat(authorVertexType.getPropertyByName("age").getOriginalType()).isEqualTo("INTEGER"); + assertThat(authorVertexType.getPropertyByName("age").getOrdinalPosition()).isEqualTo(3); + assertThat(authorVertexType.getPropertyByName("age").isFromPrimaryKey()).isFalse(); + + assertThat(bookVertexType.getProperties().size()).isEqualTo(3); + + assertThat(bookVertexType.getPropertyByName("id")).isNotNull(); + assertThat(bookVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(bookVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(bookVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(bookVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(bookVertexType.getPropertyByName("title")).isNotNull(); + assertThat(bookVertexType.getPropertyByName("title").getName()).isEqualTo("title"); + assertThat(bookVertexType.getPropertyByName("title").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(bookVertexType.getPropertyByName("title").getOrdinalPosition()).isEqualTo(2); + assertThat(bookVertexType.getPropertyByName("title").isFromPrimaryKey()).isFalse(); + + assertThat(bookVertexType.getPropertyByName("authorId")).isNotNull(); + assertThat(bookVertexType.getPropertyByName("authorId").getName()).isEqualTo("authorId"); + assertThat(bookVertexType.getPropertyByName("authorId").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(bookVertexType.getPropertyByName("authorId").getOrdinalPosition()).isEqualTo(3); + assertThat(bookVertexType.getPropertyByName("authorId").isFromPrimaryKey()).isFalse(); + + assertThat(articleVertexType.getProperties().size()).isEqualTo(4); + + assertThat(articleVertexType.getPropertyByName("id")).isNotNull(); + assertThat(articleVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(articleVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(articleVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(articleVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(articleVertexType.getPropertyByName("title")).isNotNull(); + assertThat(articleVertexType.getPropertyByName("title").getName()).isEqualTo("title"); + assertThat(articleVertexType.getPropertyByName("title").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(articleVertexType.getPropertyByName("title").getOrdinalPosition()).isEqualTo(2); + assertThat(articleVertexType.getPropertyByName("title").isFromPrimaryKey()).isFalse(); + + assertThat(articleVertexType.getPropertyByName("date")).isNotNull(); + assertThat(articleVertexType.getPropertyByName("date").getName()).isEqualTo("date"); + assertThat(articleVertexType.getPropertyByName("date").getOriginalType()).isEqualTo("DATE"); + assertThat(articleVertexType.getPropertyByName("date").getOrdinalPosition()).isEqualTo(3); + assertThat(articleVertexType.getPropertyByName("date").isFromPrimaryKey()).isFalse(); + + assertThat(articleVertexType.getPropertyByName("authorId")).isNotNull(); + assertThat(articleVertexType.getPropertyByName("authorId").getName()).isEqualTo("authorId"); + assertThat(articleVertexType.getPropertyByName("authorId").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(articleVertexType.getPropertyByName("authorId").getOrdinalPosition()).isEqualTo(4); + assertThat(articleVertexType.getPropertyByName("authorId").isFromPrimaryKey()).isFalse(); + + // edges check + assertThat(mapper.getGraphModel().getEdgesType().size()).isEqualTo(1); + assertThat(authorEdgeType).isNotNull(); + + assertThat(authorEdgeType.getName()).isEqualTo("HasAuthor"); + assertThat(authorEdgeType.getProperties().size()).isEqualTo(0); + assertThat(authorEdgeType.getInVertexType().getName()).isEqualTo("Author"); + assertThat(authorEdgeType.getNumberRelationshipsRepresented()).isEqualTo(2); + + /* + * Rules check + */ + + // Classes Mapping + + assertThat(mapper.getVertexType2EVClassMappers().size()).isEqualTo(3); + assertThat(mapper.getEntity2EVClassMappers().size()).isEqualTo(3); + + Entity bookEntity = mapper.getDataBaseSchema().getEntityByName("BOOK"); + assertThat(mapper.getEVClassMappersByVertex(bookVertexType).size()).isEqualTo(1); + EVClassMapper bookClassMapper = mapper.getEVClassMappersByVertex(bookVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(bookEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(bookEntity).get(0)).isEqualTo(bookClassMapper); + assertThat(bookEntity).isEqualTo(bookClassMapper.getEntity()); + assertThat(bookVertexType).isEqualTo(bookClassMapper.getVertexType()); + + assertThat(bookClassMapper.getAttribute2property().size()).isEqualTo(3); + assertThat(bookClassMapper.getProperty2attribute().size()).isEqualTo(3); + assertThat(bookClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(bookClassMapper.getAttribute2property().get("TITLE")).isEqualTo("title"); + assertThat(bookClassMapper.getAttribute2property().get("AUTHOR_ID")).isEqualTo("authorId"); + assertThat(bookClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(bookClassMapper.getProperty2attribute().get("title")).isEqualTo("TITLE"); + assertThat(bookClassMapper.getProperty2attribute().get("authorId")).isEqualTo("AUTHOR_ID"); + + Entity authorEntity = mapper.getDataBaseSchema().getEntityByName("AUTHOR"); + assertThat(mapper.getEVClassMappersByVertex(authorVertexType).size()).isEqualTo(1); + EVClassMapper authorClassMapper = mapper.getEVClassMappersByVertex(authorVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(authorEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(authorEntity).get(0)) + .isEqualTo(authorClassMapper); + assertThat(authorEntity).isEqualTo(authorClassMapper.getEntity()); + assertThat(authorVertexType).isEqualTo(authorClassMapper.getVertexType()); + + assertThat(authorClassMapper.getAttribute2property().size()).isEqualTo(3); + assertThat(authorClassMapper.getProperty2attribute().size()).isEqualTo(3); + assertThat(authorClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(authorClassMapper.getAttribute2property().get("NAME")).isEqualTo("name"); + assertThat(authorClassMapper.getAttribute2property().get("AGE")).isEqualTo("age"); + assertThat(authorClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(authorClassMapper.getProperty2attribute().get("name")).isEqualTo("NAME"); + assertThat(authorClassMapper.getProperty2attribute().get("age")).isEqualTo("AGE"); + + Entity articleEntity = mapper.getDataBaseSchema().getEntityByName("ARTICLE"); + assertThat(mapper.getEVClassMappersByVertex(articleVertexType).size()).isEqualTo(1); + EVClassMapper articleClassMapper = mapper.getEVClassMappersByVertex(articleVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(articleEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(articleEntity).get(0)) + .isEqualTo(articleClassMapper); + assertThat(articleEntity).isEqualTo(articleClassMapper.getEntity()); + assertThat(articleVertexType).isEqualTo(articleClassMapper.getVertexType()); + + assertThat(articleClassMapper.getAttribute2property().size()).isEqualTo(4); + assertThat(articleClassMapper.getProperty2attribute().size()).isEqualTo(4); + assertThat(articleClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(articleClassMapper.getAttribute2property().get("TITLE")).isEqualTo("title"); + assertThat(articleClassMapper.getAttribute2property().get("DATE")).isEqualTo("date"); + assertThat(articleClassMapper.getAttribute2property().get("AUTHOR_ID")).isEqualTo("authorId"); + assertThat(articleClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(articleClassMapper.getProperty2attribute().get("title")).isEqualTo("TITLE"); + assertThat(articleClassMapper.getProperty2attribute().get("date")).isEqualTo("DATE"); + assertThat(articleClassMapper.getProperty2attribute().get("authorId")).isEqualTo("AUTHOR_ID"); + + // Relationships-Edges Mapping + + Iterator it = bookEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship hasAuthorRelationship1 = it.next(); + assertThat(it.hasNext()).isFalse(); + it = articleEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship hasAuthorRelationship2 = it.next(); + assertThat(it.hasNext()).isFalse(); + + assertThat(mapper.getRelationship2edgeType().size()).isEqualTo(2); + assertThat(mapper.getRelationship2edgeType().get(hasAuthorRelationship1)) + .isEqualTo(authorEdgeType); + assertThat(mapper.getRelationship2edgeType().get(hasAuthorRelationship2)) + .isEqualTo(authorEdgeType); + + assertThat(mapper.getEdgeType2relationships().size()).isEqualTo(1); + assertThat(mapper.getEdgeType2relationships().get(authorEdgeType).size()).isEqualTo(2); + assertThat( + mapper + .getEdgeType2relationships() + .get(authorEdgeType) + .contains(hasAuthorRelationship1)) + .isTrue(); + assertThat( + mapper + .getEdgeType2relationships() + .get(authorEdgeType) + .contains(hasAuthorRelationship2)) + .isTrue(); + + // JoinVertexes-AggregatorEdges Mapping + + assertThat(mapper.getJoinVertex2aggregatorEdges().size()).isEqualTo(0); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } finally { + try { + // Dropping Source DB Schema and OrientGraph + String dbDropping = "drop schema public cascade"; + st.execute(dbDropping); + connection.close(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } } - - @Test - /* - * Two tables Foreign and Parent with a composite primary key imported from the parent table. - */ - - public void buildGraphModelFromThreeTablesWithOneCompositePK() { - Connection connection = null; - Statement st = null; - - try { - Class.forName(this.driver); - connection = DriverManager.getConnection(this.jurl, this.username, this.password); - - String authorTableBuilding = - "create memory table AUTHOR (NAME varchar(256) not null," + " SURNAME varchar(256) not null, AGE integer, primary key (NAME,SURNAME))"; - st = connection.createStatement(); - st.execute(authorTableBuilding); - - String bookTableBuilding = - "create memory table BOOK (ID varchar(256) not null, TITLE varchar(256)," + - " AUTHOR_NAME varchar(256) not null, AUTHOR_SURNAME varchar(256) not null, primary key (ID)," + - " foreign key (AUTHOR_NAME,AUTHOR_SURNAME) references AUTHOR(NAME,SURNAME))"; - st.execute(bookTableBuilding); - - this.mapper = new ER2GraphMapper(dataSource, null, null, dbQueryEngine, dataTypeHandler, executionStrategy, nameResolver, statistics); - mapper.buildSourceDatabaseSchema(); - mapper.buildGraphModel(new JavaConventionNameResolver()); - - /* - * Testing context information - */ - - assertEquals(2, statistics.totalNumberOfModelVertices); - assertEquals(2, statistics.builtModelVertexTypes); - assertEquals(1, statistics.totalNumberOfModelEdges); - assertEquals(1, statistics.builtModelEdgeTypes); - - /* - * Testing built graph model - */ - VertexType authorVertexType = mapper.getGraphModel().getVertexTypeByName("Author"); - VertexType bookVertexType = mapper.getGraphModel().getVertexTypeByName("Book"); - EdgeType authorEdgeType = mapper.getGraphModel().getEdgeTypeByName("Book2Author"); - - // vertices check - assertEquals(2, mapper.getGraphModel().getVerticesType().size()); - assertNotNull(authorVertexType); - assertNotNull(bookVertexType); - - // properties check - assertEquals(3, authorVertexType.getProperties().size()); - - assertNotNull(authorVertexType.getPropertyByName("name")); - assertEquals("name", authorVertexType.getPropertyByName("name").getName()); - assertEquals("VARCHAR", authorVertexType.getPropertyByName("name").getOriginalType()); - assertEquals(1, authorVertexType.getPropertyByName("name").getOrdinalPosition()); - assertEquals(true, authorVertexType.getPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(authorVertexType.getPropertyByName("surname")); - assertEquals("surname", authorVertexType.getPropertyByName("surname").getName()); - assertEquals("VARCHAR", authorVertexType.getPropertyByName("surname").getOriginalType()); - assertEquals(2, authorVertexType.getPropertyByName("surname").getOrdinalPosition()); - assertEquals(true, authorVertexType.getPropertyByName("surname").isFromPrimaryKey()); - - assertNotNull(authorVertexType.getPropertyByName("age")); - assertEquals("age", authorVertexType.getPropertyByName("age").getName()); - assertEquals("INTEGER", authorVertexType.getPropertyByName("age").getOriginalType()); - assertEquals(3, authorVertexType.getPropertyByName("age").getOrdinalPosition()); - assertEquals(false, authorVertexType.getPropertyByName("age").isFromPrimaryKey()); - - assertEquals(4, bookVertexType.getProperties().size()); - - assertNotNull(bookVertexType.getPropertyByName("id")); - assertEquals("id", bookVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", bookVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, bookVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, bookVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(bookVertexType.getPropertyByName("title")); - assertEquals("title", bookVertexType.getPropertyByName("title").getName()); - assertEquals("VARCHAR", bookVertexType.getPropertyByName("title").getOriginalType()); - assertEquals(2, bookVertexType.getPropertyByName("title").getOrdinalPosition()); - assertEquals(false, bookVertexType.getPropertyByName("title").isFromPrimaryKey()); - - assertNotNull(bookVertexType.getPropertyByName("authorName")); - assertEquals("authorName", bookVertexType.getPropertyByName("authorName").getName()); - assertEquals("VARCHAR", bookVertexType.getPropertyByName("authorName").getOriginalType()); - assertEquals(3, bookVertexType.getPropertyByName("authorName").getOrdinalPosition()); - assertEquals(false, bookVertexType.getPropertyByName("authorName").isFromPrimaryKey()); - - assertNotNull(bookVertexType.getPropertyByName("authorSurname")); - assertEquals("authorSurname", bookVertexType.getPropertyByName("authorSurname").getName()); - assertEquals("VARCHAR", bookVertexType.getPropertyByName("authorSurname").getOriginalType()); - assertEquals(4, bookVertexType.getPropertyByName("authorSurname").getOrdinalPosition()); - assertEquals(false, bookVertexType.getPropertyByName("authorSurname").isFromPrimaryKey()); - - // edges check - assertEquals(1, mapper.getGraphModel().getEdgesType().size()); - assertNotNull(authorEdgeType); - - assertEquals("Book2Author", authorEdgeType.getName()); - assertEquals(0, authorEdgeType.getProperties().size()); - assertEquals("Author", authorEdgeType.getInVertexType().getName()); - assertEquals(1, authorEdgeType.getNumberRelationshipsRepresented()); - - /* - * Rules check - */ - - // Classes Mapping - - assertEquals(2, mapper.getVertexType2EVClassMappers().size()); - assertEquals(2, mapper.getEntity2EVClassMappers().size()); - - Entity bookEntity = mapper.getDataBaseSchema().getEntityByName("BOOK"); - assertEquals(1, mapper.getEVClassMappersByVertex(bookVertexType).size()); - EVClassMapper bookClassMapper = mapper.getEVClassMappersByVertex(bookVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(bookEntity).size()); - assertEquals(bookClassMapper, mapper.getEVClassMappersByEntity(bookEntity).get(0)); - assertEquals(bookClassMapper.getEntity(), bookEntity); - assertEquals(bookClassMapper.getVertexType(), bookVertexType); - - assertEquals(4, bookClassMapper.getAttribute2property().size()); - assertEquals(4, bookClassMapper.getProperty2attribute().size()); - assertEquals("id", bookClassMapper.getAttribute2property().get("ID")); - assertEquals("title", bookClassMapper.getAttribute2property().get("TITLE")); - assertEquals("authorName", bookClassMapper.getAttribute2property().get("AUTHOR_NAME")); - assertEquals("authorSurname", bookClassMapper.getAttribute2property().get("AUTHOR_SURNAME")); - assertEquals("ID", bookClassMapper.getProperty2attribute().get("id")); - assertEquals("TITLE", bookClassMapper.getProperty2attribute().get("title")); - assertEquals("AUTHOR_NAME", bookClassMapper.getProperty2attribute().get("authorName")); - assertEquals("AUTHOR_SURNAME", bookClassMapper.getProperty2attribute().get("authorSurname")); - - Entity authorEntity = mapper.getDataBaseSchema().getEntityByName("AUTHOR"); - assertEquals(1, mapper.getEVClassMappersByVertex(authorVertexType).size()); - EVClassMapper authorClassMapper = mapper.getEVClassMappersByVertex(authorVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(authorEntity).size()); - assertEquals(authorClassMapper, mapper.getEVClassMappersByEntity(authorEntity).get(0)); - assertEquals(authorClassMapper.getEntity(), authorEntity); - assertEquals(authorClassMapper.getVertexType(), authorVertexType); - - assertEquals(3, authorClassMapper.getAttribute2property().size()); - assertEquals(3, authorClassMapper.getProperty2attribute().size()); - assertEquals("name", authorClassMapper.getAttribute2property().get("NAME")); - assertEquals("surname", authorClassMapper.getAttribute2property().get("SURNAME")); - assertEquals("age", authorClassMapper.getAttribute2property().get("AGE")); - assertEquals("NAME", authorClassMapper.getProperty2attribute().get("name")); - assertEquals("SURNAME", authorClassMapper.getProperty2attribute().get("surname")); - assertEquals("AGE", authorClassMapper.getProperty2attribute().get("age")); - - // Relationships-Edges Mapping - - Iterator it = bookEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship hasAuthorRelationship = it.next(); - assertFalse(it.hasNext()); - - assertEquals(1, mapper.getRelationship2edgeType().size()); - assertEquals(authorEdgeType, mapper.getRelationship2edgeType().get(hasAuthorRelationship)); - - assertEquals(1, mapper.getEdgeType2relationships().size()); - assertEquals(1, mapper.getEdgeType2relationships().get(authorEdgeType).size()); - assertTrue(mapper.getEdgeType2relationships().get(authorEdgeType).contains(hasAuthorRelationship)); - - // JoinVertexes-AggregatorEdges Mapping - - assertEquals(0, mapper.getJoinVertex2aggregatorEdges().size()); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } finally { - try { - // Dropping Source DB Schema and OrientGraph - String dbDropping = "drop schema public cascade"; - st.execute(dbDropping); - connection.close(); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } - } + } + + /* + * Two tables Foreign and Parent with a composite primary key imported from the parent table. + */ + + @Test + void buildGraphModelFromThreeTablesWithOneCompositePK() { + Connection connection = null; + Statement st = null; + + try { + Class.forName(this.driver); + connection = DriverManager.getConnection(this.jurl, this.username, this.password); + + String authorTableBuilding = + "create memory table AUTHOR (NAME varchar(256) not null," + + " SURNAME varchar(256) not null, AGE integer, primary key (NAME,SURNAME))"; + st = connection.createStatement(); + st.execute(authorTableBuilding); + + String bookTableBuilding = + "create memory table BOOK (ID varchar(256) not null, TITLE varchar(256), AUTHOR_NAME" + + " varchar(256) not null, AUTHOR_SURNAME varchar(256) not null, primary key (ID)," + + " foreign key (AUTHOR_NAME,AUTHOR_SURNAME) references AUTHOR(NAME,SURNAME))"; + st.execute(bookTableBuilding); + + this.mapper = + new ER2GraphMapper( + dataSource, + null, + null, + dbQueryEngine, + dataTypeHandler, + executionStrategy, + nameResolver, + statistics); + mapper.buildSourceDatabaseSchema(); + mapper.buildGraphModel(new JavaConventionNameResolver()); + + /* + * Testing context information + */ + + assertThat(statistics.totalNumberOfModelVertices).isEqualTo(2); + assertThat(statistics.builtModelVertexTypes).isEqualTo(2); + assertThat(statistics.totalNumberOfModelEdges).isEqualTo(1); + assertThat(statistics.builtModelEdgeTypes).isEqualTo(1); + + /* + * Testing built graph model + */ + VertexType authorVertexType = mapper.getGraphModel().getVertexTypeByName("Author"); + VertexType bookVertexType = mapper.getGraphModel().getVertexTypeByName("Book"); + EdgeType authorEdgeType = mapper.getGraphModel().getEdgeTypeByName("Book2Author"); + + // vertices check + assertThat(mapper.getGraphModel().getVerticesType().size()).isEqualTo(2); + assertThat(authorVertexType).isNotNull(); + assertThat(bookVertexType).isNotNull(); + + // properties check + assertThat(authorVertexType.getProperties().size()).isEqualTo(3); + + assertThat(authorVertexType.getPropertyByName("name")).isNotNull(); + assertThat(authorVertexType.getPropertyByName("name").getName()).isEqualTo("name"); + assertThat(authorVertexType.getPropertyByName("name").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(authorVertexType.getPropertyByName("name").getOrdinalPosition()).isEqualTo(1); + assertThat(authorVertexType.getPropertyByName("name").isFromPrimaryKey()).isTrue(); + + assertThat(authorVertexType.getPropertyByName("surname")).isNotNull(); + assertThat(authorVertexType.getPropertyByName("surname").getName()).isEqualTo("surname"); + assertThat(authorVertexType.getPropertyByName("surname").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(authorVertexType.getPropertyByName("surname").getOrdinalPosition()).isEqualTo(2); + assertThat(authorVertexType.getPropertyByName("surname").isFromPrimaryKey()).isTrue(); + + assertThat(authorVertexType.getPropertyByName("age")).isNotNull(); + assertThat(authorVertexType.getPropertyByName("age").getName()).isEqualTo("age"); + assertThat(authorVertexType.getPropertyByName("age").getOriginalType()).isEqualTo("INTEGER"); + assertThat(authorVertexType.getPropertyByName("age").getOrdinalPosition()).isEqualTo(3); + assertThat(authorVertexType.getPropertyByName("age").isFromPrimaryKey()).isFalse(); + + assertThat(bookVertexType.getProperties().size()).isEqualTo(4); + + assertThat(bookVertexType.getPropertyByName("id")).isNotNull(); + assertThat(bookVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(bookVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(bookVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(bookVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(bookVertexType.getPropertyByName("title")).isNotNull(); + assertThat(bookVertexType.getPropertyByName("title").getName()).isEqualTo("title"); + assertThat(bookVertexType.getPropertyByName("title").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(bookVertexType.getPropertyByName("title").getOrdinalPosition()).isEqualTo(2); + assertThat(bookVertexType.getPropertyByName("title").isFromPrimaryKey()).isFalse(); + + assertThat(bookVertexType.getPropertyByName("authorName")).isNotNull(); + assertThat(bookVertexType.getPropertyByName("authorName").getName()).isEqualTo("authorName"); + assertThat(bookVertexType.getPropertyByName("authorName").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(bookVertexType.getPropertyByName("authorName").getOrdinalPosition()).isEqualTo(3); + assertThat(bookVertexType.getPropertyByName("authorName").isFromPrimaryKey()).isFalse(); + + assertThat(bookVertexType.getPropertyByName("authorSurname")).isNotNull(); + assertThat(bookVertexType.getPropertyByName("authorSurname").getName()) + .isEqualTo("authorSurname"); + assertThat(bookVertexType.getPropertyByName("authorSurname").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(bookVertexType.getPropertyByName("authorSurname").getOrdinalPosition()) + .isEqualTo(4); + assertThat(bookVertexType.getPropertyByName("authorSurname").isFromPrimaryKey()).isFalse(); + + // edges check + assertThat(mapper.getGraphModel().getEdgesType().size()).isEqualTo(1); + assertThat(authorEdgeType).isNotNull(); + + assertThat(authorEdgeType.getName()).isEqualTo("Book2Author"); + assertThat(authorEdgeType.getProperties().size()).isEqualTo(0); + assertThat(authorEdgeType.getInVertexType().getName()).isEqualTo("Author"); + assertThat(authorEdgeType.getNumberRelationshipsRepresented()).isEqualTo(1); + + /* + * Rules check + */ + + // Classes Mapping + + assertThat(mapper.getVertexType2EVClassMappers().size()).isEqualTo(2); + assertThat(mapper.getEntity2EVClassMappers().size()).isEqualTo(2); + + Entity bookEntity = mapper.getDataBaseSchema().getEntityByName("BOOK"); + assertThat(mapper.getEVClassMappersByVertex(bookVertexType).size()).isEqualTo(1); + EVClassMapper bookClassMapper = mapper.getEVClassMappersByVertex(bookVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(bookEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(bookEntity).get(0)).isEqualTo(bookClassMapper); + assertThat(bookEntity).isEqualTo(bookClassMapper.getEntity()); + assertThat(bookVertexType).isEqualTo(bookClassMapper.getVertexType()); + + assertThat(bookClassMapper.getAttribute2property().size()).isEqualTo(4); + assertThat(bookClassMapper.getProperty2attribute().size()).isEqualTo(4); + assertThat(bookClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(bookClassMapper.getAttribute2property().get("TITLE")).isEqualTo("title"); + assertThat(bookClassMapper.getAttribute2property().get("AUTHOR_NAME")) + .isEqualTo("authorName"); + assertThat(bookClassMapper.getAttribute2property().get("AUTHOR_SURNAME")) + .isEqualTo("authorSurname"); + assertThat(bookClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(bookClassMapper.getProperty2attribute().get("title")).isEqualTo("TITLE"); + assertThat(bookClassMapper.getProperty2attribute().get("authorName")) + .isEqualTo("AUTHOR_NAME"); + assertThat(bookClassMapper.getProperty2attribute().get("authorSurname")) + .isEqualTo("AUTHOR_SURNAME"); + + Entity authorEntity = mapper.getDataBaseSchema().getEntityByName("AUTHOR"); + assertThat(mapper.getEVClassMappersByVertex(authorVertexType).size()).isEqualTo(1); + EVClassMapper authorClassMapper = mapper.getEVClassMappersByVertex(authorVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(authorEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(authorEntity).get(0)) + .isEqualTo(authorClassMapper); + assertThat(authorEntity).isEqualTo(authorClassMapper.getEntity()); + assertThat(authorVertexType).isEqualTo(authorClassMapper.getVertexType()); + + assertThat(authorClassMapper.getAttribute2property().size()).isEqualTo(3); + assertThat(authorClassMapper.getProperty2attribute().size()).isEqualTo(3); + assertThat(authorClassMapper.getAttribute2property().get("NAME")).isEqualTo("name"); + assertThat(authorClassMapper.getAttribute2property().get("SURNAME")).isEqualTo("surname"); + assertThat(authorClassMapper.getAttribute2property().get("AGE")).isEqualTo("age"); + assertThat(authorClassMapper.getProperty2attribute().get("name")).isEqualTo("NAME"); + assertThat(authorClassMapper.getProperty2attribute().get("surname")).isEqualTo("SURNAME"); + assertThat(authorClassMapper.getProperty2attribute().get("age")).isEqualTo("AGE"); + + // Relationships-Edges Mapping + + Iterator it = bookEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship hasAuthorRelationship = it.next(); + assertThat(it.hasNext()).isFalse(); + + assertThat(mapper.getRelationship2edgeType().size()).isEqualTo(1); + assertThat(mapper.getRelationship2edgeType().get(hasAuthorRelationship)) + .isEqualTo(authorEdgeType); + + assertThat(mapper.getEdgeType2relationships().size()).isEqualTo(1); + assertThat(mapper.getEdgeType2relationships().get(authorEdgeType).size()).isEqualTo(1); + assertThat( + mapper + .getEdgeType2relationships() + .get(authorEdgeType) + .contains(hasAuthorRelationship)) + .isTrue(); + + // JoinVertexes-AggregatorEdges Mapping + + assertThat(mapper.getJoinVertex2aggregatorEdges().size()).isEqualTo(0); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } finally { + try { + // Dropping Source DB Schema and OrientGraph + String dbDropping = "drop schema public cascade"; + st.execute(dbDropping); + connection.close(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } } - - @Test - /* - * Three tables: 2 Parent and 1 join table which imports two different simple primary key. - */ - - public void buildGraphModelFromJoinTableAnd2ParentTables() { - Connection connection = null; - Statement st = null; - - try { - Class.forName(this.driver); - connection = DriverManager.getConnection(this.jurl, this.username, this.password); - - String filmTableBuilding = "create memory table FILM (ID varchar(256) not null," + " TITLE varchar(256) not null, YEAR date, primary key (ID))"; - st = connection.createStatement(); - st.execute(filmTableBuilding); - - String actorTableBuilding = - "create memory table ACTOR (ID varchar(256) not null," + " NAME varchar(256) not null, SURNAME varchar(256) not null, primary key (ID))"; - st.execute(actorTableBuilding); - - String film2actorTableBuilding = - "create memory table FILM_ACTOR (FILM_ID varchar(256) not null," + - " ACTOR_ID varchar(256) not null, primary key (FILM_ID,ACTOR_ID)," + - " foreign key (FILM_ID) references FILM(ID)," + - " foreign key (ACTOR_ID) references ACTOR(ID))"; - st.execute(film2actorTableBuilding); - - this.mapper = new ER2GraphMapper(dataSource, null, null, dbQueryEngine, dataTypeHandler, executionStrategy, nameResolver, statistics); - mapper.buildSourceDatabaseSchema(); - mapper.buildGraphModel(new JavaConventionNameResolver()); - - /* - * Testing context information - */ - - assertEquals(3, statistics.totalNumberOfModelVertices); - assertEquals(3, statistics.builtModelVertexTypes); - assertEquals(2, statistics.totalNumberOfModelEdges); - assertEquals(2, statistics.builtModelEdgeTypes); - - /* - * Testing built graph model - */ - VertexType actorVertexType = mapper.getGraphModel().getVertexTypeByName("Actor"); - VertexType filmVertexType = mapper.getGraphModel().getVertexTypeByName("Film"); - VertexType film2actorVertexType = mapper.getGraphModel().getVertexTypeByName("FilmActor"); - EdgeType actorEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasActor"); - EdgeType filmEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasFilm"); - - // vertices check - assertEquals(3, mapper.getGraphModel().getVerticesType().size()); - assertNotNull(actorVertexType); - assertNotNull(filmVertexType); - assertNotNull(film2actorVertexType); - - // properties check - assertEquals(3, actorVertexType.getProperties().size()); - - assertNotNull(actorVertexType.getPropertyByName("id")); - assertEquals("id", actorVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", actorVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, actorVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, actorVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(actorVertexType.getPropertyByName("name")); - assertEquals("name", actorVertexType.getPropertyByName("name").getName()); - assertEquals("VARCHAR", actorVertexType.getPropertyByName("name").getOriginalType()); - assertEquals(2, actorVertexType.getPropertyByName("name").getOrdinalPosition()); - assertEquals(false, actorVertexType.getPropertyByName("name").isFromPrimaryKey()); - - assertNotNull(actorVertexType.getPropertyByName("surname")); - assertEquals("surname", actorVertexType.getPropertyByName("surname").getName()); - assertEquals("VARCHAR", actorVertexType.getPropertyByName("surname").getOriginalType()); - assertEquals(3, actorVertexType.getPropertyByName("surname").getOrdinalPosition()); - assertEquals(false, actorVertexType.getPropertyByName("surname").isFromPrimaryKey()); - - assertEquals(3, filmVertexType.getProperties().size()); - - assertNotNull(filmVertexType.getPropertyByName("id")); - assertEquals("id", filmVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", filmVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, filmVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, filmVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(filmVertexType.getPropertyByName("title")); - assertEquals("title", filmVertexType.getPropertyByName("title").getName()); - assertEquals("VARCHAR", filmVertexType.getPropertyByName("title").getOriginalType()); - assertEquals(2, filmVertexType.getPropertyByName("title").getOrdinalPosition()); - assertEquals(false, filmVertexType.getPropertyByName("title").isFromPrimaryKey()); - - assertNotNull(filmVertexType.getPropertyByName("year")); - assertEquals("year", filmVertexType.getPropertyByName("year").getName()); - assertEquals("DATE", filmVertexType.getPropertyByName("year").getOriginalType()); - assertEquals(3, filmVertexType.getPropertyByName("year").getOrdinalPosition()); - assertEquals(false, filmVertexType.getPropertyByName("year").isFromPrimaryKey()); - - assertEquals(2, film2actorVertexType.getProperties().size()); - - assertNotNull(film2actorVertexType.getPropertyByName("filmId")); - assertEquals("filmId", film2actorVertexType.getPropertyByName("filmId").getName()); - assertEquals("VARCHAR", film2actorVertexType.getPropertyByName("filmId").getOriginalType()); - assertEquals(1, film2actorVertexType.getPropertyByName("filmId").getOrdinalPosition()); - assertEquals(true, film2actorVertexType.getPropertyByName("filmId").isFromPrimaryKey()); - - assertNotNull(film2actorVertexType.getPropertyByName("actorId")); - assertEquals("actorId", film2actorVertexType.getPropertyByName("actorId").getName()); - assertEquals("VARCHAR", film2actorVertexType.getPropertyByName("actorId").getOriginalType()); - assertEquals(2, film2actorVertexType.getPropertyByName("actorId").getOrdinalPosition()); - assertEquals(true, film2actorVertexType.getPropertyByName("actorId").isFromPrimaryKey()); - - // edges check - assertEquals(2, mapper.getGraphModel().getEdgesType().size()); - assertNotNull(filmEdgeType); - assertNotNull(actorEdgeType); - - assertEquals("HasFilm", filmEdgeType.getName()); - assertEquals(0, filmEdgeType.getProperties().size()); - assertEquals("Film", filmEdgeType.getInVertexType().getName()); - assertEquals(1, filmEdgeType.getNumberRelationshipsRepresented()); - - assertEquals("HasActor", actorEdgeType.getName()); - assertEquals(0, actorEdgeType.getProperties().size()); - assertEquals("Actor", actorEdgeType.getInVertexType().getName()); - assertEquals(1, actorEdgeType.getNumberRelationshipsRepresented()); - - /* - * Rules check - */ - - // Classes Mapping - - assertEquals(3, mapper.getVertexType2EVClassMappers().size()); - assertEquals(3, mapper.getEntity2EVClassMappers().size()); - - Entity filmEntity = mapper.getDataBaseSchema().getEntityByName("FILM"); - assertEquals(1, mapper.getEVClassMappersByVertex(filmVertexType).size()); - EVClassMapper filmClassMapper = mapper.getEVClassMappersByVertex(filmVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(filmEntity).size()); - assertEquals(filmClassMapper, mapper.getEVClassMappersByEntity(filmEntity).get(0)); - assertEquals(filmClassMapper.getEntity(), filmEntity); - assertEquals(filmClassMapper.getVertexType(), filmVertexType); - - assertEquals(3, filmClassMapper.getAttribute2property().size()); - assertEquals(3, filmClassMapper.getProperty2attribute().size()); - assertEquals("id", filmClassMapper.getAttribute2property().get("ID")); - assertEquals("title", filmClassMapper.getAttribute2property().get("TITLE")); - assertEquals("year", filmClassMapper.getAttribute2property().get("YEAR")); - assertEquals("ID", filmClassMapper.getProperty2attribute().get("id")); - assertEquals("TITLE", filmClassMapper.getProperty2attribute().get("title")); - assertEquals("YEAR", filmClassMapper.getProperty2attribute().get("year")); - - Entity actorEntity = mapper.getDataBaseSchema().getEntityByName("ACTOR"); - assertEquals(1, mapper.getEVClassMappersByVertex(actorVertexType).size()); - EVClassMapper actorClassMapper = mapper.getEVClassMappersByVertex(actorVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(actorEntity).size()); - assertEquals(actorClassMapper, mapper.getEVClassMappersByEntity(actorEntity).get(0)); - assertEquals(actorClassMapper.getEntity(), actorEntity); - assertEquals(actorClassMapper.getVertexType(), actorVertexType); - - assertEquals(3, actorClassMapper.getAttribute2property().size()); - assertEquals(3, actorClassMapper.getProperty2attribute().size()); - assertEquals("id", actorClassMapper.getAttribute2property().get("ID")); - assertEquals("name", actorClassMapper.getAttribute2property().get("NAME")); - assertEquals("surname", actorClassMapper.getAttribute2property().get("SURNAME")); - assertEquals("ID", actorClassMapper.getProperty2attribute().get("id")); - assertEquals("NAME", actorClassMapper.getProperty2attribute().get("name")); - assertEquals("SURNAME", actorClassMapper.getProperty2attribute().get("surname")); - - Entity filmActorEntity = mapper.getDataBaseSchema().getEntityByName("FILM_ACTOR"); - assertEquals(1, mapper.getEVClassMappersByVertex(film2actorVertexType).size()); - EVClassMapper filmActorClassMapper = mapper.getEVClassMappersByVertex(film2actorVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(filmActorEntity).size()); - assertEquals(filmActorClassMapper, mapper.getEVClassMappersByEntity(filmActorEntity).get(0)); - assertEquals(filmActorClassMapper.getEntity(), filmActorEntity); - assertEquals(filmActorClassMapper.getVertexType(), film2actorVertexType); - - assertEquals(2, filmActorClassMapper.getAttribute2property().size()); - assertEquals(2, filmActorClassMapper.getProperty2attribute().size()); - assertEquals("filmId", filmActorClassMapper.getAttribute2property().get("FILM_ID")); - assertEquals("actorId", filmActorClassMapper.getAttribute2property().get("ACTOR_ID")); - assertEquals("FILM_ID", filmActorClassMapper.getProperty2attribute().get("filmId")); - assertEquals("ACTOR_ID", filmActorClassMapper.getProperty2attribute().get("actorId")); - - // Relationships-Edges Mapping - - Iterator it = filmActorEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship hasActorRelationship = it.next(); - CanonicalRelationship hasFilmRelationship = it.next(); - assertFalse(it.hasNext()); - - assertEquals(2, mapper.getRelationship2edgeType().size()); - assertEquals(filmEdgeType, mapper.getRelationship2edgeType().get(hasFilmRelationship)); - assertEquals(actorEdgeType, mapper.getRelationship2edgeType().get(hasActorRelationship)); - - assertEquals(2, mapper.getEdgeType2relationships().size()); - assertEquals(1, mapper.getEdgeType2relationships().get(filmEdgeType).size()); - assertTrue(mapper.getEdgeType2relationships().get(filmEdgeType).contains(hasFilmRelationship)); - assertEquals(1, mapper.getEdgeType2relationships().get(actorEdgeType).size()); - assertTrue(mapper.getEdgeType2relationships().get(actorEdgeType).contains(hasActorRelationship)); - - // JoinVertexes-AggregatorEdges Mapping - - assertEquals(0, mapper.getJoinVertex2aggregatorEdges().size()); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } finally { - try { - // Dropping Source DB Schema and OrientGraph - String dbDropping = "drop schema public cascade"; - st.execute(dbDropping); - connection.close(); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } - } + } + + /* + * Three tables: 2 Parent and 1 join table which imports two different simple primary key. + */ + + @Test + void buildGraphModelFromJoinTableAnd2ParentTables() { + Connection connection = null; + Statement st = null; + + try { + Class.forName(this.driver); + connection = DriverManager.getConnection(this.jurl, this.username, this.password); + + String filmTableBuilding = + "create memory table FILM (ID varchar(256) not null," + + " TITLE varchar(256) not null, YEAR date, primary key (ID))"; + st = connection.createStatement(); + st.execute(filmTableBuilding); + + String actorTableBuilding = + "create memory table ACTOR (ID varchar(256) not null," + + " NAME varchar(256) not null, SURNAME varchar(256) not null, primary key (ID))"; + st.execute(actorTableBuilding); + + String film2actorTableBuilding = + "create memory table FILM_ACTOR (FILM_ID varchar(256) not null," + + " ACTOR_ID varchar(256) not null, primary key (FILM_ID,ACTOR_ID)," + + " foreign key (FILM_ID) references FILM(ID)," + + " foreign key (ACTOR_ID) references ACTOR(ID))"; + st.execute(film2actorTableBuilding); + + this.mapper = + new ER2GraphMapper( + dataSource, + null, + null, + dbQueryEngine, + dataTypeHandler, + executionStrategy, + nameResolver, + statistics); + mapper.buildSourceDatabaseSchema(); + mapper.buildGraphModel(new JavaConventionNameResolver()); + + /* + * Testing context information + */ + + assertThat(statistics.totalNumberOfModelVertices).isEqualTo(3); + assertThat(statistics.builtModelVertexTypes).isEqualTo(3); + assertThat(statistics.totalNumberOfModelEdges).isEqualTo(2); + assertThat(statistics.builtModelEdgeTypes).isEqualTo(2); + + /* + * Testing built graph model + */ + VertexType actorVertexType = mapper.getGraphModel().getVertexTypeByName("Actor"); + VertexType filmVertexType = mapper.getGraphModel().getVertexTypeByName("Film"); + VertexType film2actorVertexType = mapper.getGraphModel().getVertexTypeByName("FilmActor"); + EdgeType actorEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasActor"); + EdgeType filmEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasFilm"); + + // vertices check + assertThat(mapper.getGraphModel().getVerticesType().size()).isEqualTo(3); + assertThat(actorVertexType).isNotNull(); + assertThat(filmVertexType).isNotNull(); + assertThat(film2actorVertexType).isNotNull(); + + // properties check + assertThat(actorVertexType.getProperties().size()).isEqualTo(3); + + assertThat(actorVertexType.getPropertyByName("id")).isNotNull(); + assertThat(actorVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(actorVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(actorVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(actorVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(actorVertexType.getPropertyByName("name")).isNotNull(); + assertThat(actorVertexType.getPropertyByName("name").getName()).isEqualTo("name"); + assertThat(actorVertexType.getPropertyByName("name").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(actorVertexType.getPropertyByName("name").getOrdinalPosition()).isEqualTo(2); + assertThat(actorVertexType.getPropertyByName("name").isFromPrimaryKey()).isFalse(); + + assertThat(actorVertexType.getPropertyByName("surname")).isNotNull(); + assertThat(actorVertexType.getPropertyByName("surname").getName()).isEqualTo("surname"); + assertThat(actorVertexType.getPropertyByName("surname").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(actorVertexType.getPropertyByName("surname").getOrdinalPosition()).isEqualTo(3); + assertThat(actorVertexType.getPropertyByName("surname").isFromPrimaryKey()).isFalse(); + + assertThat(filmVertexType.getProperties().size()).isEqualTo(3); + + assertThat(filmVertexType.getPropertyByName("id")).isNotNull(); + assertThat(filmVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(filmVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(filmVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(filmVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(filmVertexType.getPropertyByName("title")).isNotNull(); + assertThat(filmVertexType.getPropertyByName("title").getName()).isEqualTo("title"); + assertThat(filmVertexType.getPropertyByName("title").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(filmVertexType.getPropertyByName("title").getOrdinalPosition()).isEqualTo(2); + assertThat(filmVertexType.getPropertyByName("title").isFromPrimaryKey()).isFalse(); + + assertThat(filmVertexType.getPropertyByName("year")).isNotNull(); + assertThat(filmVertexType.getPropertyByName("year").getName()).isEqualTo("year"); + assertThat(filmVertexType.getPropertyByName("year").getOriginalType()).isEqualTo("DATE"); + assertThat(filmVertexType.getPropertyByName("year").getOrdinalPosition()).isEqualTo(3); + assertThat(filmVertexType.getPropertyByName("year").isFromPrimaryKey()).isFalse(); + + assertThat(film2actorVertexType.getProperties().size()).isEqualTo(2); + + assertThat(film2actorVertexType.getPropertyByName("filmId")).isNotNull(); + assertThat(film2actorVertexType.getPropertyByName("filmId").getName()).isEqualTo("filmId"); + assertThat(film2actorVertexType.getPropertyByName("filmId").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(film2actorVertexType.getPropertyByName("filmId").getOrdinalPosition()) + .isEqualTo(1); + assertThat(film2actorVertexType.getPropertyByName("filmId").isFromPrimaryKey()).isTrue(); + + assertThat(film2actorVertexType.getPropertyByName("actorId")).isNotNull(); + assertThat(film2actorVertexType.getPropertyByName("actorId").getName()).isEqualTo("actorId"); + assertThat(film2actorVertexType.getPropertyByName("actorId").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(film2actorVertexType.getPropertyByName("actorId").getOrdinalPosition()) + .isEqualTo(2); + assertThat(film2actorVertexType.getPropertyByName("actorId").isFromPrimaryKey()).isTrue(); + + // edges check + assertThat(mapper.getGraphModel().getEdgesType().size()).isEqualTo(2); + assertThat(filmEdgeType).isNotNull(); + assertThat(actorEdgeType).isNotNull(); + + assertThat(filmEdgeType.getName()).isEqualTo("HasFilm"); + assertThat(filmEdgeType.getProperties().size()).isEqualTo(0); + assertThat(filmEdgeType.getInVertexType().getName()).isEqualTo("Film"); + assertThat(filmEdgeType.getNumberRelationshipsRepresented()).isEqualTo(1); + + assertThat(actorEdgeType.getName()).isEqualTo("HasActor"); + assertThat(actorEdgeType.getProperties().size()).isEqualTo(0); + assertThat(actorEdgeType.getInVertexType().getName()).isEqualTo("Actor"); + assertThat(actorEdgeType.getNumberRelationshipsRepresented()).isEqualTo(1); + + /* + * Rules check + */ + + // Classes Mapping + + assertThat(mapper.getVertexType2EVClassMappers().size()).isEqualTo(3); + assertThat(mapper.getEntity2EVClassMappers().size()).isEqualTo(3); + + Entity filmEntity = mapper.getDataBaseSchema().getEntityByName("FILM"); + assertThat(mapper.getEVClassMappersByVertex(filmVertexType).size()).isEqualTo(1); + EVClassMapper filmClassMapper = mapper.getEVClassMappersByVertex(filmVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(filmEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(filmEntity).get(0)).isEqualTo(filmClassMapper); + assertThat(filmEntity).isEqualTo(filmClassMapper.getEntity()); + assertThat(filmVertexType).isEqualTo(filmClassMapper.getVertexType()); + + assertThat(filmClassMapper.getAttribute2property().size()).isEqualTo(3); + assertThat(filmClassMapper.getProperty2attribute().size()).isEqualTo(3); + assertThat(filmClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(filmClassMapper.getAttribute2property().get("TITLE")).isEqualTo("title"); + assertThat(filmClassMapper.getAttribute2property().get("YEAR")).isEqualTo("year"); + assertThat(filmClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(filmClassMapper.getProperty2attribute().get("title")).isEqualTo("TITLE"); + assertThat(filmClassMapper.getProperty2attribute().get("year")).isEqualTo("YEAR"); + + Entity actorEntity = mapper.getDataBaseSchema().getEntityByName("ACTOR"); + assertThat(mapper.getEVClassMappersByVertex(actorVertexType).size()).isEqualTo(1); + EVClassMapper actorClassMapper = mapper.getEVClassMappersByVertex(actorVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(actorEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(actorEntity).get(0)).isEqualTo(actorClassMapper); + assertThat(actorEntity).isEqualTo(actorClassMapper.getEntity()); + assertThat(actorVertexType).isEqualTo(actorClassMapper.getVertexType()); + + assertThat(actorClassMapper.getAttribute2property().size()).isEqualTo(3); + assertThat(actorClassMapper.getProperty2attribute().size()).isEqualTo(3); + assertThat(actorClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(actorClassMapper.getAttribute2property().get("NAME")).isEqualTo("name"); + assertThat(actorClassMapper.getAttribute2property().get("SURNAME")).isEqualTo("surname"); + assertThat(actorClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(actorClassMapper.getProperty2attribute().get("name")).isEqualTo("NAME"); + assertThat(actorClassMapper.getProperty2attribute().get("surname")).isEqualTo("SURNAME"); + + Entity filmActorEntity = mapper.getDataBaseSchema().getEntityByName("FILM_ACTOR"); + assertThat(mapper.getEVClassMappersByVertex(film2actorVertexType).size()).isEqualTo(1); + EVClassMapper filmActorClassMapper = + mapper.getEVClassMappersByVertex(film2actorVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(filmActorEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(filmActorEntity).get(0)) + .isEqualTo(filmActorClassMapper); + assertThat(filmActorEntity).isEqualTo(filmActorClassMapper.getEntity()); + assertThat(film2actorVertexType).isEqualTo(filmActorClassMapper.getVertexType()); + + assertThat(filmActorClassMapper.getAttribute2property().size()).isEqualTo(2); + assertThat(filmActorClassMapper.getProperty2attribute().size()).isEqualTo(2); + assertThat(filmActorClassMapper.getAttribute2property().get("FILM_ID")).isEqualTo("filmId"); + assertThat(filmActorClassMapper.getAttribute2property().get("ACTOR_ID")).isEqualTo("actorId"); + assertThat(filmActorClassMapper.getProperty2attribute().get("filmId")).isEqualTo("FILM_ID"); + assertThat(filmActorClassMapper.getProperty2attribute().get("actorId")).isEqualTo("ACTOR_ID"); + + // Relationships-Edges Mapping + + Iterator it = + filmActorEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship hasActorRelationship = it.next(); + CanonicalRelationship hasFilmRelationship = it.next(); + assertThat(it.hasNext()).isFalse(); + + assertThat(mapper.getRelationship2edgeType().size()).isEqualTo(2); + assertThat(mapper.getRelationship2edgeType().get(hasFilmRelationship)) + .isEqualTo(filmEdgeType); + assertThat(mapper.getRelationship2edgeType().get(hasActorRelationship)) + .isEqualTo(actorEdgeType); + + assertThat(mapper.getEdgeType2relationships().size()).isEqualTo(2); + assertThat(mapper.getEdgeType2relationships().get(filmEdgeType).size()).isEqualTo(1); + assertThat(mapper.getEdgeType2relationships().get(filmEdgeType).contains(hasFilmRelationship)) + .isTrue(); + assertThat(mapper.getEdgeType2relationships().get(actorEdgeType).size()).isEqualTo(1); + assertThat( + mapper.getEdgeType2relationships().get(actorEdgeType).contains(hasActorRelationship)) + .isTrue(); + + // JoinVertexes-AggregatorEdges Mapping + + assertThat(mapper.getJoinVertex2aggregatorEdges().size()).isEqualTo(0); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } finally { + try { + // Dropping Source DB Schema and OrientGraph + String dbDropping = "drop schema public cascade"; + st.execute(dbDropping); + connection.close(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } } - - @Test - /* - * Two tables: 1 Foreign and 1 Parent (parent has an inner referential integrity). - * The primary key is imported both by the foreign table and the attribute of the parent table itself. - */ - - public void buildGraphModelFromTwoTablesWithOneSimplePKImportedTwice() { - Connection connection = null; - Statement st = null; - - try { - Class.forName(this.driver); - connection = DriverManager.getConnection(this.jurl, this.username, this.password); - - String parentTableBuilding = - "create memory table EMPLOYEE (EMP_ID varchar(256) not null," + - " MGR_ID varchar(256) not null, NAME varchar(256) not null, primary key (EMP_ID), " + - " foreign key (MGR_ID) references EMPLOYEE(EMP_ID))"; - st = connection.createStatement(); - st.execute(parentTableBuilding); - - String foreignTableBuilding = - "create memory table PROJECT (ID varchar(256)," + - " TITLE varchar(256) not null, PROJECT_MANAGER varchar(256) not null, primary key (ID)," + - " foreign key (PROJECT_MANAGER) references EMPLOYEE(EMP_ID))"; - st.execute(foreignTableBuilding); - - this.mapper = new ER2GraphMapper(dataSource, null, null, dbQueryEngine, dataTypeHandler, executionStrategy, nameResolver, statistics); - mapper.buildSourceDatabaseSchema(); - mapper.buildGraphModel(new JavaConventionNameResolver()); - - /* - * Testing context information - */ - - assertEquals(2, statistics.totalNumberOfModelVertices); - assertEquals(2, statistics.builtModelVertexTypes); - assertEquals(2, statistics.totalNumberOfModelEdges); - assertEquals(2, statistics.builtModelEdgeTypes); - - /* - * Testing built graph model - */ - VertexType employeeVertexType = mapper.getGraphModel().getVertexTypeByName("Employee"); - VertexType projectVertexType = mapper.getGraphModel().getVertexTypeByName("Project"); - EdgeType projectManagerEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasProjectManager"); - EdgeType mgrEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasMgr"); - - // vertices check - assertEquals(2, mapper.getGraphModel().getVerticesType().size()); - assertNotNull(employeeVertexType); - assertNotNull(projectVertexType); - - // properties check - assertEquals(3, employeeVertexType.getProperties().size()); - - assertNotNull(employeeVertexType.getPropertyByName("empId")); - assertEquals("empId", employeeVertexType.getPropertyByName("empId").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("empId").getOriginalType()); - assertEquals(1, employeeVertexType.getPropertyByName("empId").getOrdinalPosition()); - assertEquals(true, employeeVertexType.getPropertyByName("empId").isFromPrimaryKey()); - - assertNotNull(employeeVertexType.getPropertyByName("mgrId")); - assertEquals("mgrId", employeeVertexType.getPropertyByName("mgrId").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("mgrId").getOriginalType()); - assertEquals(2, employeeVertexType.getPropertyByName("mgrId").getOrdinalPosition()); - assertEquals(false, employeeVertexType.getPropertyByName("mgrId").isFromPrimaryKey()); - - assertNotNull(employeeVertexType.getPropertyByName("name")); - assertEquals("name", employeeVertexType.getPropertyByName("name").getName()); - assertEquals("VARCHAR", employeeVertexType.getPropertyByName("name").getOriginalType()); - assertEquals(3, employeeVertexType.getPropertyByName("name").getOrdinalPosition()); - assertEquals(false, employeeVertexType.getPropertyByName("name").isFromPrimaryKey()); - - assertEquals(3, projectVertexType.getProperties().size()); - - assertNotNull(projectVertexType.getPropertyByName("id")); - assertEquals("id", projectVertexType.getPropertyByName("id").getName()); - assertEquals("VARCHAR", projectVertexType.getPropertyByName("id").getOriginalType()); - assertEquals(1, projectVertexType.getPropertyByName("id").getOrdinalPosition()); - assertEquals(true, projectVertexType.getPropertyByName("id").isFromPrimaryKey()); - - assertNotNull(projectVertexType.getPropertyByName("title")); - assertEquals("title", projectVertexType.getPropertyByName("title").getName()); - assertEquals("VARCHAR", projectVertexType.getPropertyByName("title").getOriginalType()); - assertEquals(2, projectVertexType.getPropertyByName("title").getOrdinalPosition()); - assertEquals(false, projectVertexType.getPropertyByName("title").isFromPrimaryKey()); - - assertNotNull(projectVertexType.getPropertyByName("projectManager")); - assertEquals("projectManager", projectVertexType.getPropertyByName("projectManager").getName()); - assertEquals("VARCHAR", projectVertexType.getPropertyByName("projectManager").getOriginalType()); - assertEquals(3, projectVertexType.getPropertyByName("projectManager").getOrdinalPosition()); - assertEquals(false, projectVertexType.getPropertyByName("projectManager").isFromPrimaryKey()); - - // edges check - assertEquals(2, mapper.getGraphModel().getEdgesType().size()); - assertNotNull(mgrEdgeType); - assertNotNull(projectManagerEdgeType); - - assertEquals("HasMgr", mgrEdgeType.getName()); - assertEquals(0, mgrEdgeType.getProperties().size()); - assertEquals("Employee", mgrEdgeType.getInVertexType().getName()); - assertEquals(1, mgrEdgeType.getNumberRelationshipsRepresented()); - - assertEquals("HasProjectManager", projectManagerEdgeType.getName()); - assertEquals(0, projectManagerEdgeType.getProperties().size()); - assertEquals("Employee", projectManagerEdgeType.getInVertexType().getName()); - assertEquals(1, projectManagerEdgeType.getNumberRelationshipsRepresented()); - - /* - * Rules check - */ - - // Classes Mapping - - assertEquals(2, mapper.getVertexType2EVClassMappers().size()); - assertEquals(2, mapper.getEntity2EVClassMappers().size()); - - Entity employeeEntity = mapper.getDataBaseSchema().getEntityByName("EMPLOYEE"); - assertEquals(1, mapper.getEVClassMappersByVertex(employeeVertexType).size()); - EVClassMapper employeeClassMapper = mapper.getEVClassMappersByVertex(employeeVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(employeeEntity).size()); - assertEquals(employeeClassMapper, mapper.getEVClassMappersByEntity(employeeEntity).get(0)); - assertEquals(employeeClassMapper.getEntity(), employeeEntity); - assertEquals(employeeClassMapper.getVertexType(), employeeVertexType); - - assertEquals(3, employeeClassMapper.getAttribute2property().size()); - assertEquals(3, employeeClassMapper.getProperty2attribute().size()); - assertEquals("empId", employeeClassMapper.getAttribute2property().get("EMP_ID")); - assertEquals("mgrId", employeeClassMapper.getAttribute2property().get("MGR_ID")); - assertEquals("name", employeeClassMapper.getAttribute2property().get("NAME")); - assertEquals("EMP_ID", employeeClassMapper.getProperty2attribute().get("empId")); - assertEquals("MGR_ID", employeeClassMapper.getProperty2attribute().get("mgrId")); - assertEquals("NAME", employeeClassMapper.getProperty2attribute().get("name")); - - Entity projectEntity = mapper.getDataBaseSchema().getEntityByName("PROJECT"); - assertEquals(1, mapper.getEVClassMappersByVertex(projectVertexType).size()); - EVClassMapper projectClassMapper = mapper.getEVClassMappersByVertex(projectVertexType).get(0); - assertEquals(1, mapper.getEVClassMappersByEntity(projectEntity).size()); - assertEquals(projectClassMapper, mapper.getEVClassMappersByEntity(projectEntity).get(0)); - assertEquals(projectClassMapper.getEntity(), projectEntity); - assertEquals(projectClassMapper.getVertexType(), projectVertexType); - - assertEquals(3, projectClassMapper.getAttribute2property().size()); - assertEquals(3, projectClassMapper.getProperty2attribute().size()); - assertEquals("id", projectClassMapper.getAttribute2property().get("ID")); - assertEquals("title", projectClassMapper.getAttribute2property().get("TITLE")); - assertEquals("projectManager", projectClassMapper.getAttribute2property().get("PROJECT_MANAGER")); - assertEquals("ID", projectClassMapper.getProperty2attribute().get("id")); - assertEquals("TITLE", projectClassMapper.getProperty2attribute().get("title")); - assertEquals("PROJECT_MANAGER", projectClassMapper.getProperty2attribute().get("projectManager")); - - // Relationships-Edges Mapping - - Iterator it = employeeEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship hasManagerRelationship = it.next(); - assertFalse(it.hasNext()); - it = projectEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship hasProjectManagerRelationship = it.next(); - assertFalse(it.hasNext()); - - assertEquals(2, mapper.getRelationship2edgeType().size()); - assertEquals(mgrEdgeType, mapper.getRelationship2edgeType().get(hasManagerRelationship)); - assertEquals(projectManagerEdgeType, mapper.getRelationship2edgeType().get(hasProjectManagerRelationship)); - - assertEquals(2, mapper.getEdgeType2relationships().size()); - assertEquals(1, mapper.getEdgeType2relationships().get(mgrEdgeType).size()); - assertTrue(mapper.getEdgeType2relationships().get(mgrEdgeType).contains(hasManagerRelationship)); - assertEquals(1, mapper.getEdgeType2relationships().get(projectManagerEdgeType).size()); - assertTrue(mapper.getEdgeType2relationships().get(projectManagerEdgeType).contains(hasProjectManagerRelationship)); - - // JoinVertexes-AggregatorEdges Mapping - - assertEquals(0, mapper.getJoinVertex2aggregatorEdges().size()); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } finally { - try { - // Dropping Source DB Schema and OrientGraph - String dbDropping = "drop schema public cascade"; - st.execute(dbDropping); - connection.close(); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } - } + } + + /* + * Two tables: 1 Foreign and 1 Parent (parent has an inner referential integrity). + * The primary key is imported both by the foreign table and the attribute of the parent table itself. + */ + + @Test + void buildGraphModelFromTwoTablesWithOneSimplePKImportedTwice() { + Connection connection = null; + Statement st = null; + + try { + Class.forName(this.driver); + connection = DriverManager.getConnection(this.jurl, this.username, this.password); + + String parentTableBuilding = + "create memory table EMPLOYEE (EMP_ID varchar(256) not null," + + " MGR_ID varchar(256) not null, NAME varchar(256) not null, primary key (EMP_ID), " + + " foreign key (MGR_ID) references EMPLOYEE(EMP_ID))"; + st = connection.createStatement(); + st.execute(parentTableBuilding); + + String foreignTableBuilding = + "create memory table PROJECT (ID varchar(256), TITLE varchar(256) not null," + + " PROJECT_MANAGER varchar(256) not null, primary key (ID), foreign key" + + " (PROJECT_MANAGER) references EMPLOYEE(EMP_ID))"; + st.execute(foreignTableBuilding); + + this.mapper = + new ER2GraphMapper( + dataSource, + null, + null, + dbQueryEngine, + dataTypeHandler, + executionStrategy, + nameResolver, + statistics); + mapper.buildSourceDatabaseSchema(); + mapper.buildGraphModel(new JavaConventionNameResolver()); + + /* + * Testing context information + */ + + assertThat(statistics.totalNumberOfModelVertices).isEqualTo(2); + assertThat(statistics.builtModelVertexTypes).isEqualTo(2); + assertThat(statistics.totalNumberOfModelEdges).isEqualTo(2); + assertThat(statistics.builtModelEdgeTypes).isEqualTo(2); + + /* + * Testing built graph model + */ + VertexType employeeVertexType = mapper.getGraphModel().getVertexTypeByName("Employee"); + VertexType projectVertexType = mapper.getGraphModel().getVertexTypeByName("Project"); + EdgeType projectManagerEdgeType = + mapper.getGraphModel().getEdgeTypeByName("HasProjectManager"); + EdgeType mgrEdgeType = mapper.getGraphModel().getEdgeTypeByName("HasMgr"); + + // vertices check + assertThat(mapper.getGraphModel().getVerticesType().size()).isEqualTo(2); + assertThat(employeeVertexType).isNotNull(); + assertThat(projectVertexType).isNotNull(); + + // properties check + assertThat(employeeVertexType.getProperties().size()).isEqualTo(3); + + assertThat(employeeVertexType.getPropertyByName("empId")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("empId").getName()).isEqualTo("empId"); + assertThat(employeeVertexType.getPropertyByName("empId").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("empId").getOrdinalPosition()).isEqualTo(1); + assertThat(employeeVertexType.getPropertyByName("empId").isFromPrimaryKey()).isTrue(); + + assertThat(employeeVertexType.getPropertyByName("mgrId")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("mgrId").getName()).isEqualTo("mgrId"); + assertThat(employeeVertexType.getPropertyByName("mgrId").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("mgrId").getOrdinalPosition()).isEqualTo(2); + assertThat(employeeVertexType.getPropertyByName("mgrId").isFromPrimaryKey()).isFalse(); + + assertThat(employeeVertexType.getPropertyByName("name")).isNotNull(); + assertThat(employeeVertexType.getPropertyByName("name").getName()).isEqualTo("name"); + assertThat(employeeVertexType.getPropertyByName("name").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(employeeVertexType.getPropertyByName("name").getOrdinalPosition()).isEqualTo(3); + assertThat(employeeVertexType.getPropertyByName("name").isFromPrimaryKey()).isFalse(); + + assertThat(projectVertexType.getProperties().size()).isEqualTo(3); + + assertThat(projectVertexType.getPropertyByName("id")).isNotNull(); + assertThat(projectVertexType.getPropertyByName("id").getName()).isEqualTo("id"); + assertThat(projectVertexType.getPropertyByName("id").getOriginalType()).isEqualTo("VARCHAR"); + assertThat(projectVertexType.getPropertyByName("id").getOrdinalPosition()).isEqualTo(1); + assertThat(projectVertexType.getPropertyByName("id").isFromPrimaryKey()).isTrue(); + + assertThat(projectVertexType.getPropertyByName("title")).isNotNull(); + assertThat(projectVertexType.getPropertyByName("title").getName()).isEqualTo("title"); + assertThat(projectVertexType.getPropertyByName("title").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(projectVertexType.getPropertyByName("title").getOrdinalPosition()).isEqualTo(2); + assertThat(projectVertexType.getPropertyByName("title").isFromPrimaryKey()).isFalse(); + + assertThat(projectVertexType.getPropertyByName("projectManager")).isNotNull(); + assertThat(projectVertexType.getPropertyByName("projectManager").getName()) + .isEqualTo("projectManager"); + assertThat(projectVertexType.getPropertyByName("projectManager").getOriginalType()) + .isEqualTo("VARCHAR"); + assertThat(projectVertexType.getPropertyByName("projectManager").getOrdinalPosition()) + .isEqualTo(3); + assertThat(projectVertexType.getPropertyByName("projectManager").isFromPrimaryKey()) + .isFalse(); + + // edges check + assertThat(mapper.getGraphModel().getEdgesType().size()).isEqualTo(2); + assertThat(mgrEdgeType).isNotNull(); + assertThat(projectManagerEdgeType).isNotNull(); + + assertThat(mgrEdgeType.getName()).isEqualTo("HasMgr"); + assertThat(mgrEdgeType.getProperties().size()).isEqualTo(0); + assertThat(mgrEdgeType.getInVertexType().getName()).isEqualTo("Employee"); + assertThat(mgrEdgeType.getNumberRelationshipsRepresented()).isEqualTo(1); + + assertThat(projectManagerEdgeType.getName()).isEqualTo("HasProjectManager"); + assertThat(projectManagerEdgeType.getProperties().size()).isEqualTo(0); + assertThat(projectManagerEdgeType.getInVertexType().getName()).isEqualTo("Employee"); + assertThat(projectManagerEdgeType.getNumberRelationshipsRepresented()).isEqualTo(1); + + /* + * Rules check + */ + + // Classes Mapping + + assertThat(mapper.getVertexType2EVClassMappers().size()).isEqualTo(2); + assertThat(mapper.getEntity2EVClassMappers().size()).isEqualTo(2); + + Entity employeeEntity = mapper.getDataBaseSchema().getEntityByName("EMPLOYEE"); + assertThat(mapper.getEVClassMappersByVertex(employeeVertexType).size()).isEqualTo(1); + EVClassMapper employeeClassMapper = + mapper.getEVClassMappersByVertex(employeeVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(employeeEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(employeeEntity).get(0)) + .isEqualTo(employeeClassMapper); + assertThat(employeeEntity).isEqualTo(employeeClassMapper.getEntity()); + assertThat(employeeVertexType).isEqualTo(employeeClassMapper.getVertexType()); + + assertThat(employeeClassMapper.getAttribute2property().size()).isEqualTo(3); + assertThat(employeeClassMapper.getProperty2attribute().size()).isEqualTo(3); + assertThat(employeeClassMapper.getAttribute2property().get("EMP_ID")).isEqualTo("empId"); + assertThat(employeeClassMapper.getAttribute2property().get("MGR_ID")).isEqualTo("mgrId"); + assertThat(employeeClassMapper.getAttribute2property().get("NAME")).isEqualTo("name"); + assertThat(employeeClassMapper.getProperty2attribute().get("empId")).isEqualTo("EMP_ID"); + assertThat(employeeClassMapper.getProperty2attribute().get("mgrId")).isEqualTo("MGR_ID"); + assertThat(employeeClassMapper.getProperty2attribute().get("name")).isEqualTo("NAME"); + + Entity projectEntity = mapper.getDataBaseSchema().getEntityByName("PROJECT"); + assertThat(mapper.getEVClassMappersByVertex(projectVertexType).size()).isEqualTo(1); + EVClassMapper projectClassMapper = mapper.getEVClassMappersByVertex(projectVertexType).get(0); + assertThat(mapper.getEVClassMappersByEntity(projectEntity).size()).isEqualTo(1); + assertThat(mapper.getEVClassMappersByEntity(projectEntity).get(0)) + .isEqualTo(projectClassMapper); + assertThat(projectEntity).isEqualTo(projectClassMapper.getEntity()); + assertThat(projectVertexType).isEqualTo(projectClassMapper.getVertexType()); + + assertThat(projectClassMapper.getAttribute2property().size()).isEqualTo(3); + assertThat(projectClassMapper.getProperty2attribute().size()).isEqualTo(3); + assertThat(projectClassMapper.getAttribute2property().get("ID")).isEqualTo("id"); + assertThat(projectClassMapper.getAttribute2property().get("TITLE")).isEqualTo("title"); + assertThat(projectClassMapper.getAttribute2property().get("PROJECT_MANAGER")) + .isEqualTo("projectManager"); + assertThat(projectClassMapper.getProperty2attribute().get("id")).isEqualTo("ID"); + assertThat(projectClassMapper.getProperty2attribute().get("title")).isEqualTo("TITLE"); + assertThat(projectClassMapper.getProperty2attribute().get("projectManager")) + .isEqualTo("PROJECT_MANAGER"); + + // Relationships-Edges Mapping + + Iterator it = employeeEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship hasManagerRelationship = it.next(); + assertThat(it.hasNext()).isFalse(); + it = projectEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship hasProjectManagerRelationship = it.next(); + assertThat(it.hasNext()).isFalse(); + + assertThat(mapper.getRelationship2edgeType().size()).isEqualTo(2); + assertThat(mapper.getRelationship2edgeType().get(hasManagerRelationship)) + .isEqualTo(mgrEdgeType); + assertThat(mapper.getRelationship2edgeType().get(hasProjectManagerRelationship)) + .isEqualTo(projectManagerEdgeType); + + assertThat(mapper.getEdgeType2relationships().size()).isEqualTo(2); + assertThat(mapper.getEdgeType2relationships().get(mgrEdgeType).size()).isEqualTo(1); + assertThat( + mapper.getEdgeType2relationships().get(mgrEdgeType).contains(hasManagerRelationship)) + .isTrue(); + assertThat(mapper.getEdgeType2relationships().get(projectManagerEdgeType).size()) + .isEqualTo(1); + assertThat( + mapper + .getEdgeType2relationships() + .get(projectManagerEdgeType) + .contains(hasProjectManagerRelationship)) + .isTrue(); + + // JoinVertexes-AggregatorEdges Mapping + + assertThat(mapper.getJoinVertex2aggregatorEdges().size()).isEqualTo(0); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } finally { + try { + // Dropping Source DB Schema and OrientGraph + String dbDropping = "drop schema public cascade"; + st.execute(dbDropping); + connection.close(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } } + } } diff --git a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/mapper/SourceSchemaBuildingTest.java b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/mapper/SourceSchemaBuildingTest.java index 152f2e3e..a183e847 100644 --- a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/mapper/SourceSchemaBuildingTest.java +++ b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/mapper/SourceSchemaBuildingTest.java @@ -40,10 +40,8 @@ * #L% */ -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.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import com.arcadeanalytics.provider.DataSourceInfo; import com.arcadeanalytics.provider.rdbms.context.Statistics; @@ -65,860 +63,959 @@ /** * @author Gabriele Ponzi */ - -public class SourceSchemaBuildingTest { - - private ER2GraphMapper mapper; - private DBQueryEngine dbQueryEngine; - private String driver = "org.hsqldb.jdbc.JDBCDriver"; - private String jurl = "jdbc:hsqldb:mem:mydb"; - private String username = "SA"; - private String password = ""; - private DataSourceInfo dataSource; - private String executionStrategy; - private NameResolver nameResolver; - private DBMSDataTypeHandler dataTypeHandler; - private Statistics statistics; - - @BeforeEach - public void init() { - this.dataSource = - new DataSourceInfo( - 1L, - "RDBMS_HSQL", - "testDataSource", - "desc", - "mem", - 1234, - "mydb", - username, - password, - false, - "{}", - false, - false, - "", - 22, - "", - false - ); - dbQueryEngine = new DBQueryEngine(dataSource, 300); - executionStrategy = "not_specified"; - nameResolver = new JavaConventionNameResolver(); - dataTypeHandler = new HSQLDBDataTypeHandler(); - - statistics = new Statistics(); - - this.mapper = new ER2GraphMapper(dataSource, null, null, dbQueryEngine, dataTypeHandler, executionStrategy, nameResolver, statistics); - } - - @Test - /* - * Two Foreign tables and one Parent with a simple primary key imported from the parent table. - */ - - public void buildSourceSchemaFromTwoTablesWithOneSimplePK() { - Connection connection = null; - Statement st = null; - - try { - Class.forName(this.driver); - connection = DriverManager.getConnection(this.jurl, this.username, this.password); - - String parentTableBuilding = - "create memory table PARENT_AUTHOR (AUTHOR_ID varchar(256) not null," + " AUTHOR_NAME varchar(256) not null, primary key (AUTHOR_ID))"; - st = connection.createStatement(); - st.execute(parentTableBuilding); - - String foreignTableBuilding = - "create memory table FOREIGN_BOOK (BOOK_ID varchar(256) not null, TITLE varchar(256)," + - " AUTHOR varchar(256) not null, primary key (BOOK_ID), foreign key (AUTHOR) references PARENT_AUTHOR(AUTHOR_ID))"; - st.execute(foreignTableBuilding); - - this.mapper.buildSourceDatabaseSchema(); - - /* - * Testing context information - */ - - assertEquals(2, statistics.totalNumberOfEntities); - assertEquals(2, statistics.builtEntities); - assertEquals(1, statistics.totalNumberOfRelationships); - assertEquals(1, statistics.builtRelationships); - - /* - * Testing built source db schema - */ - - Entity parentEntity = mapper.getDataBaseSchema().getEntityByName("PARENT_AUTHOR"); - Entity foreignEntity = mapper.getDataBaseSchema().getEntityByName("FOREIGN_BOOK"); - - // entities check - assertEquals(2, mapper.getDataBaseSchema().getEntities().size()); - assertEquals(1, mapper.getDataBaseSchema().getCanonicalRelationships().size()); - assertNotNull(parentEntity); - assertNotNull(foreignEntity); - - // attributes check - assertEquals(2, parentEntity.getAttributes().size()); - - assertNotNull(parentEntity.getAttributeByName("AUTHOR_ID")); - assertEquals("AUTHOR_ID", parentEntity.getAttributeByName("AUTHOR_ID").getName()); - assertEquals("VARCHAR", parentEntity.getAttributeByName("AUTHOR_ID").getDataType()); - assertEquals(1, parentEntity.getAttributeByName("AUTHOR_ID").getOrdinalPosition()); - assertEquals("PARENT_AUTHOR", parentEntity.getAttributeByName("AUTHOR_ID").getBelongingEntity().getName()); - - assertNotNull(parentEntity.getAttributeByName("AUTHOR_NAME")); - assertEquals("AUTHOR_NAME", parentEntity.getAttributeByName("AUTHOR_NAME").getName()); - assertEquals("VARCHAR", parentEntity.getAttributeByName("AUTHOR_NAME").getDataType()); - assertEquals(2, parentEntity.getAttributeByName("AUTHOR_NAME").getOrdinalPosition()); - assertEquals("PARENT_AUTHOR", parentEntity.getAttributeByName("AUTHOR_NAME").getBelongingEntity().getName()); - - assertEquals(3, foreignEntity.getAttributes().size()); - - assertNotNull(foreignEntity.getAttributeByName("BOOK_ID")); - assertEquals("BOOK_ID", foreignEntity.getAttributeByName("BOOK_ID").getName()); - assertEquals("VARCHAR", foreignEntity.getAttributeByName("BOOK_ID").getDataType()); - assertEquals(1, foreignEntity.getAttributeByName("BOOK_ID").getOrdinalPosition()); - assertEquals("FOREIGN_BOOK", foreignEntity.getAttributeByName("BOOK_ID").getBelongingEntity().getName()); - - assertNotNull(foreignEntity.getAttributeByName("TITLE")); - assertEquals("TITLE", foreignEntity.getAttributeByName("TITLE").getName()); - assertEquals("VARCHAR", foreignEntity.getAttributeByName("TITLE").getDataType()); - assertEquals(2, foreignEntity.getAttributeByName("TITLE").getOrdinalPosition()); - assertEquals("FOREIGN_BOOK", foreignEntity.getAttributeByName("TITLE").getBelongingEntity().getName()); - - assertNotNull(foreignEntity.getAttributeByName("AUTHOR")); - assertEquals("AUTHOR", foreignEntity.getAttributeByName("AUTHOR").getName()); - assertEquals("VARCHAR", foreignEntity.getAttributeByName("AUTHOR").getDataType()); - assertEquals(3, foreignEntity.getAttributeByName("AUTHOR").getOrdinalPosition()); - assertEquals("FOREIGN_BOOK", foreignEntity.getAttributeByName("AUTHOR").getBelongingEntity().getName()); - - // relationship, primary and foreign key check - assertEquals(1, foreignEntity.getOutCanonicalRelationships().size()); - assertEquals(0, parentEntity.getOutCanonicalRelationships().size()); - assertEquals(0, foreignEntity.getInCanonicalRelationships().size()); - assertEquals(1, parentEntity.getInCanonicalRelationships().size()); - assertEquals(0, parentEntity.getForeignKeys().size()); - assertEquals(1, foreignEntity.getForeignKeys().size()); - - Iterator it = foreignEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship currentRelationship = it.next(); - assertEquals("PARENT_AUTHOR", currentRelationship.getParentEntity().getName()); - assertEquals("FOREIGN_BOOK", currentRelationship.getForeignEntity().getName()); - assertEquals(parentEntity.getPrimaryKey(), currentRelationship.getPrimaryKey()); - assertEquals(foreignEntity.getForeignKeys().get(0), currentRelationship.getForeignKey()); - - Iterator it2 = parentEntity.getInCanonicalRelationships().iterator(); - CanonicalRelationship currentRelationship2 = it2.next(); - assertEquals(currentRelationship, currentRelationship2); - - assertEquals("AUTHOR", foreignEntity.getForeignKeys().get(0).getInvolvedAttributes().get(0).getName()); - assertEquals("AUTHOR_ID", parentEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()); - - assertFalse(it.hasNext()); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } finally { - try { - // Dropping Source DB Schema and OrientGraph - String dbDropping = "drop schema public cascade"; - st.execute(dbDropping); - connection.close(); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } - } +class SourceSchemaBuildingTest { + + private ER2GraphMapper mapper; + private DBQueryEngine dbQueryEngine; + private String driver = "org.hsqldb.jdbc.JDBCDriver"; + private String jurl = "jdbc:hsqldb:mem:mydb"; + private String username = "SA"; + private String password = ""; + private DataSourceInfo dataSource; + private String executionStrategy; + private NameResolver nameResolver; + private DBMSDataTypeHandler dataTypeHandler; + private Statistics statistics; + + @BeforeEach + void init() { + this.dataSource = + new DataSourceInfo( + 1L, + "RDBMS_HSQL", + "testDataSource", + "desc", + "mem", + 1234, + "mydb", + username, + password, + false, + "{}", + false, + false, + "", + 22, + "", + false); + dbQueryEngine = new DBQueryEngine(dataSource, 300); + executionStrategy = "not_specified"; + nameResolver = new JavaConventionNameResolver(); + dataTypeHandler = new HSQLDBDataTypeHandler(); + + statistics = new Statistics(); + + this.mapper = + new ER2GraphMapper( + dataSource, + null, + null, + dbQueryEngine, + dataTypeHandler, + executionStrategy, + nameResolver, + statistics); + } + + /* + * Two Foreign tables and one Parent with a simple primary key imported from the parent table. + */ + + @Test + void buildSourceSchemaFromTwoTablesWithOneSimplePK() { + Connection connection = null; + Statement st = null; + + try { + Class.forName(this.driver); + connection = DriverManager.getConnection(this.jurl, this.username, this.password); + + String parentTableBuilding = + "create memory table PARENT_AUTHOR (AUTHOR_ID varchar(256) not null," + + " AUTHOR_NAME varchar(256) not null, primary key (AUTHOR_ID))"; + st = connection.createStatement(); + st.execute(parentTableBuilding); + + String foreignTableBuilding = + "create memory table FOREIGN_BOOK (BOOK_ID varchar(256) not null, TITLE varchar(256)," + + " AUTHOR varchar(256) not null, primary key (BOOK_ID), foreign key (AUTHOR)" + + " references PARENT_AUTHOR(AUTHOR_ID))"; + st.execute(foreignTableBuilding); + + this.mapper.buildSourceDatabaseSchema(); + + /* + * Testing context information + */ + + assertThat(statistics.totalNumberOfEntities).isEqualTo(2); + assertThat(statistics.builtEntities).isEqualTo(2); + assertThat(statistics.totalNumberOfRelationships).isEqualTo(1); + assertThat(statistics.builtRelationships).isEqualTo(1); + + /* + * Testing built source db schema + */ + + Entity parentEntity = mapper.getDataBaseSchema().getEntityByName("PARENT_AUTHOR"); + Entity foreignEntity = mapper.getDataBaseSchema().getEntityByName("FOREIGN_BOOK"); + + // entities check + assertThat(mapper.getDataBaseSchema().getEntities().size()).isEqualTo(2); + assertThat(mapper.getDataBaseSchema().getCanonicalRelationships().size()).isEqualTo(1); + assertThat(parentEntity).isNotNull(); + assertThat(foreignEntity).isNotNull(); + + // attributes check + assertThat(parentEntity.getAttributes().size()).isEqualTo(2); + + assertThat(parentEntity.getAttributeByName("AUTHOR_ID")).isNotNull(); + assertThat(parentEntity.getAttributeByName("AUTHOR_ID").getName()).isEqualTo("AUTHOR_ID"); + assertThat(parentEntity.getAttributeByName("AUTHOR_ID").getDataType()).isEqualTo("VARCHAR"); + assertThat(parentEntity.getAttributeByName("AUTHOR_ID").getOrdinalPosition()).isEqualTo(1); + assertThat(parentEntity.getAttributeByName("AUTHOR_ID").getBelongingEntity().getName()) + .isEqualTo("PARENT_AUTHOR"); + + assertThat(parentEntity.getAttributeByName("AUTHOR_NAME")).isNotNull(); + assertThat(parentEntity.getAttributeByName("AUTHOR_NAME").getName()).isEqualTo("AUTHOR_NAME"); + assertThat(parentEntity.getAttributeByName("AUTHOR_NAME").getDataType()).isEqualTo("VARCHAR"); + assertThat(parentEntity.getAttributeByName("AUTHOR_NAME").getOrdinalPosition()).isEqualTo(2); + assertThat(parentEntity.getAttributeByName("AUTHOR_NAME").getBelongingEntity().getName()) + .isEqualTo("PARENT_AUTHOR"); + + assertThat(foreignEntity.getAttributes().size()).isEqualTo(3); + + assertThat(foreignEntity.getAttributeByName("BOOK_ID")).isNotNull(); + assertThat(foreignEntity.getAttributeByName("BOOK_ID").getName()).isEqualTo("BOOK_ID"); + assertThat(foreignEntity.getAttributeByName("BOOK_ID").getDataType()).isEqualTo("VARCHAR"); + assertThat(foreignEntity.getAttributeByName("BOOK_ID").getOrdinalPosition()).isEqualTo(1); + assertThat(foreignEntity.getAttributeByName("BOOK_ID").getBelongingEntity().getName()) + .isEqualTo("FOREIGN_BOOK"); + + assertThat(foreignEntity.getAttributeByName("TITLE")).isNotNull(); + assertThat(foreignEntity.getAttributeByName("TITLE").getName()).isEqualTo("TITLE"); + assertThat(foreignEntity.getAttributeByName("TITLE").getDataType()).isEqualTo("VARCHAR"); + assertThat(foreignEntity.getAttributeByName("TITLE").getOrdinalPosition()).isEqualTo(2); + assertThat(foreignEntity.getAttributeByName("TITLE").getBelongingEntity().getName()) + .isEqualTo("FOREIGN_BOOK"); + + assertThat(foreignEntity.getAttributeByName("AUTHOR")).isNotNull(); + assertThat(foreignEntity.getAttributeByName("AUTHOR").getName()).isEqualTo("AUTHOR"); + assertThat(foreignEntity.getAttributeByName("AUTHOR").getDataType()).isEqualTo("VARCHAR"); + assertThat(foreignEntity.getAttributeByName("AUTHOR").getOrdinalPosition()).isEqualTo(3); + assertThat(foreignEntity.getAttributeByName("AUTHOR").getBelongingEntity().getName()) + .isEqualTo("FOREIGN_BOOK"); + + // relationship, primary and foreign key check + assertThat(foreignEntity.getOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(parentEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(foreignEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(parentEntity.getInCanonicalRelationships().size()).isEqualTo(1); + assertThat(parentEntity.getForeignKeys().size()).isEqualTo(0); + assertThat(foreignEntity.getForeignKeys().size()).isEqualTo(1); + + Iterator it = foreignEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship currentRelationship = it.next(); + assertThat(currentRelationship.getParentEntity().getName()).isEqualTo("PARENT_AUTHOR"); + assertThat(currentRelationship.getForeignEntity().getName()).isEqualTo("FOREIGN_BOOK"); + assertThat(currentRelationship.getPrimaryKey()).isEqualTo(parentEntity.getPrimaryKey()); + assertThat(currentRelationship.getForeignKey()) + .isEqualTo(foreignEntity.getForeignKeys().get(0)); + + Iterator it2 = parentEntity.getInCanonicalRelationships().iterator(); + CanonicalRelationship currentRelationship2 = it2.next(); + assertThat(currentRelationship2).isEqualTo(currentRelationship); + + assertThat(foreignEntity.getForeignKeys().get(0).getInvolvedAttributes().get(0).getName()) + .isEqualTo("AUTHOR"); + assertThat(parentEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()) + .isEqualTo("AUTHOR_ID"); + + assertThat(it.hasNext()).isFalse(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } finally { + try { + // Dropping Source DB Schema and OrientGraph + String dbDropping = "drop schema public cascade"; + st.execute(dbDropping); + connection.close(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } } - - @Test - /* - * Two Foreign tables and one Parent with a composite primary key imported from the parent table. - */ - - public void buildSourceSchemaFromThreeTablesWithOneCompositePK() { - Connection connection = null; - Statement st = null; - - try { - Class.forName(this.driver); - connection = DriverManager.getConnection(this.jurl, this.username, this.password); - - String parentTableBuilding = - "create memory table PARENT_AUTHOR (AUTHOR_NAME varchar(256) not null," + - " AUTHOR_SURNAME varchar(256) not null, AGE INTEGER, primary key (AUTHOR_NAME,AUTHOR_SURNAME))"; - st = connection.createStatement(); - st.execute(parentTableBuilding); - - String foreignTableBuilding = - "create memory table FOREIGN_BOOK (TITLE varchar(256)," + - " AUTHOR_NAME varchar(256) not null, AUTHOR_SURNAME varchar(256) not null, primary key (TITLE)," + - " foreign key (AUTHOR_NAME,AUTHOR_SURNAME) references PARENT_AUTHOR(AUTHOR_NAME,AUTHOR_SURNAME))"; - st.execute(foreignTableBuilding); - - mapper.buildSourceDatabaseSchema(); - - /* - * Testing context information - */ - - assertEquals(2, statistics.totalNumberOfEntities); - assertEquals(2, statistics.builtEntities); - assertEquals(1, statistics.totalNumberOfRelationships); - assertEquals(1, statistics.builtRelationships); - - /* - * Testing built source db schema - */ - - Entity parentEntity = mapper.getDataBaseSchema().getEntityByName("PARENT_AUTHOR"); - Entity foreignEntity = mapper.getDataBaseSchema().getEntityByName("FOREIGN_BOOK"); - - // entities check - assertEquals(2, mapper.getDataBaseSchema().getEntities().size()); - assertEquals(1, mapper.getDataBaseSchema().getCanonicalRelationships().size()); - assertNotNull(parentEntity); - assertNotNull(foreignEntity); - - // attributes check - assertEquals(3, parentEntity.getAttributes().size()); - - assertNotNull(parentEntity.getAttributeByName("AUTHOR_NAME")); - assertEquals("AUTHOR_NAME", parentEntity.getAttributeByName("AUTHOR_NAME").getName()); - assertEquals("VARCHAR", parentEntity.getAttributeByName("AUTHOR_NAME").getDataType()); - assertEquals(1, parentEntity.getAttributeByName("AUTHOR_NAME").getOrdinalPosition()); - assertEquals("PARENT_AUTHOR", parentEntity.getAttributeByName("AUTHOR_NAME").getBelongingEntity().getName()); - - assertNotNull(parentEntity.getAttributeByName("AUTHOR_SURNAME")); - assertEquals("AUTHOR_SURNAME", parentEntity.getAttributeByName("AUTHOR_SURNAME").getName()); - assertEquals("VARCHAR", parentEntity.getAttributeByName("AUTHOR_SURNAME").getDataType()); - assertEquals(2, parentEntity.getAttributeByName("AUTHOR_SURNAME").getOrdinalPosition()); - assertEquals("PARENT_AUTHOR", parentEntity.getAttributeByName("AUTHOR_SURNAME").getBelongingEntity().getName()); - - assertNotNull(parentEntity.getAttributeByName("AGE")); - assertEquals("AGE", parentEntity.getAttributeByName("AGE").getName()); - assertEquals("INTEGER", parentEntity.getAttributeByName("AGE").getDataType()); - assertEquals(3, parentEntity.getAttributeByName("AGE").getOrdinalPosition()); - assertEquals("PARENT_AUTHOR", parentEntity.getAttributeByName("AGE").getBelongingEntity().getName()); - - assertEquals(3, foreignEntity.getAttributes().size()); - - assertNotNull(foreignEntity.getAttributeByName("TITLE")); - assertEquals("TITLE", foreignEntity.getAttributeByName("TITLE").getName()); - assertEquals("VARCHAR", foreignEntity.getAttributeByName("TITLE").getDataType()); - assertEquals(1, foreignEntity.getAttributeByName("TITLE").getOrdinalPosition()); - assertEquals("FOREIGN_BOOK", foreignEntity.getAttributeByName("TITLE").getBelongingEntity().getName()); - - assertNotNull(foreignEntity.getAttributeByName("AUTHOR_NAME")); - assertEquals("AUTHOR_NAME", foreignEntity.getAttributeByName("AUTHOR_NAME").getName()); - assertEquals("VARCHAR", foreignEntity.getAttributeByName("AUTHOR_NAME").getDataType()); - assertEquals(2, foreignEntity.getAttributeByName("AUTHOR_NAME").getOrdinalPosition()); - assertEquals("FOREIGN_BOOK", foreignEntity.getAttributeByName("AUTHOR_NAME").getBelongingEntity().getName()); - - assertNotNull(foreignEntity.getAttributeByName("AUTHOR_SURNAME")); - assertEquals("AUTHOR_SURNAME", foreignEntity.getAttributeByName("AUTHOR_SURNAME").getName()); - assertEquals("VARCHAR", foreignEntity.getAttributeByName("AUTHOR_SURNAME").getDataType()); - assertEquals(3, foreignEntity.getAttributeByName("AUTHOR_SURNAME").getOrdinalPosition()); - assertEquals("FOREIGN_BOOK", foreignEntity.getAttributeByName("AUTHOR_SURNAME").getBelongingEntity().getName()); - - // relationship, primary and foreign key check - assertEquals(1, foreignEntity.getOutCanonicalRelationships().size()); - assertEquals(0, parentEntity.getOutCanonicalRelationships().size()); - assertEquals(0, foreignEntity.getInCanonicalRelationships().size()); - assertEquals(1, parentEntity.getInCanonicalRelationships().size()); - assertEquals(0, parentEntity.getForeignKeys().size()); - assertEquals(1, foreignEntity.getForeignKeys().size()); - - Iterator it = foreignEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship currentRelationship = it.next(); - assertEquals("PARENT_AUTHOR", currentRelationship.getParentEntity().getName()); - assertEquals("FOREIGN_BOOK", currentRelationship.getForeignEntity().getName()); - assertEquals(parentEntity.getPrimaryKey(), currentRelationship.getPrimaryKey()); - assertEquals(foreignEntity.getForeignKeys().get(0), currentRelationship.getForeignKey()); - - Iterator it2 = parentEntity.getInCanonicalRelationships().iterator(); - CanonicalRelationship currentRelationship2 = it2.next(); - assertEquals(currentRelationship, currentRelationship2); - - assertEquals("AUTHOR_NAME", foreignEntity.getForeignKeys().get(0).getInvolvedAttributes().get(0).getName()); - assertEquals("AUTHOR_SURNAME", foreignEntity.getForeignKeys().get(0).getInvolvedAttributes().get(1).getName()); - assertEquals("AUTHOR_NAME", parentEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()); - assertEquals("AUTHOR_SURNAME", parentEntity.getPrimaryKey().getInvolvedAttributes().get(1).getName()); - - assertFalse(it.hasNext()); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } finally { - try { - // Dropping Source DB Schema and OrientGraph - String dbDropping = "drop schema public cascade"; - st.execute(dbDropping); - connection.close(); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } - } + } + + /* + * Two Foreign tables and one Parent with a composite primary key imported from the parent table. + */ + + @Test + void buildSourceSchemaFromThreeTablesWithOneCompositePK() { + Connection connection = null; + Statement st = null; + + try { + Class.forName(this.driver); + connection = DriverManager.getConnection(this.jurl, this.username, this.password); + + String parentTableBuilding = + "create memory table PARENT_AUTHOR (AUTHOR_NAME varchar(256) not null, AUTHOR_SURNAME" + + " varchar(256) not null, AGE INTEGER, primary key (AUTHOR_NAME,AUTHOR_SURNAME))"; + st = connection.createStatement(); + st.execute(parentTableBuilding); + + String foreignTableBuilding = + "create memory table FOREIGN_BOOK (TITLE varchar(256), AUTHOR_NAME varchar(256) not" + + " null, AUTHOR_SURNAME varchar(256) not null, primary key (TITLE), foreign key" + + " (AUTHOR_NAME,AUTHOR_SURNAME) references" + + " PARENT_AUTHOR(AUTHOR_NAME,AUTHOR_SURNAME))"; + st.execute(foreignTableBuilding); + + mapper.buildSourceDatabaseSchema(); + + /* + * Testing context information + */ + + assertThat(statistics.totalNumberOfEntities).isEqualTo(2); + assertThat(statistics.builtEntities).isEqualTo(2); + assertThat(statistics.totalNumberOfRelationships).isEqualTo(1); + assertThat(statistics.builtRelationships).isEqualTo(1); + + /* + * Testing built source db schema + */ + + Entity parentEntity = mapper.getDataBaseSchema().getEntityByName("PARENT_AUTHOR"); + Entity foreignEntity = mapper.getDataBaseSchema().getEntityByName("FOREIGN_BOOK"); + + // entities check + assertThat(mapper.getDataBaseSchema().getEntities().size()).isEqualTo(2); + assertThat(mapper.getDataBaseSchema().getCanonicalRelationships().size()).isEqualTo(1); + assertThat(parentEntity).isNotNull(); + assertThat(foreignEntity).isNotNull(); + + // attributes check + assertThat(parentEntity.getAttributes().size()).isEqualTo(3); + + assertThat(parentEntity.getAttributeByName("AUTHOR_NAME")).isNotNull(); + assertThat(parentEntity.getAttributeByName("AUTHOR_NAME").getName()).isEqualTo("AUTHOR_NAME"); + assertThat(parentEntity.getAttributeByName("AUTHOR_NAME").getDataType()).isEqualTo("VARCHAR"); + assertThat(parentEntity.getAttributeByName("AUTHOR_NAME").getOrdinalPosition()).isEqualTo(1); + assertThat(parentEntity.getAttributeByName("AUTHOR_NAME").getBelongingEntity().getName()) + .isEqualTo("PARENT_AUTHOR"); + + assertThat(parentEntity.getAttributeByName("AUTHOR_SURNAME")).isNotNull(); + assertThat(parentEntity.getAttributeByName("AUTHOR_SURNAME").getName()) + .isEqualTo("AUTHOR_SURNAME"); + assertThat(parentEntity.getAttributeByName("AUTHOR_SURNAME").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(parentEntity.getAttributeByName("AUTHOR_SURNAME").getOrdinalPosition()) + .isEqualTo(2); + assertThat(parentEntity.getAttributeByName("AUTHOR_SURNAME").getBelongingEntity().getName()) + .isEqualTo("PARENT_AUTHOR"); + + assertThat(parentEntity.getAttributeByName("AGE")).isNotNull(); + assertThat(parentEntity.getAttributeByName("AGE").getName()).isEqualTo("AGE"); + assertThat(parentEntity.getAttributeByName("AGE").getDataType()).isEqualTo("INTEGER"); + assertThat(parentEntity.getAttributeByName("AGE").getOrdinalPosition()).isEqualTo(3); + assertThat(parentEntity.getAttributeByName("AGE").getBelongingEntity().getName()) + .isEqualTo("PARENT_AUTHOR"); + + assertThat(foreignEntity.getAttributes().size()).isEqualTo(3); + + assertThat(foreignEntity.getAttributeByName("TITLE")).isNotNull(); + assertThat(foreignEntity.getAttributeByName("TITLE").getName()).isEqualTo("TITLE"); + assertThat(foreignEntity.getAttributeByName("TITLE").getDataType()).isEqualTo("VARCHAR"); + assertThat(foreignEntity.getAttributeByName("TITLE").getOrdinalPosition()).isEqualTo(1); + assertThat(foreignEntity.getAttributeByName("TITLE").getBelongingEntity().getName()) + .isEqualTo("FOREIGN_BOOK"); + + assertThat(foreignEntity.getAttributeByName("AUTHOR_NAME")).isNotNull(); + assertThat(foreignEntity.getAttributeByName("AUTHOR_NAME").getName()) + .isEqualTo("AUTHOR_NAME"); + assertThat(foreignEntity.getAttributeByName("AUTHOR_NAME").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(foreignEntity.getAttributeByName("AUTHOR_NAME").getOrdinalPosition()).isEqualTo(2); + assertThat(foreignEntity.getAttributeByName("AUTHOR_NAME").getBelongingEntity().getName()) + .isEqualTo("FOREIGN_BOOK"); + + assertThat(foreignEntity.getAttributeByName("AUTHOR_SURNAME")).isNotNull(); + assertThat(foreignEntity.getAttributeByName("AUTHOR_SURNAME").getName()) + .isEqualTo("AUTHOR_SURNAME"); + assertThat(foreignEntity.getAttributeByName("AUTHOR_SURNAME").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(foreignEntity.getAttributeByName("AUTHOR_SURNAME").getOrdinalPosition()) + .isEqualTo(3); + assertThat(foreignEntity.getAttributeByName("AUTHOR_SURNAME").getBelongingEntity().getName()) + .isEqualTo("FOREIGN_BOOK"); + + // relationship, primary and foreign key check + assertThat(foreignEntity.getOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(parentEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(foreignEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(parentEntity.getInCanonicalRelationships().size()).isEqualTo(1); + assertThat(parentEntity.getForeignKeys().size()).isEqualTo(0); + assertThat(foreignEntity.getForeignKeys().size()).isEqualTo(1); + + Iterator it = foreignEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship currentRelationship = it.next(); + assertThat(currentRelationship.getParentEntity().getName()).isEqualTo("PARENT_AUTHOR"); + assertThat(currentRelationship.getForeignEntity().getName()).isEqualTo("FOREIGN_BOOK"); + assertThat(currentRelationship.getPrimaryKey()).isEqualTo(parentEntity.getPrimaryKey()); + assertThat(currentRelationship.getForeignKey()) + .isEqualTo(foreignEntity.getForeignKeys().get(0)); + + Iterator it2 = parentEntity.getInCanonicalRelationships().iterator(); + CanonicalRelationship currentRelationship2 = it2.next(); + assertThat(currentRelationship2).isEqualTo(currentRelationship); + + assertThat(foreignEntity.getForeignKeys().get(0).getInvolvedAttributes().get(0).getName()) + .isEqualTo("AUTHOR_NAME"); + assertThat(foreignEntity.getForeignKeys().get(0).getInvolvedAttributes().get(1).getName()) + .isEqualTo("AUTHOR_SURNAME"); + assertThat(parentEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()) + .isEqualTo("AUTHOR_NAME"); + assertThat(parentEntity.getPrimaryKey().getInvolvedAttributes().get(1).getName()) + .isEqualTo("AUTHOR_SURNAME"); + + assertThat(it.hasNext()).isFalse(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } finally { + try { + // Dropping Source DB Schema and OrientGraph + String dbDropping = "drop schema public cascade"; + st.execute(dbDropping); + connection.close(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } } - - @Test - /* - * Two Foreign tables and one Parent with a simple primary key imported twice from the parent table. - */ - - public void buildSourceSchemaFromThreeTablesWithOneSimplePKImportedTwice() { - Connection connection = null; - Statement st = null; - - try { - Class.forName(this.driver); - connection = DriverManager.getConnection(this.jurl, this.username, this.password); - - String parentTableBuilding = - "create memory table PARENT_PERSON (PERSON_ID varchar(256) not null," + " NAME varchar(256) not null, primary key (PERSON_ID))"; - st = connection.createStatement(); - st.execute(parentTableBuilding); - - String foreignTableBuilding = - "create memory table FOREIGN_ARTICLE (TITLE varchar(256)," + - " AUTHOR varchar(256) not null, TRANSLATOR varchar(256) not null, primary key (TITLE)," + - " foreign key (AUTHOR) references PARENT_PERSON(PERSON_ID)," + - " foreign key (TRANSLATOR) references PARENT_PERSON(PERSON_ID))"; - st.execute(foreignTableBuilding); - - mapper.buildSourceDatabaseSchema(); - - /* - * Testing context information - */ - - assertEquals(2, statistics.totalNumberOfEntities); - assertEquals(2, statistics.builtEntities); - assertEquals(2, statistics.totalNumberOfRelationships); - assertEquals(2, statistics.builtRelationships); - - /* - * Testing built source db schema - */ - - Entity parentEntity = mapper.getDataBaseSchema().getEntityByName("PARENT_PERSON"); - Entity foreignEntity = mapper.getDataBaseSchema().getEntityByName("FOREIGN_ARTICLE"); - - // entities check - assertEquals(2, mapper.getDataBaseSchema().getEntities().size()); - assertEquals(2, mapper.getDataBaseSchema().getCanonicalRelationships().size()); - assertNotNull(parentEntity); - assertNotNull(foreignEntity); - - // attributes check - assertEquals(2, parentEntity.getAttributes().size()); - - assertNotNull(parentEntity.getAttributeByName("PERSON_ID")); - assertEquals("PERSON_ID", parentEntity.getAttributeByName("PERSON_ID").getName()); - assertEquals("VARCHAR", parentEntity.getAttributeByName("PERSON_ID").getDataType()); - assertEquals(1, parentEntity.getAttributeByName("PERSON_ID").getOrdinalPosition()); - assertEquals("PARENT_PERSON", parentEntity.getAttributeByName("PERSON_ID").getBelongingEntity().getName()); - - assertNotNull(parentEntity.getAttributeByName("NAME")); - assertEquals("NAME", parentEntity.getAttributeByName("NAME").getName()); - assertEquals("VARCHAR", parentEntity.getAttributeByName("NAME").getDataType()); - assertEquals(2, parentEntity.getAttributeByName("NAME").getOrdinalPosition()); - assertEquals("PARENT_PERSON", parentEntity.getAttributeByName("NAME").getBelongingEntity().getName()); - - assertEquals(3, foreignEntity.getAttributes().size()); - - assertNotNull(foreignEntity.getAttributeByName("TITLE")); - assertEquals("TITLE", foreignEntity.getAttributeByName("TITLE").getName()); - assertEquals("VARCHAR", foreignEntity.getAttributeByName("TITLE").getDataType()); - assertEquals(1, foreignEntity.getAttributeByName("TITLE").getOrdinalPosition()); - assertEquals("FOREIGN_ARTICLE", foreignEntity.getAttributeByName("TITLE").getBelongingEntity().getName()); - - assertNotNull(foreignEntity.getAttributeByName("AUTHOR")); - assertEquals("AUTHOR", foreignEntity.getAttributeByName("AUTHOR").getName()); - assertEquals("VARCHAR", foreignEntity.getAttributeByName("AUTHOR").getDataType()); - assertEquals(2, foreignEntity.getAttributeByName("AUTHOR").getOrdinalPosition()); - assertEquals("FOREIGN_ARTICLE", foreignEntity.getAttributeByName("AUTHOR").getBelongingEntity().getName()); - - assertNotNull(foreignEntity.getAttributeByName("TRANSLATOR")); - assertEquals("TRANSLATOR", foreignEntity.getAttributeByName("TRANSLATOR").getName()); - assertEquals("VARCHAR", foreignEntity.getAttributeByName("TRANSLATOR").getDataType()); - assertEquals(3, foreignEntity.getAttributeByName("TRANSLATOR").getOrdinalPosition()); - assertEquals("FOREIGN_ARTICLE", foreignEntity.getAttributeByName("TRANSLATOR").getBelongingEntity().getName()); - - // relationship, primary and foreign key check - assertEquals(2, foreignEntity.getOutCanonicalRelationships().size()); - assertEquals(0, parentEntity.getOutCanonicalRelationships().size()); - assertEquals(0, foreignEntity.getInCanonicalRelationships().size()); - assertEquals(2, parentEntity.getInCanonicalRelationships().size()); - assertEquals(0, parentEntity.getForeignKeys().size()); - assertEquals(2, foreignEntity.getForeignKeys().size()); - - // first relationship - Iterator it = foreignEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship currentRelationship = it.next(); - assertEquals("PARENT_PERSON", currentRelationship.getParentEntity().getName()); - assertEquals("FOREIGN_ARTICLE", currentRelationship.getForeignEntity().getName()); - assertEquals(parentEntity.getPrimaryKey(), currentRelationship.getPrimaryKey()); - assertEquals(foreignEntity.getForeignKeys().get(0), currentRelationship.getForeignKey()); - - Iterator it2 = parentEntity.getInCanonicalRelationships().iterator(); - CanonicalRelationship currentRelationship2 = it2.next(); - assertEquals(currentRelationship, currentRelationship2); - - assertEquals("AUTHOR", foreignEntity.getForeignKeys().get(0).getInvolvedAttributes().get(0).getName()); - assertEquals("PERSON_ID", parentEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()); - - // second relationship - currentRelationship = it.next(); - assertEquals("PARENT_PERSON", currentRelationship.getParentEntity().getName()); - assertEquals("FOREIGN_ARTICLE", currentRelationship.getForeignEntity().getName()); - assertEquals(parentEntity.getPrimaryKey(), currentRelationship.getPrimaryKey()); - assertEquals(foreignEntity.getForeignKeys().get(1), currentRelationship.getForeignKey()); - - currentRelationship2 = it2.next(); - assertEquals(currentRelationship, currentRelationship2); - - assertEquals("TRANSLATOR", foreignEntity.getForeignKeys().get(1).getInvolvedAttributes().get(0).getName()); - assertEquals("PERSON_ID", parentEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()); - - assertFalse(it.hasNext()); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } finally { - try { - // Dropping Source DB Schema and OrientGraph - String dbDropping = "drop schema public cascade"; - st.execute(dbDropping); - connection.close(); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } - } + } + + /* + * Two Foreign tables and one Parent with a simple primary key imported twice from the parent table. + */ + + @Test + void buildSourceSchemaFromThreeTablesWithOneSimplePKImportedTwice() { + Connection connection = null; + Statement st = null; + + try { + Class.forName(this.driver); + connection = DriverManager.getConnection(this.jurl, this.username, this.password); + + String parentTableBuilding = + "create memory table PARENT_PERSON (PERSON_ID varchar(256) not null," + + " NAME varchar(256) not null, primary key (PERSON_ID))"; + st = connection.createStatement(); + st.execute(parentTableBuilding); + + String foreignTableBuilding = + "create memory table FOREIGN_ARTICLE (TITLE varchar(256), AUTHOR varchar(256) not null," + + " TRANSLATOR varchar(256) not null, primary key (TITLE), foreign key (AUTHOR)" + + " references PARENT_PERSON(PERSON_ID), foreign key (TRANSLATOR) references" + + " PARENT_PERSON(PERSON_ID))"; + st.execute(foreignTableBuilding); + + mapper.buildSourceDatabaseSchema(); + + /* + * Testing context information + */ + + assertThat(statistics.totalNumberOfEntities).isEqualTo(2); + assertThat(statistics.builtEntities).isEqualTo(2); + assertThat(statistics.totalNumberOfRelationships).isEqualTo(2); + assertThat(statistics.builtRelationships).isEqualTo(2); + + /* + * Testing built source db schema + */ + + Entity parentEntity = mapper.getDataBaseSchema().getEntityByName("PARENT_PERSON"); + Entity foreignEntity = mapper.getDataBaseSchema().getEntityByName("FOREIGN_ARTICLE"); + + // entities check + assertThat(mapper.getDataBaseSchema().getEntities().size()).isEqualTo(2); + assertThat(mapper.getDataBaseSchema().getCanonicalRelationships().size()).isEqualTo(2); + assertThat(parentEntity).isNotNull(); + assertThat(foreignEntity).isNotNull(); + + // attributes check + assertThat(parentEntity.getAttributes().size()).isEqualTo(2); + + assertThat(parentEntity.getAttributeByName("PERSON_ID")).isNotNull(); + assertThat(parentEntity.getAttributeByName("PERSON_ID").getName()).isEqualTo("PERSON_ID"); + assertThat(parentEntity.getAttributeByName("PERSON_ID").getDataType()).isEqualTo("VARCHAR"); + assertThat(parentEntity.getAttributeByName("PERSON_ID").getOrdinalPosition()).isEqualTo(1); + assertThat(parentEntity.getAttributeByName("PERSON_ID").getBelongingEntity().getName()) + .isEqualTo("PARENT_PERSON"); + + assertThat(parentEntity.getAttributeByName("NAME")).isNotNull(); + assertThat(parentEntity.getAttributeByName("NAME").getName()).isEqualTo("NAME"); + assertThat(parentEntity.getAttributeByName("NAME").getDataType()).isEqualTo("VARCHAR"); + assertThat(parentEntity.getAttributeByName("NAME").getOrdinalPosition()).isEqualTo(2); + assertThat(parentEntity.getAttributeByName("NAME").getBelongingEntity().getName()) + .isEqualTo("PARENT_PERSON"); + + assertThat(foreignEntity.getAttributes().size()).isEqualTo(3); + + assertThat(foreignEntity.getAttributeByName("TITLE")).isNotNull(); + assertThat(foreignEntity.getAttributeByName("TITLE").getName()).isEqualTo("TITLE"); + assertThat(foreignEntity.getAttributeByName("TITLE").getDataType()).isEqualTo("VARCHAR"); + assertThat(foreignEntity.getAttributeByName("TITLE").getOrdinalPosition()).isEqualTo(1); + assertThat(foreignEntity.getAttributeByName("TITLE").getBelongingEntity().getName()) + .isEqualTo("FOREIGN_ARTICLE"); + + assertThat(foreignEntity.getAttributeByName("AUTHOR")).isNotNull(); + assertThat(foreignEntity.getAttributeByName("AUTHOR").getName()).isEqualTo("AUTHOR"); + assertThat(foreignEntity.getAttributeByName("AUTHOR").getDataType()).isEqualTo("VARCHAR"); + assertThat(foreignEntity.getAttributeByName("AUTHOR").getOrdinalPosition()).isEqualTo(2); + assertThat(foreignEntity.getAttributeByName("AUTHOR").getBelongingEntity().getName()) + .isEqualTo("FOREIGN_ARTICLE"); + + assertThat(foreignEntity.getAttributeByName("TRANSLATOR")).isNotNull(); + assertThat(foreignEntity.getAttributeByName("TRANSLATOR").getName()).isEqualTo("TRANSLATOR"); + assertThat(foreignEntity.getAttributeByName("TRANSLATOR").getDataType()).isEqualTo("VARCHAR"); + assertThat(foreignEntity.getAttributeByName("TRANSLATOR").getOrdinalPosition()).isEqualTo(3); + assertThat(foreignEntity.getAttributeByName("TRANSLATOR").getBelongingEntity().getName()) + .isEqualTo("FOREIGN_ARTICLE"); + + // relationship, primary and foreign key check + assertThat(foreignEntity.getOutCanonicalRelationships().size()).isEqualTo(2); + assertThat(parentEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(foreignEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(parentEntity.getInCanonicalRelationships().size()).isEqualTo(2); + assertThat(parentEntity.getForeignKeys().size()).isEqualTo(0); + assertThat(foreignEntity.getForeignKeys().size()).isEqualTo(2); + + // first relationship + Iterator it = foreignEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship currentRelationship = it.next(); + assertThat(currentRelationship.getParentEntity().getName()).isEqualTo("PARENT_PERSON"); + assertThat(currentRelationship.getForeignEntity().getName()).isEqualTo("FOREIGN_ARTICLE"); + assertThat(currentRelationship.getPrimaryKey()).isEqualTo(parentEntity.getPrimaryKey()); + assertThat(currentRelationship.getForeignKey()) + .isEqualTo(foreignEntity.getForeignKeys().get(0)); + + Iterator it2 = parentEntity.getInCanonicalRelationships().iterator(); + CanonicalRelationship currentRelationship2 = it2.next(); + assertThat(currentRelationship2).isEqualTo(currentRelationship); + + assertThat(foreignEntity.getForeignKeys().get(0).getInvolvedAttributes().get(0).getName()) + .isEqualTo("AUTHOR"); + assertThat(parentEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()) + .isEqualTo("PERSON_ID"); + + // second relationship + currentRelationship = it.next(); + assertThat(currentRelationship.getParentEntity().getName()).isEqualTo("PARENT_PERSON"); + assertThat(currentRelationship.getForeignEntity().getName()).isEqualTo("FOREIGN_ARTICLE"); + assertThat(currentRelationship.getPrimaryKey()).isEqualTo(parentEntity.getPrimaryKey()); + assertThat(currentRelationship.getForeignKey()) + .isEqualTo(foreignEntity.getForeignKeys().get(1)); + + currentRelationship2 = it2.next(); + assertThat(currentRelationship2).isEqualTo(currentRelationship); + + assertThat(foreignEntity.getForeignKeys().get(1).getInvolvedAttributes().get(0).getName()) + .isEqualTo("TRANSLATOR"); + assertThat(parentEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()) + .isEqualTo("PERSON_ID"); + + assertThat(it.hasNext()).isFalse(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } finally { + try { + // Dropping Source DB Schema and OrientGraph + String dbDropping = "drop schema public cascade"; + st.execute(dbDropping); + connection.close(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } } - - @Test - /* - * Two Foreign tables and one Parent with a composite primary key imported twice from the parent table. - */ - - public void buildSourceSchemaFromThreeTablesWithOneCompositePKImportedTwice() { - Connection connection = null; - Statement st = null; - - try { - Class.forName(this.driver); - connection = DriverManager.getConnection(this.jurl, this.username, this.password); - - String parentTableBuilding = - "create memory table PARENT_PERSON (NAME varchar(256) not null," + " SURNAME varchar(256) not null, primary key (NAME,SURNAME))"; - st = connection.createStatement(); - st.execute(parentTableBuilding); - - String foreignTableBuilding = - "create memory table FOREIGN_ARTICLE (TITLE varchar(256)," + - " AUTHOR_NAME varchar(256) not null, AUTHOR_SURNAME varchar(256) not null, TRANSLATOR_NAME varchar(256) not null," + - " TRANSLATOR_SURNAME varchar(256) not null, primary key (TITLE)," + - " foreign key (AUTHOR_NAME,AUTHOR_SURNAME) references PARENT_PERSON(NAME,SURNAME)," + - " foreign key (TRANSLATOR_NAME,TRANSLATOR_SURNAME) references PARENT_PERSON(NAME,SURNAME))"; - st.execute(foreignTableBuilding); - - mapper.buildSourceDatabaseSchema(); - - /* - * Testing context information - */ - - assertEquals(2, statistics.totalNumberOfEntities); - assertEquals(2, statistics.builtEntities); - assertEquals(2, statistics.totalNumberOfRelationships); - assertEquals(2, statistics.builtRelationships); - - /* - * Testing built source db schema - */ - - Entity parentEntity = mapper.getDataBaseSchema().getEntityByName("PARENT_PERSON"); - Entity foreignEntity = mapper.getDataBaseSchema().getEntityByName("FOREIGN_ARTICLE"); - - // entities check - assertEquals(2, mapper.getDataBaseSchema().getEntities().size()); - assertEquals(2, mapper.getDataBaseSchema().getCanonicalRelationships().size()); - assertNotNull(parentEntity); - assertNotNull(foreignEntity); - - // attributes check - assertEquals(2, parentEntity.getAttributes().size()); - - assertNotNull(parentEntity.getAttributeByName("NAME")); - assertEquals("NAME", parentEntity.getAttributeByName("NAME").getName()); - assertEquals("VARCHAR", parentEntity.getAttributeByName("NAME").getDataType()); - assertEquals(1, parentEntity.getAttributeByName("NAME").getOrdinalPosition()); - assertEquals("PARENT_PERSON", parentEntity.getAttributeByName("NAME").getBelongingEntity().getName()); - - assertNotNull(parentEntity.getAttributeByName("SURNAME")); - assertEquals("SURNAME", parentEntity.getAttributeByName("SURNAME").getName()); - assertEquals("VARCHAR", parentEntity.getAttributeByName("SURNAME").getDataType()); - assertEquals(2, parentEntity.getAttributeByName("SURNAME").getOrdinalPosition()); - assertEquals("PARENT_PERSON", parentEntity.getAttributeByName("SURNAME").getBelongingEntity().getName()); - - assertEquals(5, foreignEntity.getAttributes().size()); - - assertNotNull(foreignEntity.getAttributeByName("TITLE")); - assertEquals("TITLE", foreignEntity.getAttributeByName("TITLE").getName()); - assertEquals("VARCHAR", foreignEntity.getAttributeByName("TITLE").getDataType()); - assertEquals(1, foreignEntity.getAttributeByName("TITLE").getOrdinalPosition()); - assertEquals("FOREIGN_ARTICLE", foreignEntity.getAttributeByName("TITLE").getBelongingEntity().getName()); - - assertNotNull(foreignEntity.getAttributeByName("AUTHOR_NAME")); - assertEquals("AUTHOR_NAME", foreignEntity.getAttributeByName("AUTHOR_NAME").getName()); - assertEquals("VARCHAR", foreignEntity.getAttributeByName("AUTHOR_NAME").getDataType()); - assertEquals(2, foreignEntity.getAttributeByName("AUTHOR_NAME").getOrdinalPosition()); - assertEquals("FOREIGN_ARTICLE", foreignEntity.getAttributeByName("AUTHOR_NAME").getBelongingEntity().getName()); - - assertNotNull(foreignEntity.getAttributeByName("AUTHOR_SURNAME")); - assertEquals("AUTHOR_SURNAME", foreignEntity.getAttributeByName("AUTHOR_SURNAME").getName()); - assertEquals("VARCHAR", foreignEntity.getAttributeByName("AUTHOR_SURNAME").getDataType()); - assertEquals(3, foreignEntity.getAttributeByName("AUTHOR_SURNAME").getOrdinalPosition()); - assertEquals("FOREIGN_ARTICLE", foreignEntity.getAttributeByName("AUTHOR_SURNAME").getBelongingEntity().getName()); - - assertNotNull(foreignEntity.getAttributeByName("TRANSLATOR_NAME")); - assertEquals("TRANSLATOR_NAME", foreignEntity.getAttributeByName("TRANSLATOR_NAME").getName()); - assertEquals("VARCHAR", foreignEntity.getAttributeByName("TRANSLATOR_NAME").getDataType()); - assertEquals(4, foreignEntity.getAttributeByName("TRANSLATOR_NAME").getOrdinalPosition()); - assertEquals("FOREIGN_ARTICLE", foreignEntity.getAttributeByName("TRANSLATOR_NAME").getBelongingEntity().getName()); - - assertNotNull(foreignEntity.getAttributeByName("TRANSLATOR_SURNAME")); - assertEquals("TRANSLATOR_SURNAME", foreignEntity.getAttributeByName("TRANSLATOR_SURNAME").getName()); - assertEquals("VARCHAR", foreignEntity.getAttributeByName("TRANSLATOR_SURNAME").getDataType()); - assertEquals(5, foreignEntity.getAttributeByName("TRANSLATOR_SURNAME").getOrdinalPosition()); - assertEquals("FOREIGN_ARTICLE", foreignEntity.getAttributeByName("TRANSLATOR_SURNAME").getBelongingEntity().getName()); - - // relationship, primary and foreign key check - assertEquals(2, foreignEntity.getOutCanonicalRelationships().size()); - assertEquals(0, parentEntity.getOutCanonicalRelationships().size()); - assertEquals(0, foreignEntity.getInCanonicalRelationships().size()); - assertEquals(2, parentEntity.getInCanonicalRelationships().size()); - assertEquals(0, parentEntity.getForeignKeys().size()); - assertEquals(2, foreignEntity.getForeignKeys().size()); - - // first relationship - Iterator it = foreignEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship currentRelationship = it.next(); - assertEquals("PARENT_PERSON", currentRelationship.getParentEntity().getName()); - assertEquals("FOREIGN_ARTICLE", currentRelationship.getForeignEntity().getName()); - assertEquals(parentEntity.getPrimaryKey(), currentRelationship.getPrimaryKey()); - assertEquals(foreignEntity.getForeignKeys().get(0), currentRelationship.getForeignKey()); - - Iterator it2 = parentEntity.getInCanonicalRelationships().iterator(); - CanonicalRelationship currentRelationship2 = it2.next(); - assertEquals(currentRelationship, currentRelationship2); - - assertEquals("AUTHOR_NAME", foreignEntity.getForeignKeys().get(0).getInvolvedAttributes().get(0).getName()); - assertEquals("AUTHOR_SURNAME", foreignEntity.getForeignKeys().get(0).getInvolvedAttributes().get(1).getName()); - assertEquals("NAME", parentEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()); - assertEquals("SURNAME", parentEntity.getPrimaryKey().getInvolvedAttributes().get(1).getName()); - - // second relationship - currentRelationship = it.next(); - assertEquals("PARENT_PERSON", currentRelationship.getParentEntity().getName()); - assertEquals("FOREIGN_ARTICLE", currentRelationship.getForeignEntity().getName()); - assertEquals(parentEntity.getPrimaryKey(), currentRelationship.getPrimaryKey()); - assertEquals(foreignEntity.getForeignKeys().get(1), currentRelationship.getForeignKey()); - assertFalse(it.hasNext()); - - currentRelationship2 = it2.next(); - assertEquals(currentRelationship, currentRelationship2); - - assertEquals("TRANSLATOR_NAME", foreignEntity.getForeignKeys().get(1).getInvolvedAttributes().get(0).getName()); - assertEquals("TRANSLATOR_SURNAME", foreignEntity.getForeignKeys().get(1).getInvolvedAttributes().get(1).getName()); - assertEquals("NAME", parentEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()); - assertEquals("SURNAME", parentEntity.getPrimaryKey().getInvolvedAttributes().get(1).getName()); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } finally { - try { - // Dropping Source DB Schema and OrientGraph - String dbDropping = "drop schema public cascade"; - st.execute(dbDropping); - connection.close(); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } - } + } + + /* + * Two Foreign tables and one Parent with a composite primary key imported twice from the parent table. + */ + + @Test + void buildSourceSchemaFromThreeTablesWithOneCompositePKImportedTwice() { + Connection connection = null; + Statement st = null; + + try { + Class.forName(this.driver); + connection = DriverManager.getConnection(this.jurl, this.username, this.password); + + String parentTableBuilding = + "create memory table PARENT_PERSON (NAME varchar(256) not null," + + " SURNAME varchar(256) not null, primary key (NAME,SURNAME))"; + st = connection.createStatement(); + st.execute(parentTableBuilding); + + String foreignTableBuilding = + "create memory table FOREIGN_ARTICLE (TITLE varchar(256), AUTHOR_NAME varchar(256) not" + + " null, AUTHOR_SURNAME varchar(256) not null, TRANSLATOR_NAME varchar(256) not" + + " null, TRANSLATOR_SURNAME varchar(256) not null, primary key (TITLE), foreign key" + + " (AUTHOR_NAME,AUTHOR_SURNAME) references PARENT_PERSON(NAME,SURNAME), foreign key" + + " (TRANSLATOR_NAME,TRANSLATOR_SURNAME) references PARENT_PERSON(NAME,SURNAME))"; + st.execute(foreignTableBuilding); + + mapper.buildSourceDatabaseSchema(); + + /* + * Testing context information + */ + + assertThat(statistics.totalNumberOfEntities).isEqualTo(2); + assertThat(statistics.builtEntities).isEqualTo(2); + assertThat(statistics.totalNumberOfRelationships).isEqualTo(2); + assertThat(statistics.builtRelationships).isEqualTo(2); + + /* + * Testing built source db schema + */ + + Entity parentEntity = mapper.getDataBaseSchema().getEntityByName("PARENT_PERSON"); + Entity foreignEntity = mapper.getDataBaseSchema().getEntityByName("FOREIGN_ARTICLE"); + + // entities check + assertThat(mapper.getDataBaseSchema().getEntities().size()).isEqualTo(2); + assertThat(mapper.getDataBaseSchema().getCanonicalRelationships().size()).isEqualTo(2); + assertThat(parentEntity).isNotNull(); + assertThat(foreignEntity).isNotNull(); + + // attributes check + assertThat(parentEntity.getAttributes().size()).isEqualTo(2); + + assertThat(parentEntity.getAttributeByName("NAME")).isNotNull(); + assertThat(parentEntity.getAttributeByName("NAME").getName()).isEqualTo("NAME"); + assertThat(parentEntity.getAttributeByName("NAME").getDataType()).isEqualTo("VARCHAR"); + assertThat(parentEntity.getAttributeByName("NAME").getOrdinalPosition()).isEqualTo(1); + assertThat(parentEntity.getAttributeByName("NAME").getBelongingEntity().getName()) + .isEqualTo("PARENT_PERSON"); + + assertThat(parentEntity.getAttributeByName("SURNAME")).isNotNull(); + assertThat(parentEntity.getAttributeByName("SURNAME").getName()).isEqualTo("SURNAME"); + assertThat(parentEntity.getAttributeByName("SURNAME").getDataType()).isEqualTo("VARCHAR"); + assertThat(parentEntity.getAttributeByName("SURNAME").getOrdinalPosition()).isEqualTo(2); + assertThat(parentEntity.getAttributeByName("SURNAME").getBelongingEntity().getName()) + .isEqualTo("PARENT_PERSON"); + + assertThat(foreignEntity.getAttributes().size()).isEqualTo(5); + + assertThat(foreignEntity.getAttributeByName("TITLE")).isNotNull(); + assertThat(foreignEntity.getAttributeByName("TITLE").getName()).isEqualTo("TITLE"); + assertThat(foreignEntity.getAttributeByName("TITLE").getDataType()).isEqualTo("VARCHAR"); + assertThat(foreignEntity.getAttributeByName("TITLE").getOrdinalPosition()).isEqualTo(1); + assertThat(foreignEntity.getAttributeByName("TITLE").getBelongingEntity().getName()) + .isEqualTo("FOREIGN_ARTICLE"); + + assertThat(foreignEntity.getAttributeByName("AUTHOR_NAME")).isNotNull(); + assertThat(foreignEntity.getAttributeByName("AUTHOR_NAME").getName()) + .isEqualTo("AUTHOR_NAME"); + assertThat(foreignEntity.getAttributeByName("AUTHOR_NAME").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(foreignEntity.getAttributeByName("AUTHOR_NAME").getOrdinalPosition()).isEqualTo(2); + assertThat(foreignEntity.getAttributeByName("AUTHOR_NAME").getBelongingEntity().getName()) + .isEqualTo("FOREIGN_ARTICLE"); + + assertThat(foreignEntity.getAttributeByName("AUTHOR_SURNAME")).isNotNull(); + assertThat(foreignEntity.getAttributeByName("AUTHOR_SURNAME").getName()) + .isEqualTo("AUTHOR_SURNAME"); + assertThat(foreignEntity.getAttributeByName("AUTHOR_SURNAME").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(foreignEntity.getAttributeByName("AUTHOR_SURNAME").getOrdinalPosition()) + .isEqualTo(3); + assertThat(foreignEntity.getAttributeByName("AUTHOR_SURNAME").getBelongingEntity().getName()) + .isEqualTo("FOREIGN_ARTICLE"); + + assertThat(foreignEntity.getAttributeByName("TRANSLATOR_NAME")).isNotNull(); + assertThat(foreignEntity.getAttributeByName("TRANSLATOR_NAME").getName()) + .isEqualTo("TRANSLATOR_NAME"); + assertThat(foreignEntity.getAttributeByName("TRANSLATOR_NAME").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(foreignEntity.getAttributeByName("TRANSLATOR_NAME").getOrdinalPosition()) + .isEqualTo(4); + assertThat(foreignEntity.getAttributeByName("TRANSLATOR_NAME").getBelongingEntity().getName()) + .isEqualTo("FOREIGN_ARTICLE"); + + assertThat(foreignEntity.getAttributeByName("TRANSLATOR_SURNAME")).isNotNull(); + assertThat(foreignEntity.getAttributeByName("TRANSLATOR_SURNAME").getName()) + .isEqualTo("TRANSLATOR_SURNAME"); + assertThat(foreignEntity.getAttributeByName("TRANSLATOR_SURNAME").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(foreignEntity.getAttributeByName("TRANSLATOR_SURNAME").getOrdinalPosition()) + .isEqualTo(5); + assertThat( + foreignEntity.getAttributeByName("TRANSLATOR_SURNAME").getBelongingEntity().getName()) + .isEqualTo("FOREIGN_ARTICLE"); + + // relationship, primary and foreign key check + assertThat(foreignEntity.getOutCanonicalRelationships().size()).isEqualTo(2); + assertThat(parentEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(foreignEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(parentEntity.getInCanonicalRelationships().size()).isEqualTo(2); + assertThat(parentEntity.getForeignKeys().size()).isEqualTo(0); + assertThat(foreignEntity.getForeignKeys().size()).isEqualTo(2); + + // first relationship + Iterator it = foreignEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship currentRelationship = it.next(); + assertThat(currentRelationship.getParentEntity().getName()).isEqualTo("PARENT_PERSON"); + assertThat(currentRelationship.getForeignEntity().getName()).isEqualTo("FOREIGN_ARTICLE"); + assertThat(currentRelationship.getPrimaryKey()).isEqualTo(parentEntity.getPrimaryKey()); + assertThat(currentRelationship.getForeignKey()) + .isEqualTo(foreignEntity.getForeignKeys().get(0)); + + Iterator it2 = parentEntity.getInCanonicalRelationships().iterator(); + CanonicalRelationship currentRelationship2 = it2.next(); + assertThat(currentRelationship2).isEqualTo(currentRelationship); + + assertThat(foreignEntity.getForeignKeys().get(0).getInvolvedAttributes().get(0).getName()) + .isEqualTo("AUTHOR_NAME"); + assertThat(foreignEntity.getForeignKeys().get(0).getInvolvedAttributes().get(1).getName()) + .isEqualTo("AUTHOR_SURNAME"); + assertThat(parentEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()) + .isEqualTo("NAME"); + assertThat(parentEntity.getPrimaryKey().getInvolvedAttributes().get(1).getName()) + .isEqualTo("SURNAME"); + + // second relationship + currentRelationship = it.next(); + assertThat(currentRelationship.getParentEntity().getName()).isEqualTo("PARENT_PERSON"); + assertThat(currentRelationship.getForeignEntity().getName()).isEqualTo("FOREIGN_ARTICLE"); + assertThat(currentRelationship.getPrimaryKey()).isEqualTo(parentEntity.getPrimaryKey()); + assertThat(currentRelationship.getForeignKey()) + .isEqualTo(foreignEntity.getForeignKeys().get(1)); + assertThat(it.hasNext()).isFalse(); + + currentRelationship2 = it2.next(); + assertThat(currentRelationship2).isEqualTo(currentRelationship); + + assertThat(foreignEntity.getForeignKeys().get(1).getInvolvedAttributes().get(0).getName()) + .isEqualTo("TRANSLATOR_NAME"); + assertThat(foreignEntity.getForeignKeys().get(1).getInvolvedAttributes().get(1).getName()) + .isEqualTo("TRANSLATOR_SURNAME"); + assertThat(parentEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()) + .isEqualTo("NAME"); + assertThat(parentEntity.getPrimaryKey().getInvolvedAttributes().get(1).getName()) + .isEqualTo("SURNAME"); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } finally { + try { + // Dropping Source DB Schema and OrientGraph + String dbDropping = "drop schema public cascade"; + st.execute(dbDropping); + connection.close(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } } - - @Test - /* - * Two tables: 1 Foreign and 1 Parent (parent has an inner referential integrity). - * The primary key is imported both by the foreign table and from the first attribute of the parent table itself. - */ - - public void buildSourceSchemaFromTwoTablesWithOneSimplePKImportedTwice() { - Connection connection = null; - Statement st = null; - - try { - Class.forName(this.driver); - connection = DriverManager.getConnection(this.jurl, this.username, this.password); - - String parentTableBuilding = - "create memory table PARENT_EMPLOYEE (EMP_ID varchar(256) not null," + - " MGR_ID varchar(256) not null, NAME varchar(256) not null, primary key (EMP_ID), " + - " foreign key (MGR_ID) references PARENT_EMPLOYEE(EMP_ID))"; - st = connection.createStatement(); - st.execute(parentTableBuilding); - - String foreignTableBuilding = - "create memory table FOREIGN_PROJECT (PROJECT_ID varchar(256)," + - " TITLE varchar(256) not null, PROJECT_MANAGER varchar(256) not null, primary key (PROJECT_ID)," + - " foreign key (PROJECT_MANAGER) references PARENT_EMPLOYEE(EMP_ID))"; - st.execute(foreignTableBuilding); - - mapper.buildSourceDatabaseSchema(); - - /* - * Testing context information - */ - - assertEquals(2, statistics.totalNumberOfEntities); - assertEquals(2, statistics.builtEntities); - assertEquals(2, statistics.totalNumberOfRelationships); - assertEquals(2, statistics.builtRelationships); - - /* - * Testing built source db schema - */ - - Entity parentEntity = mapper.getDataBaseSchema().getEntityByName("PARENT_EMPLOYEE"); - Entity foreignEntity = mapper.getDataBaseSchema().getEntityByName("FOREIGN_PROJECT"); - - // entities check - assertEquals(2, mapper.getDataBaseSchema().getEntities().size()); - assertEquals(2, mapper.getDataBaseSchema().getCanonicalRelationships().size()); - assertNotNull(parentEntity); - assertNotNull(foreignEntity); - - // attributes check - assertEquals(3, parentEntity.getAttributes().size()); - - assertNotNull(parentEntity.getAttributeByName("EMP_ID")); - assertEquals("EMP_ID", parentEntity.getAttributeByName("EMP_ID").getName()); - assertEquals("VARCHAR", parentEntity.getAttributeByName("EMP_ID").getDataType()); - assertEquals(1, parentEntity.getAttributeByName("EMP_ID").getOrdinalPosition()); - assertEquals("PARENT_EMPLOYEE", parentEntity.getAttributeByName("EMP_ID").getBelongingEntity().getName()); - - assertNotNull(parentEntity.getAttributeByName("MGR_ID")); - assertEquals("MGR_ID", parentEntity.getAttributeByName("MGR_ID").getName()); - assertEquals("VARCHAR", parentEntity.getAttributeByName("MGR_ID").getDataType()); - assertEquals(2, parentEntity.getAttributeByName("MGR_ID").getOrdinalPosition()); - assertEquals("PARENT_EMPLOYEE", parentEntity.getAttributeByName("MGR_ID").getBelongingEntity().getName()); - - assertNotNull(parentEntity.getAttributeByName("NAME")); - assertEquals("NAME", parentEntity.getAttributeByName("NAME").getName()); - assertEquals("VARCHAR", parentEntity.getAttributeByName("NAME").getDataType()); - assertEquals(3, parentEntity.getAttributeByName("NAME").getOrdinalPosition()); - assertEquals("PARENT_EMPLOYEE", parentEntity.getAttributeByName("NAME").getBelongingEntity().getName()); - - assertEquals(3, foreignEntity.getAttributes().size()); - - assertNotNull(foreignEntity.getAttributeByName("PROJECT_ID")); - assertEquals("PROJECT_ID", foreignEntity.getAttributeByName("PROJECT_ID").getName()); - assertEquals("VARCHAR", foreignEntity.getAttributeByName("PROJECT_ID").getDataType()); - assertEquals(1, foreignEntity.getAttributeByName("PROJECT_ID").getOrdinalPosition()); - assertEquals("FOREIGN_PROJECT", foreignEntity.getAttributeByName("PROJECT_ID").getBelongingEntity().getName()); - - assertNotNull(foreignEntity.getAttributeByName("TITLE")); - assertEquals("TITLE", foreignEntity.getAttributeByName("TITLE").getName()); - assertEquals("VARCHAR", foreignEntity.getAttributeByName("TITLE").getDataType()); - assertEquals(2, foreignEntity.getAttributeByName("TITLE").getOrdinalPosition()); - assertEquals("FOREIGN_PROJECT", foreignEntity.getAttributeByName("TITLE").getBelongingEntity().getName()); - - assertNotNull(foreignEntity.getAttributeByName("PROJECT_MANAGER")); - assertEquals("PROJECT_MANAGER", foreignEntity.getAttributeByName("PROJECT_MANAGER").getName()); - assertEquals("VARCHAR", foreignEntity.getAttributeByName("PROJECT_MANAGER").getDataType()); - assertEquals(3, foreignEntity.getAttributeByName("PROJECT_MANAGER").getOrdinalPosition()); - assertEquals("FOREIGN_PROJECT", foreignEntity.getAttributeByName("PROJECT_MANAGER").getBelongingEntity().getName()); - - // relationship, primary and foreign key check - assertEquals(1, foreignEntity.getOutCanonicalRelationships().size()); - assertEquals(1, parentEntity.getOutCanonicalRelationships().size()); - assertEquals(0, foreignEntity.getInCanonicalRelationships().size()); - assertEquals(2, parentEntity.getInCanonicalRelationships().size()); - assertEquals(1, parentEntity.getForeignKeys().size()); - assertEquals(1, foreignEntity.getForeignKeys().size()); - - // first relationship - Iterator it = foreignEntity.getOutCanonicalRelationships().iterator(); - CanonicalRelationship currentRelationship = it.next(); - assertEquals("PARENT_EMPLOYEE", currentRelationship.getParentEntity().getName()); - assertEquals("FOREIGN_PROJECT", currentRelationship.getForeignEntity().getName()); - assertEquals(parentEntity.getPrimaryKey(), currentRelationship.getPrimaryKey()); - assertEquals(foreignEntity.getForeignKeys().get(0), currentRelationship.getForeignKey()); - - Iterator it2 = parentEntity.getInCanonicalRelationships().iterator(); - CanonicalRelationship currentRelationship2 = it2.next(); - assertEquals(currentRelationship, currentRelationship2); - - assertEquals("PROJECT_MANAGER", foreignEntity.getForeignKeys().get(0).getInvolvedAttributes().get(0).getName()); - assertEquals("EMP_ID", parentEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()); - - // second relationship - it = parentEntity.getOutCanonicalRelationships().iterator(); - currentRelationship = it.next(); - assertEquals("PARENT_EMPLOYEE", currentRelationship.getParentEntity().getName()); - assertEquals("PARENT_EMPLOYEE", currentRelationship.getForeignEntity().getName()); - assertEquals(parentEntity.getPrimaryKey(), currentRelationship.getPrimaryKey()); - assertEquals(parentEntity.getForeignKeys().get(0), currentRelationship.getForeignKey()); - - currentRelationship2 = it2.next(); - assertEquals(currentRelationship, currentRelationship2); - - assertEquals("MGR_ID", parentEntity.getForeignKeys().get(0).getInvolvedAttributes().get(0).getName()); - assertEquals("EMP_ID", parentEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()); - - assertFalse(it.hasNext()); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } finally { - try { - // Dropping Source DB Schema and OrientGraph - String dbDropping = "drop schema public cascade"; - st.execute(dbDropping); - connection.close(); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } - } + } + + /* + * Two tables: 1 Foreign and 1 Parent (parent has an inner referential integrity). + * The primary key is imported both by the foreign table and from the first attribute of the parent table itself. + */ + + @Test + void buildSourceSchemaFromTwoTablesWithOneSimplePKImportedTwice() { + Connection connection = null; + Statement st = null; + + try { + Class.forName(this.driver); + connection = DriverManager.getConnection(this.jurl, this.username, this.password); + + String parentTableBuilding = + "create memory table PARENT_EMPLOYEE (EMP_ID varchar(256) not null," + + " MGR_ID varchar(256) not null, NAME varchar(256) not null, primary key (EMP_ID), " + + " foreign key (MGR_ID) references PARENT_EMPLOYEE(EMP_ID))"; + st = connection.createStatement(); + st.execute(parentTableBuilding); + + String foreignTableBuilding = + "create memory table FOREIGN_PROJECT (PROJECT_ID varchar(256), TITLE varchar(256) not" + + " null, PROJECT_MANAGER varchar(256) not null, primary key (PROJECT_ID), foreign" + + " key (PROJECT_MANAGER) references PARENT_EMPLOYEE(EMP_ID))"; + st.execute(foreignTableBuilding); + + mapper.buildSourceDatabaseSchema(); + + /* + * Testing context information + */ + + assertThat(statistics.totalNumberOfEntities).isEqualTo(2); + assertThat(statistics.builtEntities).isEqualTo(2); + assertThat(statistics.totalNumberOfRelationships).isEqualTo(2); + assertThat(statistics.builtRelationships).isEqualTo(2); + + /* + * Testing built source db schema + */ + + Entity parentEntity = mapper.getDataBaseSchema().getEntityByName("PARENT_EMPLOYEE"); + Entity foreignEntity = mapper.getDataBaseSchema().getEntityByName("FOREIGN_PROJECT"); + + // entities check + assertThat(mapper.getDataBaseSchema().getEntities().size()).isEqualTo(2); + assertThat(mapper.getDataBaseSchema().getCanonicalRelationships().size()).isEqualTo(2); + assertThat(parentEntity).isNotNull(); + assertThat(foreignEntity).isNotNull(); + + // attributes check + assertThat(parentEntity.getAttributes().size()).isEqualTo(3); + + assertThat(parentEntity.getAttributeByName("EMP_ID")).isNotNull(); + assertThat(parentEntity.getAttributeByName("EMP_ID").getName()).isEqualTo("EMP_ID"); + assertThat(parentEntity.getAttributeByName("EMP_ID").getDataType()).isEqualTo("VARCHAR"); + assertThat(parentEntity.getAttributeByName("EMP_ID").getOrdinalPosition()).isEqualTo(1); + assertThat(parentEntity.getAttributeByName("EMP_ID").getBelongingEntity().getName()) + .isEqualTo("PARENT_EMPLOYEE"); + + assertThat(parentEntity.getAttributeByName("MGR_ID")).isNotNull(); + assertThat(parentEntity.getAttributeByName("MGR_ID").getName()).isEqualTo("MGR_ID"); + assertThat(parentEntity.getAttributeByName("MGR_ID").getDataType()).isEqualTo("VARCHAR"); + assertThat(parentEntity.getAttributeByName("MGR_ID").getOrdinalPosition()).isEqualTo(2); + assertThat(parentEntity.getAttributeByName("MGR_ID").getBelongingEntity().getName()) + .isEqualTo("PARENT_EMPLOYEE"); + + assertThat(parentEntity.getAttributeByName("NAME")).isNotNull(); + assertThat(parentEntity.getAttributeByName("NAME").getName()).isEqualTo("NAME"); + assertThat(parentEntity.getAttributeByName("NAME").getDataType()).isEqualTo("VARCHAR"); + assertThat(parentEntity.getAttributeByName("NAME").getOrdinalPosition()).isEqualTo(3); + assertThat(parentEntity.getAttributeByName("NAME").getBelongingEntity().getName()) + .isEqualTo("PARENT_EMPLOYEE"); + + assertThat(foreignEntity.getAttributes().size()).isEqualTo(3); + + assertThat(foreignEntity.getAttributeByName("PROJECT_ID")).isNotNull(); + assertThat(foreignEntity.getAttributeByName("PROJECT_ID").getName()).isEqualTo("PROJECT_ID"); + assertThat(foreignEntity.getAttributeByName("PROJECT_ID").getDataType()).isEqualTo("VARCHAR"); + assertThat(foreignEntity.getAttributeByName("PROJECT_ID").getOrdinalPosition()).isEqualTo(1); + assertThat(foreignEntity.getAttributeByName("PROJECT_ID").getBelongingEntity().getName()) + .isEqualTo("FOREIGN_PROJECT"); + + assertThat(foreignEntity.getAttributeByName("TITLE")).isNotNull(); + assertThat(foreignEntity.getAttributeByName("TITLE").getName()).isEqualTo("TITLE"); + assertThat(foreignEntity.getAttributeByName("TITLE").getDataType()).isEqualTo("VARCHAR"); + assertThat(foreignEntity.getAttributeByName("TITLE").getOrdinalPosition()).isEqualTo(2); + assertThat(foreignEntity.getAttributeByName("TITLE").getBelongingEntity().getName()) + .isEqualTo("FOREIGN_PROJECT"); + + assertThat(foreignEntity.getAttributeByName("PROJECT_MANAGER")).isNotNull(); + assertThat(foreignEntity.getAttributeByName("PROJECT_MANAGER").getName()) + .isEqualTo("PROJECT_MANAGER"); + assertThat(foreignEntity.getAttributeByName("PROJECT_MANAGER").getDataType()) + .isEqualTo("VARCHAR"); + assertThat(foreignEntity.getAttributeByName("PROJECT_MANAGER").getOrdinalPosition()) + .isEqualTo(3); + assertThat(foreignEntity.getAttributeByName("PROJECT_MANAGER").getBelongingEntity().getName()) + .isEqualTo("FOREIGN_PROJECT"); + + // relationship, primary and foreign key check + assertThat(foreignEntity.getOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(parentEntity.getOutCanonicalRelationships().size()).isEqualTo(1); + assertThat(foreignEntity.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(parentEntity.getInCanonicalRelationships().size()).isEqualTo(2); + assertThat(parentEntity.getForeignKeys().size()).isEqualTo(1); + assertThat(foreignEntity.getForeignKeys().size()).isEqualTo(1); + + // first relationship + Iterator it = foreignEntity.getOutCanonicalRelationships().iterator(); + CanonicalRelationship currentRelationship = it.next(); + assertThat(currentRelationship.getParentEntity().getName()).isEqualTo("PARENT_EMPLOYEE"); + assertThat(currentRelationship.getForeignEntity().getName()).isEqualTo("FOREIGN_PROJECT"); + assertThat(currentRelationship.getPrimaryKey()).isEqualTo(parentEntity.getPrimaryKey()); + assertThat(currentRelationship.getForeignKey()) + .isEqualTo(foreignEntity.getForeignKeys().get(0)); + + Iterator it2 = parentEntity.getInCanonicalRelationships().iterator(); + CanonicalRelationship currentRelationship2 = it2.next(); + assertThat(currentRelationship2).isEqualTo(currentRelationship); + + assertThat(foreignEntity.getForeignKeys().get(0).getInvolvedAttributes().get(0).getName()) + .isEqualTo("PROJECT_MANAGER"); + assertThat(parentEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()) + .isEqualTo("EMP_ID"); + + // second relationship + it = parentEntity.getOutCanonicalRelationships().iterator(); + currentRelationship = it.next(); + assertThat(currentRelationship.getParentEntity().getName()).isEqualTo("PARENT_EMPLOYEE"); + assertThat(currentRelationship.getForeignEntity().getName()).isEqualTo("PARENT_EMPLOYEE"); + assertThat(currentRelationship.getPrimaryKey()).isEqualTo(parentEntity.getPrimaryKey()); + assertThat(currentRelationship.getForeignKey()) + .isEqualTo(parentEntity.getForeignKeys().get(0)); + + currentRelationship2 = it2.next(); + assertThat(currentRelationship2).isEqualTo(currentRelationship); + + assertThat(parentEntity.getForeignKeys().get(0).getInvolvedAttributes().get(0).getName()) + .isEqualTo("MGR_ID"); + assertThat(parentEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()) + .isEqualTo("EMP_ID"); + + assertThat(it.hasNext()).isFalse(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } finally { + try { + // Dropping Source DB Schema and OrientGraph + String dbDropping = "drop schema public cascade"; + st.execute(dbDropping); + connection.close(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } } - - @Test - /* - * Join table and 2 parent tables. - */ - - public void buildSourceSchemaFromJoinTableAnd2ParentTables() { - Connection connection = null; - Statement st = null; - - try { - Class.forName(this.driver); - connection = DriverManager.getConnection(this.jurl, this.username, this.password); - - String filmTableBuilding = - "create memory table FILM (ID varchar(256) not null, TITLE varchar(256) not null," + - " YEAR varchar(256) not null, DIRECTOR varchar(256) not null, primary key (ID))"; - st = connection.createStatement(); - st.execute(filmTableBuilding); - - String actorTableBuilding = - "create memory table ACTOR (ID varchar(256) not null, NAME varchar(256) not null," + " SURNAME varchar(256) not null, primary key (ID))"; - st = connection.createStatement(); - st.execute(actorTableBuilding); - - String joinTableBuilding = - "create memory table FILM2ACTOR (FILM_ID varchar(256) not null," + - " ACTOR_ID varchar(256) not null, SALARY varchar(256)," + - " primary key (FILM_ID,ACTOR_ID)," + - " foreign key (FILM_ID) references FILM(ID)," + - " foreign key (ACTOR_ID) references ACTOR(ID))"; - st.execute(joinTableBuilding); - - connection.commit(); - - mapper.buildSourceDatabaseSchema(); - - /* - * Testing context information - */ - - assertEquals(3, statistics.totalNumberOfEntities); - assertEquals(3, statistics.builtEntities); - assertEquals(2, statistics.totalNumberOfRelationships); - assertEquals(2, statistics.builtRelationships); - - /* - * Testing built source db schema - */ - - Entity filmEntity = mapper.getDataBaseSchema().getEntityByName("FILM"); - Entity actorEntity = mapper.getDataBaseSchema().getEntityByName("ACTOR"); - Entity film2actor = mapper.getDataBaseSchema().getEntityByName("FILM2ACTOR"); - - // entities check - assertEquals(3, mapper.getDataBaseSchema().getEntities().size()); - assertEquals(2, mapper.getDataBaseSchema().getCanonicalRelationships().size()); - assertNotNull(filmEntity); - assertNotNull(actorEntity); - assertNotNull(film2actor); - - // attributes check - assertEquals(4, filmEntity.getAttributes().size()); - assertEquals(3, actorEntity.getAttributes().size()); - assertEquals(3, film2actor.getAttributes().size()); - - // relationship, primary and foreign key check - assertEquals(0, filmEntity.getOutCanonicalRelationships().size()); - assertEquals(0, actorEntity.getOutCanonicalRelationships().size()); - assertEquals(2, film2actor.getOutCanonicalRelationships().size()); - assertEquals(1, filmEntity.getInCanonicalRelationships().size()); - assertEquals(1, actorEntity.getInCanonicalRelationships().size()); - assertEquals(0, film2actor.getInCanonicalRelationships().size()); - assertEquals(0, filmEntity.getForeignKeys().size()); - assertEquals(0, actorEntity.getForeignKeys().size()); - assertEquals(2, film2actor.getForeignKeys().size()); - - // first relationship - Iterator it = film2actor.getOutCanonicalRelationships().iterator(); - CanonicalRelationship currentRelationship = it.next(); - assertEquals("ACTOR", currentRelationship.getParentEntity().getName()); - assertEquals("FILM2ACTOR", currentRelationship.getForeignEntity().getName()); - assertEquals(actorEntity.getPrimaryKey(), currentRelationship.getPrimaryKey()); - assertEquals(film2actor.getForeignKeys().get(0), currentRelationship.getForeignKey()); - - Iterator it2 = actorEntity.getInCanonicalRelationships().iterator(); - CanonicalRelationship currentRelationship2 = it2.next(); - assertEquals(currentRelationship, currentRelationship2); - - assertEquals("ACTOR_ID", film2actor.getForeignKeys().get(0).getInvolvedAttributes().get(0).getName()); - assertEquals("ID", actorEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()); - - // second relationship - currentRelationship = it.next(); - assertEquals("FILM", currentRelationship.getParentEntity().getName()); - assertEquals("FILM2ACTOR", currentRelationship.getForeignEntity().getName()); - assertEquals(filmEntity.getPrimaryKey(), currentRelationship.getPrimaryKey()); - assertEquals(film2actor.getForeignKeys().get(1), currentRelationship.getForeignKey()); - - Iterator it3 = filmEntity.getInCanonicalRelationships().iterator(); - CanonicalRelationship currentRelationship3 = it3.next(); - assertEquals(currentRelationship, currentRelationship3); - - assertEquals("FILM_ID", film2actor.getForeignKeys().get(1).getInvolvedAttributes().get(0).getName()); - assertEquals("ID", filmEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()); - - assertFalse(it.hasNext()); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } finally { - try { - // Dropping Source DB Schema and OrientGraph - String dbDropping = "drop schema public cascade"; - st.execute(dbDropping); - connection.close(); - } catch (Exception e) { - e.printStackTrace(); - fail(); - } - } + } + + /* + * Join table and 2 parent tables. + */ + + @Test + void buildSourceSchemaFromJoinTableAnd2ParentTables() { + Connection connection = null; + Statement st = null; + + try { + Class.forName(this.driver); + connection = DriverManager.getConnection(this.jurl, this.username, this.password); + + String filmTableBuilding = + "create memory table FILM (ID varchar(256) not null, TITLE varchar(256) not null," + + " YEAR varchar(256) not null, DIRECTOR varchar(256) not null, primary key (ID))"; + st = connection.createStatement(); + st.execute(filmTableBuilding); + + String actorTableBuilding = + "create memory table ACTOR (ID varchar(256) not null, NAME varchar(256) not null," + + " SURNAME varchar(256) not null, primary key (ID))"; + st = connection.createStatement(); + st.execute(actorTableBuilding); + + String joinTableBuilding = + "create memory table FILM2ACTOR (FILM_ID varchar(256) not null," + + " ACTOR_ID varchar(256) not null, SALARY varchar(256)," + + " primary key (FILM_ID,ACTOR_ID)," + + " foreign key (FILM_ID) references FILM(ID)," + + " foreign key (ACTOR_ID) references ACTOR(ID))"; + st.execute(joinTableBuilding); + + connection.commit(); + + mapper.buildSourceDatabaseSchema(); + + /* + * Testing context information + */ + + assertThat(statistics.totalNumberOfEntities).isEqualTo(3); + assertThat(statistics.builtEntities).isEqualTo(3); + assertThat(statistics.totalNumberOfRelationships).isEqualTo(2); + assertThat(statistics.builtRelationships).isEqualTo(2); + + /* + * Testing built source db schema + */ + + Entity filmEntity = mapper.getDataBaseSchema().getEntityByName("FILM"); + Entity actorEntity = mapper.getDataBaseSchema().getEntityByName("ACTOR"); + Entity film2actor = mapper.getDataBaseSchema().getEntityByName("FILM2ACTOR"); + + // entities check + assertThat(mapper.getDataBaseSchema().getEntities().size()).isEqualTo(3); + assertThat(mapper.getDataBaseSchema().getCanonicalRelationships().size()).isEqualTo(2); + assertThat(filmEntity).isNotNull(); + assertThat(actorEntity).isNotNull(); + assertThat(film2actor).isNotNull(); + + // attributes check + assertThat(filmEntity.getAttributes().size()).isEqualTo(4); + assertThat(actorEntity.getAttributes().size()).isEqualTo(3); + assertThat(film2actor.getAttributes().size()).isEqualTo(3); + + // relationship, primary and foreign key check + assertThat(filmEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(actorEntity.getOutCanonicalRelationships().size()).isEqualTo(0); + assertThat(film2actor.getOutCanonicalRelationships().size()).isEqualTo(2); + assertThat(filmEntity.getInCanonicalRelationships().size()).isEqualTo(1); + assertThat(actorEntity.getInCanonicalRelationships().size()).isEqualTo(1); + assertThat(film2actor.getInCanonicalRelationships().size()).isEqualTo(0); + assertThat(filmEntity.getForeignKeys().size()).isEqualTo(0); + assertThat(actorEntity.getForeignKeys().size()).isEqualTo(0); + assertThat(film2actor.getForeignKeys().size()).isEqualTo(2); + + // first relationship + Iterator it = film2actor.getOutCanonicalRelationships().iterator(); + CanonicalRelationship currentRelationship = it.next(); + assertThat(currentRelationship.getParentEntity().getName()).isEqualTo("ACTOR"); + assertThat(currentRelationship.getForeignEntity().getName()).isEqualTo("FILM2ACTOR"); + assertThat(currentRelationship.getPrimaryKey()).isEqualTo(actorEntity.getPrimaryKey()); + assertThat(currentRelationship.getForeignKey()).isEqualTo(film2actor.getForeignKeys().get(0)); + + Iterator it2 = actorEntity.getInCanonicalRelationships().iterator(); + CanonicalRelationship currentRelationship2 = it2.next(); + assertThat(currentRelationship2).isEqualTo(currentRelationship); + + assertThat(film2actor.getForeignKeys().get(0).getInvolvedAttributes().get(0).getName()) + .isEqualTo("ACTOR_ID"); + assertThat(actorEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()) + .isEqualTo("ID"); + + // second relationship + currentRelationship = it.next(); + assertThat(currentRelationship.getParentEntity().getName()).isEqualTo("FILM"); + assertThat(currentRelationship.getForeignEntity().getName()).isEqualTo("FILM2ACTOR"); + assertThat(currentRelationship.getPrimaryKey()).isEqualTo(filmEntity.getPrimaryKey()); + assertThat(currentRelationship.getForeignKey()).isEqualTo(film2actor.getForeignKeys().get(1)); + + Iterator it3 = filmEntity.getInCanonicalRelationships().iterator(); + CanonicalRelationship currentRelationship3 = it3.next(); + assertThat(currentRelationship3).isEqualTo(currentRelationship); + + assertThat(film2actor.getForeignKeys().get(1).getInvolvedAttributes().get(0).getName()) + .isEqualTo("FILM_ID"); + assertThat(filmEntity.getPrimaryKey().getInvolvedAttributes().get(0).getName()) + .isEqualTo("ID"); + + assertThat(it.hasNext()).isFalse(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } finally { + try { + // Dropping Source DB Schema and OrientGraph + String dbDropping = "drop schema public cascade"; + st.execute(dbDropping); + connection.close(); + } catch (Exception e) { + e.printStackTrace(); + fail(""); + } } + } } diff --git a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/resolver/JavaNameResolverTest.java b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/resolver/JavaNameResolverTest.java index d904a35c..75e16314 100644 --- a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/resolver/JavaNameResolverTest.java +++ b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/resolver/JavaNameResolverTest.java @@ -40,7 +40,7 @@ * #L% */ -import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import com.arcadeanalytics.provider.rdbms.nameresolver.JavaConventionNameResolver; import org.junit.jupiter.api.BeforeEach; @@ -49,238 +49,242 @@ /** * @author Gabriele Ponzi */ - -public class JavaNameResolverTest { - - private JavaConventionNameResolver nameResolver; - - @BeforeEach - public void init() { - this.nameResolver = new JavaConventionNameResolver(); - } - - @Test - /* - * Resolve Vertex Class Name (Java Class Convention) - */ - - public void resolveVertexClassNameWithJavaConvention() { - String candidateName = ""; - String newCandidateName = ""; - - // No white space nor underscore - - candidateName = "testClass"; // NOT acceptable (one or more uppercase char, except the first one) - assertEquals(false, nameResolver.isCompliantToJavaClassConvention(candidateName)); - newCandidateName = nameResolver.resolveVertexName(candidateName); - assertEquals(true, nameResolver.isCompliantToJavaClassConvention(newCandidateName)); - assertEquals("TestClass", newCandidateName); - - candidateName = "Testclass"; // acceptable (one or more uppercase char, the first one included) - assertEquals(true, nameResolver.isCompliantToJavaClassConvention(candidateName)); - - candidateName = "TestClass"; // acceptable (one or more uppercase char, except the first one) - assertEquals(true, nameResolver.isCompliantToJavaClassConvention(candidateName)); - - candidateName = "testclass"; // NOT acceptable (no uppercase chars) - assertEquals(false, nameResolver.isCompliantToJavaClassConvention(candidateName)); - newCandidateName = nameResolver.resolveVertexName(candidateName); - assertEquals(true, nameResolver.isCompliantToJavaClassConvention(newCandidateName)); - assertEquals("Testclass", newCandidateName); - - candidateName = "TESTCLASS"; // NOT acceptable (no lowercase chars) - assertEquals(false, nameResolver.isCompliantToJavaClassConvention(candidateName)); - newCandidateName = nameResolver.resolveVertexName(candidateName); - assertEquals(true, nameResolver.isCompliantToJavaClassConvention(newCandidateName)); - assertEquals("Testclass", newCandidateName); - - // White space - - candidateName = "test Class"; // NOT acceptable - assertEquals(false, nameResolver.isCompliantToJavaClassConvention(candidateName)); - newCandidateName = nameResolver.resolveVertexName(candidateName); - assertEquals(true, nameResolver.isCompliantToJavaClassConvention(newCandidateName)); - assertEquals("TestClass", newCandidateName); - - candidateName = "Test class"; // NOT acceptable - assertEquals(false, nameResolver.isCompliantToJavaClassConvention(candidateName)); - newCandidateName = nameResolver.resolveVertexName(candidateName); - assertEquals(true, nameResolver.isCompliantToJavaClassConvention(newCandidateName)); - assertEquals("TestClass", newCandidateName); - - candidateName = "Test Class"; // NOT acceptable - assertEquals(false, nameResolver.isCompliantToJavaVariableConvention(candidateName)); - newCandidateName = nameResolver.resolveVertexName(candidateName); - assertEquals(true, nameResolver.isCompliantToJavaClassConvention(newCandidateName)); - assertEquals("TestClass", newCandidateName); - - candidateName = "test class"; // NOT acceptable - assertEquals(false, nameResolver.isCompliantToJavaClassConvention(candidateName)); - newCandidateName = nameResolver.resolveVertexName(candidateName); - assertEquals(true, nameResolver.isCompliantToJavaClassConvention(newCandidateName)); - assertEquals("TestClass", newCandidateName); - - candidateName = "TEST CLASS"; // NOT acceptable - assertEquals(false, nameResolver.isCompliantToJavaClassConvention(candidateName)); - newCandidateName = nameResolver.resolveVertexName(candidateName); - assertEquals(true, nameResolver.isCompliantToJavaClassConvention(newCandidateName)); - assertEquals("TestClass", newCandidateName); - - // Underscore - - candidateName = "test_Class"; // NOT acceptable - assertEquals(false, nameResolver.isCompliantToJavaClassConvention(candidateName)); - newCandidateName = nameResolver.resolveVertexName(candidateName); - assertEquals(true, nameResolver.isCompliantToJavaClassConvention(newCandidateName)); - assertEquals("TestClass", newCandidateName); - - candidateName = "Test_class"; // NOT acceptable - assertEquals(false, nameResolver.isCompliantToJavaClassConvention(candidateName)); - newCandidateName = nameResolver.resolveVertexName(candidateName); - assertEquals(true, nameResolver.isCompliantToJavaClassConvention(newCandidateName)); - assertEquals("TestClass", newCandidateName); - - candidateName = "Test_Class"; // NOT acceptable - assertEquals(false, nameResolver.isCompliantToJavaClassConvention(candidateName)); - newCandidateName = nameResolver.resolveVertexName(candidateName); - assertEquals(true, nameResolver.isCompliantToJavaClassConvention(newCandidateName)); - assertEquals("TestClass", newCandidateName); - - candidateName = "test_class"; // NOT acceptable - assertEquals(false, nameResolver.isCompliantToJavaClassConvention(candidateName)); - newCandidateName = nameResolver.resolveVertexName(candidateName); - assertEquals(true, nameResolver.isCompliantToJavaClassConvention(newCandidateName)); - assertEquals("TestClass", newCandidateName); - - candidateName = "TEST_CLASS"; // NOT acceptable - assertEquals(false, nameResolver.isCompliantToJavaClassConvention(candidateName)); - newCandidateName = nameResolver.resolveVertexName(candidateName); - assertEquals(true, nameResolver.isCompliantToJavaClassConvention(newCandidateName)); - assertEquals("TestClass", newCandidateName); - } - - @Test - /* - * Resolve Vertex Class Name (Java Class Convention) - * Test-Fix: Resolver supports names ending with '_'. - */ - - public void resolveVertexClassNameWithJavaConventionNamesEndingWithUnderscore() { - String candidateName = ""; - String newCandidateName = ""; - - // No white space nor underscore - - candidateName = "testClass_"; // NOT acceptable (one or more uppercase char, except the first one) - assertEquals(false, nameResolver.isCompliantToJavaClassConvention(candidateName)); - newCandidateName = nameResolver.toJavaClassConvention(candidateName); - assertEquals(true, nameResolver.isCompliantToJavaClassConvention(newCandidateName)); - assertEquals("TestClass", newCandidateName); - - candidateName = "test_class_"; // NOT acceptable (one or more uppercase char, except the first one) - assertEquals(false, nameResolver.isCompliantToJavaClassConvention(candidateName)); - newCandidateName = nameResolver.toJavaClassConvention(candidateName); - assertEquals(true, nameResolver.isCompliantToJavaClassConvention(newCandidateName)); - assertEquals("TestClass", newCandidateName); - } - - @Test - /* - * Resolve Vertex Property (Java Variable Convention) - */ - - public void resolveVertexPropertyNameWithJavaConvention() { - String candidateName = ""; - String newCandidateName = ""; - - // No white space nor underscore - - candidateName = "testVariable"; // acceptable (one or more uppercase char, except the first one) - assertEquals(true, nameResolver.isCompliantToJavaVariableConvention(candidateName)); - - candidateName = "Testvariable"; // NOT acceptable (one or more uppercase char, the first one included) - assertEquals(false, nameResolver.isCompliantToJavaVariableConvention(candidateName)); - newCandidateName = nameResolver.resolveVertexProperty(candidateName); - assertEquals(true, nameResolver.isCompliantToJavaVariableConvention(newCandidateName)); - assertEquals("testvariable", newCandidateName); - - candidateName = "TestVariable"; // NOT acceptable (one or more uppercase char, except the first one) - assertEquals(false, nameResolver.isCompliantToJavaVariableConvention(candidateName)); - newCandidateName = nameResolver.resolveVertexProperty(candidateName); - assertEquals(true, nameResolver.isCompliantToJavaVariableConvention(newCandidateName)); - assertEquals("testVariable", newCandidateName); - - candidateName = "testvariable"; // acceptable (no uppercase chars) - assertEquals(true, nameResolver.isCompliantToJavaVariableConvention(candidateName)); - - candidateName = "TESTVARIABLE"; // NOT acceptable (no lowercase chars) - assertEquals(false, nameResolver.isCompliantToJavaVariableConvention(candidateName)); - newCandidateName = nameResolver.resolveVertexProperty(candidateName); - assertEquals(true, nameResolver.isCompliantToJavaVariableConvention(newCandidateName)); - assertEquals("testvariable", newCandidateName); - - // White space - - candidateName = "test Variable"; // NOT acceptable - assertEquals(false, nameResolver.isCompliantToJavaVariableConvention(candidateName)); - newCandidateName = nameResolver.resolveVertexProperty(candidateName); - assertEquals(true, nameResolver.isCompliantToJavaVariableConvention(newCandidateName)); - assertEquals("testVariable", newCandidateName); - - candidateName = "Test variable"; // NOT acceptable - assertEquals(false, nameResolver.isCompliantToJavaVariableConvention(candidateName)); - newCandidateName = nameResolver.resolveVertexProperty(candidateName); - assertEquals(true, nameResolver.isCompliantToJavaVariableConvention(newCandidateName)); - assertEquals("testVariable", newCandidateName); - - candidateName = "Test Variable"; // NOT acceptable - assertEquals(false, nameResolver.isCompliantToJavaVariableConvention(candidateName)); - newCandidateName = nameResolver.resolveVertexProperty(candidateName); - assertEquals(true, nameResolver.isCompliantToJavaVariableConvention(newCandidateName)); - assertEquals("testVariable", newCandidateName); - - candidateName = "test variable"; // NOT acceptable - assertEquals(false, nameResolver.isCompliantToJavaVariableConvention(candidateName)); - newCandidateName = nameResolver.resolveVertexProperty(candidateName); - assertEquals(true, nameResolver.isCompliantToJavaVariableConvention(newCandidateName)); - assertEquals("testVariable", newCandidateName); - - candidateName = "TEST VARIABLE"; // NOT acceptable - assertEquals(false, nameResolver.isCompliantToJavaVariableConvention(candidateName)); - newCandidateName = nameResolver.resolveVertexProperty(candidateName); - assertEquals(true, nameResolver.isCompliantToJavaVariableConvention(newCandidateName)); - assertEquals("testVariable", newCandidateName); - - // Underscore - - candidateName = "test_Variable"; // NOT acceptable - assertEquals(false, nameResolver.isCompliantToJavaVariableConvention(candidateName)); - newCandidateName = nameResolver.resolveVertexProperty(candidateName); - assertEquals(true, nameResolver.isCompliantToJavaVariableConvention(newCandidateName)); - assertEquals("testVariable", newCandidateName); - - candidateName = "Test_variable"; // NOT acceptable - assertEquals(false, nameResolver.isCompliantToJavaVariableConvention(candidateName)); - newCandidateName = nameResolver.resolveVertexProperty(candidateName); - assertEquals(true, nameResolver.isCompliantToJavaVariableConvention(newCandidateName)); - assertEquals("testVariable", newCandidateName); - - candidateName = "Test_Variable"; // NOT acceptable - assertEquals(false, nameResolver.isCompliantToJavaVariableConvention(candidateName)); - newCandidateName = nameResolver.resolveVertexProperty(candidateName); - assertEquals(true, nameResolver.isCompliantToJavaVariableConvention(newCandidateName)); - assertEquals("testVariable", newCandidateName); - - candidateName = "test_variable"; // NOT acceptable - assertEquals(false, nameResolver.isCompliantToJavaVariableConvention(candidateName)); - newCandidateName = nameResolver.resolveVertexProperty(candidateName); - assertEquals(true, nameResolver.isCompliantToJavaVariableConvention(newCandidateName)); - assertEquals("testVariable", newCandidateName); - - candidateName = "TEST_VARIABLE"; // NOT acceptable - assertEquals(false, nameResolver.isCompliantToJavaVariableConvention(candidateName)); - newCandidateName = nameResolver.resolveVertexProperty(candidateName); - assertEquals(true, nameResolver.isCompliantToJavaVariableConvention(newCandidateName)); - assertEquals("testVariable", newCandidateName); - } +class JavaNameResolverTest { + + private JavaConventionNameResolver nameResolver; + + @BeforeEach + void init() { + this.nameResolver = new JavaConventionNameResolver(); + } + + /* + * Resolve Vertex Class Name (Java Class Convention) + */ + + @Test + void resolveVertexClassNameWithJavaConvention() { + String candidateName = ""; + String newCandidateName = ""; + + // No white space nor underscore + + candidateName = + "testClass"; // NOT acceptable (one or more uppercase char, except the first one) + assertThat(nameResolver.isCompliantToJavaClassConvention(candidateName)).isFalse(); + newCandidateName = nameResolver.resolveVertexName(candidateName); + assertThat(nameResolver.isCompliantToJavaClassConvention(newCandidateName)).isTrue(); + assertThat(newCandidateName).isEqualTo("TestClass"); + + candidateName = "Testclass"; // acceptable (one or more uppercase char, the first one included) + assertThat(nameResolver.isCompliantToJavaClassConvention(candidateName)).isTrue(); + + candidateName = "TestClass"; // acceptable (one or more uppercase char, except the first one) + assertThat(nameResolver.isCompliantToJavaClassConvention(candidateName)).isTrue(); + + candidateName = "testclass"; // NOT acceptable (no uppercase chars) + assertThat(nameResolver.isCompliantToJavaClassConvention(candidateName)).isFalse(); + newCandidateName = nameResolver.resolveVertexName(candidateName); + assertThat(nameResolver.isCompliantToJavaClassConvention(newCandidateName)).isTrue(); + assertThat(newCandidateName).isEqualTo("Testclass"); + + candidateName = "TESTCLASS"; // NOT acceptable (no lowercase chars) + assertThat(nameResolver.isCompliantToJavaClassConvention(candidateName)).isFalse(); + newCandidateName = nameResolver.resolveVertexName(candidateName); + assertThat(nameResolver.isCompliantToJavaClassConvention(newCandidateName)).isTrue(); + assertThat(newCandidateName).isEqualTo("Testclass"); + + // White space + + candidateName = "test Class"; // NOT acceptable + assertThat(nameResolver.isCompliantToJavaClassConvention(candidateName)).isFalse(); + newCandidateName = nameResolver.resolveVertexName(candidateName); + assertThat(nameResolver.isCompliantToJavaClassConvention(newCandidateName)).isTrue(); + assertThat(newCandidateName).isEqualTo("TestClass"); + + candidateName = "Test class"; // NOT acceptable + assertThat(nameResolver.isCompliantToJavaClassConvention(candidateName)).isFalse(); + newCandidateName = nameResolver.resolveVertexName(candidateName); + assertThat(nameResolver.isCompliantToJavaClassConvention(newCandidateName)).isTrue(); + assertThat(newCandidateName).isEqualTo("TestClass"); + + candidateName = "Test Class"; // NOT acceptable + assertThat(nameResolver.isCompliantToJavaVariableConvention(candidateName)).isFalse(); + newCandidateName = nameResolver.resolveVertexName(candidateName); + assertThat(nameResolver.isCompliantToJavaClassConvention(newCandidateName)).isTrue(); + assertThat(newCandidateName).isEqualTo("TestClass"); + + candidateName = "test class"; // NOT acceptable + assertThat(nameResolver.isCompliantToJavaClassConvention(candidateName)).isFalse(); + newCandidateName = nameResolver.resolveVertexName(candidateName); + assertThat(nameResolver.isCompliantToJavaClassConvention(newCandidateName)).isTrue(); + assertThat(newCandidateName).isEqualTo("TestClass"); + + candidateName = "TEST CLASS"; // NOT acceptable + assertThat(nameResolver.isCompliantToJavaClassConvention(candidateName)).isFalse(); + newCandidateName = nameResolver.resolveVertexName(candidateName); + assertThat(nameResolver.isCompliantToJavaClassConvention(newCandidateName)).isTrue(); + assertThat(newCandidateName).isEqualTo("TestClass"); + + // Underscore + + candidateName = "test_Class"; // NOT acceptable + assertThat(nameResolver.isCompliantToJavaClassConvention(candidateName)).isFalse(); + newCandidateName = nameResolver.resolveVertexName(candidateName); + assertThat(nameResolver.isCompliantToJavaClassConvention(newCandidateName)).isTrue(); + assertThat(newCandidateName).isEqualTo("TestClass"); + + candidateName = "Test_class"; // NOT acceptable + assertThat(nameResolver.isCompliantToJavaClassConvention(candidateName)).isFalse(); + newCandidateName = nameResolver.resolveVertexName(candidateName); + assertThat(nameResolver.isCompliantToJavaClassConvention(newCandidateName)).isTrue(); + assertThat(newCandidateName).isEqualTo("TestClass"); + + candidateName = "Test_Class"; // NOT acceptable + assertThat(nameResolver.isCompliantToJavaClassConvention(candidateName)).isFalse(); + newCandidateName = nameResolver.resolveVertexName(candidateName); + assertThat(nameResolver.isCompliantToJavaClassConvention(newCandidateName)).isTrue(); + assertThat(newCandidateName).isEqualTo("TestClass"); + + candidateName = "test_class"; // NOT acceptable + assertThat(nameResolver.isCompliantToJavaClassConvention(candidateName)).isFalse(); + newCandidateName = nameResolver.resolveVertexName(candidateName); + assertThat(nameResolver.isCompliantToJavaClassConvention(newCandidateName)).isTrue(); + assertThat(newCandidateName).isEqualTo("TestClass"); + + candidateName = "TEST_CLASS"; // NOT acceptable + assertThat(nameResolver.isCompliantToJavaClassConvention(candidateName)).isFalse(); + newCandidateName = nameResolver.resolveVertexName(candidateName); + assertThat(nameResolver.isCompliantToJavaClassConvention(newCandidateName)).isTrue(); + assertThat(newCandidateName).isEqualTo("TestClass"); + } + + /* + * Resolve Vertex Class Name (Java Class Convention) + * Test-Fix: Resolver supports names ending with '_'. + */ + + @Test + void resolveVertexClassNameWithJavaConventionNamesEndingWithUnderscore() { + String candidateName = ""; + String newCandidateName = ""; + + // No white space nor underscore + + candidateName = + "testClass_"; // NOT acceptable (one or more uppercase char, except the first one) + assertThat(nameResolver.isCompliantToJavaClassConvention(candidateName)).isFalse(); + newCandidateName = nameResolver.toJavaClassConvention(candidateName); + assertThat(nameResolver.isCompliantToJavaClassConvention(newCandidateName)).isTrue(); + assertThat(newCandidateName).isEqualTo("TestClass"); + + candidateName = + "test_class_"; // NOT acceptable (one or more uppercase char, except the first one) + assertThat(nameResolver.isCompliantToJavaClassConvention(candidateName)).isFalse(); + newCandidateName = nameResolver.toJavaClassConvention(candidateName); + assertThat(nameResolver.isCompliantToJavaClassConvention(newCandidateName)).isTrue(); + assertThat(newCandidateName).isEqualTo("TestClass"); + } + + /* + * Resolve Vertex Property (Java Variable Convention) + */ + + @Test + void resolveVertexPropertyNameWithJavaConvention() { + String candidateName = ""; + String newCandidateName = ""; + + // No white space nor underscore + + candidateName = "testVariable"; // acceptable (one or more uppercase char, except the first one) + assertThat(nameResolver.isCompliantToJavaVariableConvention(candidateName)).isTrue(); + + candidateName = + "Testvariable"; // NOT acceptable (one or more uppercase char, the first one included) + assertThat(nameResolver.isCompliantToJavaVariableConvention(candidateName)).isFalse(); + newCandidateName = nameResolver.resolveVertexProperty(candidateName); + assertThat(nameResolver.isCompliantToJavaVariableConvention(newCandidateName)).isTrue(); + assertThat(newCandidateName).isEqualTo("testvariable"); + + candidateName = + "TestVariable"; // NOT acceptable (one or more uppercase char, except the first one) + assertThat(nameResolver.isCompliantToJavaVariableConvention(candidateName)).isFalse(); + newCandidateName = nameResolver.resolveVertexProperty(candidateName); + assertThat(nameResolver.isCompliantToJavaVariableConvention(newCandidateName)).isTrue(); + assertThat(newCandidateName).isEqualTo("testVariable"); + + candidateName = "testvariable"; // acceptable (no uppercase chars) + assertThat(nameResolver.isCompliantToJavaVariableConvention(candidateName)).isTrue(); + + candidateName = "TESTVARIABLE"; // NOT acceptable (no lowercase chars) + assertThat(nameResolver.isCompliantToJavaVariableConvention(candidateName)).isFalse(); + newCandidateName = nameResolver.resolveVertexProperty(candidateName); + assertThat(nameResolver.isCompliantToJavaVariableConvention(newCandidateName)).isTrue(); + assertThat(newCandidateName).isEqualTo("testvariable"); + + // White space + + candidateName = "test Variable"; // NOT acceptable + assertThat(nameResolver.isCompliantToJavaVariableConvention(candidateName)).isFalse(); + newCandidateName = nameResolver.resolveVertexProperty(candidateName); + assertThat(nameResolver.isCompliantToJavaVariableConvention(newCandidateName)).isTrue(); + assertThat(newCandidateName).isEqualTo("testVariable"); + + candidateName = "Test variable"; // NOT acceptable + assertThat(nameResolver.isCompliantToJavaVariableConvention(candidateName)).isFalse(); + newCandidateName = nameResolver.resolveVertexProperty(candidateName); + assertThat(nameResolver.isCompliantToJavaVariableConvention(newCandidateName)).isTrue(); + assertThat(newCandidateName).isEqualTo("testVariable"); + + candidateName = "Test Variable"; // NOT acceptable + assertThat(nameResolver.isCompliantToJavaVariableConvention(candidateName)).isFalse(); + newCandidateName = nameResolver.resolveVertexProperty(candidateName); + assertThat(nameResolver.isCompliantToJavaVariableConvention(newCandidateName)).isTrue(); + assertThat(newCandidateName).isEqualTo("testVariable"); + + candidateName = "test variable"; // NOT acceptable + assertThat(nameResolver.isCompliantToJavaVariableConvention(candidateName)).isFalse(); + newCandidateName = nameResolver.resolveVertexProperty(candidateName); + assertThat(nameResolver.isCompliantToJavaVariableConvention(newCandidateName)).isTrue(); + assertThat(newCandidateName).isEqualTo("testVariable"); + + candidateName = "TEST VARIABLE"; // NOT acceptable + assertThat(nameResolver.isCompliantToJavaVariableConvention(candidateName)).isFalse(); + newCandidateName = nameResolver.resolveVertexProperty(candidateName); + assertThat(nameResolver.isCompliantToJavaVariableConvention(newCandidateName)).isTrue(); + assertThat(newCandidateName).isEqualTo("testVariable"); + + // Underscore + + candidateName = "test_Variable"; // NOT acceptable + assertThat(nameResolver.isCompliantToJavaVariableConvention(candidateName)).isFalse(); + newCandidateName = nameResolver.resolveVertexProperty(candidateName); + assertThat(nameResolver.isCompliantToJavaVariableConvention(newCandidateName)).isTrue(); + assertThat(newCandidateName).isEqualTo("testVariable"); + + candidateName = "Test_variable"; // NOT acceptable + assertThat(nameResolver.isCompliantToJavaVariableConvention(candidateName)).isFalse(); + newCandidateName = nameResolver.resolveVertexProperty(candidateName); + assertThat(nameResolver.isCompliantToJavaVariableConvention(newCandidateName)).isTrue(); + assertThat(newCandidateName).isEqualTo("testVariable"); + + candidateName = "Test_Variable"; // NOT acceptable + assertThat(nameResolver.isCompliantToJavaVariableConvention(candidateName)).isFalse(); + newCandidateName = nameResolver.resolveVertexProperty(candidateName); + assertThat(nameResolver.isCompliantToJavaVariableConvention(newCandidateName)).isTrue(); + assertThat(newCandidateName).isEqualTo("testVariable"); + + candidateName = "test_variable"; // NOT acceptable + assertThat(nameResolver.isCompliantToJavaVariableConvention(candidateName)).isFalse(); + newCandidateName = nameResolver.resolveVertexProperty(candidateName); + assertThat(nameResolver.isCompliantToJavaVariableConvention(newCandidateName)).isTrue(); + assertThat(newCandidateName).isEqualTo("testVariable"); + + candidateName = "TEST_VARIABLE"; // NOT acceptable + assertThat(nameResolver.isCompliantToJavaVariableConvention(candidateName)).isFalse(); + newCandidateName = nameResolver.resolveVertexProperty(candidateName); + assertThat(nameResolver.isCompliantToJavaVariableConvention(newCandidateName)).isTrue(); + assertThat(newCandidateName).isEqualTo("testVariable"); + } } diff --git a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/resolver/OriginalNameResolverTest.java b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/resolver/OriginalNameResolverTest.java index 38734525..1549445e 100644 --- a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/resolver/OriginalNameResolverTest.java +++ b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/resolver/OriginalNameResolverTest.java @@ -40,7 +40,7 @@ * #L% */ -import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import com.arcadeanalytics.provider.rdbms.nameresolver.OriginalConventionNameResolver; import org.junit.jupiter.api.BeforeEach; @@ -49,165 +49,167 @@ /** * @author Gabriele Ponzi */ +class OriginalNameResolverTest { -public class OriginalNameResolverTest { + private OriginalConventionNameResolver nameResolver; - private OriginalConventionNameResolver nameResolver; + @BeforeEach + void init() { + this.nameResolver = new OriginalConventionNameResolver(); + } - @BeforeEach - public void init() { - this.nameResolver = new OriginalConventionNameResolver(); - } + /* + * Resolve Vertex Class Name (Original Class Convention) + */ - @Test - /* - * Resolve Vertex Class Name (Original Class Convention) - */ + @Test + void resolveVertexClassNameWithOriginalNameConvention() { + String candidateName = ""; + String newCandidateName = ""; - public void resolveVertexClassNameWithOriginalNameConvention() { - String candidateName = ""; - String newCandidateName = ""; + // No white space nor underscore - // No white space nor underscore + candidateName = + "testClass"; // NOT acceptable (one or more uppercase char, except the first one) + newCandidateName = nameResolver.resolveVertexName(candidateName); + assertThat(newCandidateName).isEqualTo("testClass"); - candidateName = "testClass"; // NOT acceptable (one or more uppercase char, except the first one) - newCandidateName = nameResolver.resolveVertexName(candidateName); - assertEquals("testClass", newCandidateName); + candidateName = "Testclass"; // acceptable (one or more uppercase char, the first one included) + newCandidateName = nameResolver.resolveVertexName(candidateName); + assertThat(newCandidateName).isEqualTo("Testclass"); - candidateName = "Testclass"; // acceptable (one or more uppercase char, the first one included) - newCandidateName = nameResolver.resolveVertexName(candidateName); - assertEquals("Testclass", newCandidateName); + candidateName = "TestClass"; // acceptable (one or more uppercase char, except the first one) + newCandidateName = nameResolver.resolveVertexName(candidateName); + assertThat(newCandidateName).isEqualTo("TestClass"); - candidateName = "TestClass"; // acceptable (one or more uppercase char, except the first one) - newCandidateName = nameResolver.resolveVertexName(candidateName); - assertEquals("TestClass", newCandidateName); + candidateName = "testclass"; // NOT acceptable (no uppercase chars) + newCandidateName = nameResolver.resolveVertexName(candidateName); + assertThat(newCandidateName).isEqualTo("testclass"); - candidateName = "testclass"; // NOT acceptable (no uppercase chars) - newCandidateName = nameResolver.resolveVertexName(candidateName); - assertEquals("testclass", newCandidateName); + candidateName = "TESTCLASS"; // NOT acceptable (no lowercase chars) + newCandidateName = nameResolver.resolveVertexName(candidateName); + assertThat(newCandidateName).isEqualTo("TESTCLASS"); - candidateName = "TESTCLASS"; // NOT acceptable (no lowercase chars) - newCandidateName = nameResolver.resolveVertexName(candidateName); - assertEquals("TESTCLASS", newCandidateName); + // White space - // White space + candidateName = "test Class"; // NOT acceptable + newCandidateName = nameResolver.resolveVertexName(candidateName); + assertThat(newCandidateName).isEqualTo("test_Class"); - candidateName = "test Class"; // NOT acceptable - newCandidateName = nameResolver.resolveVertexName(candidateName); - assertEquals("test_Class", newCandidateName); + candidateName = "Test class"; // NOT acceptable + newCandidateName = nameResolver.resolveVertexName(candidateName); + assertThat(newCandidateName).isEqualTo("Test_class"); - candidateName = "Test class"; // NOT acceptable - newCandidateName = nameResolver.resolveVertexName(candidateName); - assertEquals("Test_class", newCandidateName); + candidateName = "Test Class"; // NOT acceptable + newCandidateName = nameResolver.resolveVertexName(candidateName); + assertThat(newCandidateName).isEqualTo("Test_Class"); - candidateName = "Test Class"; // NOT acceptable - newCandidateName = nameResolver.resolveVertexName(candidateName); - assertEquals("Test_Class", newCandidateName); + candidateName = "test class"; // NOT acceptable + newCandidateName = nameResolver.resolveVertexName(candidateName); + assertThat(newCandidateName).isEqualTo("test_class"); - candidateName = "test class"; // NOT acceptable - newCandidateName = nameResolver.resolveVertexName(candidateName); - assertEquals("test_class", newCandidateName); + candidateName = "TEST CLASS"; // NOT acceptable + newCandidateName = nameResolver.resolveVertexName(candidateName); + assertThat(newCandidateName).isEqualTo("TEST_CLASS"); - candidateName = "TEST CLASS"; // NOT acceptable - newCandidateName = nameResolver.resolveVertexName(candidateName); - assertEquals("TEST_CLASS", newCandidateName); + // Underscore - // Underscore + candidateName = "test_Class"; // NOT acceptable + newCandidateName = nameResolver.resolveVertexName(candidateName); + assertThat(newCandidateName).isEqualTo("test_Class"); - candidateName = "test_Class"; // NOT acceptable - newCandidateName = nameResolver.resolveVertexName(candidateName); - assertEquals("test_Class", newCandidateName); + candidateName = "Test_class"; // NOT acceptable + newCandidateName = nameResolver.resolveVertexName(candidateName); + assertThat(newCandidateName).isEqualTo("Test_class"); - candidateName = "Test_class"; // NOT acceptable - newCandidateName = nameResolver.resolveVertexName(candidateName); - assertEquals("Test_class", newCandidateName); + candidateName = "Test_Class"; // NOT acceptable + newCandidateName = nameResolver.resolveVertexName(candidateName); + assertThat(newCandidateName).isEqualTo("Test_Class"); - candidateName = "Test_Class"; // NOT acceptable - newCandidateName = nameResolver.resolveVertexName(candidateName); - assertEquals("Test_Class", newCandidateName); + candidateName = "test_class"; // NOT acceptable + newCandidateName = nameResolver.resolveVertexName(candidateName); + assertThat(newCandidateName).isEqualTo("test_class"); - candidateName = "test_class"; // NOT acceptable - newCandidateName = nameResolver.resolveVertexName(candidateName); - assertEquals("test_class", newCandidateName); + candidateName = "TEST_CLASS"; // NOT acceptable + newCandidateName = nameResolver.resolveVertexName(candidateName); + assertThat(newCandidateName).isEqualTo("TEST_CLASS"); + } - candidateName = "TEST_CLASS"; // NOT acceptable - newCandidateName = nameResolver.resolveVertexName(candidateName); - assertEquals("TEST_CLASS", newCandidateName); - } + /* + * Resolve Vertex Property (Original Variable Convention) + */ - @Test - /* - * Resolve Vertex Property (Original Variable Convention) - */ + @Test + void resolveVertexPropertyNameWithOriginalNameConvention() { + String candidateName = ""; + String newCandidateName = ""; - public void resolveVertexPropertyNameWithOriginalNameConvention() { - String candidateName = ""; - String newCandidateName = ""; + // No white space nor underscore - // No white space nor underscore + candidateName = "testVariable"; // acceptable (one or more uppercase char, except the first one) + newCandidateName = nameResolver.resolveVertexProperty(candidateName); + assertThat(newCandidateName).isEqualTo("testVariable"); - candidateName = "testVariable"; // acceptable (one or more uppercase char, except the first one) - newCandidateName = nameResolver.resolveVertexProperty(candidateName); - assertEquals("testVariable", newCandidateName); + candidateName = + "Testvariable"; // NOT acceptable (one or more uppercase char, the first one included) + newCandidateName = nameResolver.resolveVertexProperty(candidateName); + assertThat(newCandidateName).isEqualTo("Testvariable"); - candidateName = "Testvariable"; // NOT acceptable (one or more uppercase char, the first one included) - newCandidateName = nameResolver.resolveVertexProperty(candidateName); - assertEquals("Testvariable", newCandidateName); + candidateName = + "TestVariable"; // NOT acceptable (one or more uppercase char, except the first one) + newCandidateName = nameResolver.resolveVertexProperty(candidateName); + assertThat(newCandidateName).isEqualTo("TestVariable"); - candidateName = "TestVariable"; // NOT acceptable (one or more uppercase char, except the first one) - newCandidateName = nameResolver.resolveVertexProperty(candidateName); - assertEquals("TestVariable", newCandidateName); + candidateName = "testvariable"; // acceptable (no uppercase chars) + newCandidateName = nameResolver.resolveVertexProperty(candidateName); + assertThat(newCandidateName).isEqualTo("testvariable"); - candidateName = "testvariable"; // acceptable (no uppercase chars) - newCandidateName = nameResolver.resolveVertexProperty(candidateName); - assertEquals("testvariable", newCandidateName); + candidateName = "TESTVARIABLE"; // NOT acceptable (no lowercase chars) + newCandidateName = nameResolver.resolveVertexProperty(candidateName); + assertThat(newCandidateName).isEqualTo("TESTVARIABLE"); - candidateName = "TESTVARIABLE"; // NOT acceptable (no lowercase chars) - newCandidateName = nameResolver.resolveVertexProperty(candidateName); - assertEquals("TESTVARIABLE", newCandidateName); + // White space - // White space + candidateName = "test Variable"; // NOT acceptable + newCandidateName = nameResolver.resolveVertexProperty(candidateName); + assertThat(newCandidateName).isEqualTo("test_Variable"); - candidateName = "test Variable"; // NOT acceptable - newCandidateName = nameResolver.resolveVertexProperty(candidateName); - assertEquals("test_Variable", newCandidateName); + candidateName = "Test variable"; // NOT acceptable + newCandidateName = nameResolver.resolveVertexProperty(candidateName); + assertThat(newCandidateName).isEqualTo("Test_variable"); - candidateName = "Test variable"; // NOT acceptable - newCandidateName = nameResolver.resolveVertexProperty(candidateName); - assertEquals("Test_variable", newCandidateName); + candidateName = "Test Variable"; // NOT acceptable + newCandidateName = nameResolver.resolveVertexProperty(candidateName); + assertThat(newCandidateName).isEqualTo("Test_Variable"); - candidateName = "Test Variable"; // NOT acceptable - newCandidateName = nameResolver.resolveVertexProperty(candidateName); - assertEquals("Test_Variable", newCandidateName); + candidateName = "test variable"; // NOT acceptable + newCandidateName = nameResolver.resolveVertexProperty(candidateName); + assertThat(newCandidateName).isEqualTo("test_variable"); - candidateName = "test variable"; // NOT acceptable - newCandidateName = nameResolver.resolveVertexProperty(candidateName); - assertEquals("test_variable", newCandidateName); + candidateName = "TEST VARIABLE"; // NOT acceptable + newCandidateName = nameResolver.resolveVertexProperty(candidateName); + assertThat(newCandidateName).isEqualTo("TEST_VARIABLE"); - candidateName = "TEST VARIABLE"; // NOT acceptable - newCandidateName = nameResolver.resolveVertexProperty(candidateName); - assertEquals("TEST_VARIABLE", newCandidateName); + // Underscore - // Underscore + candidateName = "test_Variable"; // NOT acceptable + newCandidateName = nameResolver.resolveVertexProperty(candidateName); + assertThat(newCandidateName).isEqualTo("test_Variable"); - candidateName = "test_Variable"; // NOT acceptable - newCandidateName = nameResolver.resolveVertexProperty(candidateName); - assertEquals("test_Variable", newCandidateName); + candidateName = "Test_variable"; // NOT acceptable + newCandidateName = nameResolver.resolveVertexProperty(candidateName); + assertThat(newCandidateName).isEqualTo("Test_variable"); - candidateName = "Test_variable"; // NOT acceptable - newCandidateName = nameResolver.resolveVertexProperty(candidateName); - assertEquals("Test_variable", newCandidateName); + candidateName = "Test_Variable"; // NOT acceptable + newCandidateName = nameResolver.resolveVertexProperty(candidateName); + assertThat(newCandidateName).isEqualTo("Test_Variable"); - candidateName = "Test_Variable"; // NOT acceptable - newCandidateName = nameResolver.resolveVertexProperty(candidateName); - assertEquals("Test_Variable", newCandidateName); + candidateName = "test_variable"; // NOT acceptable + newCandidateName = nameResolver.resolveVertexProperty(candidateName); + assertThat(newCandidateName).isEqualTo("test_variable"); - candidateName = "test_variable"; // NOT acceptable - newCandidateName = nameResolver.resolveVertexProperty(candidateName); - assertEquals("test_variable", newCandidateName); - - candidateName = "TEST_VARIABLE"; // NOT acceptable - newCandidateName = nameResolver.resolveVertexProperty(candidateName); - assertEquals("TEST_VARIABLE", newCandidateName); - } + candidateName = "TEST_VARIABLE"; // NOT acceptable + newCandidateName = nameResolver.resolveVertexProperty(candidateName); + assertThat(newCandidateName).isEqualTo("TEST_VARIABLE"); + } } diff --git a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/util/FunctionsHandlerTest.java b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/util/FunctionsHandlerTest.java index 073af3fd..0b92e110 100644 --- a/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/util/FunctionsHandlerTest.java +++ b/rdbms/src/test/java/com/arcadeanalytics/provider/rdbms/util/FunctionsHandlerTest.java @@ -40,8 +40,7 @@ * #L% */ -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import com.orientechnologies.orient.core.record.impl.ODocument; import java.util.Date; @@ -50,166 +49,166 @@ /** * @author Gabriele Ponzi */ - -public class FunctionsHandlerTest { - - @Test - public void timeFormatsTest() { - Date start = new Date(); - long endMillis = start.getTime() + 7713000L; - Date end = new Date(endMillis); - - String timeFormat1 = FunctionsHandler.getHMSFormat(start, end); - assertEquals("02:08:33", timeFormat1); - - String timeFormat2 = FunctionsHandler.getHMSFormat(7713000L); - assertEquals("02:08:33", timeFormat2); - } - - @Test - public void documentEqualsTest() { - // two identical documents - - String stringDoc1 = - "{\n" + - "\t\"name\": \"Book the First\",\n" + - "\t\"author\": {\n" + - "\t\t\"first_name\": \"Bob\",\n" + - "\t\t\"last_name\": \"White\",\n" + - "\t\t\"age\": \"45\",\n" + - "\t\t\"address\": {\n" + - "\t\t\t\"street\": \"Foo Street 123\",\n" + - "\t\t\t\"zip_code\": \"90001\",\n" + - "\t\t\t\"city\": \"Los Angeles\"\n" + - "\t\t}\n" + - "\t}\n" + - "}"; - - String stringDoc2 = - "{\n" + - "\t\"name\": \"Book the First\",\n" + - "\t\"author\": {\n" + - "\t\t\"first_name\": \"Bob\",\n" + - "\t\t\"last_name\": \"White\",\n" + - "\t\t\"age\": \"45\",\n" + - "\t\t\"address\": {\n" + - "\t\t\t\"street\": \"Foo Street 123\",\n" + - "\t\t\t\"zip_code\": \"90001\",\n" + - "\t\t\t\"city\": \"Los Angeles\"\n" + - "\t\t}\n" + - "\t}\n" + - "}"; - - ODocument document1 = new ODocument(); - document1.fromJSON(stringDoc1, "noMap"); - - ODocument document2 = new ODocument(); - document2.fromJSON(stringDoc2, "noMap"); - - assertTrue(FunctionsHandler.haveDocumentsSameContent(document1, document2) == true); - - // two documents with the same content (fields' order not equal) - - stringDoc2 = - "{\n" + - "\t\"name\": \"Book the First\",\n" + - "\t\"author\": {\n" + - "\t\t\"age\": \"45\",\n" + - "\t\t\"first_name\": \"Bob\",\n" + - "\t\t\"last_name\": \"White\",\n" + - "\t\t\"address\": {\n" + - "\t\t\t\"city\": \"Los Angeles\",\n" + - "\t\t\t\"zip_code\": \"90001\",\n" + - "\t\t\t\"street\": \"Foo Street 123\"\n" + - "\t\t}\n" + - "\t}\n" + - "}"; - - document2 = new ODocument(); - document2.fromJSON(stringDoc2, "noMap"); - - assertTrue(FunctionsHandler.haveDocumentsSameContent(document1, document2) == true); - - // two documents with different content (different values) - - stringDoc2 = - "{\n" + - "\t\"name\": \"Book the First\",\n" + - "\t\"author\": {\n" + - "\t\t\"age\": \"45\",\n" + - "\t\t\"first_name\": \"Bob\",\n" + - "\t\t\"last_name\": \"White\",\n" + - "\t\t\"address\": {\n" + - "\t\t\t\"city\": \"Los Angeles\",\n" + - "\t\t\t\"zip_code\": \"90002\",\n" + - "\t\t\t\"street\": \"Foo Street 456\"\n" + - "\t\t}\n" + - "\t}\n" + - "}"; - - document2 = new ODocument(); - document2.fromJSON(stringDoc2, "noMap"); - - assertTrue(FunctionsHandler.haveDocumentsSameContent(document1, document2) == false); - - // two documents with different content (different number of fields) - - stringDoc2 = - "{\n" + - "\t\"name\": \"Book the First\",\n" + - "\t\"author\": {\n" + - "\t\t\"first_name\": \"Bob\",\n" + - "\t\t\"last_name\": \"White\",\n" + - "\t\t\"address\": {\n" + - "\t\t\t\"city\": \"Los Angeles\",\n" + - "\t\t\t\"street\": \"Foo Street 456, 90002\"\n" + - "\t\t}\n" + - "\t}\n" + - "}"; - - document2 = new ODocument(); - document2.fromJSON(stringDoc2, "noMap"); - - assertTrue(FunctionsHandler.haveDocumentsSameContent(document1, document2) == false); - - // two documents with different content (different fields' name) - - stringDoc2 = - "{\n" + - "\t\"name\": \"Book the First\",\n" + - "\t\"author\": {\n" + - "\t\t\"name\": \"Bob\",\n" + - "\t\t\"surname\": \"White\",\n" + - "\t\t\"age\": \"45\",\n" + - "\t\t\"address\": {\n" + - "\t\t\t\"street\": \"Foo Street 123\",\n" + - "\t\t\t\"zip_code\": \"90001\",\n" + - "\t\t\t\"city\": \"Los Angeles\"\n" + - "\t\t}\n" + - "\t}\n" + - "}"; - - document2 = new ODocument(); - document2.fromJSON(stringDoc2, "noMap"); - - assertTrue(FunctionsHandler.haveDocumentsSameContent(document1, document2) == false); - - // two documents with different content (at least one field in doc1 is a nested document while the correspondent field in doc2 is a string) - - stringDoc2 = - "{\n" + - "\t\"name\": \"Book the First\",\n" + - "\t\"author\": {\n" + - "\t\t\"age\": \"45\",\n" + - "\t\t\"first_name\": \"Bob\",\n" + - "\t\t\"last_name\": \"White\",\n" + - "\t\t\"address\": \"Foo Street 123, 90001, Los Angeles\"\n" + - "\t}\n" + - "}"; - - document2 = new ODocument(); - document2.fromJSON(stringDoc2, "noMap"); - - assertTrue(FunctionsHandler.haveDocumentsSameContent(document1, document2) == false); - } +class FunctionsHandlerTest { + + @Test + void timeFormatsTest() { + Date start = new Date(); + long endMillis = start.getTime() + 7713000L; + Date end = new Date(endMillis); + + String timeFormat1 = FunctionsHandler.getHMSFormat(start, end); + assertThat(timeFormat1).isEqualTo("02:08:33"); + + String timeFormat2 = FunctionsHandler.getHMSFormat(7713000L); + assertThat(timeFormat2).isEqualTo("02:08:33"); + } + + @Test + void documentEqualsTest() { + // two identical documents + + String stringDoc1 = + "{\n" + + "\t\"name\": \"Book the First\",\n" + + "\t\"author\": {\n" + + "\t\t\"first_name\": \"Bob\",\n" + + "\t\t\"last_name\": \"White\",\n" + + "\t\t\"age\": \"45\",\n" + + "\t\t\"address\": {\n" + + "\t\t\t\"street\": \"Foo Street 123\",\n" + + "\t\t\t\"zip_code\": \"90001\",\n" + + "\t\t\t\"city\": \"Los Angeles\"\n" + + "\t\t}\n" + + "\t}\n" + + "}"; + + String stringDoc2 = + "{\n" + + "\t\"name\": \"Book the First\",\n" + + "\t\"author\": {\n" + + "\t\t\"first_name\": \"Bob\",\n" + + "\t\t\"last_name\": \"White\",\n" + + "\t\t\"age\": \"45\",\n" + + "\t\t\"address\": {\n" + + "\t\t\t\"street\": \"Foo Street 123\",\n" + + "\t\t\t\"zip_code\": \"90001\",\n" + + "\t\t\t\"city\": \"Los Angeles\"\n" + + "\t\t}\n" + + "\t}\n" + + "}"; + + ODocument document1 = new ODocument(); + document1.fromJSON(stringDoc1, "noMap"); + + ODocument document2 = new ODocument(); + document2.fromJSON(stringDoc2, "noMap"); + + assertThat(FunctionsHandler.haveDocumentsSameContent(document1, document2)).isEqualTo(true); + + // two documents with the same content (fields' order not equal) + + stringDoc2 = + "{\n" + + "\t\"name\": \"Book the First\",\n" + + "\t\"author\": {\n" + + "\t\t\"age\": \"45\",\n" + + "\t\t\"first_name\": \"Bob\",\n" + + "\t\t\"last_name\": \"White\",\n" + + "\t\t\"address\": {\n" + + "\t\t\t\"city\": \"Los Angeles\",\n" + + "\t\t\t\"zip_code\": \"90001\",\n" + + "\t\t\t\"street\": \"Foo Street 123\"\n" + + "\t\t}\n" + + "\t}\n" + + "}"; + + document2 = new ODocument(); + document2.fromJSON(stringDoc2, "noMap"); + + assertThat(FunctionsHandler.haveDocumentsSameContent(document1, document2)).isEqualTo(true); + + // two documents with different content (different values) + + stringDoc2 = + "{\n" + + "\t\"name\": \"Book the First\",\n" + + "\t\"author\": {\n" + + "\t\t\"age\": \"45\",\n" + + "\t\t\"first_name\": \"Bob\",\n" + + "\t\t\"last_name\": \"White\",\n" + + "\t\t\"address\": {\n" + + "\t\t\t\"city\": \"Los Angeles\",\n" + + "\t\t\t\"zip_code\": \"90002\",\n" + + "\t\t\t\"street\": \"Foo Street 456\"\n" + + "\t\t}\n" + + "\t}\n" + + "}"; + + document2 = new ODocument(); + document2.fromJSON(stringDoc2, "noMap"); + + assertThat(FunctionsHandler.haveDocumentsSameContent(document1, document2)).isEqualTo(false); + + // two documents with different content (different number of fields) + + stringDoc2 = + "{\n" + + "\t\"name\": \"Book the First\",\n" + + "\t\"author\": {\n" + + "\t\t\"first_name\": \"Bob\",\n" + + "\t\t\"last_name\": \"White\",\n" + + "\t\t\"address\": {\n" + + "\t\t\t\"city\": \"Los Angeles\",\n" + + "\t\t\t\"street\": \"Foo Street 456, 90002\"\n" + + "\t\t}\n" + + "\t}\n" + + "}"; + + document2 = new ODocument(); + document2.fromJSON(stringDoc2, "noMap"); + + assertThat(FunctionsHandler.haveDocumentsSameContent(document1, document2)).isEqualTo(false); + + // two documents with different content (different fields' name) + + stringDoc2 = + "{\n" + + "\t\"name\": \"Book the First\",\n" + + "\t\"author\": {\n" + + "\t\t\"name\": \"Bob\",\n" + + "\t\t\"surname\": \"White\",\n" + + "\t\t\"age\": \"45\",\n" + + "\t\t\"address\": {\n" + + "\t\t\t\"street\": \"Foo Street 123\",\n" + + "\t\t\t\"zip_code\": \"90001\",\n" + + "\t\t\t\"city\": \"Los Angeles\"\n" + + "\t\t}\n" + + "\t}\n" + + "}"; + + document2 = new ODocument(); + document2.fromJSON(stringDoc2, "noMap"); + + assertThat(FunctionsHandler.haveDocumentsSameContent(document1, document2)).isEqualTo(false); + + // two documents with different content (at least one field in doc1 is a nested document while + // the correspondent field in doc2 is a string) + + stringDoc2 = + "{\n" + + "\t\"name\": \"Book the First\",\n" + + "\t\"author\": {\n" + + "\t\t\"age\": \"45\",\n" + + "\t\t\"first_name\": \"Bob\",\n" + + "\t\t\"last_name\": \"White\",\n" + + "\t\t\"address\": \"Foo Street 123, 90001, Los Angeles\"\n" + + "\t}\n" + + "}"; + + document2 = new ODocument(); + document2.fromJSON(stringDoc2, "noMap"); + + assertThat(FunctionsHandler.haveDocumentsSameContent(document1, document2)).isEqualTo(false); + } } diff --git a/rdbms/src/test/kotlin/com/arcadeanalytics/provider/rdbms/PostgreSQLMetadataProviderTest.kt b/rdbms/src/test/kotlin/com/arcadeanalytics/provider/rdbms/PostgreSQLMetadataProviderTest.kt index ffb9e5b3..5fbbdf4e 100644 --- a/rdbms/src/test/kotlin/com/arcadeanalytics/provider/rdbms/PostgreSQLMetadataProviderTest.kt +++ b/rdbms/src/test/kotlin/com/arcadeanalytics/provider/rdbms/PostgreSQLMetadataProviderTest.kt @@ -23,7 +23,7 @@ import com.arcadeanalytics.provider.DataSourceInfo import com.arcadeanalytics.provider.rdbms.dataprovider.PostgreSQLContainerHolder import org.assertj.core.api.Assertions import org.assertj.core.api.Assertions.assertThat -import org.junit.Assert +import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance @@ -31,7 +31,6 @@ import org.testcontainers.containers.PostgreSQLContainer @TestInstance(TestInstance.Lifecycle.PER_CLASS) class PostgreSQLMetadataProviderTest { - private val container: PostgreSQLContainer = PostgreSQLContainerHolder.container as PostgreSQLContainer private lateinit var providerNoAggregation: RDBMSMetadataProvider @@ -43,28 +42,30 @@ class PostgreSQLMetadataProviderTest { @BeforeEach @Throws(Exception::class) fun setUp() { - dataSourceNoAggregation = DataSourceInfo( - id = 1L, - type = "RDBMS_POSTGRESQL", - name = "testDataSource", - server = container.containerIpAddress, - port = container.firstMappedPort, - username = container.username, - password = container.password, - database = container.databaseName, - aggregationEnabled = false, - ) - dataSourceWithAggregation = DataSourceInfo( - id = 1L, - type = "RDBMS_POSTGRESQL", - name = "testDataSource", - server = container.containerIpAddress, - port = container.firstMappedPort, - username = container.username, - password = container.password, - database = container.databaseName, - aggregationEnabled = true, - ) + dataSourceNoAggregation = + DataSourceInfo( + id = 1L, + type = "RDBMS_POSTGRESQL", + name = "testDataSource", + server = container.containerIpAddress, + port = container.firstMappedPort, + username = container.username, + password = container.password, + database = container.databaseName, + aggregationEnabled = false, + ) + dataSourceWithAggregation = + DataSourceInfo( + id = 1L, + type = "RDBMS_POSTGRESQL", + name = "testDataSource", + server = container.containerIpAddress, + port = container.firstMappedPort, + username = container.username, + password = container.password, + database = container.databaseName, + aggregationEnabled = true, + ) providerNoAggregation = RDBMSMetadataProvider() providerWithAggregation = RDBMSMetadataProvider() @@ -74,7 +75,8 @@ class PostgreSQLMetadataProviderTest { fun shouldFetchMetadata() { val metadata = providerNoAggregation.fetchMetadata(dataSourceNoAggregation) - assertThat(metadata.nodesClasses).isNotEmpty + assertThat(metadata.nodesClasses) + .isNotEmpty .containsKeys("actor", "address", "category", "city", "country", "customer", "film", "rental", "payment", "language") assertThat(metadata.edgesClasses).isNotEmpty @@ -91,146 +93,146 @@ class PostgreSQLMetadataProviderTest { val nodesClasses = metadata.nodesClasses val edgesClasses = metadata.edgesClasses - Assert.assertEquals(15, nodesClasses.size) - Assert.assertEquals(12, edgesClasses.size) + assertThat(nodesClasses.size).isEqualTo(15) + assertThat(edgesClasses.size).isEqualTo(12) /* * Vertices Classes check */ var currVertexClassName = "actor" - Assert.assertTrue(nodesClasses.keys.contains(currVertexClassName)) - Assert.assertNotNull(nodesClasses.get(currVertexClassName)) + assertTrue(nodesClasses.keys.contains(currVertexClassName)) + assertThat(nodesClasses.get(currVertexClassName)).isNotNull() nodesClasses.get(currVertexClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currVertexClassName, currVertexClassInfo.name) - Assert.assertEquals(200, currVertexClassInfo.cardinality) - Assert.assertEquals(4, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currVertexClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(200) + assertThat(currVertexClassInfo.properties.size).isEqualTo(4) } currVertexClassName = "address" - Assert.assertTrue(nodesClasses.keys.contains(currVertexClassName)) - Assert.assertNotNull(nodesClasses.get(currVertexClassName)) + assertTrue(nodesClasses.keys.contains(currVertexClassName)) + assertThat(nodesClasses.get(currVertexClassName)).isNotNull() nodesClasses.get(currVertexClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currVertexClassName, currVertexClassInfo.name) - Assert.assertEquals(603, currVertexClassInfo.cardinality) - Assert.assertEquals(8, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currVertexClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(603) + assertThat(currVertexClassInfo.properties.size).isEqualTo(8) } currVertexClassName = "category" - Assert.assertTrue(nodesClasses.keys.contains(currVertexClassName)) - Assert.assertNotNull(nodesClasses.get(currVertexClassName)) + assertTrue(nodesClasses.keys.contains(currVertexClassName)) + assertThat(nodesClasses.get(currVertexClassName)).isNotNull() nodesClasses.get(currVertexClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currVertexClassName, currVertexClassInfo.name) - Assert.assertEquals(16, currVertexClassInfo.cardinality) - Assert.assertEquals(3, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currVertexClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(16) + assertThat(currVertexClassInfo.properties.size).isEqualTo(3) } currVertexClassName = "city" - Assert.assertTrue(nodesClasses.keys.contains(currVertexClassName)) - Assert.assertNotNull(nodesClasses.get(currVertexClassName)) + assertTrue(nodesClasses.keys.contains(currVertexClassName)) + assertThat(nodesClasses.get(currVertexClassName)).isNotNull() nodesClasses.get(currVertexClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currVertexClassName, currVertexClassInfo.name) - Assert.assertEquals(600, currVertexClassInfo.cardinality) - Assert.assertEquals(4, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currVertexClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(600) + assertThat(currVertexClassInfo.properties.size).isEqualTo(4) } currVertexClassName = "country" - Assert.assertTrue(nodesClasses.keys.contains(currVertexClassName)) - Assert.assertNotNull(nodesClasses.get(currVertexClassName)) + assertTrue(nodesClasses.keys.contains(currVertexClassName)) + assertThat(nodesClasses.get(currVertexClassName)).isNotNull() nodesClasses.get(currVertexClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currVertexClassName, currVertexClassInfo.name) - Assert.assertEquals(109, currVertexClassInfo.cardinality) - Assert.assertEquals(3, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currVertexClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(109) + assertThat(currVertexClassInfo.properties.size).isEqualTo(3) } currVertexClassName = "customer" - Assert.assertTrue(nodesClasses.keys.contains(currVertexClassName)) - Assert.assertNotNull(nodesClasses.get(currVertexClassName)) + assertTrue(nodesClasses.keys.contains(currVertexClassName)) + assertThat(nodesClasses.get(currVertexClassName)).isNotNull() nodesClasses.get(currVertexClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currVertexClassName, currVertexClassInfo.name) - Assert.assertEquals(599, currVertexClassInfo.cardinality) - Assert.assertEquals(10, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currVertexClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(599) + assertThat(currVertexClassInfo.properties.size).isEqualTo(10) } currVertexClassName = "film" - Assert.assertTrue(nodesClasses.keys.contains(currVertexClassName)) - Assert.assertNotNull(nodesClasses.get(currVertexClassName)) + assertTrue(nodesClasses.keys.contains(currVertexClassName)) + assertThat(nodesClasses.get(currVertexClassName)).isNotNull() nodesClasses.get(currVertexClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currVertexClassName, currVertexClassInfo.name) - Assert.assertEquals(1000, currVertexClassInfo.cardinality) - Assert.assertEquals(13, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currVertexClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(1000) + assertThat(currVertexClassInfo.properties.size).isEqualTo(13) } currVertexClassName = "film_actor" - Assert.assertTrue(nodesClasses.keys.contains(currVertexClassName)) - Assert.assertNotNull(nodesClasses.get(currVertexClassName)) + assertTrue(nodesClasses.keys.contains(currVertexClassName)) + assertThat(nodesClasses.get(currVertexClassName)).isNotNull() nodesClasses.get(currVertexClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currVertexClassName, currVertexClassInfo.name) - Assert.assertEquals(5462, currVertexClassInfo.cardinality) - Assert.assertEquals(3, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currVertexClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(5462) + assertThat(currVertexClassInfo.properties.size).isEqualTo(3) } currVertexClassName = "film_category" - Assert.assertTrue(nodesClasses.keys.contains(currVertexClassName)) - Assert.assertNotNull(nodesClasses.get(currVertexClassName)) + assertTrue(nodesClasses.keys.contains(currVertexClassName)) + assertThat(nodesClasses.get(currVertexClassName)).isNotNull() nodesClasses.get(currVertexClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currVertexClassName, currVertexClassInfo.name) - Assert.assertEquals(1000, currVertexClassInfo.cardinality) - Assert.assertEquals(3, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currVertexClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(1000) + assertThat(currVertexClassInfo.properties.size).isEqualTo(3) } currVertexClassName = "inventory" - Assert.assertTrue(nodesClasses.keys.contains(currVertexClassName)) - Assert.assertNotNull(nodesClasses.get(currVertexClassName)) + assertTrue(nodesClasses.keys.contains(currVertexClassName)) + assertThat(nodesClasses.get(currVertexClassName)).isNotNull() nodesClasses.get(currVertexClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currVertexClassName, currVertexClassInfo.name) - Assert.assertEquals(4581, currVertexClassInfo.cardinality) - Assert.assertEquals(4, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currVertexClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(4581) + assertThat(currVertexClassInfo.properties.size).isEqualTo(4) } currVertexClassName = "language" - Assert.assertTrue(nodesClasses.keys.contains(currVertexClassName)) - Assert.assertNotNull(nodesClasses.get(currVertexClassName)) + assertTrue(nodesClasses.keys.contains(currVertexClassName)) + assertThat(nodesClasses.get(currVertexClassName)).isNotNull() nodesClasses.get(currVertexClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currVertexClassName, currVertexClassInfo.name) - Assert.assertEquals(6, currVertexClassInfo.cardinality) - Assert.assertEquals(3, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currVertexClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(6) + assertThat(currVertexClassInfo.properties.size).isEqualTo(3) } currVertexClassName = "payment" - Assert.assertTrue(nodesClasses.keys.contains(currVertexClassName)) - Assert.assertNotNull(nodesClasses.get(currVertexClassName)) + assertTrue(nodesClasses.keys.contains(currVertexClassName)) + assertThat(nodesClasses.get(currVertexClassName)).isNotNull() nodesClasses.get(currVertexClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currVertexClassName, currVertexClassInfo.name) - Assert.assertEquals(14596, currVertexClassInfo.cardinality) - Assert.assertEquals(6, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currVertexClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(14596) + assertThat(currVertexClassInfo.properties.size).isEqualTo(6) } currVertexClassName = "rental" - Assert.assertTrue(nodesClasses.keys.contains(currVertexClassName)) - Assert.assertNotNull(nodesClasses.get(currVertexClassName)) + assertTrue(nodesClasses.keys.contains(currVertexClassName)) + assertThat(nodesClasses.get(currVertexClassName)).isNotNull() nodesClasses.get(currVertexClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currVertexClassName, currVertexClassInfo.name) - Assert.assertEquals(16044, currVertexClassInfo.cardinality) - Assert.assertEquals(7, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currVertexClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(16044) + assertThat(currVertexClassInfo.properties.size).isEqualTo(7) } currVertexClassName = "staff" - Assert.assertTrue(nodesClasses.keys.contains(currVertexClassName)) - Assert.assertNotNull(nodesClasses.get(currVertexClassName)) + assertTrue(nodesClasses.keys.contains(currVertexClassName)) + assertThat(nodesClasses.get(currVertexClassName)).isNotNull() nodesClasses.get(currVertexClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currVertexClassName, currVertexClassInfo.name) - Assert.assertEquals(2, currVertexClassInfo.cardinality) - Assert.assertEquals(11, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currVertexClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(2) + assertThat(currVertexClassInfo.properties.size).isEqualTo(11) } currVertexClassName = "store" - Assert.assertTrue(nodesClasses.keys.contains(currVertexClassName)) - Assert.assertNotNull(nodesClasses.get(currVertexClassName)) + assertTrue(nodesClasses.keys.contains(currVertexClassName)) + assertThat(nodesClasses.get(currVertexClassName)).isNotNull() nodesClasses.get(currVertexClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currVertexClassName, currVertexClassInfo.name) - Assert.assertEquals(2, currVertexClassInfo.cardinality) - Assert.assertEquals(4, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currVertexClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(2) + assertThat(currVertexClassInfo.properties.size).isEqualTo(4) } /* @@ -238,111 +240,111 @@ class PostgreSQLMetadataProviderTest { */ var currEdgeClassName = "has_actor" - Assert.assertTrue(edgesClasses.keys.contains(currEdgeClassName)) - Assert.assertNotNull(edgesClasses.get(currEdgeClassName)) + assertTrue(edgesClasses.keys.contains(currEdgeClassName)) + assertThat(edgesClasses.get(currEdgeClassName)).isNotNull() edgesClasses.get(currEdgeClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currEdgeClassName, currVertexClassInfo.name) - Assert.assertEquals(5462, currVertexClassInfo.cardinality) - Assert.assertEquals(0, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currEdgeClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(5462) + assertThat(currVertexClassInfo.properties.size).isEqualTo(0) } currEdgeClassName = "has_address" - Assert.assertTrue(edgesClasses.keys.contains(currEdgeClassName)) - Assert.assertNotNull(edgesClasses.get(currEdgeClassName)) + assertTrue(edgesClasses.keys.contains(currEdgeClassName)) + assertThat(edgesClasses.get(currEdgeClassName)).isNotNull() edgesClasses.get(currEdgeClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currEdgeClassName, currVertexClassInfo.name) - Assert.assertEquals(603, currVertexClassInfo.cardinality) - Assert.assertEquals(0, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currEdgeClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(603) + assertThat(currVertexClassInfo.properties.size).isEqualTo(0) } currEdgeClassName = "has_category" - Assert.assertTrue(edgesClasses.keys.contains(currEdgeClassName)) - Assert.assertNotNull(edgesClasses.get(currEdgeClassName)) + assertTrue(edgesClasses.keys.contains(currEdgeClassName)) + assertThat(edgesClasses.get(currEdgeClassName)).isNotNull() edgesClasses.get(currEdgeClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currEdgeClassName, currVertexClassInfo.name) - Assert.assertEquals(1000, currVertexClassInfo.cardinality) - Assert.assertEquals(0, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currEdgeClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(1000) + assertThat(currVertexClassInfo.properties.size).isEqualTo(0) } currEdgeClassName = "has_city" - Assert.assertTrue(edgesClasses.keys.contains(currEdgeClassName)) - Assert.assertNotNull(edgesClasses.get(currEdgeClassName)) + assertTrue(edgesClasses.keys.contains(currEdgeClassName)) + assertThat(edgesClasses.get(currEdgeClassName)).isNotNull() edgesClasses.get(currEdgeClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currEdgeClassName, currVertexClassInfo.name) - Assert.assertEquals(603, currVertexClassInfo.cardinality) - Assert.assertEquals(0, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currEdgeClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(603) + assertThat(currVertexClassInfo.properties.size).isEqualTo(0) } currEdgeClassName = "has_country" - Assert.assertTrue(edgesClasses.keys.contains(currEdgeClassName)) - Assert.assertNotNull(edgesClasses.get(currEdgeClassName)) + assertTrue(edgesClasses.keys.contains(currEdgeClassName)) + assertThat(edgesClasses.get(currEdgeClassName)).isNotNull() edgesClasses.get(currEdgeClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currEdgeClassName, currVertexClassInfo.name) - Assert.assertEquals(600, currVertexClassInfo.cardinality) - Assert.assertEquals(0, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currEdgeClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(600) + assertThat(currVertexClassInfo.properties.size).isEqualTo(0) } currEdgeClassName = "has_customer" - Assert.assertTrue(edgesClasses.keys.contains(currEdgeClassName)) - Assert.assertNotNull(edgesClasses.get(currEdgeClassName)) + assertTrue(edgesClasses.keys.contains(currEdgeClassName)) + assertThat(edgesClasses.get(currEdgeClassName)).isNotNull() edgesClasses.get(currEdgeClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currEdgeClassName, currVertexClassInfo.name) - Assert.assertEquals(30640, currVertexClassInfo.cardinality) - Assert.assertEquals(0, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currEdgeClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(30640) + assertThat(currVertexClassInfo.properties.size).isEqualTo(0) } currEdgeClassName = "has_film" - Assert.assertTrue(edgesClasses.keys.contains(currEdgeClassName)) - Assert.assertNotNull(edgesClasses.get(currEdgeClassName)) + assertTrue(edgesClasses.keys.contains(currEdgeClassName)) + assertThat(edgesClasses.get(currEdgeClassName)).isNotNull() edgesClasses.get(currEdgeClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currEdgeClassName, currVertexClassInfo.name) - Assert.assertEquals(11043, currVertexClassInfo.cardinality) - Assert.assertEquals(0, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currEdgeClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(11043) + assertThat(currVertexClassInfo.properties.size).isEqualTo(0) } currEdgeClassName = "has_inventory" - Assert.assertTrue(edgesClasses.keys.contains(currEdgeClassName)) - Assert.assertNotNull(edgesClasses.get(currEdgeClassName)) + assertTrue(edgesClasses.keys.contains(currEdgeClassName)) + assertThat(edgesClasses.get(currEdgeClassName)).isNotNull() edgesClasses.get(currEdgeClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currEdgeClassName, currVertexClassInfo.name) - Assert.assertEquals(16044, currVertexClassInfo.cardinality) - Assert.assertEquals(0, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currEdgeClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(16044) + assertThat(currVertexClassInfo.properties.size).isEqualTo(0) } currEdgeClassName = "has_language" - Assert.assertTrue(edgesClasses.keys.contains(currEdgeClassName)) - Assert.assertNotNull(edgesClasses.get(currEdgeClassName)) + assertTrue(edgesClasses.keys.contains(currEdgeClassName)) + assertThat(edgesClasses.get(currEdgeClassName)).isNotNull() edgesClasses.get(currEdgeClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currEdgeClassName, currVertexClassInfo.name) - Assert.assertEquals(1000, currVertexClassInfo.cardinality) - Assert.assertEquals(0, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currEdgeClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(1000) + assertThat(currVertexClassInfo.properties.size).isEqualTo(0) } currEdgeClassName = "has_manager_staff" - Assert.assertTrue(edgesClasses.keys.contains(currEdgeClassName)) - Assert.assertNotNull(edgesClasses.get(currEdgeClassName)) + assertTrue(edgesClasses.keys.contains(currEdgeClassName)) + assertThat(edgesClasses.get(currEdgeClassName)).isNotNull() edgesClasses.get(currEdgeClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currEdgeClassName, currVertexClassInfo.name) - Assert.assertEquals(2, currVertexClassInfo.cardinality) - Assert.assertEquals(0, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currEdgeClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(2) + assertThat(currVertexClassInfo.properties.size).isEqualTo(0) } currEdgeClassName = "has_rental" - Assert.assertTrue(edgesClasses.keys.contains(currEdgeClassName)) - Assert.assertNotNull(edgesClasses.get(currEdgeClassName)) + assertTrue(edgesClasses.keys.contains(currEdgeClassName)) + assertThat(edgesClasses.get(currEdgeClassName)).isNotNull() edgesClasses.get(currEdgeClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currEdgeClassName, currVertexClassInfo.name) - Assert.assertEquals(14596, currVertexClassInfo.cardinality) - Assert.assertEquals(0, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currEdgeClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(14596) + assertThat(currVertexClassInfo.properties.size).isEqualTo(0) } currEdgeClassName = "has_staff" - Assert.assertTrue(edgesClasses.keys.contains(currEdgeClassName)) - Assert.assertNotNull(edgesClasses.get(currEdgeClassName)) + assertTrue(edgesClasses.keys.contains(currEdgeClassName)) + assertThat(edgesClasses.get(currEdgeClassName)).isNotNull() edgesClasses.get(currEdgeClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currEdgeClassName, currVertexClassInfo.name) - Assert.assertEquals(30640, currVertexClassInfo.cardinality) - Assert.assertEquals(0, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currEdgeClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(30640) + assertThat(currVertexClassInfo.properties.size).isEqualTo(0) } } @@ -357,128 +359,128 @@ class PostgreSQLMetadataProviderTest { val nodesClasses = metadata.nodesClasses val edgesClasses = metadata.edgesClasses - Assert.assertEquals(13, nodesClasses.size) - Assert.assertEquals(12, edgesClasses.size) + assertThat(nodesClasses.size).isEqualTo(13) + assertThat(edgesClasses.size).isEqualTo(12) /* * Vertices Classes check */ var currVertexClassName = "actor" - Assert.assertTrue(nodesClasses.keys.contains(currVertexClassName)) - Assert.assertNotNull(nodesClasses.get(currVertexClassName)) + assertTrue(nodesClasses.keys.contains(currVertexClassName)) + assertThat(nodesClasses.get(currVertexClassName)).isNotNull() nodesClasses.get(currVertexClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currVertexClassName, currVertexClassInfo.name) - Assert.assertEquals(200, currVertexClassInfo.cardinality) - Assert.assertEquals(4, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currVertexClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(200) + assertThat(currVertexClassInfo.properties.size).isEqualTo(4) } currVertexClassName = "address" - Assert.assertTrue(nodesClasses.keys.contains(currVertexClassName)) - Assert.assertNotNull(nodesClasses.get(currVertexClassName)) + assertTrue(nodesClasses.keys.contains(currVertexClassName)) + assertThat(nodesClasses.get(currVertexClassName)).isNotNull() nodesClasses.get(currVertexClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currVertexClassName, currVertexClassInfo.name) - Assert.assertEquals(603, currVertexClassInfo.cardinality) - Assert.assertEquals(8, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currVertexClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(603) + assertThat(currVertexClassInfo.properties.size).isEqualTo(8) } currVertexClassName = "category" - Assert.assertTrue(nodesClasses.keys.contains(currVertexClassName)) - Assert.assertNotNull(nodesClasses.get(currVertexClassName)) + assertTrue(nodesClasses.keys.contains(currVertexClassName)) + assertThat(nodesClasses.get(currVertexClassName)).isNotNull() nodesClasses.get(currVertexClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currVertexClassName, currVertexClassInfo.name) - Assert.assertEquals(16, currVertexClassInfo.cardinality) - Assert.assertEquals(3, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currVertexClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(16) + assertThat(currVertexClassInfo.properties.size).isEqualTo(3) } currVertexClassName = "city" - Assert.assertTrue(nodesClasses.keys.contains(currVertexClassName)) - Assert.assertNotNull(nodesClasses.get(currVertexClassName)) + assertTrue(nodesClasses.keys.contains(currVertexClassName)) + assertThat(nodesClasses.get(currVertexClassName)).isNotNull() nodesClasses.get(currVertexClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currVertexClassName, currVertexClassInfo.name) - Assert.assertEquals(600, currVertexClassInfo.cardinality) - Assert.assertEquals(4, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currVertexClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(600) + assertThat(currVertexClassInfo.properties.size).isEqualTo(4) } currVertexClassName = "country" - Assert.assertTrue(nodesClasses.keys.contains(currVertexClassName)) - Assert.assertNotNull(nodesClasses.get(currVertexClassName)) + assertTrue(nodesClasses.keys.contains(currVertexClassName)) + assertThat(nodesClasses.get(currVertexClassName)).isNotNull() nodesClasses.get(currVertexClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currVertexClassName, currVertexClassInfo.name) - Assert.assertEquals(109, currVertexClassInfo.cardinality) - Assert.assertEquals(3, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currVertexClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(109) + assertThat(currVertexClassInfo.properties.size).isEqualTo(3) } currVertexClassName = "customer" - Assert.assertTrue(nodesClasses.keys.contains(currVertexClassName)) - Assert.assertNotNull(nodesClasses.get(currVertexClassName)) + assertTrue(nodesClasses.keys.contains(currVertexClassName)) + assertThat(nodesClasses.get(currVertexClassName)).isNotNull() nodesClasses.get(currVertexClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currVertexClassName, currVertexClassInfo.name) - Assert.assertEquals(599, currVertexClassInfo.cardinality) - Assert.assertEquals(10, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currVertexClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(599) + assertThat(currVertexClassInfo.properties.size).isEqualTo(10) } currVertexClassName = "film" - Assert.assertTrue(nodesClasses.keys.contains(currVertexClassName)) - Assert.assertNotNull(nodesClasses.get(currVertexClassName)) + assertTrue(nodesClasses.keys.contains(currVertexClassName)) + assertThat(nodesClasses.get(currVertexClassName)).isNotNull() nodesClasses.get(currVertexClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currVertexClassName, currVertexClassInfo.name) - Assert.assertEquals(1000, currVertexClassInfo.cardinality) - Assert.assertEquals(13, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currVertexClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(1000) + assertThat(currVertexClassInfo.properties.size).isEqualTo(13) } currVertexClassName = "inventory" - Assert.assertTrue(nodesClasses.keys.contains(currVertexClassName)) - Assert.assertNotNull(nodesClasses.get(currVertexClassName)) + assertTrue(nodesClasses.keys.contains(currVertexClassName)) + assertThat(nodesClasses.get(currVertexClassName)).isNotNull() nodesClasses.get(currVertexClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currVertexClassName, currVertexClassInfo.name) - Assert.assertEquals(4581, currVertexClassInfo.cardinality) - Assert.assertEquals(4, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currVertexClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(4581) + assertThat(currVertexClassInfo.properties.size).isEqualTo(4) } currVertexClassName = "language" - Assert.assertTrue(nodesClasses.keys.contains(currVertexClassName)) - Assert.assertNotNull(nodesClasses.get(currVertexClassName)) + assertTrue(nodesClasses.keys.contains(currVertexClassName)) + assertThat(nodesClasses.get(currVertexClassName)).isNotNull() nodesClasses.get(currVertexClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currVertexClassName, currVertexClassInfo.name) - Assert.assertEquals(6, currVertexClassInfo.cardinality) - Assert.assertEquals(3, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currVertexClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(6) + assertThat(currVertexClassInfo.properties.size).isEqualTo(3) } currVertexClassName = "payment" - Assert.assertTrue(nodesClasses.keys.contains(currVertexClassName)) - Assert.assertNotNull(nodesClasses.get(currVertexClassName)) + assertTrue(nodesClasses.keys.contains(currVertexClassName)) + assertThat(nodesClasses.get(currVertexClassName)).isNotNull() nodesClasses.get(currVertexClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currVertexClassName, currVertexClassInfo.name) - Assert.assertEquals(14596, currVertexClassInfo.cardinality) - Assert.assertEquals(6, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currVertexClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(14596) + assertThat(currVertexClassInfo.properties.size).isEqualTo(6) } currVertexClassName = "rental" - Assert.assertTrue(nodesClasses.keys.contains(currVertexClassName)) - Assert.assertNotNull(nodesClasses.get(currVertexClassName)) + assertTrue(nodesClasses.keys.contains(currVertexClassName)) + assertThat(nodesClasses.get(currVertexClassName)).isNotNull() nodesClasses.get(currVertexClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currVertexClassName, currVertexClassInfo.name) - Assert.assertEquals(16044, currVertexClassInfo.cardinality) - Assert.assertEquals(7, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currVertexClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(16044) + assertThat(currVertexClassInfo.properties.size).isEqualTo(7) } currVertexClassName = "staff" - Assert.assertTrue(nodesClasses.keys.contains(currVertexClassName)) - Assert.assertNotNull(nodesClasses.get(currVertexClassName)) + assertTrue(nodesClasses.keys.contains(currVertexClassName)) + assertThat(nodesClasses.get(currVertexClassName)).isNotNull() nodesClasses.get(currVertexClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currVertexClassName, currVertexClassInfo.name) - Assert.assertEquals(2, currVertexClassInfo.cardinality) - Assert.assertEquals(11, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currVertexClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(2) + assertThat(currVertexClassInfo.properties.size).isEqualTo(11) } currVertexClassName = "store" - Assert.assertTrue(nodesClasses.keys.contains(currVertexClassName)) - Assert.assertNotNull(nodesClasses.get(currVertexClassName)) + assertTrue(nodesClasses.keys.contains(currVertexClassName)) + assertThat(nodesClasses.get(currVertexClassName)).isNotNull() nodesClasses.get(currVertexClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currVertexClassName, currVertexClassInfo.name) - Assert.assertEquals(2, currVertexClassInfo.cardinality) - Assert.assertEquals(4, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currVertexClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(2) + assertThat(currVertexClassInfo.properties.size).isEqualTo(4) } /* @@ -486,111 +488,111 @@ class PostgreSQLMetadataProviderTest { */ var currEdgeClassName = "film_actor" - Assert.assertTrue(edgesClasses.keys.contains(currEdgeClassName)) - Assert.assertNotNull(edgesClasses.get(currEdgeClassName)) + assertTrue(edgesClasses.keys.contains(currEdgeClassName)) + assertThat(edgesClasses.get(currEdgeClassName)).isNotNull() edgesClasses.get(currEdgeClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currEdgeClassName, currVertexClassInfo.name) - Assert.assertEquals(5462, currVertexClassInfo.cardinality) - Assert.assertEquals(1, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currEdgeClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(5462) + assertThat(currVertexClassInfo.properties.size).isEqualTo(1) } currEdgeClassName = "film_category" - Assert.assertTrue(edgesClasses.keys.contains(currEdgeClassName)) - Assert.assertNotNull(edgesClasses.get(currEdgeClassName)) + assertTrue(edgesClasses.keys.contains(currEdgeClassName)) + assertThat(edgesClasses.get(currEdgeClassName)).isNotNull() edgesClasses.get(currEdgeClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currEdgeClassName, currVertexClassInfo.name) - Assert.assertEquals(1000, currVertexClassInfo.cardinality) - Assert.assertEquals(1, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currEdgeClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(1000) + assertThat(currVertexClassInfo.properties.size).isEqualTo(1) } currEdgeClassName = "has_address" - Assert.assertTrue(edgesClasses.keys.contains(currEdgeClassName)) - Assert.assertNotNull(edgesClasses.get(currEdgeClassName)) + assertTrue(edgesClasses.keys.contains(currEdgeClassName)) + assertThat(edgesClasses.get(currEdgeClassName)).isNotNull() edgesClasses.get(currEdgeClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currEdgeClassName, currVertexClassInfo.name) - Assert.assertEquals(603, currVertexClassInfo.cardinality) - Assert.assertEquals(0, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currEdgeClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(603) + assertThat(currVertexClassInfo.properties.size).isEqualTo(0) } currEdgeClassName = "has_city" - Assert.assertTrue(edgesClasses.keys.contains(currEdgeClassName)) - Assert.assertNotNull(edgesClasses.get(currEdgeClassName)) + assertTrue(edgesClasses.keys.contains(currEdgeClassName)) + assertThat(edgesClasses.get(currEdgeClassName)).isNotNull() edgesClasses.get(currEdgeClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currEdgeClassName, currVertexClassInfo.name) - Assert.assertEquals(603, currVertexClassInfo.cardinality) - Assert.assertEquals(0, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currEdgeClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(603) + assertThat(currVertexClassInfo.properties.size).isEqualTo(0) } currEdgeClassName = "has_country" - Assert.assertTrue(edgesClasses.keys.contains(currEdgeClassName)) - Assert.assertNotNull(edgesClasses.get(currEdgeClassName)) + assertTrue(edgesClasses.keys.contains(currEdgeClassName)) + assertThat(edgesClasses.get(currEdgeClassName)).isNotNull() edgesClasses.get(currEdgeClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currEdgeClassName, currVertexClassInfo.name) - Assert.assertEquals(600, currVertexClassInfo.cardinality) - Assert.assertEquals(0, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currEdgeClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(600) + assertThat(currVertexClassInfo.properties.size).isEqualTo(0) } currEdgeClassName = "has_customer" - Assert.assertTrue(edgesClasses.keys.contains(currEdgeClassName)) - Assert.assertNotNull(edgesClasses.get(currEdgeClassName)) + assertTrue(edgesClasses.keys.contains(currEdgeClassName)) + assertThat(edgesClasses.get(currEdgeClassName)).isNotNull() edgesClasses.get(currEdgeClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currEdgeClassName, currVertexClassInfo.name) - Assert.assertEquals(30640, currVertexClassInfo.cardinality) - Assert.assertEquals(0, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currEdgeClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(30640) + assertThat(currVertexClassInfo.properties.size).isEqualTo(0) } currEdgeClassName = "has_film" - Assert.assertTrue(edgesClasses.keys.contains(currEdgeClassName)) - Assert.assertNotNull(edgesClasses.get(currEdgeClassName)) + assertTrue(edgesClasses.keys.contains(currEdgeClassName)) + assertThat(edgesClasses.get(currEdgeClassName)).isNotNull() edgesClasses.get(currEdgeClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currEdgeClassName, currVertexClassInfo.name) - Assert.assertEquals(4581, currVertexClassInfo.cardinality) - Assert.assertEquals(0, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currEdgeClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(4581) + assertThat(currVertexClassInfo.properties.size).isEqualTo(0) } currEdgeClassName = "has_inventory" - Assert.assertTrue(edgesClasses.keys.contains(currEdgeClassName)) - Assert.assertNotNull(edgesClasses.get(currEdgeClassName)) + assertTrue(edgesClasses.keys.contains(currEdgeClassName)) + assertThat(edgesClasses.get(currEdgeClassName)).isNotNull() edgesClasses.get(currEdgeClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currEdgeClassName, currVertexClassInfo.name) - Assert.assertEquals(16044, currVertexClassInfo.cardinality) - Assert.assertEquals(0, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currEdgeClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(16044) + assertThat(currVertexClassInfo.properties.size).isEqualTo(0) } currEdgeClassName = "has_language" - Assert.assertTrue(edgesClasses.keys.contains(currEdgeClassName)) - Assert.assertNotNull(edgesClasses.get(currEdgeClassName)) + assertTrue(edgesClasses.keys.contains(currEdgeClassName)) + assertThat(edgesClasses.get(currEdgeClassName)).isNotNull() edgesClasses.get(currEdgeClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currEdgeClassName, currVertexClassInfo.name) - Assert.assertEquals(1000, currVertexClassInfo.cardinality) - Assert.assertEquals(0, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currEdgeClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(1000) + assertThat(currVertexClassInfo.properties.size).isEqualTo(0) } currEdgeClassName = "has_manager_staff" - Assert.assertTrue(edgesClasses.keys.contains(currEdgeClassName)) - Assert.assertNotNull(edgesClasses.get(currEdgeClassName)) + assertTrue(edgesClasses.keys.contains(currEdgeClassName)) + assertThat(edgesClasses.get(currEdgeClassName)).isNotNull() edgesClasses.get(currEdgeClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currEdgeClassName, currVertexClassInfo.name) - Assert.assertEquals(2, currVertexClassInfo.cardinality) - Assert.assertEquals(0, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currEdgeClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(2) + assertThat(currVertexClassInfo.properties.size).isEqualTo(0) } currEdgeClassName = "has_rental" - Assert.assertTrue(edgesClasses.keys.contains(currEdgeClassName)) - Assert.assertNotNull(edgesClasses.get(currEdgeClassName)) + assertTrue(edgesClasses.keys.contains(currEdgeClassName)) + assertThat(edgesClasses.get(currEdgeClassName)).isNotNull() edgesClasses.get(currEdgeClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currEdgeClassName, currVertexClassInfo.name) - Assert.assertEquals(14596, currVertexClassInfo.cardinality) - Assert.assertEquals(0, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currEdgeClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(14596) + assertThat(currVertexClassInfo.properties.size).isEqualTo(0) } currEdgeClassName = "has_staff" - Assert.assertTrue(edgesClasses.keys.contains(currEdgeClassName)) - Assert.assertNotNull(edgesClasses.get(currEdgeClassName)) + assertTrue(edgesClasses.keys.contains(currEdgeClassName)) + assertThat(edgesClasses.get(currEdgeClassName)).isNotNull() edgesClasses.get(currEdgeClassName)?.let { currVertexClassInfo -> - Assert.assertEquals(currEdgeClassName, currVertexClassInfo.name) - Assert.assertEquals(30640, currVertexClassInfo.cardinality) - Assert.assertEquals(0, currVertexClassInfo.properties.size) + assertThat(currVertexClassInfo.name).isEqualTo(currEdgeClassName) + assertThat(currVertexClassInfo.cardinality).isEqualTo(30640) + assertThat(currVertexClassInfo.properties.size).isEqualTo(0) } } } diff --git a/rdbms/src/test/kotlin/com/arcadeanalytics/provider/rdbms/RDBMSTableDataProviderTest.kt b/rdbms/src/test/kotlin/com/arcadeanalytics/provider/rdbms/RDBMSTableDataProviderTest.kt index db2d594c..3fe74779 100644 --- a/rdbms/src/test/kotlin/com/arcadeanalytics/provider/rdbms/RDBMSTableDataProviderTest.kt +++ b/rdbms/src/test/kotlin/com/arcadeanalytics/provider/rdbms/RDBMSTableDataProviderTest.kt @@ -29,7 +29,6 @@ import org.junit.jupiter.api.Test import org.testcontainers.containers.PostgreSQLContainer internal class RDBMSTableDataProviderTest { - private val container: PostgreSQLContainer = PostgreSQLContainerHolder.container as PostgreSQLContainer private lateinit var provider: RDBMSTableDataProvider @@ -39,33 +38,35 @@ internal class RDBMSTableDataProviderTest { @BeforeEach @Throws(Exception::class) fun setUp() { - dataSourceInfo = DataSourceInfo( - id = 1L, - type = "RDBMS_POSTGRESQL", - name = "testDataSource", - server = container.containerIpAddress, - port = container.firstMappedPort, - username = container.username, - password = container.password, - database = container.databaseName, - aggregationEnabled = true, - ) + dataSourceInfo = + DataSourceInfo( + id = 1L, + type = "RDBMS_POSTGRESQL", + name = "testDataSource", + server = container.containerIpAddress, + port = container.firstMappedPort, + username = container.username, + password = container.password, + database = container.databaseName, + aggregationEnabled = true, + ) provider = RDBMSTableDataProvider() } @Test fun fetchData() { - val data = provider.fetchData( - dataSourceInfo, - """SELECT customer_id, SUM (amount) total_amount + val data = + provider.fetchData( + dataSourceInfo, + """SELECT customer_id, SUM (amount) total_amount | FROM payment | GROUP BY customer_id | ORDER BY total_amount DESC | - """.trimMargin(), - 100, - ) + """.trimMargin(), + 100, + ) val tableClass = data.nodesClasses[TABLE_CLASS] @@ -78,7 +79,8 @@ internal class RDBMSTableDataProviderTest { val cytoData = data.nodes.first() Assertions.assertThat(cytoData.classes).isEqualTo(TABLE_CLASS) - Assertions.assertThat(cytoData.group) + Assertions + .assertThat(cytoData.group) .isEqualTo("nodes") Assertions.assertThat(cytoData.data.id).isEqualTo("0")