epgsql_binary.erl 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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(bool, true, _) -> <<1:?int32, 1:1/big-signed-unit:8>>;
  43. encode(bool, false, _) -> <<1:?int32, 0:1/big-signed-unit:8>>;
  44. encode(int2, N, _) -> <<2:?int32, N:1/big-signed-unit:16>>;
  45. encode(int4, N, _) -> <<4:?int32, N:1/big-signed-unit:32>>;
  46. encode(int8, N, _) -> <<8:?int32, N:1/big-signed-unit:64>>;
  47. encode(float4, N, _) -> <<4:?int32, N:1/big-float-unit:32>>;
  48. encode(float8, N, _) -> <<8:?int32, N:1/big-float-unit:64>>;
  49. encode(bpchar, C, _) when is_integer(C) -> <<1:?int32, C:1/big-unsigned-unit:8>>;
  50. encode(bpchar, B, _) when is_binary(B) -> <<(byte_size(B)):?int32, B/binary>>;
  51. encode(time = Type, B, _) -> ?datetime:encode(Type, B);
  52. encode(timetz = Type, B, _) -> ?datetime:encode(Type, B);
  53. encode(date = Type, B, _) -> ?datetime:encode(Type, B);
  54. encode(timestamp = Type, B, _) -> ?datetime:encode(Type, B);
  55. encode(timestamptz = Type, B, _) -> ?datetime:encode(Type, B);
  56. encode(interval = Type, B, _) -> ?datetime:encode(Type, B);
  57. encode(bytea, B, _) when is_binary(B) -> <<(byte_size(B)):?int32, B/binary>>;
  58. encode(text, B, _) when is_binary(B) -> <<(byte_size(B)):?int32, B/binary>>;
  59. encode(varchar, B, _) when is_binary(B) -> <<(byte_size(B)):?int32, B/binary>>;
  60. encode(uuid, B, _) when is_binary(B) -> encode_uuid(B);
  61. encode({array, char}, L, Codec) when is_list(L) -> encode_array(bpchar, type2oid(bpchar, Codec), L, Codec);
  62. encode({array, Type}, L, Codec) when is_list(L) -> encode_array(Type, type2oid(Type, Codec), L, Codec);
  63. encode(hstore, {L}, _) when is_list(L) -> encode_hstore(L);
  64. encode(point, {X,Y}, _) -> encode_point({X,Y});
  65. encode(geometry, Data, _) -> encode_geometry(Data);
  66. encode(cidr, B, Codec) -> encode(bytea, encode_net(B), Codec);
  67. encode(inet, B, Codec) -> encode(bytea, encode_net(B), Codec);
  68. encode(Type, L, Codec) when is_list(L) -> encode(Type, list_to_binary(L), Codec);
  69. encode(_Type, _Value, _) -> {error, unsupported}.
  70. decode(bool, <<1:1/big-signed-unit:8>>, _) -> true;
  71. decode(bool, <<0:1/big-signed-unit:8>>, _) -> false;
  72. decode(bpchar, <<C:1/big-unsigned-unit:8>>, _) -> C;
  73. decode(int2, <<N:1/big-signed-unit:16>>, _) -> N;
  74. decode(int4, <<N:1/big-signed-unit:32>>, _) -> N;
  75. decode(int8, <<N:1/big-signed-unit:64>>, _) -> N;
  76. decode(float4, <<N:1/big-float-unit:32>>, _) -> N;
  77. decode(float8, <<N:1/big-float-unit:64>>, _) -> N;
  78. decode(record, <<_:?int32, Rest/binary>>, Codec) -> list_to_tuple(decode_record(Rest, [], Codec));
  79. decode(time = Type, B, _) -> ?datetime:decode(Type, B);
  80. decode(timetz = Type, B, _) -> ?datetime:decode(Type, B);
  81. decode(date = Type, B, _) -> ?datetime:decode(Type, B);
  82. decode(timestamp = Type, B, _) -> ?datetime:decode(Type, B);
  83. decode(timestamptz = Type, B, _) -> ?datetime:decode(Type, B);
  84. decode(interval = Type, B, _) -> ?datetime:decode(Type, B);
  85. decode(uuid, B, _) -> decode_uuid(B);
  86. decode(hstore, Hstore, _) -> decode_hstore(Hstore);
  87. decode(inet, B, _) -> decode_net(B);
  88. decode(cidr, B, _) -> decode_net(B);
  89. decode({array, _Type}, B, Codec) -> decode_array(B, Codec);
  90. decode(point, B, _) -> decode_point(B);
  91. decode(geometry, B, _) -> ewkb:decode_geometry(B);
  92. decode(_Other, Bin, _) -> Bin.
  93. encode_array(Type, Oid, A, Codec) ->
  94. {Data, {NDims, Lengths}} = encode_array(Type, A, 0, [], Codec),
  95. Lens = [<<N:?int32, 1:?int32>> || N <- lists:reverse(Lengths)],
  96. Hdr = <<NDims:?int32, 0:?int32, Oid:?int32>>,
  97. Bin = iolist_to_binary([Hdr, Lens, Data]),
  98. <<(byte_size(Bin)):?int32, Bin/binary>>.
  99. encode_array(_Type, [], NDims, Lengths, _Codec) ->
  100. {<<>>, {NDims, Lengths}};
  101. encode_array(Type, [H | _] = Array, NDims, Lengths, Codec) when not is_list(H) ->
  102. F = fun(E, Len) -> {encode(Type, E, Codec), Len + 1} end,
  103. {Data, Len} = lists:mapfoldl(F, 0, Array),
  104. {Data, {NDims + 1, [Len | Lengths]}};
  105. encode_array(uuid, [_H | _] = Array, NDims, Lengths, Codec) ->
  106. F = fun(E, Len) -> {encode(uuid, E, Codec), Len + 1} end,
  107. {Data, Len} = lists:mapfoldl(F, 0, Array),
  108. {Data, {NDims + 1, [Len | Lengths]}};
  109. encode_array(Type, Array, NDims, Lengths, Codec) ->
  110. Lengths2 = [length(Array) | Lengths],
  111. F = fun(A2, {_NDims, _Lengths}) -> encode_array(Type, A2, NDims, Lengths2, Codec) end,
  112. {Data, {NDims2, Lengths3}} = lists:mapfoldl(F, {NDims, Lengths2}, Array),
  113. {Data, {NDims2 + 1, Lengths3}}.
  114. encode_uuid(U) when is_binary(U) ->
  115. encode_uuid(binary_to_list(U));
  116. encode_uuid(U) ->
  117. Hex = [H || H <- U, H =/= $-],
  118. {ok, [Int], _} = io_lib:fread("~16u", Hex),
  119. <<16:?int32,Int:128>>.
  120. encode_hstore(HstoreEntries) ->
  121. Body = << <<(encode_hstore_entry(Entry))/binary>> || Entry <- HstoreEntries >>,
  122. <<(byte_size(Body) + 4):?int32, (length(HstoreEntries)):?int32, Body/binary>>.
  123. encode_hstore_entry({Key, Value}) ->
  124. <<(encode_hstore_key(Key))/binary, (encode_hstore_value(Value))/binary>>.
  125. encode_hstore_key(Key) -> encode_hstore_string(Key).
  126. encode_hstore_value(null) -> <<-1:?int32>>;
  127. encode_hstore_value(Val) -> encode_hstore_string(Val).
  128. encode_hstore_string(Str) when is_list(Str) -> encode_hstore_string(list_to_binary(Str));
  129. encode_hstore_string(Str) when is_atom(Str) -> encode_hstore_string(atom_to_binary(Str, utf8));
  130. encode_hstore_string(Str) when is_integer(Str) ->
  131. encode_hstore_string(erlang:integer_to_binary(Str));
  132. encode_hstore_string(Str) when is_float(Str) ->
  133. encode_hstore_string(iolist_to_binary(io_lib:format("~w", [Str])));
  134. encode_hstore_string(Str) when is_binary(Str) -> <<(byte_size(Str)):?int32, Str/binary>>.
  135. encode_net({{_, _, _, _} = IP, Mask}) ->
  136. Bin = list_to_binary(tuple_to_list(IP)),
  137. <<?INET, Mask, 1, ?IP_SIZE, Bin/binary>>;
  138. encode_net({{_, _, _, _, _, _, _, _} = IP, Mask}) ->
  139. Bin = << <<X:16>> || X <- tuple_to_list(IP) >>,
  140. <<?INET6, Mask, 1, ?IP6_SIZE, Bin/binary>>;
  141. encode_net({_, _, _, _} = IP) ->
  142. Bin = list_to_binary(tuple_to_list(IP)),
  143. <<?INET, ?MAX_IP_MASK, 0, ?IP_SIZE, Bin/binary>>;
  144. encode_net({_, _, _, _, _, _, _, _} = IP) ->
  145. Bin = << <<X:16>> || X <- tuple_to_list(IP) >>,
  146. <<?INET6, ?MAX_IP6_MASK, 0, ?IP6_SIZE, Bin/binary>>.
  147. decode_array(<<NDims:?int32, _HasNull:?int32, Oid:?int32, Rest/binary>>, Codec) ->
  148. {Dims, Data} = erlang:split_binary(Rest, NDims * 2 * 4),
  149. Lengths = [Len || <<Len:?int32, _LBound:?int32>> <= Dims],
  150. Type = oid2type(Oid, Codec),
  151. {Array, <<>>} = decode_array(Data, Type, Lengths, Codec),
  152. Array.
  153. decode_array(Data, _Type, [], _Codec) ->
  154. {[], Data};
  155. decode_array(Data, Type, [Len], Codec) ->
  156. decode_elements(Data, Type, [], Len, Codec);
  157. decode_array(Data, Type, [Len | T], Codec) ->
  158. F = fun(_N, Rest) -> decode_array(Rest, Type, T, Codec) end,
  159. lists:mapfoldl(F, Data, lists:seq(1, Len)).
  160. decode_elements(Rest, _Type, Acc, 0, _Codec) ->
  161. {lists:reverse(Acc), Rest};
  162. decode_elements(<<-1:?int32, Rest/binary>>, Type, Acc, N, Codec) ->
  163. decode_elements(Rest, Type, [null | Acc], N - 1, Codec);
  164. decode_elements(<<Len:?int32, Value:Len/binary, Rest/binary>>, Type, Acc, N, Codec) ->
  165. Value2 = decode(Type, Value, Codec),
  166. decode_elements(Rest, Type, [Value2 | Acc], N - 1, Codec).
  167. decode_record(<<>>, Acc, _Codec) ->
  168. lists:reverse(Acc);
  169. decode_record(<<_Type:?int32, -1:?int32, Rest/binary>>, Acc, Codec) ->
  170. decode_record(Rest, [null | Acc], Codec);
  171. decode_record(<<Type:?int32, Len:?int32, Value:Len/binary, Rest/binary>>, Acc, Codec) ->
  172. Value2 = decode(oid2type(Type, Codec), Value, Codec),
  173. decode_record(Rest, [Value2 | Acc], Codec).
  174. decode_uuid(<<U0:32, U1:16, U2:16, U3:16, U4:48>>) ->
  175. Format = "~8.16.0b-~4.16.0b-~4.16.0b-~4.16.0b-~12.16.0b",
  176. iolist_to_binary(io_lib:format(Format, [U0, U1, U2, U3, U4])).
  177. decode_hstore(<<NumElements:?int32, Elements/binary>>) ->
  178. {decode_hstore1(NumElements, Elements, [])}.
  179. decode_hstore1(0, _Elements, Acc) -> Acc;
  180. decode_hstore1(N, <<KeyLen:?int32, Key:KeyLen/binary, -1:?int32, Rest/binary>>, Acc) ->
  181. decode_hstore1(N - 1, Rest, [{Key, null} | Acc]);
  182. decode_hstore1(N, <<KeyLen:?int32, Key:KeyLen/binary, ValLen:?int32, Value:ValLen/binary, Rest/binary>>, Acc) ->
  183. decode_hstore1(N - 1, Rest, [{Key, Value} | Acc]).
  184. encode_point({X, Y}) when is_number(X), is_number(Y) ->
  185. <<X:1/big-float-unit:64, Y:1/big-float-unit:64>>.
  186. decode_point(<<X:1/big-float-unit:64, Y:1/big-float-unit:64>>) ->
  187. {X, Y}.
  188. encode_geometry(Data) ->
  189. Bin = ewkb:encode_geometry(Data),
  190. Size = byte_size(Bin),
  191. <<Size:?int32, Bin/binary>>.
  192. decode_net(<<?INET, Mask, 1, ?IP_SIZE, Bin/binary>>) ->
  193. {list_to_tuple(binary_to_list(Bin)), Mask};
  194. decode_net(<<?INET6, Mask, 1, ?IP6_SIZE, Bin/binary>>) ->
  195. {list_to_tuple([X || <<X:16>> <= Bin]), Mask};
  196. decode_net(<<?INET, ?MAX_IP_MASK, 0, ?IP_SIZE, Bin/binary>>) ->
  197. list_to_tuple(binary_to_list(Bin));
  198. decode_net(<<?INET6, ?MAX_IP6_MASK, 0, ?IP6_SIZE, Bin/binary>>) ->
  199. list_to_tuple([X || <<X:16>> <= Bin]).
  200. supports(bool) -> true;
  201. supports(bpchar) -> true;
  202. supports(int2) -> true;
  203. supports(int4) -> true;
  204. supports(int8) -> true;
  205. supports(float4) -> true;
  206. supports(float8) -> true;
  207. supports(bytea) -> true;
  208. supports(text) -> true;
  209. supports(varchar) -> true;
  210. supports(record) -> true;
  211. supports(date) -> true;
  212. supports(time) -> true;
  213. supports(timetz) -> true;
  214. supports(timestamp) -> true;
  215. supports(timestamptz) -> true;
  216. supports(interval) -> true;
  217. supports(uuid) -> true;
  218. supports(hstore) -> true;
  219. supports(cidr) -> true;
  220. supports(inet) -> true;
  221. supports(geometry) -> true;
  222. supports(point) -> true;
  223. supports({array, bool}) -> true;
  224. supports({array, int2}) -> true;
  225. supports({array, int4}) -> true;
  226. supports({array, int8}) -> true;
  227. supports({array, float4}) -> true;
  228. supports({array, float8}) -> true;
  229. supports({array, char}) -> true;
  230. supports({array, text}) -> true;
  231. supports({array, date}) -> true;
  232. supports({array, time}) -> true;
  233. supports({array, timetz}) -> true;
  234. supports({array, timestamp}) -> true;
  235. supports({array, timestamptz}) -> true;
  236. supports({array, interval}) -> true;
  237. supports({array, hstore}) -> true;
  238. supports({array, varchar}) -> true;
  239. supports({array, uuid}) -> true;
  240. supports({array, cidr}) -> true;
  241. supports({array, inet}) -> true;
  242. supports(_Type) -> false.