HHH-17335 Add array_remove_index function

This commit is contained in:
Christian Beikov 2023-10-24 14:16:41 +02:00
parent 865365e6ec
commit 950423e7dd
17 changed files with 359 additions and 20 deletions

View File

@ -1288,6 +1288,19 @@ include::{array-example-dir-hql}/ArrayRemoveTest.java[tags=hql-array-remove-exam
----
====
[[hql-array-remove-index-functions]]
===== `array_remove_index()`
Returns an array copy with the element at the given index removed from the array.
[[hql-array-remove-index-example]]
====
[source, JAVA, indent=0]
----
include::{array-example-dir-hql}/ArrayRemoveIndexTest.java[tags=hql-array-remove-index-example]
----
====
[[hql-user-defined-functions]]
==== Native and user-defined functions

View File

@ -474,7 +474,8 @@ public class CockroachLegacyDialect extends Dialect {
functionFactory.arrayContainsAnyNullable_operator();
functionFactory.arrayGet_bracket();
functionFactory.arraySet_unnest();
functionFactory.arrayRemove_unnest();
functionFactory.arrayRemove();
functionFactory.arrayRemoveIndex_postgresql();
functionContributions.getFunctionRegistry().register(
"trunc",

View File

@ -383,6 +383,7 @@ public class H2LegacyDialect extends Dialect {
functionFactory.arrayGet_h2();
functionFactory.arraySet_h2();
functionFactory.arrayRemove_h2();
functionFactory.arrayRemoveIndex_h2();
}
else {
// Use group_concat until 2.x as listagg was buggy

View File

@ -261,6 +261,7 @@ public class HSQLLegacyDialect extends Dialect {
functionFactory.arrayGet_unnest();
functionFactory.arraySet_hsql();
functionFactory.arrayRemove_hsql();
functionFactory.arrayRemoveIndex_unnest();
}
@Override

View File

@ -297,6 +297,7 @@ public class OracleLegacyDialect extends Dialect {
functionFactory.arrayGet_oracle();
functionFactory.arraySet_oracle();
functionFactory.arrayRemove_oracle();
functionFactory.arrayRemoveIndex_oracle();
}
@Override

View File

@ -594,7 +594,8 @@ public class PostgreSQLLegacyDialect extends Dialect {
functionFactory.arrayContainsAnyNullable_operator();
functionFactory.arrayGet_bracket();
functionFactory.arraySet_unnest();
functionFactory.arrayRemove_unnest();
functionFactory.arrayRemove();
functionFactory.arrayRemoveIndex_postgresql();
if ( getVersion().isSameOrAfter( 9, 4 ) ) {
functionFactory.makeDateTimeTimestamp();

View File

@ -461,7 +461,8 @@ public class CockroachDialect extends Dialect {
functionFactory.arrayContainsAnyNullable_operator();
functionFactory.arrayGet_bracket();
functionFactory.arraySet_unnest();
functionFactory.arrayRemove_unnest();
functionFactory.arrayRemove();
functionFactory.arrayRemoveIndex_postgresql();
functionContributions.getFunctionRegistry().register(
"trunc",

View File

@ -323,6 +323,7 @@ public class H2Dialect extends Dialect {
functionFactory.arrayGet_h2();
functionFactory.arraySet_h2();
functionFactory.arrayRemove_h2();
functionFactory.arrayRemoveIndex_h2();
}
@Override

View File

@ -201,6 +201,7 @@ public class HSQLDialect extends Dialect {
functionFactory.arrayGet_unnest();
functionFactory.arraySet_hsql();
functionFactory.arrayRemove_hsql();
functionFactory.arrayRemoveIndex_unnest();
}
@Override

View File

@ -399,6 +399,26 @@ public class OracleArrayJdbcType extends ArrayJdbcType {
false
)
);
database.addAuxiliaryDatabaseObject(
new NamedAuxiliaryDatabaseObject(
arrayTypeName + "_remove_index",
database.getDefaultNamespace(),
new String[]{
"create or replace function " + arrayTypeName + "_remove_index(arr in " + arrayTypeName +
", idx in number) return " + arrayTypeName + " deterministic is " +
"res " + arrayTypeName + ":=" + arrayTypeName + "(); begin " +
"if arr is null or idx is null then return arr; end if; " +
"for i in 1 .. arr.count loop " +
"if i<>idx then res.extend; res(res.last) := arr(i); end if; " +
"end loop; " +
"return res; " +
"end;"
},
new String[] { "drop function " + arrayTypeName + "_remove_index" },
emptySet(),
false
)
);
}
protected String createOrReplaceConcatFunction(String arrayTypeName) {

View File

@ -326,6 +326,7 @@ public class OracleDialect extends Dialect {
functionFactory.arrayGet_oracle();
functionFactory.arraySet_oracle();
functionFactory.arrayRemove_oracle();
functionFactory.arrayRemoveIndex_oracle();
}
@Override

View File

@ -642,7 +642,8 @@ public class PostgreSQLDialect extends Dialect {
functionFactory.arrayContainsAnyNullable_operator();
functionFactory.arrayGet_bracket();
functionFactory.arraySet_unnest();
functionFactory.arrayRemove_unnest();
functionFactory.arrayRemove();
functionFactory.arrayRemoveIndex_postgresql();
functionFactory.makeDateTimeTimestamp();
// Note that PostgreSQL doesn't support the OVER clause for ordered set-aggregate functions

View File

@ -22,11 +22,13 @@ import org.hibernate.dialect.function.array.ArrayContainsQuantifiedOperatorFunct
import org.hibernate.dialect.function.array.ArrayContainsOperatorFunction;
import org.hibernate.dialect.function.array.ArrayContainsQuantifiedUnnestFunction;
import org.hibernate.dialect.function.array.ArrayGetUnnestFunction;
import org.hibernate.dialect.function.array.ArrayRemoveIndexUnnestFunction;
import org.hibernate.dialect.function.array.ArraySetUnnestFunction;
import org.hibernate.dialect.function.array.ArrayViaArgumentReturnTypeResolver;
import org.hibernate.dialect.function.array.ElementViaArrayArgumentReturnTypeResolver;
import org.hibernate.dialect.function.array.H2ArrayContainsQuantifiedEmulation;
import org.hibernate.dialect.function.array.H2ArrayRemoveFunction;
import org.hibernate.dialect.function.array.H2ArrayRemoveIndexFunction;
import org.hibernate.dialect.function.array.H2ArraySetFunction;
import org.hibernate.dialect.function.array.HSQLArrayPositionFunction;
import org.hibernate.dialect.function.array.HSQLArrayRemoveFunction;
@ -38,6 +40,7 @@ import org.hibernate.dialect.function.array.OracleArrayGetFunction;
import org.hibernate.dialect.function.array.OracleArrayLengthFunction;
import org.hibernate.dialect.function.array.OracleArrayPositionFunction;
import org.hibernate.dialect.function.array.OracleArrayRemoveFunction;
import org.hibernate.dialect.function.array.OracleArrayRemoveIndexFunction;
import org.hibernate.dialect.function.array.OracleArraySetFunction;
import org.hibernate.dialect.function.array.PostgreSQLArrayConcatFunction;
import org.hibernate.dialect.function.array.PostgreSQLArrayPositionFunction;
@ -3013,6 +3016,22 @@ public class CommonFunctionFactory {
functionRegistry.register( "array_set", new OracleArraySetFunction() );
}
/**
* CockroachDB and PostgreSQL array_remove() function
*/
public void arrayRemove() {
functionRegistry.namedDescriptorBuilder( "array_remove" )
.setArgumentsValidator(
StandardArgumentsValidators.composite(
StandardArgumentsValidators.exactly( 2 ),
ArrayAndElementArgumentValidator.DEFAULT_INSTANCE
)
)
.setReturnTypeResolver( ArrayViaArgumentReturnTypeResolver.DEFAULT_INSTANCE )
.setArgumentTypeResolver( ArrayAndElementArgumentTypeResolver.DEFAULT_INSTANCE )
.register();
}
/**
* H2 array_remove() function
*/
@ -3027,26 +3046,38 @@ public class CommonFunctionFactory {
functionRegistry.register( "array_remove", new HSQLArrayRemoveFunction() );
}
/**
* CockroachDB and PostgreSQL array_remove() function
*/
public void arrayRemove_unnest() {
functionRegistry.namedDescriptorBuilder( "array_remove" )
.setArgumentsValidator(
StandardArgumentsValidators.composite(
StandardArgumentsValidators.exactly( 2 ),
ArrayAndElementArgumentValidator.DEFAULT_INSTANCE
)
)
.setReturnTypeResolver( ArrayViaArgumentReturnTypeResolver.DEFAULT_INSTANCE )
.setArgumentTypeResolver( ArrayAndElementArgumentTypeResolver.DEFAULT_INSTANCE )
.register();
}
/**
* Oracle array_remove() function
*/
public void arrayRemove_oracle() {
functionRegistry.register( "array_remove", new OracleArrayRemoveFunction() );
}
/**
* H2 array_remove_index() function
*/
public void arrayRemoveIndex_h2() {
functionRegistry.register( "array_remove_index", new H2ArrayRemoveIndexFunction() );
}
/**
* HSQL, CockroachDB and PostgreSQL array_remove_index() function
*/
public void arrayRemoveIndex_unnest() {
functionRegistry.register( "array_remove_index", new ArrayRemoveIndexUnnestFunction( false ) );
}
/**
* HSQL, CockroachDB and PostgreSQL array_remove_index() function
*/
public void arrayRemoveIndex_postgresql() {
functionRegistry.register( "array_remove_index", new ArrayRemoveIndexUnnestFunction( true ) );
}
/**
* Oracle array_remove_index() function
*/
public void arrayRemoveIndex_oracle() {
functionRegistry.register( "array_remove_index", new OracleArrayRemoveIndexFunction() );
}
}

View File

@ -0,0 +1,71 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.dialect.function.array;
import java.util.List;
import org.hibernate.query.sqm.function.AbstractSqmSelfRenderingFunctionDescriptor;
import org.hibernate.query.sqm.produce.function.ArgumentTypesValidator;
import org.hibernate.query.sqm.produce.function.StandardArgumentsValidators;
import org.hibernate.query.sqm.produce.function.StandardFunctionArgumentTypeResolvers;
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.Expression;
import static org.hibernate.query.sqm.produce.function.FunctionParameterType.ANY;
import static org.hibernate.query.sqm.produce.function.FunctionParameterType.INTEGER;
/**
* Encapsulates the validator, return type and argument type resolvers for the array_remove_index functions.
* Subclasses only have to implement the rendering.
*/
public class ArrayRemoveIndexUnnestFunction extends AbstractSqmSelfRenderingFunctionDescriptor {
private final boolean castEmptyArrayLiteral;
public ArrayRemoveIndexUnnestFunction(boolean castEmptyArrayLiteral) {
super(
"array_remove_index",
StandardArgumentsValidators.composite(
new ArgumentTypesValidator( null, ANY, INTEGER ),
ArrayArgumentValidator.DEFAULT_INSTANCE
),
ArrayViaArgumentReturnTypeResolver.DEFAULT_INSTANCE,
StandardFunctionArgumentTypeResolvers.composite(
StandardFunctionArgumentTypeResolvers.invariant( ANY, INTEGER ),
StandardFunctionArgumentTypeResolvers.IMPLIED_RESULT_TYPE
)
);
this.castEmptyArrayLiteral = castEmptyArrayLiteral;
}
@Override
public void render(
SqlAppender sqlAppender,
List<? extends SqlAstNode> sqlAstArguments,
SqlAstTranslator<?> walker) {
final Expression arrayExpression = (Expression) sqlAstArguments.get( 0 );
final Expression indexExpression = (Expression) sqlAstArguments.get( 1 );
sqlAppender.append( "case when ");
arrayExpression.accept( walker );
sqlAppender.append( " is null then null else coalesce((select array_agg(t.val) from unnest(" );
arrayExpression.accept( walker );
sqlAppender.append( ") with ordinality t(val,idx) where t.idx is distinct from " );
indexExpression.accept( walker );
sqlAppender.append( "),");
if ( castEmptyArrayLiteral ) {
sqlAppender.append( "cast(array[] as " );
sqlAppender.append( ArrayTypeHelper.getArrayTypeName( arrayExpression.getExpressionType(), walker ) );
sqlAppender.append( ')' );
}
else {
sqlAppender.append( "array[]" );
}
sqlAppender.append(") end" );
}
}

View File

@ -0,0 +1,48 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.dialect.function.array;
import java.util.List;
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.Expression;
/**
* H2 array_remove_index function.
*/
public class H2ArrayRemoveIndexFunction extends ArrayRemoveIndexUnnestFunction {
public H2ArrayRemoveIndexFunction() {
super( false );
}
@Override
public void render(
SqlAppender sqlAppender,
List<? extends SqlAstNode> sqlAstArguments,
SqlAstTranslator<?> walker) {
final Expression arrayExpression = (Expression) sqlAstArguments.get( 0 );
final Expression indexExpression = (Expression) sqlAstArguments.get( 1 );
sqlAppender.append( "case when ");
arrayExpression.accept( walker );
sqlAppender.append( " is null then null else coalesce((select array_agg(array_get(");
arrayExpression.accept( walker );
sqlAppender.append(",i.idx)) from system_range(1," );
sqlAppender.append( Integer.toString( getMaximumArraySize() ) );
sqlAppender.append( ") i(idx) where i.idx<=coalesce(cardinality(");
arrayExpression.accept( walker );
sqlAppender.append("),0) and i.idx is distinct from " );
indexExpression.accept( walker );
sqlAppender.append( "),array[]) end" );
}
protected int getMaximumArraySize() {
return 1000;
}
}

View File

@ -0,0 +1,41 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.dialect.function.array;
import java.util.List;
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.Expression;
/**
* Oracle array_remove_index function.
*/
public class OracleArrayRemoveIndexFunction extends ArrayRemoveIndexUnnestFunction {
public OracleArrayRemoveIndexFunction() {
super( false );
}
@Override
public void render(
SqlAppender sqlAppender,
List<? extends SqlAstNode> sqlAstArguments,
SqlAstTranslator<?> walker) {
final String arrayTypeName = ArrayTypeHelper.getArrayTypeName(
( (Expression) sqlAstArguments.get( 0 ) ).getExpressionType(),
walker
);
sqlAppender.append( arrayTypeName );
sqlAppender.append( "_remove_index(" );
sqlAstArguments.get( 0 ).accept( walker );
sqlAppender.append( ',' );
sqlAstArguments.get( 1 ).accept( walker );
sqlAppender.append( ')' );
}
}

View File

@ -0,0 +1,105 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.orm.test.function.array;
import java.util.List;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.testing.orm.junit.DialectFeatureChecks;
import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.RequiresDialectFeature;
import org.hibernate.testing.orm.junit.ServiceRegistry;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.hibernate.testing.orm.junit.Setting;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import jakarta.persistence.Tuple;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* @author Christian Beikov
*/
@DomainModel(annotatedClasses = EntityWithArrays.class)
@SessionFactory
@RequiresDialectFeature( feature = DialectFeatureChecks.SupportsStructuralArrays.class)
// Make sure this stuff runs on a dedicated connection pool,
// otherwise we might run into ORA-21700: object does not exist or is marked for delete
// because the JDBC connection or database session caches something that should have been invalidated
@ServiceRegistry(settings = @Setting(name = AvailableSettings.CONNECTION_PROVIDER, value = ""))
public class ArrayRemoveIndexTest {
@BeforeEach
public void prepareData(SessionFactoryScope scope) {
scope.inTransaction( em -> {
em.persist( new EntityWithArrays( 1L, new String[]{} ) );
em.persist( new EntityWithArrays( 2L, new String[]{ "abc", null, "def" } ) );
em.persist( new EntityWithArrays( 3L, null ) );
} );
}
@AfterEach
public void cleanup(SessionFactoryScope scope) {
scope.inTransaction( em -> {
em.createMutationQuery( "delete from EntityWithArrays" ).executeUpdate();
} );
}
@Test
public void testRemove(SessionFactoryScope scope) {
scope.inSession( em -> {
//tag::hql-array-remove-index-example[]
List<Tuple> results = em.createQuery( "select e.id, array_remove_index(e.theArray, 1) from EntityWithArrays e order by e.id", Tuple.class )
.getResultList();
//end::hql-array-remove-index-example[]
assertEquals( 3, results.size() );
assertEquals( 1L, results.get( 0 ).get( 0 ) );
assertArrayEquals( new String[] {}, results.get( 0 ).get( 1, String[].class ) );
assertEquals( 2L, results.get( 1 ).get( 0 ) );
assertArrayEquals( new String[] { null, "def" }, results.get( 1 ).get( 1, String[].class ) );
assertEquals( 3L, results.get( 2 ).get( 0 ) );
assertNull( results.get( 2 ).get( 1, String[].class ) );
} );
}
@Test
public void testRemoveNullIndex(SessionFactoryScope scope) {
scope.inSession( em -> {
List<Tuple> results = em.createQuery( "select e.id, array_remove_index(e.theArray, null) from EntityWithArrays e order by e.id", Tuple.class )
.getResultList();
assertEquals( 3, results.size() );
assertEquals( 1L, results.get( 0 ).get( 0 ) );
assertArrayEquals( new String[] {}, results.get( 0 ).get( 1, String[].class ) );
assertEquals( 2L, results.get( 1 ).get( 0 ) );
assertArrayEquals( new String[] { "abc", null, "def" }, results.get( 1 ).get( 1, String[].class ) );
assertEquals( 3L, results.get( 2 ).get( 0 ) );
assertNull( results.get( 2 ).get( 1, String[].class ) );
} );
}
@Test
public void testRemoveNonExisting(SessionFactoryScope scope) {
scope.inSession( em -> {
List<Tuple> results = em.createQuery( "select e.id, array_remove_index(e.theArray, 10000) from EntityWithArrays e order by e.id", Tuple.class )
.getResultList();
assertEquals( 3, results.size() );
assertEquals( 1L, results.get( 0 ).get( 0 ) );
assertArrayEquals( new String[] {}, results.get( 0 ).get( 1, String[].class ) );
assertEquals( 2L, results.get( 1 ).get( 0 ) );
assertArrayEquals( new String[] { "abc", null, "def" }, results.get( 1 ).get( 1, String[].class ) );
assertEquals( 3L, results.get( 2 ).get( 0 ) );
assertNull( results.get( 2 ).get( 1, String[].class ) );
} );
}
}