|
| 1 | +package org.springframework.data.relational.core.dialect.condition; |
| 2 | + |
| 3 | +import org.springframework.data.relational.core.dialect.PostgresDialect; |
| 4 | + |
| 5 | +/** |
| 6 | + * {@link DialectCriteriaCondition DialectCriteriaConditions} that are specific to {@link PostgresDialect PostgreSQL Dialect} |
| 7 | + * |
| 8 | + * @author Mikhail Polivakha |
| 9 | + */ |
| 10 | +public class Postgres { |
| 11 | + |
| 12 | + /** |
| 13 | + * Creates a condition that checks that the assumed column of an {@link java.sql.Array} type |
| 14 | + * contains an array of any values |
| 15 | + * |
| 16 | + * @param values array that assumed column should contain |
| 17 | + * @return crafted {@link DialectCriteriaCondition} |
| 18 | + */ |
| 19 | + public static DialectCriteriaCondition arrayContains(Object... values) { |
| 20 | + return () -> "@> ARRAY[%s]".formatted(toLiterals(false, values)); |
| 21 | + } |
| 22 | + |
| 23 | + /** |
| 24 | + * Creates a condition that checks that the assumed column of an {@link java.sql.Array} type |
| 25 | + * contains an array of {@link String} values. |
| 26 | + * |
| 27 | + * @param values array of {@link String String} that assumed column should contain |
| 28 | + * @return crafted {@link DialectCriteriaCondition} |
| 29 | + */ |
| 30 | + public static DialectCriteriaCondition arrayContains(String... values) { |
| 31 | + return () -> "@> ARRAY[%s]::text[]".formatted(toLiterals(true, values)); |
| 32 | + } |
| 33 | + |
| 34 | + /** |
| 35 | + * Creates a condition that checks that the assumed column of an {@link java.sql.Array} type |
| 36 | + * contains an array of a single {@link String} value. |
| 37 | + * |
| 38 | + * @param value array of {@link String String} that assumed value should contain |
| 39 | + * @return crafted {@link DialectCriteriaCondition} |
| 40 | + */ |
| 41 | + public static DialectCriteriaCondition arrayContains(String value) { |
| 42 | + return arrayContains(new String[]{value}); |
| 43 | + } |
| 44 | + |
| 45 | + @SafeVarargs |
| 46 | + private static <T> String toLiterals(boolean quoted, T... values) { |
| 47 | + StringBuilder result = new StringBuilder(); |
| 48 | + for (int i = 0; i < values.length; i++) { |
| 49 | + T value = values[i]; |
| 50 | + |
| 51 | + if (value != null) { |
| 52 | + if (quoted) { |
| 53 | + result.append('\'').append(value).append('\''); |
| 54 | + } else { |
| 55 | + result.append(value); |
| 56 | + } |
| 57 | + } else { |
| 58 | + result.append("NULL"); |
| 59 | + } |
| 60 | + |
| 61 | + if (i != values.length - 1) { |
| 62 | + result.append(","); |
| 63 | + } |
| 64 | + } |
| 65 | + return result.toString(); |
| 66 | + } |
| 67 | +} |
0 commit comments