Browse Source

Fix backward-incompatible change. #109

When integer or float or atom is passed as parameter value of
text / varchar column, convert it to string
Сергей Прохоров 7 years ago
parent
commit
5d5468a452
2 changed files with 26 additions and 2 deletions
  1. 12 1
      src/datatypes/epgsql_codec_text.erl
  2. 14 1
      test/epgsql_SUITE.erl

+ 12 - 1
src/datatypes/epgsql_codec_text.erl

@@ -25,6 +25,17 @@ names() ->
 
 encode(String, Name, State) when is_list(String) ->
     encode(list_to_binary(String), Name, State);
-encode(Bin, _, _) when is_binary(Bin) -> Bin.
+encode(Bin, _, _) when is_binary(Bin) -> Bin;
+encode(Other, _Name, _State) ->
+    %% This is for backward compatibitlty! Maybe add warning?
+    %% error_logger:warning_msg(
+    %%   "epgsql_codec_text.erl: Deprecated attempt to encode '~p' as '~s'",
+    %%   [Other, Name]),
+    encode_compat(Other).
+
+encode_compat(A) when is_atom(A)    -> atom_to_binary(A, utf8);
+encode_compat(I) when is_integer(I) -> integer_to_binary(I);
+encode_compat(F) when is_float(F)   -> float_to_binary(F).
+
 
 decode(Bin, _, _) -> Bin.

+ 14 - 1
test/epgsql_SUITE.erl

@@ -669,7 +669,20 @@ character_type(Config) ->
     One   = unicode:characters_to_binary([16#10D360]),
     check_type(Config, bpchar, "'A'", $A, [1, $1, 16#7F, Alpha, Ka, One], "c_char"),
     check_type(Config, text, "'hi'", <<"hi">>, [<<"">>, <<"hi">>]),
-    check_type(Config, varchar, "'hi'", <<"hi">>, [<<"">>, <<"hi">>]).
+    check_type(Config, varchar, "'hi'", <<"hi">>, [<<"">>, <<"hi">>]),
+    %% Deprecated casts
+    epgsql_ct:with_connection(
+      Config,
+      fun(C) ->
+              Module = ?config(module, Config),
+              ?assertMatch({ok, _, [{<<"my_atom">>}]},
+                           Module:equery(C, "SELECT $1::varchar", [my_atom])),
+              ?assertMatch({ok, _, [{<<"12345">>}]},
+                           Module:equery(C, "SELECT $1::varchar", [12345])),
+              FloatBin = erlang:float_to_binary(1.2345),
+              ?assertMatch({ok, _, [{FloatBin}]},
+                           Module:equery(C, "SELECT $1::varchar", [1.2345]))
+      end).
 
 uuid_type(Config) ->
     check_type(Config, uuid,