31 lines
826 B
Elixir
31 lines
826 B
Elixir
defmodule Towerops.QueryHelpers do
|
|
@moduledoc """
|
|
Helpers for building safe SQL queries.
|
|
|
|
Provides utilities for sanitizing user input before using it in SQL LIKE/ILIKE queries.
|
|
"""
|
|
|
|
@doc """
|
|
Sanitizes a string for use in SQL LIKE/ILIKE queries by escaping
|
|
the wildcard characters `%` and `_`, and the escape character `\\`.
|
|
|
|
## Examples
|
|
|
|
iex> Towerops.QueryHelpers.sanitize_like("100%")
|
|
"100\\\\%"
|
|
|
|
iex> Towerops.QueryHelpers.sanitize_like("some_value")
|
|
"some\\\\_value"
|
|
|
|
iex> Towerops.QueryHelpers.sanitize_like("hello world")
|
|
"hello world"
|
|
|
|
"""
|
|
@spec sanitize_like(String.t()) :: String.t()
|
|
def sanitize_like(query) when is_binary(query) do
|
|
query
|
|
|> String.replace("\\", "\\\\")
|
|
|> String.replace("%", "\\%")
|
|
|> String.replace("_", "\\_")
|
|
end
|
|
end
|