epgsql_binary.erl 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. %%% Copyright (C) 2008 - Will Glozer. All rights reserved.
  2. -module(epgsql_binary).
  3. -export([new_codec/1,
  4. update_type_cache/2,
  5. type2oid/2, oid2type/2,
  6. encode/3, decode/3, supports/1]).
  7. -record(codec, {
  8. type2oid = [],
  9. oid2type = []
  10. }).
  11. -include("epgsql_binary.hrl").
  12. -define(datetime, (get(datetime_mod))).
  13. -define(INET, 2).
  14. -define(INET6, 3).
  15. -define(IP_SIZE, 4).
  16. -define(IP6_SIZE, 16).
  17. -define(MAX_IP_MASK, 32).
  18. -define(MAX_IP6_MASK, 128).
  19. new_codec([]) -> #codec{}.
  20. update_type_cache(TypeInfos, Codec) ->
  21. Type2Oid = lists:flatmap(
  22. fun({NameBin, ElementOid, ArrayOid}) ->
  23. Name = erlang:binary_to_atom(NameBin, utf8),
  24. [{Name, ElementOid}, {{array, Name}, ArrayOid}]
  25. end,
  26. TypeInfos),
  27. Oid2Type = [{Oid, Type} || {Type, Oid} <- Type2Oid],
  28. Codec#codec{type2oid = Type2Oid, oid2type = Oid2Type}.
  29. oid2type(Oid, #codec{oid2type = Oid2Type}) ->
  30. case epgsql_types:oid2type(Oid) of
  31. {unknown_oid, _} ->
  32. proplists:get_value(Oid, Oid2Type, {unknown_oid, Oid});
  33. Type -> Type
  34. end.
  35. type2oid(Type, #codec{type2oid = Type2Oid}) ->
  36. case epgsql_types:type2oid(Type) of
  37. {unknown_type, _} ->
  38. proplists:get_value(Type, Type2Oid, {unknown_type, Type});
  39. Oid -> Oid
  40. end.
  41. encode(_Any, null, _) -> <<-1:?int32>>;
  42. encode(_Any, undefined, _) -> <<-1:?int32>>;
  43. encode(bool, true, _) -> <<1:?int32, 1:1/big-signed-unit:8>>;
  44. encode(bool, false, _) -> <<1:?int32, 0:1/big-signed-unit:8>>;
  45. encode(int2, N, _) -> <<2:?int32, N:1/big-signed-unit:16>>;
  46. encode(int4, N, _) -> <<4:?int32, N:1/big-signed-unit:32>>;
  47. encode(int8, N, _) -> <<8:?int32, N:1/big-signed-unit:64>>;
  48. encode(float4, N, _) -> <<4:?int32, N:1/big-float-unit:32>>;
  49. encode(float8, N, _) -> <<8:?int32, N:1/big-float-unit:64>>;
  50. encode(bpchar, C, _) when is_integer(C) -> <<1:?int32, C:1/big-unsigned-unit:8>>;
  51. encode(bpchar, B, _) when is_binary(B) -> <<(byte_size(B)):?int32, B/binary>>;
  52. encode(time = Type, B, _) -> ?datetime:encode(Type, B);
  53. encode(timetz = Type, B, _) -> ?datetime:encode(Type, B);
  54. encode(date = Type, B, _) -> ?datetime:encode(Type, B);
  55. encode(timestamp = Type, B, _) -> ?datetime:encode(Type, B);
  56. encode(timestamptz = Type, B, _) -> ?datetime:encode(Type, B);
  57. encode(interval = Type, B, _) -> ?datetime:encode(Type, B);
  58. encode(bytea, B, _) when is_binary(B) -> <<(byte_size(B)):?int32, B/binary>>;
  59. encode(text, B, _) when is_binary(B) -> <<(byte_size(B)):?int32, B/binary>>;
  60. encode(varchar, B, _) when is_binary(B) -> <<(byte_size(B)):?int32, B/binary>>;
  61. encode(json, B, _) when is_binary(B) -> <<(byte_size(B)):?int32, B/binary>>;
  62. encode(jsonb, B, _) when is_binary(B) -> <<(byte_size(B)):?int32, B/binary>>;
  63. encode(uuid, B, _) when is_binary(B) -> encode_uuid(B);
  64. encode({array, char}, L, Codec) when is_list(L) -> encode_array(bpchar, type2oid(bpchar, Codec), L, Codec);
  65. encode({array, Type}, L, Codec) when is_list(L) -> encode_array(Type, type2oid(Type, Codec), L, Codec);
  66. encode(hstore, {L}, _) when is_list(L) -> encode_hstore(L);
  67. encode(point, {X,Y}, _) -> encode_point({X,Y});
  68. encode(geometry, Data, _) -> encode_geometry(Data);
  69. encode(cidr, B, Codec) -> encode(bytea, encode_net(B), Codec);
  70. encode(inet, B, Codec) -> encode(bytea, encode_net(B), Codec);
  71. encode(int4range, R, _) when is_tuple(R) -> encode_int4range(R);
  72. encode(Type, L, Codec) when is_list(L) -> encode(Type, list_to_binary(L), Codec);
  73. encode(_Type, _Value, _) -> {error, unsupported}.
  74. decode(bool, <<1:1/big-signed-unit:8>>, _) -> true;
  75. decode(bool, <<0:1/big-signed-unit:8>>, _) -> false;
  76. decode(bpchar, <<C:1/big-unsigned-unit:8>>, _) -> C;
  77. decode(int2, <<N:1/big-signed-unit:16>>, _) -> N;
  78. decode(int4, <<N:1/big-signed-unit:32>>, _) -> N;
  79. decode(int8, <<N:1/big-signed-unit:64>>, _) -> N;
  80. decode(float4, <<N:1/big-float-unit:32>>, _) -> N;
  81. decode(float8, <<N:1/big-float-unit:64>>, _) -> N;
  82. decode(record, <<_:?int32, Rest/binary>>, Codec) -> list_to_tuple(decode_record(Rest, [], Codec));
  83. decode(time = Type, B, _) -> ?datetime:decode(Type, B);
  84. decode(timetz = Type, B, _) -> ?datetime:decode(Type, B);
  85. decode(date = Type, B, _) -> ?datetime:decode(Type, B);
  86. decode(timestamp = Type, B, _) -> ?datetime:decode(Type, B);
  87. decode(timestamptz = Type, B, _) -> ?datetime:decode(Type, B);
  88. decode(interval = Type, B, _) -> ?datetime:decode(Type, B);
  89. decode(uuid, B, _) -> decode_uuid(B);
  90. decode(hstore, Hstore, _) -> decode_hstore(Hstore);
  91. decode(inet, B, _) -> decode_net(B);
  92. decode(cidr, B, _) -> decode_net(B);
  93. decode({array, _Type}, B, Codec) -> decode_array(B, Codec);
  94. decode(point, B, _) -> decode_point(B);
  95. decode(geometry, B, _) -> ewkb:decode_geometry(B);
  96. decode(int4range, B, _) -> decode_int4range(B);
  97. decode(_Other, Bin, _) -> Bin.
  98. encode_array(Type, Oid, A, Codec) ->
  99. {Data, {NDims, Lengths}} = encode_array(Type, A, 0, [], Codec),
  100. Lens = [<<N:?int32, 1:?int32>> || N <- lists:reverse(Lengths)],
  101. Hdr = <<NDims:?int32, 0:?int32, Oid:?int32>>,
  102. Bin = iolist_to_binary([Hdr, Lens, Data]),
  103. <<(byte_size(Bin)):?int32, Bin/binary>>.
  104. encode_array(_Type, [], NDims, Lengths, _Codec) ->
  105. {<<>>, {NDims, Lengths}};
  106. encode_array(Type, [H | _] = Array, NDims, Lengths, Codec) when not is_list(H) ->
  107. F = fun(E, Len) -> {encode(Type, E, Codec), Len + 1} end,
  108. {Data, Len} = lists:mapfoldl(F, 0, Array),
  109. {Data, {NDims + 1, [Len | Lengths]}};
  110. encode_array(uuid, [_H | _] = Array, NDims, Lengths, Codec) ->
  111. F = fun(E, Len) -> {encode(uuid, E, Codec), Len + 1} end,
  112. {Data, Len} = lists:mapfoldl(F, 0, Array),
  113. {Data, {NDims + 1, [Len | Lengths]}};
  114. encode_array(Type, Array, NDims, Lengths, Codec) ->
  115. Lengths2 = [length(Array) | Lengths],
  116. F = fun(A2, {_NDims, _Lengths}) -> encode_array(Type, A2, NDims, Lengths2, Codec) end,
  117. {Data, {NDims2, Lengths3}} = lists:mapfoldl(F, {NDims, Lengths2}, Array),
  118. {Data, {NDims2 + 1, Lengths3}}.
  119. encode_uuid(U) when is_binary(U) ->
  120. encode_uuid(binary_to_list(U));
  121. encode_uuid(U) ->
  122. Hex = [H || H <- U, H =/= $-],
  123. {ok, [Int], _} = io_lib:fread("~16u", Hex),
  124. <<16:?int32,Int:128>>.
  125. encode_hstore(HstoreEntries) ->
  126. Body = << <<(encode_hstore_entry(Entry))/binary>> || Entry <- HstoreEntries >>,
  127. <<(byte_size(Body) + 4):?int32, (length(HstoreEntries)):?int32, Body/binary>>.
  128. encode_hstore_entry({Key, Value}) ->
  129. <<(encode_hstore_key(Key))/binary, (encode_hstore_value(Value))/binary>>.
  130. encode_hstore_key(Key) -> encode_hstore_string(Key).
  131. encode_hstore_value(null) -> <<-1:?int32>>;
  132. encode_hstore_value(undefined) -> <<-1:?int32>>;
  133. encode_hstore_value(Val) -> encode_hstore_string(Val).
  134. encode_hstore_string(Str) when is_list(Str) -> encode_hstore_string(list_to_binary(Str));
  135. encode_hstore_string(Str) when is_atom(Str) -> encode_hstore_string(atom_to_binary(Str, utf8));
  136. encode_hstore_string(Str) when is_integer(Str) ->
  137. %% FIXME - we can use integer_to_binary when we deprecate R15
  138. encode_hstore_string(list_to_binary(integer_to_list(Str)));
  139. encode_hstore_string(Str) when is_float(Str) ->
  140. encode_hstore_string(iolist_to_binary(io_lib:format("~w", [Str])));
  141. encode_hstore_string(Str) when is_binary(Str) -> <<(byte_size(Str)):?int32, Str/binary>>.
  142. encode_net({{_, _, _, _} = IP, Mask}) ->
  143. Bin = list_to_binary(tuple_to_list(IP)),
  144. <<?INET, Mask, 1, ?IP_SIZE, Bin/binary>>;
  145. encode_net({{_, _, _, _, _, _, _, _} = IP, Mask}) ->
  146. Bin = << <<X:16>> || X <- tuple_to_list(IP) >>,
  147. <<?INET6, Mask, 1, ?IP6_SIZE, Bin/binary>>;
  148. encode_net({_, _, _, _} = IP) ->
  149. Bin = list_to_binary(tuple_to_list(IP)),
  150. <<?INET, ?MAX_IP_MASK, 0, ?IP_SIZE, Bin/binary>>;
  151. encode_net({_, _, _, _, _, _, _, _} = IP) ->
  152. Bin = << <<X:16>> || X <- tuple_to_list(IP) >>,
  153. <<?INET6, ?MAX_IP6_MASK, 0, ?IP6_SIZE, Bin/binary>>.
  154. decode_array(<<NDims:?int32, _HasNull:?int32, Oid:?int32, Rest/binary>>, Codec) ->
  155. {Dims, Data} = erlang:split_binary(Rest, NDims * 2 * 4),
  156. Lengths = [Len || <<Len:?int32, _LBound:?int32>> <= Dims],
  157. Type = oid2type(Oid, Codec),
  158. {Array, <<>>} = decode_array(Data, Type, Lengths, Codec),
  159. Array.
  160. decode_array(Data, _Type, [], _Codec) ->
  161. {[], Data};
  162. decode_array(Data, Type, [Len], Codec) ->
  163. decode_elements(Data, Type, [], Len, Codec);
  164. decode_array(Data, Type, [Len | T], Codec) ->
  165. F = fun(_N, Rest) -> decode_array(Rest, Type, T, Codec) end,
  166. lists:mapfoldl(F, Data, lists:seq(1, Len)).
  167. decode_elements(Rest, _Type, Acc, 0, _Codec) ->
  168. {lists:reverse(Acc), Rest};
  169. decode_elements(<<-1:?int32, Rest/binary>>, Type, Acc, N, Codec) ->
  170. decode_elements(Rest, Type, [null | Acc], N - 1, Codec);
  171. decode_elements(<<Len:?int32, Value:Len/binary, Rest/binary>>, Type, Acc, N, Codec) ->
  172. Value2 = decode(Type, Value, Codec),
  173. decode_elements(Rest, Type, [Value2 | Acc], N - 1, Codec).
  174. decode_record(<<>>, Acc, _Codec) ->
  175. lists:reverse(Acc);
  176. decode_record(<<_Type:?int32, -1:?int32, Rest/binary>>, Acc, Codec) ->
  177. decode_record(Rest, [null | Acc], Codec);
  178. decode_record(<<Type:?int32, Len:?int32, Value:Len/binary, Rest/binary>>, Acc, Codec) ->
  179. Value2 = decode(oid2type(Type, Codec), Value, Codec),
  180. decode_record(Rest, [Value2 | Acc], Codec).
  181. decode_uuid(<<U0:32, U1:16, U2:16, U3:16, U4:48>>) ->
  182. Format = "~8.16.0b-~4.16.0b-~4.16.0b-~4.16.0b-~12.16.0b",
  183. iolist_to_binary(io_lib:format(Format, [U0, U1, U2, U3, U4])).
  184. decode_hstore(<<NumElements:?int32, Elements/binary>>) ->
  185. {decode_hstore1(NumElements, Elements, [])}.
  186. decode_hstore1(0, _Elements, Acc) -> Acc;
  187. decode_hstore1(N, <<KeyLen:?int32, Key:KeyLen/binary, -1:?int32, Rest/binary>>, Acc) ->
  188. decode_hstore1(N - 1, Rest, [{Key, null} | Acc]);
  189. decode_hstore1(N, <<KeyLen:?int32, Key:KeyLen/binary, ValLen:?int32, Value:ValLen/binary, Rest/binary>>, Acc) ->
  190. decode_hstore1(N - 1, Rest, [{Key, Value} | Acc]).
  191. encode_point({X, Y}) when is_number(X), is_number(Y) ->
  192. <<X:1/big-float-unit:64, Y:1/big-float-unit:64>>.
  193. decode_point(<<X:1/big-float-unit:64, Y:1/big-float-unit:64>>) ->
  194. {X, Y}.
  195. encode_geometry(Data) ->
  196. Bin = ewkb:encode_geometry(Data),
  197. Size = byte_size(Bin),
  198. <<Size:?int32, Bin/binary>>.
  199. decode_net(<<?INET, Mask, 1, ?IP_SIZE, Bin/binary>>) ->
  200. {list_to_tuple(binary_to_list(Bin)), Mask};
  201. decode_net(<<?INET6, Mask, 1, ?IP6_SIZE, Bin/binary>>) ->
  202. {list_to_tuple([X || <<X:16>> <= Bin]), Mask};
  203. decode_net(<<?INET, ?MAX_IP_MASK, 0, ?IP_SIZE, Bin/binary>>) ->
  204. list_to_tuple(binary_to_list(Bin));
  205. decode_net(<<?INET6, ?MAX_IP6_MASK, 0, ?IP6_SIZE, Bin/binary>>) ->
  206. list_to_tuple([X || <<X:16>> <= Bin]).
  207. %% @doc encode an int4range
  208. encode_int4range({minus_infinity, plus_infinity}) ->
  209. <<1:?int32, 24:1/big-signed-unit:8>>;
  210. encode_int4range({From, plus_infinity}) ->
  211. FromInt = to_int(From),
  212. <<9:?int32, 18:1/big-signed-unit:8, 4:?int32, FromInt:?int32>>;
  213. encode_int4range({minus_infinity, To}) ->
  214. ToInt = to_int(To),
  215. <<9:?int32, 8:1/big-signed-unit:8, 4:?int32, ToInt:?int32>>;
  216. encode_int4range({From, To}) ->
  217. FromInt = to_int(From),
  218. ToInt = to_int(To),
  219. <<17:?int32, 2:1/big-signed-unit:8, 4:?int32, FromInt:?int32, 4:?int32, ToInt:?int32>>.
  220. to_int(N) when is_integer(N) -> N;
  221. to_int(S) when is_list(S) -> erlang:list_to_integer(S);
  222. to_int(B) when is_binary(B) -> erlang:binary_to_integer(B).
  223. %% @doc decode an int4range
  224. decode_int4range(<<2:1/big-signed-unit:8, 4:?int32, From:?int32, 4:?int32, To:?int32>>) -> {From, To};
  225. decode_int4range(<<8:1/big-signed-unit:8, 4:?int32, To:?int32>>) -> {minus_infinity, To};
  226. decode_int4range(<<18:1/big-signed-unit:8, 4:?int32, From:?int32>>) -> {From, plus_infinity};
  227. decode_int4range(<<24:1/big-signed-unit:8>>) -> {minus_infinity, plus_infinity}.
  228. supports(bool) -> true;
  229. supports(bpchar) -> true;
  230. supports(int2) -> true;
  231. supports(int4) -> true;
  232. supports(int8) -> true;
  233. supports(float4) -> true;
  234. supports(float8) -> true;
  235. supports(bytea) -> true;
  236. supports(text) -> true;
  237. supports(varchar) -> true;
  238. supports(record) -> true;
  239. supports(date) -> true;
  240. supports(time) -> true;
  241. supports(timetz) -> true;
  242. supports(timestamp) -> true;
  243. supports(timestamptz) -> true;
  244. supports(interval) -> true;
  245. supports(uuid) -> true;
  246. supports(hstore) -> true;
  247. supports(cidr) -> true;
  248. supports(inet) -> true;
  249. supports(geometry) -> true;
  250. supports(point) -> true;
  251. supports(json) -> true;
  252. supports({array, bool}) -> true;
  253. supports({array, int2}) -> true;
  254. supports({array, int4}) -> true;
  255. supports({array, int8}) -> true;
  256. supports({array, float4}) -> true;
  257. supports({array, float8}) -> true;
  258. supports({array, char}) -> true;
  259. supports({array, text}) -> true;
  260. supports({array, date}) -> true;
  261. supports({array, time}) -> true;
  262. supports({array, timetz}) -> true;
  263. supports({array, timestamp}) -> true;
  264. supports({array, timestamptz}) -> true;
  265. supports({array, interval}) -> true;
  266. supports({array, hstore}) -> true;
  267. supports({array, varchar}) -> true;
  268. supports({array, uuid}) -> true;
  269. supports({array, cidr}) -> true;
  270. supports({array, inet}) -> true;
  271. supports({array, json}) -> true;
  272. supports(_Type) -> false.