From b201ac2d721a06b9ccea0421a845f10b76e94d7a Mon Sep 17 00:00:00 2001 From: Christophe De Troyer Date: Wed, 19 Jul 2023 20:05:24 +0200 Subject: [PATCH] Fix for casting boolean values in MySQL (#538) --- lib/ecto/adapters/myxql/connection.ex | 4 ++++ test/ecto/adapters/myxql_test.exs | 10 ++++++++++ 2 files changed, 14 insertions(+) diff --git a/lib/ecto/adapters/myxql/connection.ex b/lib/ecto/adapters/myxql/connection.ex index e6612ea3..c85e5cd5 100644 --- a/lib/ecto/adapters/myxql/connection.ex +++ b/lib/ecto/adapters/myxql/connection.ex @@ -674,6 +674,10 @@ if Code.ensure_loaded?(MyXQL) do [expr(other, sources, query), " + 0"] end + defp expr(%Ecto.Query.Tagged{value: other, type: :boolean}, sources, query) do + ["IF(", expr(other, sources, query), ", TRUE, FALSE)"] + end + defp expr(%Ecto.Query.Tagged{value: other, type: type}, sources, query) do ["CAST(", expr(other, sources, query), " AS ", ecto_cast_to_db(type, query), ?)] end diff --git a/test/ecto/adapters/myxql_test.exs b/test/ecto/adapters/myxql_test.exs index 5f305d96..e63aac05 100644 --- a/test/ecto/adapters/myxql_test.exs +++ b/test/ecto/adapters/myxql_test.exs @@ -590,6 +590,16 @@ defmodule Ecto.Adapters.MyXQLTest do assert all(query) == ~s{SELECT CAST(? AS char) FROM `schema` AS s0} end + test "boolean type true is cast with an if" do + query = Schema |> select([], type(^true, :boolean)) |> plan() + assert all(query) == ~s{SELECT IF(?, TRUE, FALSE) FROM `schema` AS s0} + end + + test "boolean type false is cast with an if" do + query = Schema |> select([], type(^false, :boolean)) |> plan() + assert all(query) == ~s{SELECT IF(?, TRUE, FALSE) FROM `schema` AS s0} + end + test "json_extract_path" do query = Schema |> select([s], json_extract_path(s.meta, [0, 1])) |> plan() assert all(query) == ~s{SELECT json_extract(s0.`meta`, '$[0][1]') FROM `schema` AS s0}