org.ehrbase.jooq.pg.util.AdditionalSQLFunctions Maven / Gradle / Ivy
/*
* Copyright (c) 2024 vitasystems GmbH.
*
* This file is part of project EHRbase
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ehrbase.jooq.pg.util;
import java.util.Arrays;
import java.util.stream.Stream;
import org.jooq.AggregateFunction;
import org.jooq.Field;
import org.jooq.JSONB;
import org.jooq.impl.DSL;
import org.jooq.impl.SQLDataType;
public final class AdditionalSQLFunctions {
private AdditionalSQLFunctions() {
// NOOP
}
public static Field jsonb_array_elements(Field jsonbArray) {
return DSL.function("jsonb_array_elements", JSONB.class, jsonbArray);
}
public static Field jsonb_extract_path_text(Class aClass, Field jsonb, String... path) {
Field>[] arguments = Stream.concat(
Stream.of(jsonb), Arrays.stream(path).map(DSL::inline))
.toArray(Field>[]::new);
return DSL.function("jsonb_extract_path_text", aClass, arguments);
}
public static Field jsonb_dv_ordered_magnitude(Field dvOrderedField) {
return DSL.function("jsonb_dv_ordered_magnitude", JSONB.class, dvOrderedField);
}
/*
data -> path[0] -> … -> path[n] ->> 0
*/
public static Field jsonbAttributePathText(Field jsonb, String... path) {
Field jsonbField = jsonb;
for (String att : path) {
jsonbField = DSL.jsonbGetAttribute(jsonbField, DSL.inline(att));
}
return DSL.jsonbGetElementAsText(jsonbField, DSL.inline(0));
}
public static Field to_jsonb(Object value) {
Field> inline = DSL.inline(value);
if (value instanceof String) {
inline = inline.cast(String.class);
}
return to_jsonb(inline);
}
public static Field to_jsonb(Field target) {
return DSL.function("to_jsonb", JSONB.class, target);
}
public static AggregateFunction max_dv_ordered(Field> f) {
return DSL.aggregate("max_dv_ordered", SQLDataType.JSONB, f);
}
public static AggregateFunction min_dv_ordered(Field> f) {
return DSL.aggregate("min_dv_ordered", SQLDataType.JSONB, f);
}
/**
* DSL::count returns an integer.
* Since row counts may require a long we have to use this workaround.
*
* @param distinct
* @param f
* @return
*/
public static AggregateFunction count(boolean distinct, Field> f) {
return distinct
? DSL.aggregateDistinct("count", SQLDataType.BIGINT, f)
: DSL.aggregate("count", SQLDataType.BIGINT, f == null ? DSL.field(DSL.raw("*")) : f);
}
}