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 @@ -2506,16 +2506,9 @@ There are several ways to call native or user-defined SQL functions.
- A native or user-defined function may be called using JPQL's `function` syntax, for example, ``function('sinh', phi)``.
(This is the easiest way, but not the best way.)
- A user-written `FunctionContributor` may register user-defined functions.
- A custom `Dialect` may register additional native functions by overriding `initializeFunctionRegistry()`.
- A custom `Dialect` may register additional native functions by overriding `initializeFunctionRegistry()`. <<hql-user-defined-functions-implementation, Example of implementation.>>

[TIP]
====
Registering a function isn't hard, but is beyond the scope of this chapter.

(It's even possible to use the APIs Hibernate provides to make your own _portable_ functions!)
====

Fortunately, every built-in `Dialect` already registers many native functions for the database it supports.
Fortunately, every built-in `Dialect` already registers many native functions for the database it supports. So there is no need to define this functions explicitly.

[TIP]
====
Expand Down Expand Up @@ -4160,3 +4153,130 @@ Hibernate does emulate the `search` and `cycle` clauses though if necessary, so

Note that most modern database versions support recursive CTEs already.
====

[[hql-user-defined-functions-implementation]]
=== User-defined functions implementation

Hibernate Dialects can register additional functions known to be available for that particular database product.
These functions are also available in HQL (and JPQL, though only when using Hibernate as the JPA provider, obviously).
However, they would only be available when using that database Dialect.
Applications that aim for database portability should avoid using functions in this category.

Application developers can also supply their own set of functions.
This would usually represent either user-defined SQL functions or aliases for snippets of SQL.

Such function can be declared by using the `register()` method of `org.hibernate.query.sqm.function.SqmFunctionRegistry`.

For example, we have the following SQL function:

[[hql-user-defined-function-example]]
.Custom aggregate function
====
[source, SQL, indent=0]
----
include::{extrasdir}/hql-user-defined-function-example.sql[]
----
====

Also, we have the `Employee` entity.

[[hql-user-defined-function-domain-model]]
.Domain model
====
[source, JAVA, indent=0]
----
include::{example-dir-hql}/customFunctions/Employee.java[tags=hql-examples-domain-model-example]
----
====

Let’s persist the following entities in our database:

[[hql-user-defined-function-inital-data]]
.Initial data
====
[source, JAVA, indent=0]
----
include::{example-dir-hql}/customFunctions/CustomDialectFunctionTest.java[tags=hql-user-defined-dialect-function-inital-data]
----
====

The first step for implementing a custom function is to create a custom dialect `ExtendedPGDialect`, which inherits from `PostgreSQLDialect`.

[[hql-user-defined-dialect-function-cutom-dialect]]
.Custom dialect
====
[source, JAVA, indent=0]
----
include::{example-dir-hql}/customFunctions/ExtendedPGDialect.java[tags=hql-user-defined-dialect-function-custom-dialect]
----
====

Secondly, we will set the `ExtendedPGDialect` to Hibernate config.

[[hql-user-defined-dialect-function-cutom-dialect-property]]
.Custom dialect property
====
[source, xml, indent=0]
----
<session-factory>
<!-- Other properties -->
<property name="hibernate.dialect">path.to.the.ExtendedPGDialect</property>
</session-factory>
----
====

For implementing custom function we should inherit the new class `CountItemsGreaterValSqmFunction` from `AbstractSqmSelfRenderingFunctionDescriptor` class.

[NOTE]
====
Constructor of `org.hibernate.query.sqm.function.AbstractSqmSelfRenderingFunctionDescriptor` contains the following fields:

* `String name` - name of the function _in the database_
* `FunctionKind` - type of the function: `NORMAL`, `AGGREGATE`, `ORDERED_SET_AGGREGATE` or `WINDOW`
* `ArgumentsValidator` - validator of the arguments provided to an JPQL/HQL function
* `FunctionReturnTypeResolver` - resolver of the function return type
* `FunctionArgumentTypeResolver` - resolver of the function argument types
====

[[hql-user-defined-dialect-function-sqm-renderer]]
.Custom function renderer
====
[source, JAVA, indent=0]
----
include::{example-dir-hql}/customFunctions/CountItemsGreaterValSqmFunction.java[tags=hql-user-defined-dialect-function-sqm-renderer]
----
====

Next step we should define the renderer:

[[hql-user-defined-dialect-function-sqm-renderer-definition]]
.Custom function renderer definition
====
[source, JAVA, indent=0]
----
include::{example-dir-hql}/customFunctions/CountItemsGreaterValSqmFunction.java[tags=hql-user-defined-dialect-function-sqm-renderer-definition]
----
====

Then we'll extend the `initializeFunctionRegistry()` method of the `ExtendedPGDialect` with new the logic:
adding `CountItemsGreaterValSqmFunction` to the default function registry of `FunctionContributions`.

[[hql-user-defined-dialect-function-registry-extending]]
.Custom dialect
====
[source, JAVA, indent=0]
----
include::{example-dir-hql}/customFunctions/ExtendedPGDialect.java[tags=hql-user-defined-dialect-function-registry-extending]
----
====

Once the `countItemsGreaterVal` function has been registered, we are able to use it in our JPQL/HQL queries.

[[hql-user-defined-dialect-function-test]]
.Test of the custom function
====
[source, JAVA, indent=0]
----
include::{example-dir-hql}/customFunctions/CustomDialectFunctionTest.java[tags=hql-user-defined-dialect-function-test]
----
====
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
CREATE OR REPLACE FUNCTION greater_than(count BIGINT, value NUMERIC, gr_val NUMERIC)
RETURNS BIGINT AS
$$
BEGIN
RETURN CASE WHEN value > gr_val THEN (count + 1)::BIGINT ELSE count::BIGINT END;
END;
$$ LANGUAGE "plpgsql";

CREATE OR REPLACE FUNCTION agg_final(c bigint) RETURNS BIGINT AS
$$
BEGIN
return c;
END;
$$ LANGUAGE "plpgsql";

CREATE OR REPLACE AGGREGATE count_items_greater_val(NUMERIC, NUMERIC) (
SFUNC = greater_than,
STYPE = BIGINT,
FINALFUNC = agg_final,
INITCOND = 0);
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
/*
* SPDX-License-Identifier: Apache-2.0
* Copyright Red Hat Inc. and Hibernate Authors
*/
package org.hibernate.orm.test.hql.customFunctions;

import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.function.CastFunction;
import org.hibernate.metamodel.mapping.JdbcMapping;
import org.hibernate.query.sqm.function.AbstractSqmSelfRenderingFunctionDescriptor;
import org.hibernate.query.sqm.function.FunctionKind;
import org.hibernate.query.sqm.produce.function.*;
import org.hibernate.sql.ast.Clause;
import org.hibernate.sql.ast.SqlAstTranslator;
import org.hibernate.sql.ast.spi.SqlAppender;
import org.hibernate.sql.ast.tree.SqlAstNode;
import org.hibernate.sql.ast.tree.expression.CastTarget;
import org.hibernate.sql.ast.tree.expression.Expression;
import org.hibernate.sql.ast.tree.predicate.Predicate;
import org.hibernate.type.BasicType;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.type.spi.TypeConfiguration;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

import static org.hibernate.query.sqm.produce.function.FunctionParameterType.NUMERIC;

//tag::hql-user-defined-dialect-function-sqm-renderer[]
public class CountItemsGreaterValSqmFunction extends AbstractSqmSelfRenderingFunctionDescriptor {
private final CastFunction castFunction;
private final BasicType<BigDecimal> bigDecimalType;

public CountItemsGreaterValSqmFunction(String name, Dialect dialect, TypeConfiguration typeConfiguration) {
super(
name,
FunctionKind.AGGREGATE,
/* Function consumes 2 numeric typed args:
- the aggregation argument
- the bottom edge for the count predicate*/
new ArgumentTypesValidator(StandardArgumentsValidators.exactly(2),
FunctionParameterType.NUMERIC,
FunctionParameterType.NUMERIC
),
// Function returns one value - the number of items
StandardFunctionReturnTypeResolvers.invariant(
typeConfiguration.getBasicTypeRegistry()
.resolve(StandardBasicTypes.BIG_INTEGER)
),
StandardFunctionArgumentTypeResolvers.invariant(
typeConfiguration, NUMERIC, NUMERIC
)
);
// Extracting cast function for setting input arguments to correct the type
castFunction = new CastFunction(
dialect,
dialect.getPreferredSqlTypeCodeForBoolean()
);
bigDecimalType = typeConfiguration.getBasicTypeRegistry()
.resolve(StandardBasicTypes.BIG_DECIMAL);
}

@Override
public void render(
SqlAppender sqlAppender,
List<? extends SqlAstNode> sqlAstArguments,
SqlAstTranslator<?> walker) {
render(sqlAppender, sqlAstArguments, null, walker);
}

//tag::hql-user-defined-dialect-function-sqm-renderer-definition[]
@Override
public void render(
SqlAppender sqlAppender,
List<? extends SqlAstNode> sqlAstArguments,
Predicate filter,
SqlAstTranslator<?> translator) {
Comment on lines +73 to +78
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm really not sure how much of an open invitation we really want to be giving to users to start depending on some of these SPIs in their application programs.

Yes, it's true that org.hibernate.sql.ast and org.hibernate.sql.ast.tree are technically SPIs, but they're both marked @Incubating for the very good reason that:

  1. they're an extremely broad SPI surface, and
  2. not really stabilized in any meaningful sense.

So I would leave this undocumented for now.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's close this and the Jira then.

I didn't find an issue about adding a proper API to define custom functions though. Should I create one, or is this not a feature we want to expose beyond an incubating SPI?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't find an issue about adding a proper API to define custom functions though.

I did have something at some stage.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should I create one

Yeah go ahead.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The intent was always to allow users to contribute custom function definitions. It's just a question of getting the SPI correct.

// Renderer definition
//end::hql-user-defined-dialect-function-sqm-renderer[]

// Appending name of SQL function to result query
sqlAppender.appendSql(getName());
sqlAppender.appendSql('(');

// Extracting 2 arguments
final Expression first_arg = (Expression) sqlAstArguments.get(0);
final Expression second_arg = (Expression) sqlAstArguments.get(1);

// If JPQL contains "filter" expression, but database doesn't support it
// then append: function_name(case when (filter_expr) then (argument) else null end)
final boolean caseWrapper = filter != null && !translator.supportsFilterClause();
if (caseWrapper) {
translator.getCurrentClauseStack().push(Clause.WHERE);
sqlAppender.appendSql("case when ");

filter.accept(translator);
translator.getCurrentClauseStack().pop();

sqlAppender.appendSql(" then ");
renderArgument(sqlAppender, translator, first_arg);
sqlAppender.appendSql(" else null end)");
} else {
renderArgument(sqlAppender, translator, first_arg);
sqlAppender.appendSql(", ");
renderArgument(sqlAppender, translator, second_arg);
sqlAppender.appendSql(')');
if (filter != null) {
translator.getCurrentClauseStack().push(Clause.WHERE);
sqlAppender.appendSql(" filter (where ");

filter.accept(translator);
sqlAppender.appendSql(')');
translator.getCurrentClauseStack().pop();
}
}
//tag::hql-user-defined-dialect-function-sqm-renderer[]
}

//end::hql-user-defined-dialect-function-sqm-renderer[]
private void renderArgument(
SqlAppender sqlAppender,
SqlAstTranslator<?> translator,
Expression arg) {
// Extracting the type of argument
final JdbcMapping sourceMapping = arg.getExpressionType().getJdbcMappings().get(0);
if (sourceMapping.getJdbcType().isNumber()) {
castFunction.render(sqlAppender,
Arrays.asList(arg, new CastTarget(bigDecimalType)),
translator
);
} else {
arg.accept(translator);
}
}
//tag::hql-user-defined-dialect-function-sqm-renderer[]
//end::hql-user-defined-dialect-function-sqm-renderer-definition[]
}
//end::hql-user-defined-dialect-function-sqm-renderer[]
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* SPDX-License-Identifier: Apache-2.0
* Copyright Red Hat Inc. and Hibernate Authors
*/
package org.hibernate.orm.test.hql.customFunctions;

import jakarta.persistence.EntityManager;
import org.hibernate.Session;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.PostgreSQLDialect;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.hibernate.testing.orm.junit.RequiresDialect;
import org.junit.Test;


import java.sql.Statement;

import static org.hibernate.testing.transaction.TransactionUtil.doInJPA;
import static org.junit.Assert.assertEquals;

@RequiresDialect(PostgreSQLDialect.class)
public class CustomDialectFunctionTest extends BaseCoreFunctionalTestCase {

@Override
protected void configure(Configuration configuration) {
super.configure(configuration);
configuration.addAnnotatedClass(Employee.class);

configuration.setProperty(AvailableSettings.DIALECT, "org.hibernate.orm.test.hql.customFunctions.ExtendedPGDialect");
}

@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[]{
Employee.class
};
}

@Test
@RequiresDialect(PostgreSQLDialect.class)
public void test_custom_sqm_functions() {
doInJPA(this::sessionFactory, session -> {
try (EntityManager entityManager = session.getEntityManagerFactory().createEntityManager()) {
var tx = entityManager.getTransaction();
tx.begin();

entityManager.unwrap(Session.class).doWork(connection -> {
try (Statement statement = connection.createStatement()) {
statement.executeUpdate(
"create or replace function greater_than(c bigint, val numeric, gr_val numeric) returns bigint as $$ begin return case when val > gr_val then (c + 1)::bigint else c::bigint end; end; $$ language 'plpgsql'; " +
"create or replace function agg_final(c bigint) returns bigint as $$ begin return c; end; $$ language 'plpgsql'; " +
"create or replace aggregate count_items_greater_val(numeric, numeric) (sfunc = greater_than, stype = bigint, finalfunc = agg_final, initcond = 0);"
);
}
});

//tag::hql-user-defined-dialect-function-inital-data[]
entityManager.persist(new Employee(1L, 200L, "Jonn", "Robson"));
entityManager.persist(new Employee(2L, 350L, "Bert", "Marshall"));
entityManager.persist(new Employee(3L, 360L, "Joey", "Barton"));
entityManager.persist(new Employee(4L, 400L, "Bert", "Marshall"));
//end::hql-user-defined-dialect-function-inital-data[]

tx.commit();
//tag::hql-user-defined-dialect-function-test[]
var res = entityManager
.createQuery("select count_items_greater_val(salary, 220) from Employee")
.getSingleResult();
assertEquals(3L, res);
//end::hql-user-defined-dialect-function-test[]
}
});
}

}
Loading