From 5543b114199963e48258c1cc9ebb52e64039f0ce Mon Sep 17 00:00:00 2001 From: dbulahov Date: Mon, 23 Nov 2026 10:10:33 +0300 Subject: [PATCH] dialect(postgresql): version checks, tested on PostgreSQL in Docker The dialect wrote SQL that older servers refused. Each feature now checks the version; a dialect without a version says yes: - ORDER BY ... NULLS FIRST/LAST: the version is compared as numbers (as strings "10" came before "8.3") - bit_xor from 14 - CREATE PROCEDURE from 11, its OUT parameters from 14 - PERCENTILE_DISC/CONT from 9.4, make_date from 9.4 - materialized views from 9.3, their IF NOT EXISTS from 9.5 - DROP FUNCTION without the types from 10 (the API says so) - EXECUTE PROCEDURE in a trigger before 11 - a trigger function's body that holds $$ gets its own dollar quote Tested only, no change needed: MERGE, RETURNING, STRING_AGG, CREATE FUNCTION and CREATE OR REPLACE TRIGGER. Docker tests run with -Dintegration.docker=true. Signed-off-by: --- .../dialect/api/generator/DdlGenerator.java | 3 +- .../db/postgresql/PostgreSqlDialect.java | 93 +++++++++-- .../PostgreSqlBitAggregationTest.java | 89 +++++++++++ .../PostgreSqlCreateFunctionTest.java | 150 +++++++++++++++++ .../PostgreSqlCreateOrReplaceTriggerTest.java | 92 +++++++++++ .../PostgreSqlCreateProcedureTest.java | 151 ++++++++++++++++++ .../PostgreSqlDateFromPartsTest.java | 93 +++++++++++ .../integration/PostgreSqlListAggTest.java | 125 +++++++++++++++ .../PostgreSqlMaterializedViewTest.java | 112 +++++++++++++ .../PostgreSqlMergeGeneratorTest.java | 127 +++++++++++++++ .../PostgreSqlOrderByNullsTest.java | 77 +++++++++ .../integration/PostgreSqlPercentileTest.java | 106 ++++++++++++ .../integration/PostgreSqlReturningTest.java | 139 ++++++++++++++++ .../PostgreSqlTriggerUsingProcedureTest.java | 131 +++++++++++++++ .../PostgreSqlVersionSelectTest.java | 80 ++++++++++ 15 files changed, 1551 insertions(+), 17 deletions(-) create mode 100644 dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlBitAggregationTest.java create mode 100644 dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlCreateFunctionTest.java create mode 100644 dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlCreateOrReplaceTriggerTest.java create mode 100644 dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlCreateProcedureTest.java create mode 100644 dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlDateFromPartsTest.java create mode 100644 dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlListAggTest.java create mode 100644 dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlMaterializedViewTest.java create mode 100644 dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlMergeGeneratorTest.java create mode 100644 dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlOrderByNullsTest.java create mode 100644 dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlPercentileTest.java create mode 100644 dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlReturningTest.java create mode 100644 dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlTriggerUsingProcedureTest.java create mode 100644 dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlVersionSelectTest.java diff --git a/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/generator/DdlGenerator.java b/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/generator/DdlGenerator.java index 5c810280..59e0a08c 100644 --- a/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/generator/DdlGenerator.java +++ b/dialect/api/src/main/java/org/eclipse/daanse/sql/dialect/api/generator/DdlGenerator.java @@ -1093,7 +1093,8 @@ default Optional createProcedure(RoutineDefinition procedure, boolean or * database has overloads. With {@code ifExists} a missing function is no error where the dialect * can say so. * - * @return empty where the dialect writes no routines + * @return empty where the dialect writes no routines, or cannot name the function without its + * types where the signature gives none */ default Optional dropFunction(RoutineSignature function, boolean ifExists) { return Optional.empty(); diff --git a/dialect/db/postgresql/src/main/java/org/eclipse/daanse/sql/dialect/db/postgresql/PostgreSqlDialect.java b/dialect/db/postgresql/src/main/java/org/eclipse/daanse/sql/dialect/db/postgresql/PostgreSqlDialect.java index 8b46cf49..e16bcb9f 100644 --- a/dialect/db/postgresql/src/main/java/org/eclipse/daanse/sql/dialect/db/postgresql/PostgreSqlDialect.java +++ b/dialect/db/postgresql/src/main/java/org/eclipse/daanse/sql/dialect/db/postgresql/PostgreSqlDialect.java @@ -265,12 +265,15 @@ public Optional createTriggerProcedure(String procedureName, String sche String qualified = schemaName != null && !schemaName.isBlank() ? quoteIdentifier(schemaName, procedureName).toString() : quoteIdentifier(procedureName).toString(); - return Optional.of("CREATE OR REPLACE FUNCTION " + qualified + "() RETURNS trigger LANGUAGE plpgsql AS $$ " - + body + " $$"); + // the body in a dollar quote that does not occur in it, as createFunction writes one + return Optional.of("CREATE OR REPLACE FUNCTION " + qualified + "() RETURNS trigger LANGUAGE plpgsql AS " + + dollarQuoted(body)); } /** - * PostgreSQL: {@code CREATE TRIGGER … EXECUTE FUNCTION schema.procedureName()}. + * PostgreSQL: {@code CREATE TRIGGER … EXECUTE FUNCTION schema.procedureName()}, since 11; before that + * {@code EXECUTE PROCEDURE}, which 11 still reads but no longer documents. A dialect made without a connection + * knows no version and writes {@code EXECUTE FUNCTION}. */ @Override public String createTriggerUsingProcedure(String triggerName, String schemaName, @@ -283,7 +286,8 @@ public String createTriggerUsingProcedure(String triggerName, String schemaName, ? quoteIdentifier(schemaName, procedureName).toString() : quoteIdentifier(procedureName).toString(); return createTrigger(triggerName, timing, event, table, scope, whenCondition, - "EXECUTE FUNCTION " + qualified + "()"); + (dialectVersion.isUnknownOrAtLeast(11, 0) ? "EXECUTE FUNCTION " : "EXECUTE PROCEDURE ") + qualified + + "()"); } /** PostgreSQL: {@code DROP FUNCTION [IF EXISTS] schema.procedureName()}. */ @@ -324,8 +328,9 @@ public boolean supportsRenameSequence() { @Override public StringBuilder generateOrderByNulls(CharSequence expr, boolean ascending, boolean collateNullsLast) { - // Support for "ORDER BY ... NULLS LAST" was introduced in Postgres 8.3. - if (productVersion.compareTo("8.3") >= 0) { + // Support for "ORDER BY ... NULLS LAST" was introduced in Postgres 8.3. The version is compared as numbers: + // as strings "10.23" came before "8.3", and every PostgreSQL from 10 on wrote the CASE WHEN of the fallback. + if (dialectVersion.isUnknownOrAtLeast(8, 3)) { return generateOrderByNullsAnsi(expr, ascending, collateNullsLast); } else { return super.generateOrderByNulls(expr, ascending, collateNullsLast); @@ -472,6 +477,9 @@ public boolean supportsListAgg() { @Override public java.util.Optional generateBitAggregation(BitOperation operation, CharSequence operand) { + if (!supportsBitAggregation(operation)) { + return java.util.Optional.empty(); + } StringBuilder buf = new StringBuilder(64); StringBuilder result = switch (operation) { case AND -> buf.append("bit_and(").append(operand).append(")"); @@ -487,14 +495,24 @@ public java.util.Optional generateBitAggregation(BitOperation operation, return java.util.Optional.of(result.toString()); } + /** + * PostgreSQL has {@code bit_and} and {@code bit_or} of old, {@code bit_xor} only since 14: XOR and NXOR need 14. + * A dialect made without a connection knows no version and says yes. + */ @Override public boolean supportsBitAggregation(BitOperation operation) { - return true; // PostgreSQL supports all bit operations + return switch (operation) { + case XOR, NXOR -> dialectVersion.isUnknownOrAtLeast(14, 0); + case AND, OR, NAND, NOR -> true; + }; } @Override public java.util.Optional generatePercentileDisc(double percentile, boolean desc, String tableName, String columnName) { + if (!supportsPercentileDisc()) { + return java.util.Optional.empty(); + } return java.util.Optional .of((buildPercentileFunction("PERCENTILE_DISC", percentile, desc, tableName, columnName)).toString()); } @@ -502,6 +520,9 @@ public java.util.Optional generatePercentileDisc(double percentile, bool @Override public java.util.Optional generatePercentileCont(double percentile, boolean desc, String tableName, String columnName) { + if (!supportsPercentileCont()) { + return java.util.Optional.empty(); + } return java.util.Optional .of((buildPercentileFunction("PERCENTILE_CONT", percentile, desc, tableName, columnName)).toString()); } @@ -514,14 +535,19 @@ public java.util.Optional generateNthValueAgg(CharSequence operand, bool ")[" + AggregationGenerator.nthIndex(n) + "]").toString()); } + /** + * PostgreSQL has the ordered-set aggregates {@code percentile_disc} and {@code percentile_cont … WITHIN GROUP} since + * 9.4. A dialect made without a connection knows no version and says yes. + */ @Override public boolean supportsPercentileDisc() { - return true; + return dialectVersion.isUnknownOrAtLeast(9, 4); } + /** As {@link #supportsPercentileDisc()}: since 9.4. */ @Override public boolean supportsPercentileCont() { - return true; + return dialectVersion.isUnknownOrAtLeast(9, 4); } @Override @@ -533,7 +559,10 @@ public boolean supportsNthValue() { @Override public StringBuilder generateKnownFunction(org.eclipse.daanse.sql.dialect.api.generator.KnownFunction function, java.util.List arguments) { - if (function == org.eclipse.daanse.sql.dialect.api.generator.KnownFunction.DATE_FROM_PARTS) { + // make_date came with 9.4; before that the ISO text yyyy-mm-dd of the default is read as a date. A dialect + // made without a connection knows no version and writes make_date. + if (function == org.eclipse.daanse.sql.dialect.api.generator.KnownFunction.DATE_FROM_PARTS + && dialectVersion.isUnknownOrAtLeast(9, 4)) { if (arguments.size() != 3) { throw new IllegalArgumentException("DATE_FROM_PARTS expects 3 argument(s), got " + arguments.size()); } @@ -583,10 +612,23 @@ private static String unlessItExists(String create) { return "DO " + quote + " BEGIN " + create + "; EXCEPTION WHEN duplicate_object THEN NULL; END " + quote; } - /** PostgreSQL keeps a materialized view's rows from its creation on, until it is refreshed. */ + /** + * PostgreSQL keeps a materialized view's rows from its creation on, until it is refreshed: since 9.3. A dialect + * made without a connection knows no version and says yes. + */ @Override public boolean supportsMaterializedViews() { - return true; + return dialectVersion.isUnknownOrAtLeast(9, 3); + } + + /** + * {@code CREATE MATERIALIZED VIEW IF NOT EXISTS} came with 9.5; before that {@code ifNotExists} is not written, and + * the statement fails on an existing view, as the contract says. + */ + @Override + public Optional createMaterializedView(org.eclipse.daanse.sql.model.schema.TableReference view, + String selectSql, boolean ifNotExists) { + return super.createMaterializedView(view, selectSql, ifNotExists && dialectVersion.isUnknownOrAtLeast(9, 5)); } /** PostgreSQL: a partial index, {@code CREATE INDEX … WHERE condition}. */ @@ -629,10 +671,19 @@ public Optional createFunction(RoutineDefinition function, boolean orRep + function.language() + " AS " + dollarQuoted(function.body())); } - /** {@code CREATE [OR REPLACE] PROCEDURE s.p (n integer, INOUT total integer) LANGUAGE l AS $$body$$}. */ + /** + * {@code CREATE [OR REPLACE] PROCEDURE s.p (n integer, INOUT total integer) LANGUAGE l AS $$body$$}. PostgreSQL has + * procedures since 11 and an {@code OUT} parameter of a procedure since 14; before that none is written. A dialect + * made without a connection knows no version and writes it. + */ @Override public Optional createProcedure(RoutineDefinition procedure, boolean orReplace) { - if (!routineLanguages().contains(procedure.language().toLowerCase(Locale.ROOT))) { + if (!routineLanguages().contains(procedure.language().toLowerCase(Locale.ROOT)) + || !dialectVersion.isUnknownOrAtLeast(11, 0)) { + return Optional.empty(); + } + if (!dialectVersion.isUnknownOrAtLeast(14, 0) + && procedure.parameters().stream().anyMatch(p -> p.mode() == ParameterMode.OUT)) { return Optional.empty(); } return Optional.of("CREATE " + (orReplace ? "OR REPLACE " : "") + "PROCEDURE " @@ -640,15 +691,25 @@ public Optional createProcedure(RoutineDefinition procedure, boolean orR + " LANGUAGE " + procedure.language() + " AS " + dollarQuoted(procedure.body())); } - /** {@code DROP FUNCTION [IF EXISTS] s.f [(integer, text)]}: the types name one of several overloads. */ + /** + * {@code DROP FUNCTION [IF EXISTS] s.f [(integer, text)]}: the types name one of several overloads. A function is + * named without its types since PostgreSQL 10; before that such a signature gives no statement. A dialect made + * without a connection knows no version and writes it. + */ @Override public Optional dropFunction(RoutineSignature function, boolean ifExists) { + if (function.parameterTypes() == null && !dialectVersion.isUnknownOrAtLeast(10, 0)) { + return Optional.empty(); + } return Optional.of("DROP FUNCTION " + (ifExists ? "IF EXISTS " : "") + signature(function)); } - /** {@code DROP PROCEDURE [IF EXISTS] s.p [(integer, integer)]}. */ + /** {@code DROP PROCEDURE [IF EXISTS] s.p [(integer, integer)]}, from PostgreSQL 11 on, which has procedures. */ @Override public Optional dropProcedure(RoutineSignature procedure, boolean ifExists) { + if (!dialectVersion.isUnknownOrAtLeast(11, 0)) { + return Optional.empty(); + } return Optional.of("DROP PROCEDURE " + (ifExists ? "IF EXISTS " : "") + signature(procedure)); } diff --git a/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlBitAggregationTest.java b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlBitAggregationTest.java new file mode 100644 index 00000000..b9f18a9d --- /dev/null +++ b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlBitAggregationTest.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.postgresql.integration; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.EnumSet; +import java.util.Map; +import java.util.Set; + +import org.eclipse.daanse.sql.model.sql.BitOperation; +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.postgresql.PostgreSqlDialect; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.PostgreSQLContainer; + +/** + * PostgreSQL has {@code bit_and} and {@code bit_or} of old, {@code bit_xor} only since 14. The dialect is built from a + * live connection: each bit aggregation it offers must compute the right value on the server, and on 13 it must not + * offer XOR and NXOR, which the server would refuse. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class PostgreSqlBitAggregationTest { + + /** 14 = 1110, 11 = 1011, 7 = 0111; the NULL is left out by every aggregate. */ + private static final String SETUP = """ + CREATE TABLE flags(v INT); + INSERT INTO flags VALUES (14), (11), (NULL), (7); + """; + + /** AND = 0010, OR = 1111, XOR = 0010; NAND, NOR and NXOR are their bitwise complements. */ + private static final Map EXPECTED = Map.of(BitOperation.AND, 2, BitOperation.OR, 15, + BitOperation.XOR, 2, BitOperation.NAND, ~2, BitOperation.NOR, ~15, BitOperation.NXOR, ~2); + + private static final Set XOR = EnumSet.of(BitOperation.XOR, BitOperation.NXOR); + + @ParameterizedTest(name = "postgres:{0}, xor -> {1}") + @CsvSource({ "13-alpine, false", "14-alpine, true", "16-alpine, true" }) + void bit_aggregation(String tag, boolean xorExpected) throws Exception { + try (PostgreSQLContainer pg = new PostgreSQLContainer<>("postgres:" + tag)) { + pg.start(); + try (Connection c = pg.createConnection(""); Statement st = c.createStatement()) { + st.execute(SETUP); + PostgreSqlDialect dialect = new PostgreSqlDialect(DialectInitData.fromConnection(c)); + + for (BitOperation op : BitOperation.values()) { + boolean expected = xorExpected || !XOR.contains(op); + assertThat(dialect.supportsBitAggregation(op)).as(op + " supported").isEqualTo(expected); + + var sql = dialect.generateBitAggregation(op, "v"); + if (!expected) { + assertThat(sql).as(op + " is not generated").isEmpty(); + continue; + } + assertThat(sql).as(op + " is generated").isPresent(); + assertThat(value(st, "SELECT " + sql.get() + " FROM flags")).as(op + ": " + sql.get()) + .isEqualTo(EXPECTED.get(op)); + } + + if (!xorExpected) { + assertThatThrownBy(() -> value(st, "SELECT bit_xor(v) FROM flags")) + .as("PostgreSQL 13 knows no bit_xor").isInstanceOf(SQLException.class) + .hasMessageContaining("does not exist"); + } + } + } + } + + private static int value(Statement st, String sql) throws SQLException { + try (ResultSet rs = st.executeQuery(sql)) { + assertThat(rs.next()).isTrue(); + return rs.getInt(1); + } + } +} diff --git a/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlCreateFunctionTest.java b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlCreateFunctionTest.java new file mode 100644 index 00000000..f0445557 --- /dev/null +++ b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlCreateFunctionTest.java @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.postgresql.integration; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.ParameterMode; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineDefinition; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineParameter; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineSignature; +import org.eclipse.daanse.sql.dialect.db.postgresql.PostgreSqlDialect; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.PostgreSQLContainer; + +/** + * The dialect is built from a live connection, and each function it writes must be created and called on the server: + * in SQL and in PL/pgSQL, with a return type, with {@code OUT} parameters that make the result, returning a table, + * replaced, overloaded and dropped by its types. {@code DROP FUNCTION name} without the types came with PostgreSQL 10; + * before that the dialect must write no such statement, for the server would refuse it. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class PostgreSqlCreateFunctionTest { + + /** A SQL body names its parameters by position: by name only since 9.2. */ + private static final RoutineDefinition ADD = function("add", "integer", "sql", "SELECT $1 + $2", + RoutineParameter.in("a", "integer"), RoutineParameter.in("b", "integer")); + + private static final RoutineDefinition ADD_PLUS_ONE = function("add", "integer", "sql", "SELECT $1 + $2 + 1", + RoutineParameter.in("a", "integer"), RoutineParameter.in("b", "integer")); + + /** An overload of add, of two texts. */ + private static final RoutineDefinition ADD_TEXT = function("add", "text", "sql", "SELECT $1 || $2", + RoutineParameter.in("a", "text"), RoutineParameter.in("b", "text")); + + private static final RoutineDefinition MUL = function("mul", "integer", "plpgsql", "BEGIN RETURN a * b; END", + RoutineParameter.in("a", "integer"), RoutineParameter.in("b", "integer")); + + /** No return type: the OUT parameters make the result. */ + private static final RoutineDefinition DIVMOD = function("divmod", null, "plpgsql", + "BEGIN q := a / b; r := a % b; END", RoutineParameter.in("a", "integer"), + RoutineParameter.in("b", "integer"), new RoutineParameter("q", ParameterMode.OUT, "integer"), + new RoutineParameter("r", ParameterMode.OUT, "integer")); + + private static final RoutineDefinition UPTO = function("upto", "TABLE(n integer)", "sql", + "SELECT generate_series(1, $1)", RoutineParameter.in("k", "integer")); + + /** A body that holds {@code $$} itself, which the dialect must quote with another dollar quote. */ + private static final RoutineDefinition DOLLAR = function("dollar", "text", "sql", "SELECT $$x$$::text"); + + @ParameterizedTest(name = "postgres:{0} -> DROP FUNCTION without types {1}") + @CsvSource({ "9.1, false", "9.6, false", "10-alpine, true", "16-alpine, true" }) + void create_function(String tag, boolean dropByName) throws Exception { + try (PostgreSQLContainer pg = new PostgreSQLContainer<>("postgres:" + tag)) { + pg.start(); + try (Connection c = pg.createConnection(""); Statement st = c.createStatement()) { + st.execute("CREATE SCHEMA rt"); + PostgreSqlDialect dialect = new PostgreSqlDialect(DialectInitData.fromConnection(c)); + + st.execute(sql(dialect, ADD, false)); + assertThat(rows(st, "SELECT rt.add(2, 3)")).containsExactly("5"); + + assertThatThrownBy(() -> st.execute(sql(dialect, ADD_PLUS_ONE, false))) + .as("without OR REPLACE the second one fails").isInstanceOf(SQLException.class) + .hasMessageContaining("already exists"); + st.execute(sql(dialect, ADD_PLUS_ONE, true)); + assertThat(rows(st, "SELECT rt.add(2, 3)")).as("OR REPLACE took the new body").containsExactly("6"); + + st.execute(sql(dialect, MUL, false)); + assertThat(rows(st, "SELECT rt.mul(4, 5)")).as("PL/pgSQL, by the parameters' names") + .containsExactly("20"); + + st.execute(sql(dialect, DIVMOD, false)); + assertThat(rows(st, "SELECT q || '/' || r FROM rt.divmod(17, 5)")).as("OUT parameters as the result") + .containsExactly("3/2"); + + st.execute(sql(dialect, UPTO, false)); + assertThat(rows(st, "SELECT n FROM rt.upto(3)")).as("a table").containsExactly("1", "2", "3"); + + String dollar = sql(dialect, DOLLAR, false); + assertThat(dollar).contains("$body$"); + st.execute(dollar); + assertThat(rows(st, "SELECT rt.dollar()")).containsExactly("x"); + + assertThat(dialect.createFunction(function("f", "integer", "java", "x"), false)) + .as("a body in a language the dialect does not write").isEmpty(); + + st.execute(sql(dialect, ADD_TEXT, false)); + st.execute(dialect.dropFunction(signature("add", "integer", "integer"), false).orElseThrow()); + assertThatThrownBy(() -> rows(st, "SELECT rt.add(2, 3)")).as("the integer overload is dropped") + .isInstanceOf(SQLException.class).hasMessageContaining("does not exist"); + assertThat(rows(st, "SELECT rt.add('x', 'y')")).as("the text one is left").containsExactly("xy"); + st.execute(dialect.dropFunction(signature("add", "integer", "integer"), true).orElseThrow()); + + var byName = dialect.dropFunction(signature("mul"), false); + if (dropByName) { + st.execute(byName.orElseThrow()); + assertThatThrownBy(() -> rows(st, "SELECT rt.mul(4, 5)")).as("dropped by its name") + .isInstanceOf(SQLException.class).hasMessageContaining("does not exist"); + st.execute(dialect.dropFunction(signature("mul"), true).orElseThrow()); + } else { + assertThat(byName).as("no DROP FUNCTION without the types before 10").isEmpty(); + assertThatThrownBy(() -> st.execute("DROP FUNCTION rt.mul")) + .as("the server refuses it").isInstanceOf(SQLException.class) + .hasMessageContaining("syntax error"); + } + } + } + } + + private static RoutineDefinition function(String name, String returnType, String language, String body, + RoutineParameter... parameters) { + return new RoutineDefinition("rt", name, List.of(parameters), returnType, language, body); + } + + private static RoutineSignature signature(String name, String... types) { + return new RoutineSignature("rt", name, types.length == 0 ? null : List.of(types)); + } + + private static String sql(PostgreSqlDialect dialect, RoutineDefinition function, boolean orReplace) { + return dialect.createFunction(function, orReplace).orElseThrow(); + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } + return out; + } +} diff --git a/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlCreateOrReplaceTriggerTest.java b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlCreateOrReplaceTriggerTest.java new file mode 100644 index 00000000..9c216088 --- /dev/null +++ b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlCreateOrReplaceTriggerTest.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.postgresql.integration; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.postgresql.PostgreSqlDialect; +import org.eclipse.daanse.sql.model.schema.SchemaReference; +import org.eclipse.daanse.sql.model.schema.TableReference; +import org.eclipse.daanse.sql.model.schema.Trigger; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.PostgreSQLContainer; + +/** + * {@code CREATE OR REPLACE TRIGGER} came with PostgreSQL 14. The dialect is built from a live connection and must say + * so: from 14 on its trigger replaces the one before, on 13 it writes a plain {@code CREATE TRIGGER}, and the server + * would refuse the {@code OR REPLACE} form. + */ +//@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class PostgreSqlCreateOrReplaceTriggerTest { + + private static final TableReference ITEMS = new TableReference( + Optional.of(new SchemaReference(Optional.empty(), "public")), "items", TableReference.TYPE_TABLE); + + private static final String SETUP = """ + CREATE TABLE items(id INT, mark VARCHAR(10)); + CREATE FUNCTION mark_v1() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN NEW.mark := 'v1'; RETURN NEW; END $$; + CREATE FUNCTION mark_v2() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN NEW.mark := 'v2'; RETURN NEW; END $$; + """; + + @ParameterizedTest(name = "postgres:{0} -> {1}") + @CsvSource({ "13-alpine, false", "14-alpine, true", "16-alpine, true" }) + void create_or_replace_trigger(String tag, boolean expected) throws Exception { + try (PostgreSQLContainer pg = new PostgreSQLContainer<>("postgres:" + tag)) { + pg.start(); + try (Connection c = pg.createConnection(""); Statement st = c.createStatement()) { + st.execute(SETUP); + PostgreSqlDialect dialect = new PostgreSqlDialect(DialectInitData.fromConnection(c)); + + assertThat(dialect.supportsCreateOrReplaceTrigger()).isEqualTo(expected); + + String first = trigger(dialect, "mark_v1"); + String second = trigger(dialect, "mark_v2"); + assertThat(first.startsWith("CREATE OR REPLACE TRIGGER")).isEqualTo(expected); + + st.execute(first); + assertThat(markOfInsert(st, 1)).isEqualTo("v1"); + + if (expected) { + st.execute(second); + assertThat(markOfInsert(st, 2)).as("the second trigger replaced the first").isEqualTo("v2"); + } else { + assertThatThrownBy(() -> st.execute(second)).as("a plain CREATE TRIGGER of the same name") + .isInstanceOf(SQLException.class).hasMessageContaining("already exists"); + String orReplace = second.replaceFirst("^CREATE TRIGGER", "CREATE OR REPLACE TRIGGER"); + assertThatThrownBy(() -> st.execute(orReplace)).as("PostgreSQL 13 knows no OR REPLACE") + .isInstanceOf(SQLException.class).hasMessageContaining("syntax error"); + } + } + } + } + + private static String trigger(PostgreSqlDialect dialect, String function) { + return dialect.createTrigger("items_mark", Trigger.TriggerTiming.BEFORE, Trigger.TriggerEvent.INSERT, ITEMS, + Trigger.TriggerScope.ROW, null, "EXECUTE FUNCTION " + function + "()", true); + } + + private static String markOfInsert(Statement st, int id) throws SQLException { + st.execute("INSERT INTO items(id) VALUES (" + id + ")"); + try (ResultSet rs = st.executeQuery("SELECT mark FROM items WHERE id = " + id)) { + assertThat(rs.next()).isTrue(); + return rs.getString(1); + } + } +} diff --git a/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlCreateProcedureTest.java b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlCreateProcedureTest.java new file mode 100644 index 00000000..64bf8825 --- /dev/null +++ b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlCreateProcedureTest.java @@ -0,0 +1,151 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.postgresql.integration; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.ParameterMode; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineDefinition; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineParameter; +import org.eclipse.daanse.sql.dialect.api.generator.DdlGenerator.RoutineSignature; +import org.eclipse.daanse.sql.dialect.db.postgresql.PostgreSqlDialect; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.PostgreSQLContainer; + +/** + * PostgreSQL has procedures since 11, and {@code OUT} parameters of a procedure since 14; before that a procedure + * passes a value back through {@code INOUT} only. The dialect is built from a live connection: each procedure it writes + * must be created and called on the server, and where the server has no procedures, or none with an {@code OUT} + * parameter, it must write none. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class PostgreSqlCreateProcedureTest { + + private static final String SETUP = """ + CREATE SCHEMA rt; + CREATE TABLE rt.log(msg VARCHAR(20)); + """; + + /** {@code total := total + n}, the sum passed back through the INOUT parameter. */ + private static final RoutineDefinition ADD_TO = plpgsql("add_to", "BEGIN total := total + n; END", + RoutineParameter.in("n", "integer"), new RoutineParameter("total", ParameterMode.INOUT, "integer")); + + /** The same name, the same signature, another body: it doubles. */ + private static final RoutineDefinition ADD_TO_TWICE = plpgsql("add_to", "BEGIN total := total + 2 * n; END", + RoutineParameter.in("n", "integer"), new RoutineParameter("total", ParameterMode.INOUT, "integer")); + + /** A body in SQL that writes a row. */ + private static final RoutineDefinition LOG_SQL = new RoutineDefinition("rt", "log_it", + List.of(RoutineParameter.in("m", "varchar")), null, "sql", "INSERT INTO rt.log VALUES (m)"); + + /** A body that holds {@code $$} itself, which the dialect must quote with another dollar quote. */ + private static final RoutineDefinition LOG_DOLLAR = plpgsql("log_dollar", + "BEGIN INSERT INTO rt.log VALUES ($$dollar$$); END"); + + /** An OUT parameter of a procedure. */ + private static final RoutineDefinition SQUARE = plpgsql("square", "BEGIN r := n * n; END", + RoutineParameter.in("n", "integer"), new RoutineParameter("r", ParameterMode.OUT, "integer")); + + @ParameterizedTest(name = "postgres:{0} -> procedures {1}, OUT {2}") + @CsvSource({ "10-alpine, false, false", "11-alpine, true, false", "13-alpine, true, false", + "14-alpine, true, true", "16-alpine, true, true" }) + void create_procedure(String tag, boolean procedures, boolean outParameters) throws Exception { + try (PostgreSQLContainer pg = new PostgreSQLContainer<>("postgres:" + tag)) { + pg.start(); + try (Connection c = pg.createConnection(""); Statement st = c.createStatement()) { + st.execute(SETUP); + PostgreSqlDialect dialect = new PostgreSqlDialect(DialectInitData.fromConnection(c)); + + if (!procedures) { + assertThat(dialect.createProcedure(ADD_TO, false)).as("no procedure on 10").isEmpty(); + assertThat(dialect.dropProcedure(signature("add_to"), true)).as("no DROP PROCEDURE on 10") + .isEmpty(); + assertThatThrownBy(() -> st.execute( + "CREATE PROCEDURE rt.p() LANGUAGE sql AS $$ SELECT 1 $$")) + .as("PostgreSQL 10 knows no CREATE PROCEDURE").isInstanceOf(SQLException.class) + .hasMessageContaining("syntax error"); + return; + } + + st.execute(sql(dialect, ADD_TO, false)); + assertThat(rows(st, "CALL rt.add_to(5, 10)")).as("INOUT passes the sum back").containsExactly("15"); + + assertThatThrownBy(() -> st.execute(sql(dialect, ADD_TO_TWICE, false))) + .as("without OR REPLACE the second one fails").isInstanceOf(SQLException.class) + .hasMessageContaining("already exists"); + st.execute(sql(dialect, ADD_TO_TWICE, true)); + assertThat(rows(st, "CALL rt.add_to(5, 10)")).as("OR REPLACE took the new body").containsExactly("20"); + + st.execute(sql(dialect, LOG_SQL, false)); + st.execute("CALL rt.log_it('sql')"); + String dollar = sql(dialect, LOG_DOLLAR, false); + assertThat(dollar).contains("$body$"); + st.execute(dollar); + st.execute("CALL rt.log_dollar()"); + assertThat(rows(st, "SELECT msg FROM rt.log ORDER BY msg")).containsExactly("dollar", "sql"); + + assertThat(dialect.createProcedure( + new RoutineDefinition("rt", "p", List.of(), null, "java", "x"), false)) + .as("a body in a language the dialect does not write").isEmpty(); + + if (outParameters) { + st.execute(sql(dialect, SQUARE, false)); + assertThat(rows(st, "CALL rt.square(7, NULL)")).as("OUT passes the square back") + .containsExactly("49"); + } else { + assertThat(dialect.createProcedure(SQUARE, false)).as("no OUT parameter of a procedure before 14") + .isEmpty(); + assertThatThrownBy(() -> st.execute( + "CREATE PROCEDURE rt.sq(n integer, OUT r integer) LANGUAGE sql AS $$ SELECT n * n $$")) + .as("the server refuses it").isInstanceOf(SQLException.class) + .hasMessageContaining("OUT"); + } + + st.execute(dialect.dropProcedure(signature("add_to", "integer", "integer"), false).orElseThrow()); + assertThatThrownBy(() -> st.execute("CALL rt.add_to(5, 10)")).as("dropped") + .isInstanceOf(SQLException.class).hasMessageContaining("does not exist"); + st.execute(dialect.dropProcedure(signature("add_to", "integer", "integer"), true).orElseThrow()); + } + } + } + + private static RoutineDefinition plpgsql(String name, String body, RoutineParameter... parameters) { + return new RoutineDefinition("rt", name, List.of(parameters), null, "plpgsql", body); + } + + private static RoutineSignature signature(String name, String... types) { + return new RoutineSignature("rt", name, types.length == 0 ? null : List.of(types)); + } + + private static String sql(PostgreSqlDialect dialect, RoutineDefinition procedure, boolean orReplace) { + return dialect.createProcedure(procedure, orReplace).orElseThrow(); + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } + return out; + } +} diff --git a/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlDateFromPartsTest.java b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlDateFromPartsTest.java new file mode 100644 index 00000000..8890160d --- /dev/null +++ b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlDateFromPartsTest.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.postgresql.integration; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.api.generator.KnownFunction; +import org.eclipse.daanse.sql.dialect.db.postgresql.PostgreSqlDialect; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.PostgreSQLContainer; + +/** + * PostgreSQL has {@code make_date(year, month, day)} since 9.4. The dialect is built from a live connection: from 9.4 + * on it writes {@code make_date}, before that the ISO text {@code yyyy-mm-dd} read as a date, and either way the + * server must make the right date, of literals and of columns of each numeric type, a NULL of a NULL part, and an + * error of a day the month does not have. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class PostgreSqlDateFromPartsTest { + + /** Each part of another type: make_date takes integers, so a smallint and a numeric part must be cast. */ + private static final String SETUP = """ + CREATE TABLE parts(id INT, y SMALLINT, m INTEGER, d NUMERIC(2)); + INSERT INTO parts VALUES (1, 2026, 11, 23), (2, 2024, 2, 29), (3, 1999, 1, 5), (4, 2026, NULL, 1); + """; + + @ParameterizedTest(name = "postgres:{0} -> make_date {1}") + @CsvSource({ "9.3, false", "9.4, true", "16-alpine, true" }) + void date_from_parts(String tag, boolean makeDate) throws Exception { + try (PostgreSQLContainer pg = new PostgreSQLContainer<>("postgres:" + tag)) { + pg.start(); + try (Connection c = pg.createConnection(""); Statement st = c.createStatement()) { + st.execute(SETUP); + PostgreSqlDialect dialect = new PostgreSqlDialect(DialectInitData.fromConnection(c)); + + String columns = dateFromParts(dialect, "y", "m", "d"); + assertThat(columns.startsWith("make_date(")).as(columns).isEqualTo(makeDate); + if (!makeDate) { + assertThat(columns).doesNotContainIgnoringCase("make_date"); + assertThatThrownBy(() -> dates(st, "SELECT make_date(2026, 1, 1)")) + .as("PostgreSQL 9.3 knows no make_date").isInstanceOf(SQLException.class) + .hasMessageContaining("does not exist"); + } + + assertThat(dates(st, "SELECT " + columns + " FROM parts ORDER BY id")).as("of columns: " + columns) + .containsExactly("2026-11-23", "2024-02-29", "1999-01-05", null); + + String literals = dateFromParts(dialect, "2026", "1", "9"); + assertThat(dates(st, "SELECT " + literals)).as("of literals, month and day of one digit: " + literals) + .containsExactly("2026-01-09"); + + String noSuchDay = dateFromParts(dialect, "2023", "2", "29"); + assertThatThrownBy(() -> dates(st, "SELECT " + noSuchDay)).as("29 February 2023: " + noSuchDay) + .isInstanceOf(SQLException.class).hasMessageContaining("out of range"); + + assertThatThrownBy(() -> dialect.generateKnownFunction(KnownFunction.DATE_FROM_PARTS, + List.of("2026", "1"))).isInstanceOf(IllegalArgumentException.class); + } + } + } + + private static String dateFromParts(PostgreSqlDialect dialect, String year, String month, String day) { + return dialect.generateKnownFunction(KnownFunction.DATE_FROM_PARTS, List.of(year, month, day)).toString(); + } + + private static List dates(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } + return out; + } +} diff --git a/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlListAggTest.java b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlListAggTest.java new file mode 100644 index 00000000..a83c66fb --- /dev/null +++ b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlListAggTest.java @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.postgresql.integration; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.postgresql.PostgreSqlDialect; +import org.eclipse.daanse.sql.model.sql.NullsOrder; +import org.eclipse.daanse.sql.model.sql.OrderedColumn; +import org.eclipse.daanse.sql.model.sql.SortDirection; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.testcontainers.containers.PostgreSQLContainer; + +/** + * PostgreSQL lists the values of a group with {@code STRING_AGG(text, separator ORDER BY …)}, since 9.0. 9.1 is the + * oldest image the Docker registry still serves, so the version without it is not run here. The dialect is built from + * a live connection, and the list it writes must come out of the server in the order asked for, without the NULLs, + * with any separator, of a column of any type and per group. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class PostgreSqlListAggTest { + + /** Group a: alice 20, bob 30, bob 10, a NULL name of 40; group b: dave 5. */ + private static final String SETUP = """ + CREATE TABLE emp(dept VARCHAR(1), name VARCHAR(10), salary INT); + INSERT INTO emp VALUES ('a', 'bob', 30), ('a', NULL, 40), ('a', 'alice', 20), ('a', 'bob', 10), + ('b', 'dave', 5); + """; + + @ParameterizedTest(name = "postgres:{0}") + @ValueSource(strings = { "9.1", "16-alpine" }) + void list_agg(String tag) throws Exception { + try (PostgreSQLContainer pg = new PostgreSQLContainer<>("postgres:" + tag)) { + pg.start(); + try (Connection c = pg.createConnection(""); Statement st = c.createStatement()) { + st.execute(SETUP); + PostgreSqlDialect dialect = new PostgreSqlDialect(DialectInitData.fromConnection(c)); + assertThat(dialect.supportsListAgg()).isTrue(); + + assertThat(list(st, dialect, "name", false, ", ", order("name", SortDirection.ASC))) + .as("ordered by the value, the NULL left out").isEqualTo("alice, bob, bob"); + assertThat(list(st, dialect, "name", false, ", ", order("salary", SortDirection.DESC))) + .as("ordered by another column").isEqualTo("bob, alice, bob"); + assertThat(list(st, dialect, "name", false, ", ", + List.of(new OrderedColumn("name", "emp", SortDirection.ASC)))) + .as("a column of the table").isEqualTo("alice, bob, bob"); + + assertThat(sorted(list(st, dialect, "name", true, ",", List.of()))) + .as("DISTINCT without an order").containsExactly("alice", "bob"); + assertThat(list(st, dialect, "name", true, ",", order("name", SortDirection.ASC))) + .as("DISTINCT with an order over other columns is left out, as the dialect says") + .isEqualTo("alice,bob,bob"); + + assertThat(list(st, dialect, "name", false, null, order("name", SortDirection.ASC))) + .as("no separator is a comma").isEqualTo("alice,bob,bob"); + assertThat(list(st, dialect, "name", false, "'", order("name", SortDirection.ASC))) + .as("a quote as separator").isEqualTo("alice'bob'bob"); + assertThat(list(st, dialect, "name", false, "\\", order("name", SortDirection.ASC))) + .as("a backslash as separator").isEqualTo("alice\\bob\\bob"); + + assertThat(list(st, dialect, "salary", false, ",", order("salary", SortDirection.ASC))) + .as("an INT column, cast to text").isEqualTo("10,20,30,40"); + assertThat(list(st, dialect, "salary", false, ",", + List.of(new OrderedColumn("name", null, Optional.of(SortDirection.ASC), + Optional.of(NullsOrder.FIRST)), new OrderedColumn("salary", null, SortDirection.ASC)))) + .as("NULLS FIRST, then a second column").isEqualTo("40,20,10,30"); + assertThat(list(st, dialect, "salary", false, ",", + List.of(new OrderedColumn("name", null, Optional.of(SortDirection.ASC), + Optional.of(NullsOrder.LAST)), new OrderedColumn("salary", null, SortDirection.ASC)))) + .as("NULLS LAST, then a second column").isEqualTo("20,10,30,40"); + + String perDept = dialect.generateListAgg("name", false, ",", null, null, + order("name", SortDirection.ASC)).orElseThrow(); + assertThat(rows(st, "SELECT dept, " + perDept + " FROM emp GROUP BY dept ORDER BY dept")) + .as("per group").containsExactly("a=alice,bob,bob", "b=dave"); + } + } + } + + private static List order(String column, SortDirection direction) { + return List.of(new OrderedColumn(column, null, direction)); + } + + private static String list(Statement st, PostgreSqlDialect dialect, String operand, boolean distinct, + String separator, List columns) throws SQLException { + String agg = dialect.generateListAgg(operand, distinct, separator, null, null, columns).orElseThrow(); + try (ResultSet rs = st.executeQuery("SELECT " + agg + " FROM emp WHERE dept = 'a'")) { + assertThat(rs.next()).isTrue(); + return rs.getString(1); + } + } + + private static List sorted(String list) { + return Arrays.stream(list.split(",")).sorted().toList(); + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1) + "=" + rs.getString(2)); + } + } + return out; + } +} diff --git a/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlMaterializedViewTest.java b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlMaterializedViewTest.java new file mode 100644 index 00000000..934e3362 --- /dev/null +++ b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlMaterializedViewTest.java @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.postgresql.integration; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.postgresql.PostgreSqlDialect; +import org.eclipse.daanse.sql.model.schema.SchemaReference; +import org.eclipse.daanse.sql.model.schema.TableReference; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.PostgreSQLContainer; + +/** + * PostgreSQL has materialized views since 9.3, and {@code CREATE MATERIALIZED VIEW IF NOT EXISTS} since 9.5. The + * dialect is built from a live connection: from 9.3 on the view it creates keeps the rows of its creation until it is + * refreshed and is dropped again; on 9.3 and 9.4 it asks for {@code IF NOT EXISTS} in vain, and the statement fails on + * an existing view, as the contract says; on 9.2 it writes no materialized view at all. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class PostgreSqlMaterializedViewTest { + + private static final TableReference TOTALS = new TableReference( + Optional.of(new SchemaReference(Optional.empty(), "public")), "region_totals", TableReference.TYPE_VIEW); + + private static final String SETUP = """ + CREATE TABLE sales(region VARCHAR(10), amount INT); + INSERT INTO sales VALUES ('EU', 10), ('EU', 20), ('US', 30); + """; + + private static final String SELECT = "SELECT region, SUM(amount) AS total FROM sales GROUP BY region"; + private static final String READ = "SELECT region, total FROM region_totals ORDER BY region"; + + @ParameterizedTest(name = "postgres:{0} -> materialized views {1}, IF NOT EXISTS {2}") + @CsvSource({ "9.2, false, false", "9.3, true, false", "9.4, true, false", "9.5, true, true", + "16-alpine, true, true" }) + void materialized_view(String tag, boolean views, boolean ifNotExists) throws Exception { + try (PostgreSQLContainer pg = new PostgreSQLContainer<>("postgres:" + tag)) { + pg.start(); + try (Connection c = pg.createConnection(""); Statement st = c.createStatement()) { + st.execute(SETUP); + PostgreSqlDialect dialect = new PostgreSqlDialect(DialectInitData.fromConnection(c)); + + assertThat(dialect.supportsMaterializedViews()).isEqualTo(views); + + if (!views) { + assertThat(dialect.createMaterializedView(TOTALS, SELECT, false)).isEmpty(); + assertThat(dialect.dropMaterializedView(TOTALS, true)).isEmpty(); + assertThatThrownBy(() -> st.execute("CREATE MATERIALIZED VIEW mv AS " + SELECT)) + .as("PostgreSQL 9.2 knows no materialized view").isInstanceOf(SQLException.class) + .hasMessageContaining("syntax error"); + return; + } + + st.execute(dialect.createMaterializedView(TOTALS, SELECT, false).orElseThrow()); + assertThat(rows(st, READ)).as("the rows of its creation").containsExactly("EU=30", "US=30"); + + st.execute("INSERT INTO sales VALUES ('US', 5)"); + assertThat(rows(st, READ)).as("kept until it is refreshed").containsExactly("EU=30", "US=30"); + st.execute("REFRESH MATERIALIZED VIEW region_totals"); + assertThat(rows(st, READ)).as("refreshed").containsExactly("EU=30", "US=35"); + + assertThatThrownBy(() -> st.execute(dialect.createMaterializedView(TOTALS, SELECT, false).orElseThrow())) + .as("a second one of the name").isInstanceOf(SQLException.class) + .hasMessageContaining("already exists"); + + String again = dialect.createMaterializedView(TOTALS, SELECT, true).orElseThrow(); + assertThat(again.contains("IF NOT EXISTS")).as(again).isEqualTo(ifNotExists); + if (ifNotExists) { + st.execute(again); + assertThat(rows(st, READ)).as("IF NOT EXISTS left it").containsExactly("EU=30", "US=35"); + } else { + assertThatThrownBy(() -> st.execute(again)).as("without IF NOT EXISTS it fails on it") + .isInstanceOf(SQLException.class).hasMessageContaining("already exists"); + } + + st.execute(dialect.dropMaterializedView(TOTALS, false).orElseThrow()); + assertThatThrownBy(() -> rows(st, READ)).as("dropped").isInstanceOf(SQLException.class) + .hasMessageContaining("does not exist"); + st.execute(dialect.dropMaterializedView(TOTALS, true).orElseThrow()); + } + } + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1) + "=" + rs.getInt(2)); + } + } + return out; + } +} diff --git a/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlMergeGeneratorTest.java b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlMergeGeneratorTest.java new file mode 100644 index 00000000..e8a62809 --- /dev/null +++ b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlMergeGeneratorTest.java @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.postgresql.integration; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.api.generator.MergeGenerator; +import org.eclipse.daanse.sql.dialect.api.generator.MergeGenerator.UpsertSpec; +import org.eclipse.daanse.sql.dialect.db.postgresql.PostgreSqlDialect; +import org.eclipse.daanse.sql.model.schema.SchemaReference; +import org.eclipse.daanse.sql.model.schema.TableReference; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.PostgreSQLContainer; + +/** + * PostgreSQL writes an upsert as {@code INSERT … ON CONFLICT}, which came with 9.5. The dialect is built from a live + * connection: from 9.5 on its upsert inserts a new key, updates or leaves an existing one; on 9.4 it has no upsert, and + * the server would refuse {@code ON CONFLICT}. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class PostgreSqlMergeGeneratorTest { + + private static final SchemaReference PUBLIC = new SchemaReference(Optional.empty(), "public"); + private static final TableReference PRODUCTS = new TableReference(Optional.of(PUBLIC), "products", + TableReference.TYPE_TABLE); + private static final TableReference STOCK = new TableReference(Optional.of(PUBLIC), "stock", + TableReference.TYPE_TABLE); + + private static final String SETUP = """ + CREATE TABLE products(id INT PRIMARY KEY, name VARCHAR(20), price INT); + CREATE TABLE stock(store VARCHAR(10), product INT, qty INT, PRIMARY KEY (store, product)); + INSERT INTO products VALUES (1, 'apple', 10); + INSERT INTO stock VALUES ('north', 1, 5); + """; + + private static final UpsertSpec UPDATE_PRODUCT = new UpsertSpec(PRODUCTS, List.of("id"), + List.of("id", "name", "price"), List.of("name", "price")); + private static final UpsertSpec IGNORE_PRODUCT = new UpsertSpec(PRODUCTS, List.of("id"), + List.of("id", "name", "price"), List.of()); + private static final UpsertSpec UPDATE_STOCK = new UpsertSpec(STOCK, List.of("store", "product"), + List.of("store", "product", "qty"), List.of("qty")); + + @ParameterizedTest(name = "postgres:{0} -> {1}") + @CsvSource({ "9.4, false", "9.5, true", "16-alpine, true" }) + void upsert(String tag, boolean expected) throws Exception { + try (PostgreSQLContainer pg = new PostgreSQLContainer<>("postgres:" + tag)) { + pg.start(); + try (Connection c = pg.createConnection(""); Statement st = c.createStatement()) { + st.execute(SETUP); + MergeGenerator merge = new PostgreSqlDialect(DialectInitData.fromConnection(c)).mergeGenerator(); + + assertThat(merge.supportsMerge()).isEqualTo(expected); + + if (!expected) { + assertThat(merge.upsert(UPDATE_PRODUCT, List.of("1", "'pear'", "20"))).isEmpty(); + assertThatThrownBy(() -> st.execute( + "INSERT INTO products VALUES (1, 'pear', 20) ON CONFLICT (id) DO NOTHING")) + .as("PostgreSQL 9.4 knows no ON CONFLICT").isInstanceOf(SQLException.class) + .hasMessageContaining("syntax error"); + return; + } + + st.execute(sql(merge, UPDATE_PRODUCT, "2", "'banana'", "7")); + assertThat(rows(st, "SELECT id, name, price FROM products ORDER BY id")) + .as("a new key is inserted").containsExactly("1|apple|10", "2|banana|7"); + + st.execute(sql(merge, UPDATE_PRODUCT, "1", "'apple'", "12")); + assertThat(rows(st, "SELECT id, name, price FROM products ORDER BY id")) + .as("an existing key is updated").containsExactly("1|apple|12", "2|banana|7"); + + String ignore = sql(merge, IGNORE_PRODUCT, "1", "'cherry'", "99"); + assertThat(ignore).endsWith("DO NOTHING"); + st.execute(ignore); + assertThat(rows(st, "SELECT id, name, price FROM products ORDER BY id")) + .as("without update columns an existing key is left").containsExactly("1|apple|12", "2|banana|7"); + + st.execute(sql(merge, UPDATE_STOCK, "'north'", "1", "8")); + st.execute(sql(merge, UPDATE_STOCK, "'south'", "1", "3")); + assertThat(rows(st, "SELECT store, product, qty FROM stock ORDER BY store")) + .as("a composite key").containsExactly("north|1|8", "south|1|3"); + + assertThatThrownBy(() -> merge.upsert(UPDATE_PRODUCT, List.of("3"))) + .isInstanceOf(IllegalArgumentException.class); + } + } + } + + private static String sql(MergeGenerator merge, UpsertSpec spec, String... values) { + return merge.upsert(spec, List.of(values)).orElseThrow(); + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + int n = rs.getMetaData().getColumnCount(); + while (rs.next()) { + StringBuilder row = new StringBuilder(); + for (int i = 1; i <= n; i++) { + if (i > 1) + row.append('|'); + row.append(rs.getString(i)); + } + out.add(row.toString()); + } + } + return out; + } +} diff --git a/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlOrderByNullsTest.java b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlOrderByNullsTest.java new file mode 100644 index 00000000..6e19d6ee --- /dev/null +++ b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlOrderByNullsTest.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.postgresql.integration; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.postgresql.PostgreSqlDialect; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.testcontainers.containers.PostgreSQLContainer; + +/** + * PostgreSQL knows {@code ORDER BY … NULLS FIRST | LAST} since 8.3. The dialect is built from a live connection: on + * every version here it must write that form, not the {@code CASE WHEN … IS NULL} of a database without it, and the + * server must put the nulls where it was asked to, in each of the four orders, the two that are not PostgreSQL's + * default among them. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class PostgreSqlOrderByNullsTest { + + private static final String SETUP = """ + CREATE TABLE numbers(v INT); + INSERT INTO numbers VALUES (2), (NULL), (1), (NULL), (3); + """; + + @ParameterizedTest(name = "postgres:{0}") + @ValueSource(strings = { "9.6", "10", "16-alpine" }) + void order_by_nulls(String tag) throws Exception { + try (PostgreSQLContainer pg = new PostgreSQLContainer<>("postgres:" + tag)) { + pg.start(); + try (Connection c = pg.createConnection(""); Statement st = c.createStatement()) { + st.execute(SETUP); + PostgreSqlDialect dialect = new PostgreSqlDialect(DialectInitData.fromConnection(c)); + + assertOrder(st, dialect, true, true, "1", "2", "3", null, null); + assertOrder(st, dialect, true, false, null, null, "1", "2", "3"); + assertOrder(st, dialect, false, true, "3", "2", "1", null, null); + assertOrder(st, dialect, false, false, null, null, "3", "2", "1"); + } + } + } + + private static void assertOrder(Statement st, PostgreSqlDialect dialect, boolean ascending, boolean nullsLast, + String... expected) throws SQLException { + String orderBy = dialect.generateOrderByNulls("v", ascending, nullsLast).toString(); + String label = (ascending ? "ASC" : "DESC") + (nullsLast ? " NULLS LAST" : " NULLS FIRST") + ": " + orderBy; + + assertThat(orderBy).as(label).endsWith(nullsLast ? "NULLS LAST" : "NULLS FIRST").doesNotContain("CASE"); + assertThat(values(st, "SELECT v FROM numbers ORDER BY " + orderBy)).as(label).containsExactly(expected); + } + + private static List values(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } + return out; + } +} diff --git a/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlPercentileTest.java b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlPercentileTest.java new file mode 100644 index 00000000..0b7f1ccf --- /dev/null +++ b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlPercentileTest.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.postgresql.integration; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.postgresql.PostgreSqlDialect; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.PostgreSQLContainer; + +/** + * PostgreSQL has the ordered-set aggregates {@code percentile_disc} and {@code percentile_cont … WITHIN GROUP} since + * 9.4. The dialect is built from a live connection: from 9.4 on each percentile it writes must compute the right value + * on the server, ascending and descending, over a whole table and per group; on 9.3 it must write none, for the server + * would refuse it. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class PostgreSqlPercentileTest { + + /** Group a: 10, 20, 30, 40 and a NULL that every aggregate leaves out; group b: 5 alone. */ + private static final String SETUP = """ + CREATE TABLE nums(grp VARCHAR(1), v INT); + INSERT INTO nums VALUES ('a', 30), ('a', 10), ('a', NULL), ('a', 40), ('a', 20), ('b', 5); + """; + + @ParameterizedTest(name = "postgres:{0} -> {1}") + @CsvSource({ "9.3, false", "9.4, true", "16-alpine, true" }) + void percentile(String tag, boolean expected) throws Exception { + try (PostgreSQLContainer pg = new PostgreSQLContainer<>("postgres:" + tag)) { + pg.start(); + try (Connection c = pg.createConnection(""); Statement st = c.createStatement()) { + st.execute(SETUP); + PostgreSqlDialect dialect = new PostgreSqlDialect(DialectInitData.fromConnection(c)); + + assertThat(dialect.supportsPercentileDisc()).as("supportsPercentileDisc").isEqualTo(expected); + assertThat(dialect.supportsPercentileCont()).as("supportsPercentileCont").isEqualTo(expected); + + if (!expected) { + assertThat(dialect.generatePercentileDisc(0.5, false, "nums", "v")).isEmpty(); + assertThat(dialect.generatePercentileCont(0.5, false, "nums", "v")).isEmpty(); + assertThatThrownBy(() -> rows(st, + "SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY v) FROM nums")) + .as("PostgreSQL 9.3 knows no WITHIN GROUP").isInstanceOf(SQLException.class) + .hasMessageContaining("syntax error"); + return; + } + + // discrete: the first value whose cumulative share reaches the percentile, a value of the column + assertValue(st, dialect.generatePercentileDisc(0.5, false, "nums", "v"), 20); + assertValue(st, dialect.generatePercentileDisc(0.25, false, "nums", "v"), 10); + assertValue(st, dialect.generatePercentileDisc(1.0, false, "nums", "v"), 40); + assertValue(st, dialect.generatePercentileDisc(0.5, true, "nums", "v"), 30); + assertValue(st, dialect.generatePercentileDisc(0.25, true, null, "v"), 40); + + // continuous: interpolated between the two neighbouring values + assertValue(st, dialect.generatePercentileCont(0.5, false, "nums", "v"), 25); + assertValue(st, dialect.generatePercentileCont(0.25, false, "nums", "v"), 17.5); + assertValue(st, dialect.generatePercentileCont(0.0, false, "nums", "v"), 10); + assertValue(st, dialect.generatePercentileCont(0.25, true, "nums", "v"), 32.5); + assertValue(st, dialect.generatePercentileCont(0.5, true, null, "v"), 25); + + String median = dialect.generatePercentileCont(0.5, false, "nums", "v").orElseThrow(); + assertThat(rows(st, "SELECT grp, " + median + " FROM nums GROUP BY grp ORDER BY grp")) + .as("per group").containsExactly("a=25.0", "b=5.0"); + } + } + } + + private static void assertValue(Statement st, Optional percentile, double expected) throws SQLException { + assertThat(percentile).isPresent(); + String sql = "SELECT " + percentile.get() + " FROM nums WHERE grp = 'a'"; + try (ResultSet rs = st.executeQuery(sql)) { + assertThat(rs.next()).isTrue(); + assertThat(rs.getDouble(1)).as(sql).isEqualTo(expected); + } + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1) + "=" + rs.getDouble(2)); + } + } + return out; + } +} diff --git a/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlReturningTest.java b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlReturningTest.java new file mode 100644 index 00000000..549f3408 --- /dev/null +++ b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlReturningTest.java @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.postgresql.integration; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.api.generator.MergeGenerator; +import org.eclipse.daanse.sql.dialect.api.generator.MergeGenerator.UpsertSpec; +import org.eclipse.daanse.sql.dialect.api.generator.ReturningGenerator; +import org.eclipse.daanse.sql.dialect.db.postgresql.PostgreSqlDialect; +import org.eclipse.daanse.sql.model.schema.SchemaReference; +import org.eclipse.daanse.sql.model.schema.TableReference; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.PostgreSQLContainer; + +/** + * PostgreSQL returns the rows a statement wrote with {@code RETURNING}, since 8.2, so on every version the registry + * still serves. The dialect is built from a live connection, and the clause it writes must bring back what an + * {@code INSERT}, an {@code UPDATE} and a {@code DELETE} wrote: a key the database made, a default, a quoted column of + * mixed case, every column; and from 9.5 on, with the dialect's upsert, the row it inserted or updated, and none where + * it did nothing. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class PostgreSqlReturningTest { + + private static final TableReference ITEMS = new TableReference( + Optional.of(new SchemaReference(Optional.empty(), "public")), "items", TableReference.TYPE_TABLE); + + /** A key the database makes, and a column of mixed case, which only a quoted name reaches, with a default. */ + private static final String SETUP = """ + CREATE TABLE items(id SERIAL PRIMARY KEY, name VARCHAR(20), "Note" VARCHAR(20) DEFAULT 'n/a'); + """; + + @ParameterizedTest(name = "postgres:{0} -> upsert {1}") + @CsvSource({ "9.1, false", "9.5, true", "16-alpine, true" }) + void returning(String tag, boolean upsert) throws Exception { + try (PostgreSQLContainer pg = new PostgreSQLContainer<>("postgres:" + tag)) { + pg.start(); + try (Connection c = pg.createConnection(""); Statement st = c.createStatement()) { + st.execute(SETUP); + PostgreSqlDialect dialect = new PostgreSqlDialect(DialectInitData.fromConnection(c)); + ReturningGenerator ret = dialect.returningGenerator(); + + assertThat(ret.supportsReturning()).isTrue(); + assertThat(ret.returning(List.of())).as("no columns, no clause").isEmpty(); + assertThat(ret.returning(null)).as("no columns, no clause").isEmpty(); + + assertThat(rows(st, "INSERT INTO items(name) VALUES ('apple')" + clause(ret, "id"))) + .as("the key the database made").containsExactly("1"); + assertThat(rows(st, "INSERT INTO items(name) VALUES ('pear'), ('plum')" + clause(ret, "id", "name"))) + .as("two rows, two columns").containsExactly("2|pear", "3|plum"); + assertThat(rows(st, "INSERT INTO items(name) VALUES ('fig')" + clause(ret, "Note"))) + .as("a quoted column of mixed case, its default").containsExactly("n/a"); + assertThat(rows(st, "INSERT INTO items(name, \"Note\") VALUES ('kiwi', 'green')" + clause(ret, "*"))) + .as("every column").containsExactly("5|kiwi|green"); + + try (PreparedStatement ps = c.prepareStatement( + "INSERT INTO items(name) VALUES (?)" + clause(ret, "id", "name"))) { + ps.setString(1, "lime"); + assertThat(rows(ps)).as("prepared, with a parameter").containsExactly("6|lime"); + } + + assertThat(rows(st, "UPDATE items SET \"Note\" = 'sold' WHERE id IN (1, 2)" + + clause(ret, "id", "Note"))) + .as("UPDATE, the new values").containsExactlyInAnyOrder("1|sold", "2|sold"); + assertThat(rows(st, "DELETE FROM items WHERE name LIKE 'p%'" + clause(ret, "name"))) + .as("DELETE, the rows it removed").containsExactlyInAnyOrder("pear", "plum"); + assertThat(rows(st, "DELETE FROM items WHERE id = 99" + clause(ret, "id"))) + .as("nothing deleted, no row").isEmpty(); + + MergeGenerator merge = dialect.mergeGenerator(); + assertThat(merge.supportsMerge()).isEqualTo(upsert); + if (upsert) { + UpsertSpec update = new UpsertSpec(ITEMS, List.of("id"), List.of("id", "name"), List.of("name")); + UpsertSpec ignore = new UpsertSpec(ITEMS, List.of("id"), List.of("id", "name"), List.of()); + + assertThat(rows(st, merge.upsert(update, List.of("1", "'apricot'")).orElseThrow() + + clause(ret, "id", "name"))).as("upsert of an existing key, the updated row") + .containsExactly("1|apricot"); + assertThat(rows(st, merge.upsert(update, List.of("50", "'mango'")).orElseThrow() + + clause(ret, "id", "name"))).as("upsert of a new key, the inserted row") + .containsExactly("50|mango"); + assertThat(rows(st, merge.upsert(ignore, List.of("50", "'melon'")).orElseThrow() + + clause(ret, "id", "name"))).as("DO NOTHING on an existing key, no row").isEmpty(); + } + } + } + } + + private static String clause(ReturningGenerator ret, String... columns) { + return ret.returning(List.of(columns)).orElseThrow(); + } + + private static List rows(Statement st, String sql) throws SQLException { + try (ResultSet rs = st.executeQuery(sql)) { + return rows(rs); + } + } + + private static List rows(PreparedStatement ps) throws SQLException { + try (ResultSet rs = ps.executeQuery()) { + return rows(rs); + } + } + + private static List rows(ResultSet rs) throws SQLException { + List out = new ArrayList<>(); + int n = rs.getMetaData().getColumnCount(); + while (rs.next()) { + StringBuilder row = new StringBuilder(); + for (int i = 1; i <= n; i++) { + if (i > 1) + row.append('|'); + row.append(rs.getString(i)); + } + out.add(row.toString()); + } + return out; + } +} diff --git a/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlTriggerUsingProcedureTest.java b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlTriggerUsingProcedureTest.java new file mode 100644 index 00000000..de9af6a2 --- /dev/null +++ b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlTriggerUsingProcedureTest.java @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.postgresql.integration; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.postgresql.PostgreSqlDialect; +import org.eclipse.daanse.sql.model.schema.SchemaReference; +import org.eclipse.daanse.sql.model.schema.TableReference; +import org.eclipse.daanse.sql.model.schema.Trigger.TriggerEvent; +import org.eclipse.daanse.sql.model.schema.Trigger.TriggerScope; +import org.eclipse.daanse.sql.model.schema.Trigger.TriggerTiming; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.containers.PostgreSQLContainer; + +/** + * A PostgreSQL trigger calls a trigger function: {@code EXECUTE FUNCTION f()} since 11, {@code EXECUTE PROCEDURE f()} + * before. The dialect is built from a live connection, and the trigger function and the trigger it writes must fire on + * the server: before a row is inserted, after a row is updated where the WHEN condition holds, once after a statement, + * with a body replaced and a body that holds {@code $$}; and both are dropped again. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class PostgreSqlTriggerUsingProcedureTest { + + private static final TableReference ITEMS = new TableReference( + Optional.of(new SchemaReference(Optional.empty(), "public")), "items", TableReference.TYPE_TABLE); + + private static final String SETUP = """ + CREATE TABLE items(id INT, mark VARCHAR(10)); + CREATE TABLE audit(op VARCHAR(10), item_id INT); + """; + + @ParameterizedTest(name = "postgres:{0} -> EXECUTE FUNCTION {1}") + @CsvSource({ "9.6, false", "10-alpine, false", "11-alpine, true", "16-alpine, true" }) + void trigger_using_procedure(String tag, boolean executeFunction) throws Exception { + try (PostgreSQLContainer pg = new PostgreSQLContainer<>("postgres:" + tag)) { + pg.start(); + try (Connection c = pg.createConnection(""); Statement st = c.createStatement()) { + st.execute(SETUP); + PostgreSqlDialect dialect = new PostgreSqlDialect(DialectInitData.fromConnection(c)); + + st.execute(procedure(dialect, "mark_row", "BEGIN NEW.mark := 'v1'; RETURN NEW; END")); + String markTrigger = dialect.createTriggerUsingProcedure("items_mark", "public", TriggerTiming.BEFORE, + TriggerEvent.INSERT, ITEMS, TriggerScope.ROW, null, "mark_row"); + assertThat(markTrigger).contains(executeFunction ? "EXECUTE FUNCTION" : "EXECUTE PROCEDURE"); + st.execute(markTrigger); + st.execute("INSERT INTO items(id) VALUES (1)"); + assertThat(rows(st, "SELECT mark FROM items WHERE id = 1")).as("BEFORE INSERT").containsExactly("v1"); + + st.execute(procedure(dialect, "mark_row", "BEGIN NEW.mark := 'v2'; RETURN NEW; END")); + st.execute("INSERT INTO items(id) VALUES (2)"); + assertThat(rows(st, "SELECT mark FROM items WHERE id = 2")).as("the replaced body") + .containsExactly("v2"); + + st.execute(procedure(dialect, "audit_row", + "BEGIN INSERT INTO audit VALUES (TG_OP, NEW.id); RETURN NULL; END")); + st.execute(dialect.createTriggerUsingProcedure("items_audit", "public", TriggerTiming.AFTER, + TriggerEvent.UPDATE, ITEMS, TriggerScope.ROW, "OLD.mark IS DISTINCT FROM NEW.mark", + "audit_row")); + st.execute("UPDATE items SET mark = 'v1' WHERE id = 1"); + assertThat(rows(st, "SELECT op FROM audit")).as("WHEN does not hold, nothing logged").isEmpty(); + st.execute("UPDATE items SET mark = 'x' WHERE id IN (1, 2)"); + assertThat(rows(st, "SELECT op || ':' || item_id FROM audit ORDER BY item_id")) + .as("AFTER UPDATE, once per row").containsExactly("UPDATE:1", "UPDATE:2"); + + st.execute("DELETE FROM audit"); + st.execute(procedure(dialect, "audit_statement", + "BEGIN INSERT INTO audit VALUES (TG_OP, NULL); RETURN NULL; END")); + st.execute(dialect.createTriggerUsingProcedure("items_delete", "public", TriggerTiming.AFTER, + TriggerEvent.DELETE, ITEMS, TriggerScope.STATEMENT, null, "audit_statement")); + st.execute("DELETE FROM items WHERE id IN (1, 2)"); + assertThat(rows(st, "SELECT op FROM audit")).as("AFTER DELETE, once for the statement") + .containsExactly("DELETE"); + + st.execute(procedure(dialect, "mark_row", "BEGIN NEW.mark := $$dollar$$; RETURN NEW; END")); + st.execute("INSERT INTO items(id) VALUES (3)"); + assertThat(rows(st, "SELECT mark FROM items WHERE id = 3")).as("a body that holds $$") + .containsExactly("dollar"); + + for (String sql : dialect.dropTriggerOnTable("items_mark", ITEMS, false)) { + st.execute(sql); + } + st.execute("INSERT INTO items(id) VALUES (4)"); + assertThat(rows(st, "SELECT mark FROM items WHERE id = 4")).as("the trigger dropped") + .containsExactly((String) null); + for (String sql : dialect.dropTriggerOnTable("items_mark", ITEMS, true)) { + st.execute(sql); + } + + st.execute(dialect.dropProcedure("mark_row", "public", false).orElseThrow()); + assertThatThrownBy(() -> rows(st, "SELECT 'public.mark_row()'::regprocedure")) + .as("the trigger function dropped").isInstanceOf(SQLException.class) + .hasMessageContaining("does not exist"); + st.execute(dialect.dropProcedure("mark_row", "public", true).orElseThrow()); + } + } + } + + private static String procedure(PostgreSqlDialect dialect, String name, String body) { + return dialect.createTriggerProcedure(name, "public", body).orElseThrow(); + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1)); + } + } + return out; + } +} diff --git a/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlVersionSelectTest.java b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlVersionSelectTest.java new file mode 100644 index 00000000..cbf56a06 --- /dev/null +++ b/dialect/db/postgresql/src/test/java/org/eclipse/daanse/sql/dialect/db/postgresql/integration/PostgreSqlVersionSelectTest.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + */ +package org.eclipse.daanse.sql.dialect.db.postgresql.integration; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.daanse.sql.dialect.api.DialectInitData; +import org.eclipse.daanse.sql.dialect.db.postgresql.PostgreSqlDialect; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.testcontainers.containers.PostgreSQLContainer; + +/** + * Starts a PostgreSQL of a given version in Docker and runs a SELECT on it. The dialect is built from the live + * connection, so its {@code supportsGroupingSets()} is checked against what the server really does. + */ +//@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class PostgreSqlVersionSelectTest { + + private static final String SETUP = """ + CREATE TABLE sales(region VARCHAR(10), product VARCHAR(10), amount INT); + INSERT INTO sales VALUES ('EU','A',10), ('EU','B',20), ('US','A',30); + """; + + private static final String GROUPING_SETS_SELECT = """ + SELECT region, SUM(amount) FROM sales + GROUP BY GROUPING SETS ((region), ()) + ORDER BY region NULLS LAST + """; + + @ParameterizedTest(name = "postgres:{0}") + @ValueSource(strings = { "9.4", "9.6", "12-alpine", "16-alpine" }) + void select_on_postgres_version(String tag) throws Exception { + try (PostgreSQLContainer pg = new PostgreSQLContainer<>("postgres:" + tag)) { + pg.start(); + try (Connection c = pg.createConnection(""); Statement st = c.createStatement()) { + + try (ResultSet rs = st.executeQuery("SELECT 1")) { + assertThat(rs.next()).isTrue(); + assertThat(rs.getInt(1)).isEqualTo(1); + } + + st.execute(SETUP); + PostgreSqlDialect dialect = new PostgreSqlDialect(DialectInitData.fromConnection(c)); + + if (dialect.supportsGroupingSets()) { + assertThat(rows(st, GROUPING_SETS_SELECT)).containsExactly("EU=30", "US=30", "null=60"); + } else { + assertThatThrownBy(() -> st.executeQuery(GROUPING_SETS_SELECT)).isInstanceOf(SQLException.class); + } + } + } + } + + private static List rows(Statement st, String sql) throws SQLException { + List out = new ArrayList<>(); + try (ResultSet rs = st.executeQuery(sql)) { + while (rs.next()) { + out.add(rs.getString(1) + "=" + rs.getInt(2)); + } + } + return out; + } +}