epgsql_binary.erl 13 KB

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