Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1093,7 +1093,8 @@ default Optional<String> 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<String> dropFunction(RoutineSignature function, boolean ifExists) {
return Optional.empty();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -265,12 +265,15 @@ public Optional<String> 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,
Expand All @@ -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()}. */
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -472,6 +477,9 @@ public boolean supportsListAgg() {

@Override
public java.util.Optional<String> 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(")");
Expand All @@ -487,21 +495,34 @@ public java.util.Optional<String> 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<String> 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());
}

@Override
public java.util.Optional<String> 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());
}
Expand All @@ -514,14 +535,19 @@ public java.util.Optional<String> 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
Expand All @@ -533,7 +559,10 @@ public boolean supportsNthValue() {
@Override
public StringBuilder generateKnownFunction(org.eclipse.daanse.sql.dialect.api.generator.KnownFunction function,
java.util.List<? extends CharSequence> 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());
}
Expand Down Expand Up @@ -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<String> 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}. */
Expand Down Expand Up @@ -629,26 +671,45 @@ public Optional<String> 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<String> 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 "
+ qualifiedRoutine(procedure.schemaName(), procedure.name()) + "(" + parameters(procedure) + ")"
+ " 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<String> 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<String> dropProcedure(RoutineSignature procedure, boolean ifExists) {
if (!dialectVersion.isUnknownOrAtLeast(11, 0)) {
return Optional.empty();
}
return Optional.of("DROP PROCEDURE " + (ifExists ? "IF EXISTS " : "") + signature(procedure));
}

Expand Down
Original file line number Diff line number Diff line change
@@ -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<BitOperation, Integer> 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<BitOperation> 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);
}
}
}
Loading
Loading