From f283075ce9a448db17be78cc588b56a242907a6b Mon Sep 17 00:00:00 2001 From: Struchkov Mark Date: Fri, 14 Jun 2024 13:50:23 +0300 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=20Jsonb?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../haiti/filter/jooq/utils/Jsonb.java | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/main/java/dev/struchkov/haiti/filter/jooq/utils/Jsonb.java diff --git a/src/main/java/dev/struchkov/haiti/filter/jooq/utils/Jsonb.java b/src/main/java/dev/struchkov/haiti/filter/jooq/utils/Jsonb.java new file mode 100644 index 0000000..2d1f8b9 --- /dev/null +++ b/src/main/java/dev/struchkov/haiti/filter/jooq/utils/Jsonb.java @@ -0,0 +1,35 @@ +package dev.struchkov.haiti.filter.jooq.utils; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static dev.struchkov.haiti.utils.Exceptions.utilityClass; + +public final class Jsonb { + + private Jsonb() { + utilityClass(); + } + + /** + * @param field - колонка в БД формата jsonb + * @param jsonField - поле в jsonb по которому будет выполняться операция фильтрации + */ + public static String jsonbField(String field, String jsonField) { + String sql; + if (jsonField.contains(".")) { + final List hierarchyFields = Arrays.stream(jsonField.split("\\.")) + .map(el -> "'" + el + "'") + .collect(Collectors.toList()); + final String lastElement = hierarchyFields.remove(hierarchyFields.size() - 1); + final String fieldPath = String.join(" -> ", hierarchyFields) + " ->> " + lastElement; + sql = "(%s #>> '{}')::jsonb -> %s".formatted(field, fieldPath); + } else { + final String fieldPath = "'" + jsonField + "'"; + sql = "(%s #>> '{}')::jsonb ->> %s".formatted(field, fieldPath); + } + return sql; + } + +}