package solutions.bitbadger.documents.common.query import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import solutions.bitbadger.documents.common.Configuration import solutions.bitbadger.documents.common.Dialect import solutions.bitbadger.documents.common.DocumentException import solutions.bitbadger.documents.common.Field import kotlin.test.assertEquals /** * Unit tests for the `Exists` object */ @DisplayName("Kotlin | Common | Query: Exists") class ExistsTest { /** Test table name */ private val tbl = "test_table" /** * Clear the connection string (resets Dialect) */ @AfterEach fun cleanUp() { Configuration.dialectValue = null } @Test @DisplayName("byId generates correctly (PostgreSQL)") fun byIdPostgres() { Configuration.dialectValue = Dialect.POSTGRESQL assertEquals( "SELECT EXISTS (SELECT 1 FROM $tbl WHERE data->>'id' = :id) AS it", Exists.byId(tbl), "Exists query not constructed correctly" ) } @Test @DisplayName("byId generates correctly (SQLite)") fun byIdSQLite() { Configuration.dialectValue = Dialect.SQLITE assertEquals( "SELECT EXISTS (SELECT 1 FROM $tbl WHERE data->>'id' = :id) AS it", Exists.byId(tbl), "Exists query not constructed correctly" ) } @Test @DisplayName("byFields generates correctly (PostgreSQL)") fun byFieldsPostgres() { Configuration.dialectValue = Dialect.POSTGRESQL assertEquals( "SELECT EXISTS (SELECT 1 FROM $tbl WHERE (data->>'it')::numeric = :test) AS it", Exists.byFields(tbl, listOf(Field.equal("it", 7, ":test"))), "Exists query not constructed correctly" ) } @Test @DisplayName("byFields generates correctly (SQLite)") fun byFieldsSQLite() { Configuration.dialectValue = Dialect.SQLITE assertEquals( "SELECT EXISTS (SELECT 1 FROM $tbl WHERE data->>'it' = :test) AS it", Exists.byFields(tbl, listOf(Field.equal("it", 7, ":test"))), "Exists query not constructed correctly" ) } @Test @DisplayName("byContains generates correctly (PostgreSQL)") fun byContainsPostgres() { Configuration.dialectValue = Dialect.POSTGRESQL assertEquals( "SELECT EXISTS (SELECT 1 FROM $tbl WHERE data @> :criteria) AS it", Exists.byContains(tbl), "Exists query not constructed correctly" ) } @Test @DisplayName("byContains fails (SQLite)") fun byContainsSQLite() { Configuration.dialectValue = Dialect.SQLITE assertThrows { Exists.byContains(tbl) } } @Test @DisplayName("byJsonPath generates correctly (PostgreSQL)") fun byJsonPathPostgres() { Configuration.dialectValue = Dialect.POSTGRESQL assertEquals( "SELECT EXISTS (SELECT 1 FROM $tbl WHERE jsonb_path_exists(data, :path::jsonpath)) AS it", Exists.byJsonPath(tbl), "Exists query not constructed correctly" ) } @Test @DisplayName("byJsonPath fails (SQLite)") fun byJsonPathSQLite() { Configuration.dialectValue = Dialect.SQLITE assertThrows { Exists.byJsonPath(tbl) } } }