filter.ex (1545B)
1 # Zenflows is designed to implement the Valueflows vocabulary, 2 # written and maintained by srfsh <info@dyne.org>. 3 # Copyright (C) 2021-2022 Dyne.org foundation <foundation@dyne.org>. 4 # 5 # This program is free software: you can redistribute it and/or modify 6 # it under the terms of the GNU Affero General Public License as published by 7 # the Free Software Foundation, either version 3 of the License, or 8 # (at your option) any later version. 9 # 10 # This program is distributed in the hope that it will be useful, 11 # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 # GNU Affero General Public License for more details. 14 # 15 # You should have received a copy of the GNU Affero General Public License 16 # along with this program. If not, see <https://www.gnu.org/licenses/>. 17 18 defmodule Zenflows.DB.Filter do 19 @moduledoc "Filtering helpers for Filter modules." 20 21 alias Ecto.Changeset 22 23 @type params() :: %{atom() => term()} 24 @type error() :: {:error, Changeset.t()} 25 @type result() :: {:ok, Ecto.Query.t()} | error() 26 27 def escape_like(v) do 28 Regex.replace(~r/\\|%|_/, v, &"\\#{&1}") 29 end 30 31 @doc """ 32 Changeset helper to check that `a` and `b` are not provided at the same time. 33 """ 34 @spec check_xor(Changeset.t(), atom(), atom()) :: Changeset.t() 35 def check_xor(cset, a, b) do 36 x = Changeset.get_change(cset, a) 37 y = Changeset.get_change(cset, b) 38 39 if x && y do 40 msg = "can't provide both" 41 42 cset 43 |> Changeset.add_error(a, msg) 44 |> Changeset.add_error(b, msg) 45 else 46 cset 47 end 48 end 49 end