Format map and list query params as JSON

This commit is contained in:
Claudio Ortolina
2026-04-11 23:57:40 +01:00
parent a983698c72
commit 02761428c1
2 changed files with 42 additions and 0 deletions
+4
View File
@@ -135,6 +135,10 @@ defmodule MusicLibrary.QueryReporter do
end end
end end
defp format_param(value) when is_list(value) or (is_map(value) and not is_struct(value)) do
"'" <> String.replace(JSON.encode!(value), "'", "''") <> "'"
end
defp format_param(value), do: "'" <> String.replace(to_string(value), "'", "''") <> "'" defp format_param(value), do: "'" <> String.replace(to_string(value), "'", "''") <> "'"
defp extract_source_location(nil), do: nil defp extract_source_location(nil), do: nil
@@ -198,6 +198,44 @@ defmodule MusicLibrary.QueryReporterTest do
assert File.read!(path) =~ "SELECT count(*) FROM records;" assert File.read!(path) =~ "SELECT count(*) FROM records;"
end end
test "interpolates map params as JSON", %{path: path} do
QueryReporter.start(path)
emit_query(
path,
"UPDATE artist_infos SET musicbrainz_data = ? WHERE id = ?",
[%{"name" => "Test Artist"}, "abc"]
)
assert File.read!(path) =~ ~s|SET musicbrainz_data = '{"name":"Test Artist"}'|
end
test "interpolates list params as JSON", %{path: path} do
QueryReporter.start(path)
emit_query(path, "UPDATE records SET genres = ?", [["rock", "pop"]])
assert File.read!(path) =~ ~s|SET genres = '["rock","pop"]'|
end
test "interpolates list of embedded maps as JSON", %{path: path} do
QueryReporter.start(path)
emit_query(
path,
"UPDATE records SET artists = ?",
[[%{"name" => "A"}, %{"name" => "B"}]]
)
assert File.read!(path) =~ ~s|SET artists = '[{"name":"A"},{"name":"B"}]'|
end
test "escapes single quotes in map JSON params", %{path: path} do
QueryReporter.start(path)
emit_query(path, "UPDATE records SET data = ?", [%{"title" => "Rock'n'Roll"}])
assert File.read!(path) =~ ~s|SET data = '{"title":"Rock''n''Roll"}'|
end
test "uses cast_params over params when both present", %{path: path} do test "uses cast_params over params when both present", %{path: path} do
QueryReporter.start(path) QueryReporter.start(path)