-
-
Notifications
You must be signed in to change notification settings - Fork 3.7k
HHH-16648 Documentation for implementing custom JPQL/HQL functions #6605
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
+484
−9
Closed
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
20 changes: 20 additions & 0 deletions
20
...c/main/asciidoc/userguide/chapters/query/hql/extras/hql-user-defined-function-example.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
139 changes: 139 additions & 0 deletions
139
...test/java/org/hibernate/orm/test/hql/customFunctions/CountItemsGreaterValSqmFunction.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) { | ||
// 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[] |
76 changes: 76 additions & 0 deletions
76
...e/src/test/java/org/hibernate/orm/test/hql/customFunctions/CustomDialectFunctionTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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[] | ||
} | ||
}); | ||
} | ||
|
||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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
andorg.hibernate.sql.ast.tree
are technically SPIs, but they're both marked@Incubating
for the very good reason that:So I would leave this undocumented for now.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I did have something at some stage.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah go ahead.
There was a problem hiding this comment.
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.