epgsql_SUITE.erl 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478
  1. -module(epgsql_SUITE).
  2. -include_lib("stdlib/include/assert.hrl").
  3. -include_lib("common_test/include/ct.hrl").
  4. -include_lib("public_key/include/public_key.hrl").
  5. -include("epgsql_tests.hrl").
  6. -include("epgsql.hrl").
  7. -export([
  8. init_per_suite/1,
  9. init_per_group/2,
  10. all/0,
  11. groups/0,
  12. end_per_group/2,
  13. end_per_suite/1
  14. ]).
  15. -compile([export_all, nowarn_export_all]).
  16. modules() ->
  17. [
  18. epgsql,
  19. epgsql_cast,
  20. epgsql_incremental
  21. ].
  22. init_per_suite(Config) ->
  23. Config.
  24. all() ->
  25. [{group, M} || M <- modules()].
  26. groups() ->
  27. Groups = [
  28. {connect, [parrallel], [
  29. connect,
  30. connect_with_application_name,
  31. connect_to_db,
  32. connect_as,
  33. connect_with_cleartext,
  34. connect_with_md5,
  35. connect_with_scram,
  36. connect_with_invalid_user,
  37. connect_with_invalid_password,
  38. connect_to_invalid_database,
  39. connect_with_other_error,
  40. connect_with_ssl,
  41. connect_with_client_cert,
  42. connect_with_invalid_client_cert,
  43. connect_to_closed_port,
  44. connect_map,
  45. connect_proplist
  46. ]},
  47. {types, [parallel], [
  48. numeric_type,
  49. character_type,
  50. uuid_type,
  51. point_type,
  52. geometry_type,
  53. uuid_select,
  54. date_time_type,
  55. json_type,
  56. misc_type,
  57. hstore_type,
  58. net_type,
  59. array_type,
  60. record_type,
  61. range_type,
  62. range8_type,
  63. date_time_range_type,
  64. custom_types,
  65. custom_null
  66. ]},
  67. {generic, [parallel], [
  68. with_transaction
  69. ]}
  70. ],
  71. Tests = [
  72. {group, connect},
  73. {group, types},
  74. prepared_query,
  75. select,
  76. insert,
  77. update,
  78. delete,
  79. create_and_drop_table,
  80. cursor,
  81. multiple_result,
  82. execute_batch,
  83. execute_batch_3_named_stmt,
  84. execute_batch_3_unnamed_stmt,
  85. execute_batch_3_sql,
  86. batch_error,
  87. single_batch,
  88. extended_select,
  89. extended_sync_ok,
  90. extended_sync_error,
  91. returning_from_insert,
  92. returning_from_update,
  93. returning_from_delete,
  94. parse,
  95. parse_column_format,
  96. parse_error,
  97. parse_and_close,
  98. bind,
  99. bind_parameter_format,
  100. bind_error,
  101. bind_and_close,
  102. execute_error,
  103. describe,
  104. describe_with_param,
  105. describe_named,
  106. describe_error,
  107. describe_portal,
  108. portal,
  109. returning,
  110. multiple_statement,
  111. multiple_portal,
  112. execute_function,
  113. parameter_get,
  114. parameter_set,
  115. text_format,
  116. query_timeout,
  117. execute_timeout,
  118. connection_closed,
  119. connection_closed_by_server,
  120. active_connection_closed,
  121. warning_notice,
  122. listen_notify,
  123. listen_notify_payload,
  124. set_notice_receiver,
  125. get_cmd_status
  126. ],
  127. Groups ++ [case Module of
  128. epgsql ->
  129. {Module, [], [{group, generic} | Tests]};
  130. _ ->
  131. {Module, [], Tests}
  132. end || Module <- modules()].
  133. end_per_suite(_Config) ->
  134. ok.
  135. init_per_group(GroupName, Config) ->
  136. case lists:member(GroupName, modules()) of
  137. true -> [{module, GroupName}|Config];
  138. false -> Config
  139. end.
  140. end_per_group(_GroupName, _Config) ->
  141. ok.
  142. -define(UUID1,
  143. <<163,189,240,40,149,151,17,227,141,6,112,24,139,130,16,73>>).
  144. -define(UUID2,
  145. <<183,55,22,52,149,151,17,227,187,167,112,24,139,130,16,73>>).
  146. -define(UUID3,
  147. <<198,188,155,66,149,151,17,227,138,98,112,24,139,130,16,73>>).
  148. -define(TIMEOUT_ERROR, {error, #error{
  149. severity = error,
  150. code = <<"57014">>,
  151. codename = query_canceled,
  152. message = <<"canceling statement due to statement timeout">>,
  153. extra = [{file, <<"postgres.c">>},
  154. {line, _},
  155. {routine, _} | _]
  156. }}).
  157. %% From uuid.erl in http://gitorious.org/avtobiff/erlang-uuid
  158. uuid_to_bin_string(<<U0:32, U1:16, U2:16, U3:16, U4:48>>) ->
  159. iolist_to_binary(io_lib:format(
  160. "~8.16.0b-~4.16.0b-~4.16.0b-~4.16.0b-~12.16.0b",
  161. [U0, U1, U2, U3, U4])).
  162. connect(Config) ->
  163. epgsql_ct:connect_only(Config, []).
  164. connect_with_application_name(Config) ->
  165. Module = ?config(module, Config),
  166. Fun = fun(C) ->
  167. Query = "select application_name from pg_stat_activity",
  168. {ok, _Columns, Rows} = Module:equery(C, Query),
  169. ?assert(lists:member({<<"app_test">>}, Rows))
  170. end,
  171. epgsql_ct:with_connection(Config,
  172. Fun,
  173. "epgsql_test",
  174. [{application_name, "app_test"}]).
  175. connect_to_db(Connect) ->
  176. epgsql_ct:connect_only(Connect, [{database, "epgsql_test_db1"}]).
  177. connect_as(Config) ->
  178. epgsql_ct:connect_only(Config, ["epgsql_test", [{database, "epgsql_test_db1"}]]).
  179. connect_with_cleartext(Config) ->
  180. epgsql_ct:connect_only(Config, [
  181. "epgsql_test_cleartext",
  182. "epgsql_test_cleartext",
  183. [{database, "epgsql_test_db1"}]
  184. ]).
  185. connect_with_md5(Config) ->
  186. epgsql_ct:connect_only(Config, [
  187. "epgsql_test_md5",
  188. "epgsql_test_md5",
  189. [{database, "epgsql_test_db1"}]
  190. ]).
  191. connect_with_scram(Config) ->
  192. PgConf = ?config(pg_config, Config),
  193. Ver = ?config(version, PgConf),
  194. (Ver >= [10, 0])
  195. andalso
  196. epgsql_ct:connect_only(
  197. Config,
  198. [
  199. "epgsql_test_scram",
  200. "epgsql_test_scram",
  201. [{database, "epgsql_test_db1"}]
  202. ]).
  203. connect_with_invalid_user(Config) ->
  204. {Host, Port} = epgsql_ct:connection_data(Config),
  205. Module = ?config(module, Config),
  206. {error, Why} = Module:connect(
  207. Host,
  208. "epgsql_test_invalid",
  209. "epgsql_test_invalid",
  210. [{port, Port}, {database, "epgsql_test_db1"}]),
  211. case Why of
  212. invalid_authorization_specification -> ok; % =< 8.4
  213. invalid_password -> ok % >= 9.0
  214. end.
  215. connect_with_invalid_password(Config) ->
  216. {Host, Port} = epgsql_ct:connection_data(Config),
  217. Module = ?config(module, Config),
  218. {error, Why} = Module:connect(
  219. Host,
  220. "epgsql_test_md5",
  221. "epgsql_test_invalid",
  222. [{port, Port}, {database, "epgsql_test_db1"}]),
  223. case Why of
  224. invalid_authorization_specification -> ok; % =< 8.4
  225. invalid_password -> ok % >= 9.0
  226. end.
  227. connect_to_invalid_database(Config) ->
  228. {Host, Port} = epgsql_ct:connection_data(Config),
  229. Module = ?config(module, Config),
  230. ?assertMatch(
  231. {error, invalid_authorization_specification},
  232. Module:connect(
  233. Host,
  234. "epgsql_test_md5",
  235. "epgsql_test_md5",
  236. [{port, Port}, {database, "epgsql_test_invalid_db"}])).
  237. connect_with_other_error(Config) ->
  238. {Host, Port} = epgsql_ct:connection_data(Config),
  239. Module = ?config(module, Config),
  240. ?assertMatch(
  241. {error,
  242. #error{severity = fatal,
  243. codename = protocol_violation}},
  244. Module:connect(
  245. Host,
  246. <<0, 0>>,
  247. "epgsql_test_invalid",
  248. [{port, Port}, {database, <<0, 0>>}])).
  249. connect_with_ssl(Config) ->
  250. Module = ?config(module, Config),
  251. epgsql_ct:with_connection(Config,
  252. fun(C) ->
  253. {ok, _Cols, [{true}]} = Module:equery(C, "select ssl_is_used()")
  254. end,
  255. "epgsql_test",
  256. [{ssl, true}]).
  257. connect_with_client_cert(Config) ->
  258. Module = ?config(module, Config),
  259. Dir = filename:join(code:lib_dir(epgsql), ?TEST_DATA_DIR),
  260. File = fun(Name) -> filename:join(Dir, Name) end,
  261. {ok, Pem} = file:read_file(File("client.crt")),
  262. [{'Certificate', Der, not_encrypted}] = public_key:pem_decode(Pem),
  263. Cert = public_key:pkix_decode_cert(Der, plain),
  264. #'TBSCertificate'{serialNumber = Serial} = Cert#'Certificate'.tbsCertificate,
  265. Serial2 = list_to_binary(integer_to_list(Serial)),
  266. epgsql_ct:with_connection(Config,
  267. fun(C) ->
  268. ?assertMatch({ok, _, [{true}]}, Module:equery(C, "select ssl_is_used()")),
  269. ?assertMatch({ok, _, [{Serial2}]}, Module:equery(C, "select ssl_client_serial()"))
  270. end,
  271. "epgsql_test_cert",
  272. [{ssl, true}, {ssl_opts, [{keyfile, File("client.key")},
  273. {certfile, File("client.crt")}]}]).
  274. connect_with_invalid_client_cert(Config) ->
  275. {Host, Port} = epgsql_ct:connection_data(Config),
  276. Module = ?config(module, Config),
  277. Dir = filename:join(code:lib_dir(epgsql), ?TEST_DATA_DIR),
  278. File = fun(Name) -> filename:join(Dir, Name) end,
  279. Trap = process_flag(trap_exit, true),
  280. ?assertMatch(
  281. {error, {ssl_negotiation_failed, _}},
  282. Module:connect(
  283. #{username => "epgsql_test_cert",
  284. database => "epgsql_test_db1",
  285. host => Host,
  286. port => Port,
  287. ssl => true,
  288. ssl_opts =>
  289. [{keyfile, File("bad-client.key")},
  290. {certfile, File("bad-client.crt")}]}
  291. )),
  292. ?assertMatch({'EXIT', _, {ssl_negotiation_failed, _}}, receive Stop -> Stop end),
  293. process_flag(trap_exit, Trap).
  294. connect_map(Config) ->
  295. {Host, Port} = epgsql_ct:connection_data(Config),
  296. Module = ?config(module, Config),
  297. Opts = #{
  298. host => Host,
  299. port => Port,
  300. database => "epgsql_test_db1",
  301. username => "epgsql_test_md5",
  302. password => "epgsql_test_md5"
  303. },
  304. {ok, C} = Module:connect(Opts),
  305. Module:close(C),
  306. epgsql_ct:flush(),
  307. ok.
  308. connect_proplist(Config) ->
  309. {Host, Port} = epgsql_ct:connection_data(Config),
  310. Module = ?config(module, Config),
  311. Opts = [
  312. {host, Host},
  313. {port, Port},
  314. {database, "epgsql_test_db1"},
  315. {username, "epgsql_test_md5"},
  316. {password, "epgsql_test_md5"}
  317. ],
  318. {ok, C} = Module:connect(Opts),
  319. Module:close(C),
  320. epgsql_ct:flush(),
  321. ok.
  322. connect_to_closed_port(Config) ->
  323. {Host, Port} = epgsql_ct:connection_data(Config),
  324. Module = ?config(module, Config),
  325. Trap = process_flag(trap_exit, true),
  326. ?assertEqual({error, econnrefused},
  327. Module:connect(
  328. Host,
  329. "epgsql_test",
  330. "epgsql_test",
  331. [{port, Port + 1}, {database, "epgsql_test_db1"}])),
  332. ?assertMatch({'EXIT', _, econnrefused}, receive Stop -> Stop end),
  333. process_flag(trap_exit, Trap).
  334. prepared_query(Config) ->
  335. Module = ?config(module, Config),
  336. epgsql_ct:with_connection(Config, fun(C) ->
  337. {ok, _} = Module:parse(C, "inc", "select $1+1", []),
  338. {ok, Cols, [{5}]} = Module:prepared_query(C, "inc", [4]),
  339. {ok, Cols, [{2}]} = Module:prepared_query(C, "inc", [1]),
  340. {ok, Cols, [{23}]} = Module:prepared_query(C, "inc", [22]),
  341. {error, _} = Module:prepared_query(C, "non_existent_query", [4])
  342. end).
  343. select(Config) ->
  344. Module = ?config(module, Config),
  345. epgsql_ct:with_connection(Config, fun(C) ->
  346. {ok, Cols, Rows} = Module:squery(C, "select * from test_table1"),
  347. [
  348. #column{name = <<"id">>, type = int4, size = 4},
  349. #column{name = <<"value">>, type = text, size = -1}
  350. ] = Cols,
  351. [{<<"1">>, <<"one">>}, {<<"2">>, <<"two">>}] = Rows
  352. end).
  353. insert(Config) ->
  354. Module = ?config(module, Config),
  355. epgsql_ct:with_rollback(Config, fun(C) ->
  356. {ok, 1} = Module:squery(C, "insert into test_table1 (id, value) values (3, 'three')")
  357. end).
  358. update(Config) ->
  359. Module = ?config(module, Config),
  360. epgsql_ct:with_rollback(Config, fun(C) ->
  361. {ok, 1} = Module:squery(C, "insert into test_table1 (id, value) values (3, 'three')"),
  362. {ok, 1} = Module:squery(C, "insert into test_table1 (id, value) values (4, 'four')"),
  363. {ok, 2} = Module:squery(C, "update test_table1 set value = 'foo' where id > 2"),
  364. {ok, _, [{<<"2">>}]} = Module:squery(C, "select count(*) from test_table1 where value = 'foo'")
  365. end).
  366. delete(Config) ->
  367. Module = ?config(module, Config),
  368. epgsql_ct:with_rollback(Config, fun(C) ->
  369. {ok, 1} = Module:squery(C, "insert into test_table1 (id, value) values (3, 'three')"),
  370. {ok, 1} = Module:squery(C, "insert into test_table1 (id, value) values (4, 'four')"),
  371. {ok, 2} = Module:squery(C, "delete from test_table1 where id > 2"),
  372. {ok, _, [{<<"2">>}]} = Module:squery(C, "select count(*) from test_table1")
  373. end).
  374. create_and_drop_table(Config) ->
  375. Module = ?config(module, Config),
  376. epgsql_ct:with_rollback(Config, fun(C) ->
  377. {ok, [], []} = Module:squery(C, "create table test_table3 (id int4)"),
  378. {ok, [#column{type = int4}], []} = Module:squery(C, "select * from test_table3"),
  379. {ok, [], []} = Module:squery(C, "drop table test_table3")
  380. end).
  381. cursor(Config) ->
  382. Module = ?config(module, Config),
  383. epgsql_ct:with_connection(Config, fun(C) ->
  384. {ok, [], []} = Module:squery(C, "begin"),
  385. {ok, [], []} = Module:squery(C, "declare c cursor for select id from test_table1"),
  386. {ok, 2} = Module:squery(C, "move forward 2 from c"),
  387. {ok, 1} = Module:squery(C, "move backward 1 from c"),
  388. {ok, 1, _Cols, [{<<"2">>}]} = Module:squery(C, "fetch next from c"),
  389. {ok, [], []} = Module:squery(C, "close c")
  390. end).
  391. multiple_result(Config) ->
  392. Module = ?config(module, Config),
  393. epgsql_ct:with_connection(Config, fun(C) ->
  394. [{ok, _, [{<<"1">>}]}, {ok, _, [{<<"2">>}]}] = Module:squery(C, "select 1; select 2"),
  395. [{ok, _, [{<<"1">>}]}, {error, #error{}}] = Module:squery(C, "select 1; select foo;")
  396. end).
  397. execute_batch(Config) ->
  398. Module = ?config(module, Config),
  399. epgsql_ct:with_connection(Config, fun(C) ->
  400. {ok, S1} = Module:parse(C, "one", "select $1", [int4]),
  401. {ok, S2} = Module:parse(C, "two", "select $1 + $2", [int4, int4]),
  402. [{ok, [{1}]}, {ok, [{3}]}] =
  403. Module:execute_batch(C, [{S1, [1]}, {S2, [1, 2]}])
  404. end).
  405. execute_batch_3_named_stmt(Config) ->
  406. Module = ?config(module, Config),
  407. epgsql_ct:with_connection(Config, fun(C) ->
  408. {ok, Stmt} = Module:parse(C, "my_stmt", "select $1 + $2", [int4, int4]),
  409. ?assertMatch(
  410. {[#column{type = int4, _ = _}], [{ok, [{3}]}, {ok, [{7}]}]},
  411. Module:execute_batch(C, Stmt, [[1, 2], [3, 4]]))
  412. end).
  413. execute_batch_3_unnamed_stmt(Config) ->
  414. Module = ?config(module, Config),
  415. epgsql_ct:with_connection(Config, fun(C) ->
  416. {ok, Stmt} = Module:parse(C, "select $1::integer + $2::integer"),
  417. ?assertMatch(
  418. {[#column{type = int4, _ = _}], [{ok, [{3}]}, {ok, [{7}]}]},
  419. Module:execute_batch(C, Stmt, [[2, 1], [4, 3]]))
  420. end).
  421. execute_batch_3_sql(Config) ->
  422. Module = ?config(module, Config),
  423. epgsql_ct:with_connection(Config, fun(C) ->
  424. ?assertMatch(
  425. {[#column{type = int4, _ = _}], [{ok, [{3}]}, {ok, [{7}]}]},
  426. Module:execute_batch(C, "select $1::integer + $2::integer", [[1, 2], [3, 4]]))
  427. end).
  428. batch_error(Config) ->
  429. Module = ?config(module, Config),
  430. epgsql_ct:with_rollback(Config, fun(C) ->
  431. {ok, S} = Module:parse(C, "insert into test_table1(id, value) values($1, $2)"),
  432. [{ok, 1}, {error, [Error, Skipped1, Skipped2]}] =
  433. Module:execute_batch(
  434. C,
  435. [{S, [3, "batch_error 3"]},
  436. {S, [2, "batch_error 2"]}, % duplicate key error
  437. {S, [5, "batch_error 5"]}, % won't be executed
  438. {S, [6, "batch_error 6"]} % won't be executed
  439. ]),
  440. ?assertMatch({error, #error{}}, Error),
  441. ?assertEqual({error, skipped}, Skipped1),
  442. ?assertEqual({error, skipped}, Skipped2)
  443. end).
  444. single_batch(Config) ->
  445. Module = ?config(module, Config),
  446. epgsql_ct:with_connection(Config, fun(C) ->
  447. {ok, S1} = Module:parse(C, "one", "select $1", [int4]),
  448. [{ok, [{1}]}] = Module:execute_batch(C, [{S1, [1]}])
  449. end).
  450. extended_select(Config) ->
  451. Module = ?config(module, Config),
  452. epgsql_ct:with_connection(Config, fun(C) ->
  453. {ok, Cols, Rows} = Module:equery(C, "select * from test_table1", []),
  454. [#column{name = <<"id">>, type = int4, size = 4},
  455. #column{name = <<"value">>, type = text, size = -1}] = Cols,
  456. [{1, <<"one">>}, {2, <<"two">>}] = Rows
  457. end).
  458. extended_sync_ok(Config) ->
  459. Module = ?config(module, Config),
  460. epgsql_ct:with_connection(Config, fun(C) ->
  461. {ok, _Cols, [{<<"one">>}]} = Module:equery(C, "select value from test_table1 where id = $1", [1]),
  462. {ok, _Cols, [{<<"two">>}]} = Module:equery(C, "select value from test_table1 where id = $1", [2])
  463. end).
  464. extended_sync_error(Config) ->
  465. Module = ?config(module, Config),
  466. epgsql_ct:with_connection(Config, fun(C) ->
  467. {error, #error{}} = Module:equery(C, "select _alue from test_table1 where id = $1", [1]),
  468. {ok, _Cols, [{<<"one">>}]} = Module:equery(C, "select value from test_table1 where id = $1", [1])
  469. end).
  470. returning_from_insert(Config) ->
  471. Module = ?config(module, Config),
  472. epgsql_ct:with_rollback(Config, fun(C) ->
  473. {ok, 1, _Cols, [{3}]} = Module:equery(C, "insert into test_table1 (id) values (3) returning id")
  474. end).
  475. returning_from_update(Config) ->
  476. Module = ?config(module, Config),
  477. epgsql_ct:with_rollback(Config, fun(C) ->
  478. {ok, 2, _Cols, [{1}, {2}]} = Module:equery(C, "update test_table1 set value = 'hi' returning id"),
  479. ?assertMatch({ok, 0, [#column{}], []},
  480. Module:equery(C, "update test_table1 set value = 'hi' where false returning id")),
  481. ?assertMatch([{ok, 2, [#column{}], [{<<"1">>}, {<<"2">>}]},
  482. {ok, 0, [#column{}], []}],
  483. Module:squery(C,
  484. "update test_table1 set value = 'hi2' returning id; "
  485. "update test_table1 set value = 'hi' where false returning id"))
  486. end).
  487. returning_from_delete(Config) ->
  488. Module = ?config(module, Config),
  489. epgsql_ct:with_rollback(Config, fun(C) ->
  490. {ok, 2, _Cols, [{1}, {2}]} = Module:equery(C, "delete from test_table1 returning id"),
  491. ?assertMatch({ok, 0, [#column{}], []},
  492. Module:equery(C, "delete from test_table1 returning id"))
  493. end).
  494. parse(Config) ->
  495. Module = ?config(module, Config),
  496. epgsql_ct:with_connection(Config, fun(C) ->
  497. {ok, S} = Module:parse(C, "select * from test_table1"),
  498. [#column{name = <<"id">>}, #column{name = <<"value">>}] = S#statement.columns,
  499. ok = Module:close(C, S),
  500. ok = Module:sync(C)
  501. end).
  502. parse_column_format(Config) ->
  503. Module = ?config(module, Config),
  504. epgsql_ct:with_connection(Config, fun(C) ->
  505. {ok, S} = Module:parse(C, "select 1::int4, false::bool, 2.0::float4"),
  506. [#column{type = int4, table_oid = 0, table_attr_number = 0},
  507. #column{type = bool, table_oid = 0, table_attr_number = 0},
  508. #column{type = float4, table_oid = 0, table_attr_number = 0}] = S#statement.columns,
  509. ok = Module:bind(C, S, []),
  510. {ok, [{1, false, 2.0}]} = Module:execute(C, S, 0),
  511. ok = Module:close(C, S),
  512. ok = Module:sync(C)
  513. end).
  514. parse_error(Config) ->
  515. Module = ?config(module, Config),
  516. epgsql_ct:with_connection(Config, fun(C) ->
  517. {error, #error{
  518. extra = [{file, _}, {line, _}, {position, <<"8">>}, {routine, _} | _]
  519. }} = Module:parse(C, "select _ from test_table1"),
  520. {ok, S} = Module:parse(C, "select * from test_table1"),
  521. [#column{name = <<"id">>}, #column{name = <<"value">>}] = S#statement.columns,
  522. ok = Module:close(C, S),
  523. ok = Module:sync(C)
  524. end).
  525. parse_and_close(Config) ->
  526. Module = ?config(module, Config),
  527. epgsql_ct:with_connection(Config, fun(C) ->
  528. Parse = fun() -> Module:parse(C, "test", "select * from test_table1", []) end,
  529. {ok, S} = Parse(),
  530. {error, #error{code = <<"42P05">>, codename = duplicate_prepared_statement}} = Parse(),
  531. Module:close(C, S),
  532. {ok, S} = Parse(),
  533. ok = Module:sync(C)
  534. end).
  535. bind(Config) ->
  536. Module = ?config(module, Config),
  537. epgsql_ct:with_connection(Config, fun(C) ->
  538. {ok, S} = Module:parse(C, "select value from test_table1 where id = $1"),
  539. ok = Module:bind(C, S, [1]),
  540. ok = Module:close(C, S),
  541. ok = Module:sync(C)
  542. end).
  543. bind_parameter_format(Config) ->
  544. Module = ?config(module, Config),
  545. epgsql_ct:with_connection(Config, fun(C) ->
  546. {ok, S} = Module:parse(C, "select $1, $2, $3", [int2, text, bool]),
  547. [int2, text, bool] = S#statement.types,
  548. ok = Module:bind(C, S, [1, "hi", true]),
  549. {ok, [{1, <<"hi">>, true}]} = Module:execute(C, S, 0),
  550. ok = Module:close(C, S),
  551. ok = Module:sync(C)
  552. end).
  553. bind_error(Config) ->
  554. Module = ?config(module, Config),
  555. epgsql_ct:with_connection(Config, fun(C) ->
  556. {ok, S} = Module:parse(C, "select $1::char"),
  557. {error, #error{}} = Module:bind(C, S, [0]),
  558. ok = Module:bind(C, S, [$A]),
  559. ok = Module:close(C, S),
  560. ok = Module:sync(C)
  561. end).
  562. bind_and_close(Config) ->
  563. Module = ?config(module, Config),
  564. epgsql_ct:with_connection(Config, fun(C) ->
  565. {ok, S} = Module:parse(C, "select * from test_table1"),
  566. ok = Module:bind(C, S, "one", []),
  567. {error, #error{code = <<"42P03">>, codename = duplicate_cursor}} = Module:bind(C, S, "one", []),
  568. ok = Module:close(C, portal, "one"),
  569. ok = Module:bind(C, S, "one", []),
  570. ok = Module:sync(C)
  571. end).
  572. execute_error(Config) ->
  573. Module = ?config(module, Config),
  574. epgsql_ct:with_connection(Config, fun(C) ->
  575. {ok, S} = Module:parse(C, "insert into test_table1 (id, value) values ($1, $2)"),
  576. ok = Module:bind(C, S, [1, <<"foo">>]),
  577. {error, #error{
  578. code = <<"23505">>, codename = unique_violation,
  579. extra = [
  580. {constraint_name, <<"test_table1_pkey">>},
  581. {detail, _},
  582. {file, _},
  583. {line, _},
  584. {routine, _},
  585. {schema_name, <<"public">>} | _%,
  586. %{table_name, <<"test_table1">>}
  587. ]
  588. }} = Module:execute(C, S, 0),
  589. {error, sync_required} = Module:bind(C, S, [3, <<"quux">>]),
  590. ok = Module:sync(C),
  591. ok = Module:bind(C, S, [3, <<"quux">>]),
  592. {ok, _} = Module:execute(C, S, 0),
  593. {ok, 1} = Module:squery(C, "delete from test_table1 where id = 3")
  594. end).
  595. describe(Config) ->
  596. Module = ?config(module, Config),
  597. epgsql_ct:with_connection(Config, fun(C) ->
  598. {ok, S} = Module:parse(C, "select * from test_table1"),
  599. [#column{name = <<"id">>}, #column{name = <<"value">>}] = S#statement.columns,
  600. {ok, S} = Module:describe(C, S),
  601. ok = Module:close(C, S),
  602. ok = Module:sync(C)
  603. end).
  604. describe_with_param(Config) ->
  605. Module = ?config(module, Config),
  606. epgsql_ct:with_connection(Config, fun(C) ->
  607. {ok, S} = Module:parse(C, "select id from test_table1 where id = $1"),
  608. ?assertEqual([int4], S#statement.types),
  609. ?assertMatch([#column{name = <<"id">>}], S#statement.columns),
  610. {ok, S} = Module:describe(C, S),
  611. ok = Module:close(C, S),
  612. ok = Module:sync(C)
  613. end).
  614. describe_named(Config) ->
  615. Module = ?config(module, Config),
  616. epgsql_ct:with_connection(Config, fun(C) ->
  617. {ok, S} = Module:parse(C, "name", "select * from test_table1", []),
  618. [#column{name = <<"id">>}, #column{name = <<"value">>}] = S#statement.columns,
  619. {ok, S} = Module:describe(C, S),
  620. ok = Module:close(C, S),
  621. ok = Module:sync(C)
  622. end).
  623. describe_error(Config) ->
  624. Module = ?config(module, Config),
  625. epgsql_ct:with_connection(Config, fun(C) ->
  626. {error, #error{}} = Module:describe(C, statement, ""),
  627. {ok, S} = Module:parse(C, "select * from test_table1"),
  628. {ok, S} = Module:describe(C, statement, ""),
  629. ok = Module:sync(C)
  630. end).
  631. describe_portal(Config) ->
  632. Module = ?config(module, Config),
  633. epgsql_ct:with_connection(Config, fun(C) ->
  634. {ok, Stmt} = Module:parse(C, "my_stmt", "select * from test_table1 WHERE id = $1", []),
  635. ok = Module:bind(C, Stmt, "my_portal", [1]),
  636. {ok, Columns} = Module:describe(C, portal, "my_portal"),
  637. ?assertMatch(
  638. [#column{name = <<"id">>,
  639. type = int4},
  640. #column{name = <<"value">>,
  641. type = text}],
  642. Columns
  643. ),
  644. ok = Module:close(C, Stmt),
  645. ok = Module:sync(C)
  646. end).
  647. portal(Config) ->
  648. Module = ?config(module, Config),
  649. epgsql_ct:with_connection(Config, fun(C) ->
  650. {ok, S} = Module:parse(C, "select value from test_table1"),
  651. ok = Module:bind(C, S, []),
  652. {partial, [{<<"one">>}]} = Module:execute(C, S, 1),
  653. {partial, [{<<"two">>}]} = Module:execute(C, S, 1),
  654. {ok, []} = Module:execute(C, S,1),
  655. ok = Module:close(C, S),
  656. ok = Module:sync(C)
  657. end).
  658. returning(Config) ->
  659. Module = ?config(module, Config),
  660. epgsql_ct:with_rollback(Config, fun(C) ->
  661. {ok, S} = Module:parse(C, "update test_table1 set value = $1 returning id"),
  662. ok = Module:bind(C, S, ["foo"]),
  663. {ok, 2, [{1}, {2}]} = Module:execute(C, S),
  664. ok = Module:sync(C)
  665. end).
  666. multiple_statement(Config) ->
  667. Module = ?config(module, Config),
  668. epgsql_ct:with_connection(Config, fun(C) ->
  669. {ok, S1} = Module:parse(C, "one", "select value from test_table1 where id = 1", []),
  670. ok = Module:bind(C, S1, []),
  671. {partial, [{<<"one">>}]} = Module:execute(C, S1, 1),
  672. {ok, S2} = Module:parse(C, "two", "select value from test_table1 where id = 2", []),
  673. ok = Module:bind(C, S2, []),
  674. {partial, [{<<"two">>}]} = Module:execute(C, S2, 1),
  675. {ok, []} = Module:execute(C, S1, 1),
  676. {ok, []} = Module:execute(C, S2, 1),
  677. ok = Module:close(C, S1),
  678. ok = Module:close(C, S2),
  679. ok = Module:sync(C)
  680. end).
  681. multiple_portal(Config) ->
  682. Module = ?config(module, Config),
  683. epgsql_ct:with_connection(Config, fun(C) ->
  684. {ok, S} = Module:parse(C, "select value from test_table1 where id = $1"),
  685. ok = Module:bind(C, S, "one", [1]),
  686. ok = Module:bind(C, S, "two", [2]),
  687. {ok, [{<<"one">>}]} = Module:execute(C, S, "one", 0),
  688. {ok, [{<<"two">>}]} = Module:execute(C, S, "two", 0),
  689. ok = Module:close(C, S),
  690. ok = Module:sync(C)
  691. end).
  692. execute_function(Config) ->
  693. Module = ?config(module, Config),
  694. epgsql_ct:with_rollback(Config, fun(C) ->
  695. {ok, _Cols1, [{3}]} = Module:equery(C, "select insert_test1(3, 'three')"),
  696. {ok, _Cols2, [{<<>>}]} = Module:equery(C, "select do_nothing()")
  697. end).
  698. parameter_get(Config) ->
  699. Module = ?config(module, Config),
  700. epgsql_ct:with_connection(Config, fun(C) ->
  701. {ok, <<"off">>} = Module:get_parameter(C, "is_superuser")
  702. end).
  703. parameter_set(Config) ->
  704. Module = ?config(module, Config),
  705. epgsql_ct:with_connection(Config, fun(C) ->
  706. {ok, [], []} = Module:squery(C, "set DateStyle = 'ISO, MDY'"),
  707. {ok, <<"ISO, MDY">>} = Module:get_parameter(C, "DateStyle"),
  708. {ok, _Cols, [{<<"2000-01-02">>}]} = Module:squery(C, "select '2000-01-02'::date"),
  709. {ok, [], []} = Module:squery(C, "set DateStyle = 'German'"),
  710. {ok, <<"German, DMY">>} = Module:get_parameter(C, "DateStyle"),
  711. {ok, _Cols, [{<<"02.01.2000">>}]} = Module:squery(C, "select '2000-01-02'::date")
  712. end).
  713. numeric_type(Config) ->
  714. check_type(Config, int2, "1", 1, [0, 256, -32768, +32767]),
  715. check_type(Config, int4, "1", 1, [0, 512, -2147483648, +2147483647]),
  716. check_type(Config, int8, "1", 1, [0, 1024, -9223372036854775808, +9223372036854775807]),
  717. check_type(Config, float4, "1.0", 1.0, [0.0, 1.23456, -1.23456]),
  718. check_type(Config, float4, "'-Infinity'", minus_infinity, [minus_infinity, plus_infinity, nan]),
  719. check_type(Config, float8, "1.0", 1.0, [0.0, 1.23456789012345, -1.23456789012345]),
  720. check_type(Config, float8, "'nan'", nan, [minus_infinity, plus_infinity, nan]),
  721. %% Check overflow protection. Connection just crashes for now instead of silently
  722. %% truncating the data. Some cleaner behaviour can be introduced later.
  723. epgsql_ct:with_connection(Config, fun(C) ->
  724. Module = ?config(module, Config),
  725. Trap = process_flag(trap_exit, true),
  726. try Module:equery(C, "SELECT $1::int2", [32768]) of
  727. {error, closed} ->
  728. %% epgsqla/epgsqli
  729. ok
  730. catch exit:Reason ->
  731. %% epgsql
  732. ?assertMatch({{{integer_overflow, int2, _}, _}, _}, Reason),
  733. receive {'EXIT', C, _} -> ok
  734. after 1000 -> error(timeout)
  735. end
  736. end,
  737. process_flag(trap_exit, Trap)
  738. end).
  739. character_type(Config) ->
  740. Alpha = unicode:characters_to_binary([16#03B1]),
  741. Ka = unicode:characters_to_binary([16#304B]),
  742. One = unicode:characters_to_binary([16#10D360]),
  743. check_type(Config, bpchar, "'A'", $A, [1, $1, 16#7F, Alpha, Ka, One], "c_char"),
  744. check_type(Config, text, "'hi'", <<"hi">>, [<<"">>, <<"hi">>]),
  745. check_type(Config, varchar, "'hi'", <<"hi">>, [<<"">>, <<"hi">>]),
  746. epgsql_ct:with_connection(
  747. Config,
  748. fun(C) ->
  749. Module = ?config(module, Config),
  750. %% IOlists
  751. ?assertMatch({ok, _, [{<<1087/utf8, 1088/utf8, 1080/utf8,
  752. 1074/utf8, 1077/utf8, 1090/utf8>>}]},
  753. Module:equery(C, "SELECT $1::text", [[1087,1088,1080,1074,1077,1090]])),
  754. %% Deprecated casts
  755. ?assertMatch({ok, _, [{<<"my_atom">>}]},
  756. Module:equery(C, "SELECT $1::varchar", [my_atom])),
  757. ?assertMatch({ok, _, [{<<"12345">>}]},
  758. Module:equery(C, "SELECT $1::varchar", [12345])),
  759. FloatBin = erlang:float_to_binary(1.2345),
  760. ?assertMatch({ok, _, [{FloatBin}]},
  761. Module:equery(C, "SELECT $1::varchar", [1.2345])),
  762. %% String bpchar
  763. ?assertMatch({ok, _, [{<<"hello world">>}]},
  764. Module:equery(C, "SELECT $1::bpchar", ["hello world"]))
  765. end).
  766. uuid_type(Config) ->
  767. check_type(Config, uuid,
  768. io_lib:format("'~s'", [uuid_to_bin_string(?UUID1)]),
  769. uuid_to_bin_string(?UUID1), []).
  770. point_type(Config) ->
  771. check_type(Config, point, "'(23.15, 100)'", {23.15, 100.0}, []).
  772. geometry_type(Config) ->
  773. check_type(Config, geometry, "'COMPOUNDCURVE(CIRCULARSTRING(0 0,1 1,1 0),(1 0,0 1))'",
  774. {compound_curve,'2d', [
  775. {circular_string,'2d', [
  776. {point,'2d',0.0,0.0,undefined,undefined},
  777. {point,'2d',1.0,1.0,undefined,undefined},
  778. {point,'2d',1.0,0.0,undefined,undefined}
  779. ]},
  780. {line_string,'2d', [
  781. {point,'2d',1.0,0.0,undefined,undefined},
  782. {point,'2d',0.0,1.0,undefined,undefined}
  783. ]}
  784. ]}, []).
  785. uuid_select(Config) ->
  786. Module = ?config(module, Config),
  787. epgsql_ct:with_rollback(Config, fun(C) ->
  788. U1 = uuid_to_bin_string(?UUID1),
  789. U2 = uuid_to_bin_string(?UUID2),
  790. U3 = uuid_to_bin_string(?UUID3),
  791. {ok, 1} =
  792. Module:equery(C, "insert into test_table2 (c_varchar, c_uuid) values ('UUID1', $1)",
  793. [U1]),
  794. {ok, 1} =
  795. Module:equery(C, "insert into test_table2 (c_varchar, c_uuid) values ('UUID2', $1)",
  796. [U2]),
  797. {ok, 1} =
  798. Module:equery(C, "insert into test_table2 (c_varchar, c_uuid) values ('UUID3', $1)",
  799. [U3]),
  800. Res = Module:equery(C, "select c_varchar, c_uuid from test_table2 where c_uuid = any($1)",
  801. [[U1, U2]]),
  802. ?assertMatch(
  803. {ok,[#column{name = <<"c_varchar">>, type = varchar},
  804. #column{name = <<"c_uuid">>, type = uuid}],
  805. [{<<"UUID1">>, U1},
  806. {<<"UUID2">>, U2}]}, Res)
  807. end).
  808. date_time_type(Config) ->
  809. Module = ?config(module, Config),
  810. epgsql_ct:with_connection(Config, fun(C) ->
  811. case Module:get_parameter(C, "integer_datetimes") of
  812. {ok, <<"on">>} -> MaxTsDate = 294276;
  813. {ok, <<"off">>} -> MaxTsDate = 5874897
  814. end,
  815. check_type(Config, date, "'2008-01-02'", {2008,1,2}, [{-4712,1,1}, {5874897,1,1}]),
  816. check_type(Config, time, "'00:01:02'", {0,1,2.0}, [{0,0,0.0}, {24,0,0.0}]),
  817. check_type(Config, timetz, "'00:01:02-01'", {{0,1,2.0},1*60*60},
  818. [{{0,0,0.0},0}, {{24,0,0.0},-13*60*60}]),
  819. check_type(Config, timestamp, "'2008-01-02 03:04:05'", {{2008,1,2},{3,4,5.0}},
  820. [{{-4712,1,1},{0,0,0.0}}, {{MaxTsDate,12,31}, {23,59,59.0}}, {1322,334285,440966}]),
  821. check_type(Config, timestamptz, "'2011-01-02 03:04:05+3'", {{2011, 1, 2}, {0, 4, 5.0}}, [{1324,875970,286983}]),
  822. check_type(Config, interval, "'1 hour 2 minutes 3.1 seconds'", {{1,2,3.1},0,0},
  823. [{{0,0,0.0},0,-178000000 * 12}, {{0,0,0.0},0,178000000 * 12}])
  824. end).
  825. json_type(Config) ->
  826. Module = ?config(module, Config),
  827. epgsql_ct:with_connection(Config, fun(C) ->
  828. check_type(Config, json, "'{}'", <<"{}">>,
  829. [<<"{}">>, <<"[]">>, <<"1">>, <<"1.0">>, <<"true">>, <<"\"string\"">>, <<"{\"key\": []}">>],
  830. get_type_col(json), C),
  831. check_type(Config, jsonb, "'{}'", <<"{}">>,
  832. [<<"{}">>, <<"[]">>, <<"1">>, <<"1.0">>, <<"true">>, <<"\"string\"">>, <<"{\"key\": []}">>],
  833. get_type_col(jsonb), C),
  834. epgsql:update_type_cache(C, [{epgsql_codec_json, epgsql_fake_json_mod}]),
  835. RowId = "json_type_custom_mod_" ++ atom_to_list(Module),
  836. {ok, 1} = Module:equery(C, "insert into test_table2 (c_varchar, c_json, c_jsonb) values ($1, $2, $3)", [RowId, {"{}"}, {"{}"}]),
  837. Res = Module:equery(C, "select c_json, c_jsonb from test_table2 where c_varchar = $1", [RowId]),
  838. ?assertMatch(
  839. {ok, [#column{name = <<"c_json">>, type = json}, #column{name = <<"c_jsonb">>, type = jsonb}],
  840. [{{<<"{}">>}, {<<"{}">>}}]},
  841. Res
  842. )
  843. end).
  844. misc_type(Config) ->
  845. check_type(Config, bool, "true", true, [true, false]),
  846. check_type(Config, bytea, "E'\001\002'", <<1,2>>, [<<>>, <<0,128,255>>]).
  847. hstore_type(Config) ->
  848. Module = ?config(module, Config),
  849. Values = [
  850. {[]},
  851. {[{null, null}]},
  852. {[{null, undefined}]},
  853. {[{1, null}]},
  854. {[{1.0, null}]},
  855. {[{1, undefined}]},
  856. {[{1.0, undefined}]},
  857. {[{<<"a">>, <<"c">>}, {<<"c">>, <<"d">>}]},
  858. {[{<<"a">>, <<"c">>}, {<<"c">>, null}]},
  859. {[{<<"a">>, <<"c">>}, {<<"c">>, undefined}]}
  860. ],
  861. check_type(Config, hstore, "''", {[]}, []),
  862. check_type(Config, hstore,
  863. "'a => 1, b => 2.0, c => null'",
  864. {[{<<"a">>, <<"1">>}, {<<"b">>, <<"2.0">>}, {<<"c">>, null}]}, Values),
  865. epgsql_ct:with_connection(
  866. Config,
  867. fun(C) ->
  868. %% Maps as input
  869. [begin
  870. {ok, _, [{Res}]} = Module:equery(C, "select $1::hstore", [maps:from_list(KV)]),
  871. ?assert(compare(hstore, Res, Jiffy))
  872. end || {KV} = Jiffy <- Values],
  873. %% Maps as output
  874. {ok, [hstore]} = epgsql:update_type_cache(
  875. C, [{epgsql_codec_hstore, #{return => map}}]),
  876. [begin
  877. {ok, _, [{Res}]} = Module:equery(C, "select $1::hstore", [maps:from_list(KV)]),
  878. HstoreMap = maps:from_list([{format_hstore_key(K), format_hstore_value(V)} || {K, V} <- KV]),
  879. ?assertEqual(HstoreMap, Res)
  880. end || {KV} <- Values],
  881. %% Proplist as output
  882. {ok, [hstore]} = epgsql:update_type_cache(
  883. C, [{epgsql_codec_hstore, #{return => proplist}}]),
  884. [begin
  885. {ok, _, [{Res}]} = Module:equery(C, "select $1::hstore", [Jiffy]),
  886. HstoreProplist = [{format_hstore_key(K), format_hstore_value(V)} || {K, V} <- KV],
  887. ?assertEqual(lists:sort(HstoreProplist), lists:sort(Res))
  888. end || {KV} = Jiffy <- Values],
  889. %% Custom nulls
  890. Nulls = [nil, 'NULL', aaaa],
  891. {ok, [hstore]} = epgsql:update_type_cache(
  892. C, [{epgsql_codec_hstore, #{return => map,
  893. nulls => Nulls}}]),
  894. K = <<"k">>,
  895. [begin
  896. {ok, _, [{Res}]} = Module:equery(C, "select $1::hstore", [#{K => V}]),
  897. ?assertEqual(#{K => nil}, Res)
  898. end || V <- Nulls]
  899. end).
  900. net_type(Config) ->
  901. check_type(Config, cidr, "'127.0.0.1/32'", {{127,0,0,1}, 32}, [{{127,0,0,1}, 32}, {{0,0,0,0,0,0,0,1}, 128}]),
  902. check_type(Config, inet, "'127.0.0.1'", {127,0,0,1}, [{127,0,0,1}, {0,0,0,0,0,0,0,1}]),
  903. %% macaddr8 available only on PG>=10
  904. check_type(Config, macaddr,
  905. "'FF:FF:FF:FF:FF:FF'", {255, 255, 255, 255, 255, 255},
  906. [{255, 255, 255, 255, 255, 255},
  907. {6, 0, 0, 0, 0, 0}]).
  908. array_type(Config) ->
  909. Module = ?config(module, Config),
  910. epgsql_ct:with_connection(Config, fun(C) ->
  911. {ok, _, [{[1, 2]}]} = Module:equery(C, "select ($1::int[])[1:2]", [[1, 2, 3]]),
  912. {ok, _, [{[{1, <<"one">>}, {2, <<"two">>}]}]} =
  913. Module:equery(C, "select Array(select (id, value) from test_table1)", []),
  914. {ok, _, [{ [[1], [null], [3], [null]] }]} =
  915. Module:equery(C, "select $1::int2[]", [ [[1], [null], [3], [undefined]] ]),
  916. Select = fun(Type, AIn) ->
  917. Query = "select $1::" ++ atom_to_list(Type) ++ "[]",
  918. {ok, _Cols, [{AOut}]} = Module:equery(C, Query, [AIn]),
  919. case lists:all(fun({VIn, VOut}) ->
  920. compare(Type, VIn, VOut)
  921. end, lists:zip(AIn, AOut)) of
  922. true -> ok;
  923. false -> ?assertEqual(AIn, AOut)
  924. end
  925. end,
  926. Select(int2, []),
  927. Select(int2, [1, 2, 3, 4]),
  928. Select(int2, [[1], [2], [3], [4]]),
  929. Select(int2, [[[[[[1, 2]]]]]]),
  930. Select(int2, [1, null, 3, undefined]),
  931. Select(int2, [[1], [null], [3], [null]]),
  932. Select(bool, [true]),
  933. Select(char, [$a, $b, $c]),
  934. Select(int4, [[1, 2]]),
  935. Select(int8, [[[[1, 2]], [[3, 4]]]]),
  936. Select(text, [<<"one">>, <<"two>">>]),
  937. Select(varchar, [<<"one">>, <<"two>">>]),
  938. Select(float4, [0.0, 1.0, 0.123]),
  939. Select(float8, [0.0, 1.0, 0.123]),
  940. Select(date, [{2008,1,2}, {2008,1,3}]),
  941. Select(time, [{0,1,2.0}, {0,1,3.0}]),
  942. Select(timetz, [{{0,1,2.0},1*60*60}, {{0,1,3.0},1*60*60}]),
  943. Select(timestamp, [{{2008,1,2},{3,4,5.0}}, {{2008,1,2},{3,4,6.0}}]),
  944. Select(timestamptz, [{{2008,1,2},{3,4,5.0}}, {{2008,1,2},{3,4,6.0}}]),
  945. Select(interval, [{{1,2,3.1},0,0}, {{1,2,3.2},0,0}]),
  946. Select(hstore, [{[{null, null}, {a, 1}, {1, 2}, {b, undefined}]}]),
  947. Select(hstore, [[{[{null, null}, {a, 1}, {1, 2}, {b, undefined}]}, {[]}], [{[{a, 1}]}, {[{null, 2}]}]]),
  948. Select(cidr, [{{127,0,0,1}, 32}, {{0,0,0,0,0,0,0,1}, 128}]),
  949. Select(inet, [{127,0,0,1}, {0,0,0,0,0,0,0,1}]),
  950. Select(json, [<<"{}">>, <<"[]">>, <<"1">>, <<"1.0">>, <<"true">>, <<"\"string\"">>, <<"{\"key\": []}">>]),
  951. Select(jsonb, [<<"{}">>, <<"[]">>, <<"1">>, <<"1.0">>, <<"true">>, <<"\"string\"">>, <<"{\"key\": []}">>])
  952. end).
  953. record_type(Config) ->
  954. Module = ?config(module, Config),
  955. epgsql_ct:with_connection(Config, fun(C) ->
  956. Select = fun(Sql, Expected) ->
  957. {ok, _Columns, [Row]} = Module:equery(C, Sql, []),
  958. ?assertMatch(Expected, Row)
  959. end,
  960. %% Simple record
  961. Select("select (1,2)", {{1, 2}}),
  962. %% Record inside other record
  963. Select("select (1, (select (2,3)))", {{1, {2, 3}}}),
  964. %% Array inside record
  965. Select("select (1, '{2,3}'::int[])", {{1, [2, 3]}}),
  966. %% Array of records inside record
  967. Select("select (0, ARRAY(select (id, value) from test_table1))", {{0,[{1,<<"one">>},{2,<<"two">>}]}}),
  968. %% Record with NULLs
  969. Select("select (1, NULL::integer, 2)", {{1, null, 2}})
  970. end).
  971. custom_types(Config) ->
  972. Module = ?config(module, Config),
  973. epgsql_ct:with_connection(Config, fun(C) ->
  974. Module:squery(C, "drop table if exists t_foo;"),
  975. Module:squery(C, "drop type if exists my_type;"),
  976. {ok, [], []} = Module:squery(C, "create type my_type as enum('foo', 'bar');"),
  977. {ok, [my_type]} = epgsql:update_type_cache(C, [{epgsql_codec_test_enum, [foo, bar]}]),
  978. {ok, [], []} = Module:squery(C, "create table t_foo (col my_type);"),
  979. {ok, S} = Module:parse(C, "insert_foo", "insert into t_foo values ($1)", [my_type]),
  980. ok = Module:bind(C, S, [bar]),
  981. {ok, 1} = Module:execute(C, S),
  982. ?assertMatch({ok, _, [{bar}]}, Module:equery(C, "SELECT col FROM t_foo"))
  983. end).
  984. custom_null(Config) ->
  985. Module = ?config(module, Config),
  986. epgsql_ct:with_connection(Config, fun(C) ->
  987. Test3 = fun(Type, In, Out) ->
  988. Q = ["SELECT $1::", Type],
  989. {ok, _, [{Res}]} = Module:equery(C, Q, [In]),
  990. ?assertEqual(Out, Res)
  991. end,
  992. Test = fun(Type, In) ->
  993. Test3(Type, In, In)
  994. end,
  995. Test("int2", nil),
  996. Test3("int2", 'NULL', nil),
  997. Test("text", nil),
  998. Test3("text", 'NULL', nil),
  999. Test3("text", null, <<"null">>),
  1000. Test("int2[]", [nil, 1, nil, 2]),
  1001. Test3("text[]", [null, <<"ok">>], [<<"null">>, <<"ok">>]),
  1002. Test3("int2[]", ['NULL', 1, nil, 2], [nil, 1, nil, 2]),
  1003. Test("int2[]", [[nil], [1], [nil], [2]]),
  1004. Test3("int2[]", [['NULL'], [1], [nil], [2]], [[nil], [1], [nil], [2]]),
  1005. ?assertMatch(
  1006. {ok, _, [{ {1, nil, {2, nil, 3}} }]},
  1007. Module:equery(C, "SELECT (1, NULL, (2, NULL, 3))", []))
  1008. end,
  1009. [{nulls, [nil, 'NULL']}]).
  1010. text_format(Config) ->
  1011. Module = ?config(module, Config),
  1012. epgsql_ct:with_connection(Config, fun(C) ->
  1013. Select = fun(Type, V) ->
  1014. V2 = list_to_binary(V),
  1015. Query = "select $1::" ++ Type,
  1016. ?assertMatch({ok, _Cols, [{V2}]}, Module:equery(C, Query, [V])),
  1017. ?assertMatch({ok, _Cols, [{V2}]}, Module:equery(C, Query, [V2]))
  1018. end,
  1019. Select("numeric", "123456")
  1020. end).
  1021. query_timeout(Config) ->
  1022. Module = ?config(module, Config),
  1023. epgsql_ct:with_connection(Config, fun(C) ->
  1024. {ok, _, _} = Module:squery(C, "SET statement_timeout = 500"),
  1025. ?assertMatch(?TIMEOUT_ERROR, Module:squery(C, "SELECT pg_sleep(1)")),
  1026. ?assertMatch(?TIMEOUT_ERROR, Module:equery(C, "SELECT pg_sleep(2)")),
  1027. {ok, _Cols, [{1}]} = Module:equery(C, "SELECT 1")
  1028. end, []).
  1029. execute_timeout(Config) ->
  1030. Module = ?config(module, Config),
  1031. epgsql_ct:with_connection(Config, fun(C) ->
  1032. {ok, _, _} = Module:squery(C, "SET statement_timeout = 500"),
  1033. {ok, S} = Module:parse(C, "select pg_sleep($1)"),
  1034. ok = Module:bind(C, S, [2]),
  1035. ?assertMatch(?TIMEOUT_ERROR, Module:execute(C, S, 0)),
  1036. ok = Module:sync(C),
  1037. ok = Module:bind(C, S, [0]),
  1038. {ok, [{<<>>}]} = Module:execute(C, S, 0),
  1039. ok = Module:close(C, S),
  1040. ok = Module:sync(C)
  1041. end, []).
  1042. connection_closed(Config) ->
  1043. {Host, Port} = epgsql_ct:connection_data(Config),
  1044. Module = ?config(module, Config),
  1045. P = self(),
  1046. spawn_link(fun() ->
  1047. process_flag(trap_exit, true),
  1048. {ok, C} = Module:connect(Host, "epgsql_test",[
  1049. {port, Port},
  1050. {database, "epgsql_test_db1"}
  1051. ]),
  1052. P ! {connected, C},
  1053. receive
  1054. Any -> P ! Any
  1055. end
  1056. end),
  1057. receive
  1058. {connected, C} ->
  1059. timer:sleep(100),
  1060. Module:close(C),
  1061. {'EXIT', C, _} = receive R -> R end
  1062. end,
  1063. epgsql_ct:flush().
  1064. connection_closed_by_server(Config) ->
  1065. Module = ?config(module, Config),
  1066. epgsql_ct:with_connection(Config, fun(C1) ->
  1067. P = self(),
  1068. spawn_link(fun() ->
  1069. process_flag(trap_exit, true),
  1070. epgsql_ct:with_connection(Config, fun(C2) ->
  1071. {ok, _, [{Pid}]} = Module:equery(C2, "select pg_backend_pid()"),
  1072. % emulate of disconnection
  1073. {ok, _, [{true}]} = Module:equery(C1,
  1074. "select pg_terminate_backend($1)", [Pid]),
  1075. receive
  1076. {'EXIT', C2, {shutdown, #error{code = <<"57P01">>}}} ->
  1077. P ! ok;
  1078. Other ->
  1079. ct:pal("Unexpected msg: ~p~n", [Other]),
  1080. P ! error
  1081. end
  1082. end)
  1083. end),
  1084. receive ok -> ok end
  1085. end).
  1086. active_connection_closed(Config) ->
  1087. {Host, Port} = epgsql_ct:connection_data(Config),
  1088. Module = ?config(module, Config),
  1089. P = self(),
  1090. F = fun() ->
  1091. process_flag(trap_exit, true),
  1092. {ok, C} = Module:connect(Host, [
  1093. {database, "epgsql_test_db1"},
  1094. {port, Port}
  1095. ]),
  1096. P ! {connected, C},
  1097. R = Module:squery(C, "select pg_sleep(10)"),
  1098. P ! R
  1099. end,
  1100. spawn_link(F),
  1101. receive
  1102. {connected, C} ->
  1103. timer:sleep(100),
  1104. Module:close(C),
  1105. {error, closed} = receive R -> R end
  1106. end,
  1107. epgsql_ct:flush().
  1108. warning_notice(Config) ->
  1109. Module = ?config(module, Config),
  1110. epgsql_ct:with_connection(Config, fun(C) ->
  1111. Q = "create function pg_temp.raise() returns void as $$
  1112. begin
  1113. raise warning 'oops';
  1114. end;
  1115. $$ language plpgsql;
  1116. select pg_temp.raise()",
  1117. [{ok, _, _}, _] = Module:squery(C, Q),
  1118. receive
  1119. {epgsql, C, {notice, #error{message = <<"oops">>, extra = Extra}}} ->
  1120. ?assertMatch([{file, _},{line, _},{routine, _} | _], Extra),
  1121. ok
  1122. after
  1123. 100 -> erlang:error(didnt_receive_notice)
  1124. end
  1125. end, [{async, self()}]).
  1126. listen_notify(Config) ->
  1127. Module = ?config(module, Config),
  1128. epgsql_ct:with_connection(Config, fun(C) ->
  1129. {ok, [], []} = Module:squery(C, "listen epgsql_test"),
  1130. {ok, _, [{Pid}]} = Module:equery(C, "select pg_backend_pid()"),
  1131. {ok, [], []} = Module:squery(C, "notify epgsql_test"),
  1132. receive
  1133. {epgsql, C, {notification, <<"epgsql_test">>, Pid, <<>>}} -> ok
  1134. after
  1135. 100 -> erlang:error(didnt_receive_notification)
  1136. end
  1137. end, [{async, self()}]).
  1138. listen_notify_payload(Config) ->
  1139. Module = ?config(module, Config),
  1140. epgsql_ct:with_min_version(Config, [9, 0], fun(C) ->
  1141. {ok, [], []} = Module:squery(C, "listen epgsql_test"),
  1142. {ok, _, [{Pid}]} = Module:equery(C, "select pg_backend_pid()"),
  1143. {ok, [], []} = Module:squery(C, "notify epgsql_test, 'test!'"),
  1144. receive
  1145. {epgsql, C, {notification, <<"epgsql_test">>, Pid, <<"test!">>}} -> ok
  1146. after
  1147. 100 -> erlang:error(didnt_receive_notification)
  1148. end
  1149. end, [{async, self()}]).
  1150. set_notice_receiver(Config) ->
  1151. Module = ?config(module, Config),
  1152. epgsql_ct:with_min_version(Config, [9, 0], fun(C) ->
  1153. {ok, [], []} = Module:squery(C, "listen epgsql_test"),
  1154. {ok, _, [{Pid}]} = Module:equery(C, "select pg_backend_pid()"),
  1155. EnsureNoNotification = fun(Payload) ->
  1156. {ok, [], []} = Module:squery(C, ["notify epgsql_test, '", Payload, "'"]),
  1157. receive
  1158. {epgsql, _, _} -> erlang:error(got_unexpected_notification)
  1159. after
  1160. 10 -> ok
  1161. end
  1162. end,
  1163. EnsureNotification = fun(Payload) ->
  1164. {ok, [], []} = Module:squery(C, ["notify epgsql_test, '", Payload, "'"]),
  1165. receive
  1166. {epgsql, C, {notification, <<"epgsql_test">>, Pid, Payload}} -> ok
  1167. after
  1168. 100 -> erlang:error(didnt_receive_notification)
  1169. end
  1170. end,
  1171. Self = self(),
  1172. EnsureNoNotification(<<"test1">>),
  1173. % Set pid()
  1174. {ok, undefined} = Module:set_notice_receiver(C, Self),
  1175. EnsureNotification(<<"test2">>),
  1176. %% test PL/PgSQL NOTICE
  1177. {ok, [], []} = Module:squery(C, ["DO $$ BEGIN RAISE WARNING 'test notice'; END $$;"]),
  1178. receive
  1179. {epgsql, C, {notice, #error{severity = warning,
  1180. code = <<"01000">>,
  1181. message = <<"test notice">>,
  1182. extra = _}}} -> ok
  1183. after
  1184. 100 -> erlang:error(didnt_receive_notice)
  1185. end,
  1186. % set registered pid
  1187. Receiver = pg_notification_receiver,
  1188. register(Receiver, Self),
  1189. {ok, Self} = Module:set_notice_receiver(C, Receiver),
  1190. EnsureNotification(<<"test3">>),
  1191. % make registered name invalid
  1192. unregister(Receiver),
  1193. EnsureNoNotification(<<"test4">>),
  1194. % disable
  1195. {ok, Receiver} = Module:set_notice_receiver(C, undefined),
  1196. EnsureNoNotification(<<"test5">>)
  1197. end, []).
  1198. get_cmd_status(Config) ->
  1199. Module = ?config(module, Config),
  1200. epgsql_ct:with_connection(Config, fun(C) ->
  1201. {ok, [], []} = Module:squery(C, "BEGIN"),
  1202. ?assertEqual({ok, 'begin'}, Module:get_cmd_status(C)),
  1203. {ok, [], []} = epgsql:equery(C, "CREATE TEMPORARY TABLE cmd_status_t(col INTEGER)"),
  1204. ?assertEqual({ok, 'create'}, Module:get_cmd_status(C)),
  1205. %% Some commands have number of affected rows in status
  1206. {ok, N} = Module:squery(C, "INSERT INTO cmd_status_t (col) VALUES (1), (2)"),
  1207. ?assertEqual({ok, {'insert', N}}, Module:get_cmd_status(C)),
  1208. {ok, 1} = Module:squery(C, "UPDATE cmd_status_t SET col=3 WHERE col=1"),
  1209. ?assertEqual({ok, {'update', 1}}, Module:get_cmd_status(C)),
  1210. %% Failed queries have no status
  1211. {error, _} = Module:squery(C, "DELETE FROM cmd_status_t WHERE not_col=2"),
  1212. ?assertEqual({ok, undefined}, Module:get_cmd_status(C)),
  1213. %% if COMMIT failed, status will be 'rollback'
  1214. {ok, [], []} = Module:squery(C, "COMMIT"),
  1215. ?assertEqual({ok, 'rollback'}, Module:get_cmd_status(C)),
  1216. %% Only last command's status returned
  1217. [_, _, _] = Module:squery(C, "BEGIN; SELECT 1; COMMIT"),
  1218. ?assertEqual({ok, 'commit'}, Module:get_cmd_status(C))
  1219. end).
  1220. range_type(Config) ->
  1221. epgsql_ct:with_min_version(Config, [9, 2], fun(_C) ->
  1222. check_type(Config, int4range, "int4range(10, 20)", {10, 20}, [
  1223. {1, 58}, {-1, 12}, {-985521, 5412687}, {minus_infinity, 0},
  1224. {984655, plus_infinity}, {minus_infinity, plus_infinity}
  1225. ]),
  1226. check_type(Config, int4range, "int4range(10, 10)", empty, [])
  1227. end, []).
  1228. range8_type(Config) ->
  1229. epgsql_ct:with_min_version(Config, [9, 2], fun(_C) ->
  1230. check_type(Config, int8range, "int8range(10, 20)", {10, 20}, [
  1231. {1, 58}, {-1, 12}, {-9223372036854775808, 5412687},
  1232. {minus_infinity, 9223372036854775807},
  1233. {984655, plus_infinity}, {minus_infinity, plus_infinity}
  1234. ]),
  1235. check_type(Config, int8range, "int8range(10, 10)", empty, [])
  1236. end, []).
  1237. date_time_range_type(Config) ->
  1238. epgsql_ct:with_min_version(Config, [9, 2], fun(_C) ->
  1239. check_type(Config, tsrange, "tsrange('2008-01-02 03:04:05', '2008-02-02 03:04:05')", {{{2008,1,2},{3,4,5.0}}, {{2008,2,2},{3,4,5.0}}}, []),
  1240. check_type(Config, tsrange, "tsrange('2008-01-02 03:04:05', '2008-02-02 03:04:05', '[]')", {{{2008,1,2},{3,4,5.0}}, {{2008,2,2},{3,4,5.0}}}, []),
  1241. check_type(Config, tsrange, "tsrange('2008-01-02 03:04:05', '2008-02-02 03:04:05', '()')", {{{2008,1,2},{3,4,5.0}}, {{2008,2,2},{3,4,5.0}}}, []),
  1242. check_type(Config, tsrange, "tsrange('2008-01-02 03:04:05', '2008-02-02 03:04:05', '[)')", {{{2008,1,2},{3,4,5.0}}, {{2008,2,2},{3,4,5.0}}}, []),
  1243. check_type(Config, tsrange, "tsrange('2008-01-02 03:04:05', '2008-02-02 03:04:05', '(]')", {{{2008,1,2},{3,4,5.0}}, {{2008,2,2},{3,4,5.0}}}, []),
  1244. check_type(Config, tsrange, "tsrange('2008-01-02 03:04:05', '2008-01-02 03:04:05')", empty, []),
  1245. check_type(Config, daterange, "daterange('2008-01-02', '2008-02-02')", {{2008,1,2}, {2008, 2, 2}}, [{{-4712,1,1}, {5874897,1,1}}]),
  1246. check_type(Config, tstzrange, "tstzrange('2011-01-02 03:04:05+3', '2011-01-02 04:04:05+3')", {{{2011, 1, 2}, {0, 4, 5.0}}, {{2011, 1, 2}, {1, 4, 5.0}}}, [{{{2011, 1, 2}, {0, 4, 5.0}}, {{2011, 1, 2}, {1, 4, 5.0}}}]),
  1247. check_type(Config, tstzrange, "tstzrange('2008-01-02 03:04:05', null)", {{{2008,1,2},{3,4,5.0}}, plus_infinity}, []),
  1248. check_type(Config, tstzrange, "tstzrange('2008-01-02 03:04:05', null, '[]')", {{{2008,1,2},{3,4,5.0}}, plus_infinity}, []),
  1249. check_type(Config, tstzrange, "tstzrange('2008-01-02 03:04:05', null, '()')", {{{2008,1,2},{3,4,5.0}}, plus_infinity}, []),
  1250. check_type(Config, tstzrange, "tstzrange(null, '2008-01-02 03:04:05')", {minus_infinity, {{2008,1,2},{3,4,5.0}}}, []),
  1251. check_type(Config, tstzrange, "tstzrange(null, '2008-01-02 03:04:05', '[]')", {minus_infinity, {{2008,1,2},{3,4,5.0}}}, []),
  1252. check_type(Config, tstzrange, "tstzrange(null, '2008-01-02 03:04:05', '()')", {minus_infinity, {{2008,1,2},{3,4,5.0}}}, [])
  1253. end, []).
  1254. with_transaction(Config) ->
  1255. Module = ?config(module, Config),
  1256. epgsql_ct:with_connection(
  1257. Config,
  1258. fun(C) ->
  1259. %% Success case
  1260. ?assertEqual(
  1261. success, Module:with_transaction(C, fun(_) -> success end)),
  1262. ?assertEqual(
  1263. success, Module:with_transaction(C, fun(_) -> success end,
  1264. [{ensure_committed, true}])),
  1265. %% begin_opts
  1266. ?assertMatch(
  1267. [{ok, _, [{<<"serializable">>}]},
  1268. {ok, _, [{<<"on">>}]}],
  1269. Module:with_transaction(
  1270. C, fun(C1) ->
  1271. Module:squery(C1, ("SHOW transaction_isolation; "
  1272. "SHOW transaction_read_only"))
  1273. end,
  1274. [{begin_opts, "READ ONLY ISOLATION LEVEL SERIALIZABLE"}])),
  1275. %% ensure_committed failure
  1276. ?assertError(
  1277. {ensure_committed_failed, rollback},
  1278. Module:with_transaction(
  1279. C, fun(C1) ->
  1280. {error, _} = Module:squery(C1, "SELECT col FROM _nowhere_"),
  1281. ok
  1282. end,
  1283. [{ensure_committed, true}])),
  1284. %% reraise
  1285. ?assertEqual(
  1286. {rollback, my_err},
  1287. Module:with_transaction(
  1288. C, fun(_) -> error(my_err) end,
  1289. [{reraise, false}])),
  1290. ?assertError(
  1291. my_err,
  1292. Module:with_transaction(
  1293. C, fun(_) -> error(my_err) end, []))
  1294. end, []).
  1295. %% =============================================================================
  1296. %% Internal functions
  1297. %% ============================================================================
  1298. get_type_col(Type) ->
  1299. "c_" ++ atom_to_list(Type).
  1300. check_type(Config, Type, In, Out, Values) ->
  1301. Column = get_type_col(Type),
  1302. check_type(Config, Type, In, Out, Values, Column).
  1303. check_type(Config, Type, In, Out, Values, Column) ->
  1304. epgsql_ct:with_connection(Config, fun(C) ->
  1305. check_type(Config, Type, In, Out, Values, Column, C)
  1306. end).
  1307. check_type(Config, Type, In, Out, Values, Column, C) ->
  1308. Module = ?config(module, Config),
  1309. Select = io_lib:format("select ~s::~w", [In, Type]),
  1310. Res = Module:equery(C, Select),
  1311. ?assertMatch({ok, [#column{type = Type}], [{Out}]}, Res),
  1312. Sql = io_lib:format("insert into test_table2 (~s) values ($1) returning ~s", [Column, Column]),
  1313. {ok, #statement{columns = [#column{type = Type}]} = S} = Module:parse(C, Sql),
  1314. Insert = fun(V) ->
  1315. ok = Module:bind(C, S, [V]),
  1316. {ok, 1, [{V2}]} = Module:execute(C, S),
  1317. case compare(Type, V, V2) of
  1318. true -> ok;
  1319. false -> error({write_read_compare_failed, io_lib:format("~p =/= ~p", [V, V2])})
  1320. end,
  1321. ok = Module:sync(C)
  1322. end,
  1323. lists:foreach(Insert, [null, undefined | Values]).
  1324. compare(_Type, null, null) -> true;
  1325. compare(_Type, undefined, null) -> true;
  1326. compare(float4, V1, V2) when is_float(V1) -> abs(V2 - V1) < 0.000001;
  1327. compare(float8, V1, V2) when is_float(V1) -> abs(V2 - V1) < 0.000000000000001;
  1328. compare(hstore, {V1}, V2) -> compare(hstore, V1, V2);
  1329. compare(hstore, V1, {V2}) -> compare(hstore, V1, V2);
  1330. compare(hstore, V1, V2) ->
  1331. orddict:from_list(format_hstore(V1)) =:= orddict:from_list(format_hstore(V2));
  1332. compare(Type, V1 = {_, _, MS}, {D2, {H2, M2, S2}}) when Type == timestamp;
  1333. Type == timestamptz ->
  1334. {D1, {H1, M1, S1}} = calendar:now_to_universal_time(V1),
  1335. ({D1, H1, M1} =:= {D2, H2, M2}) and (abs(S1 + MS/1000000 - S2) < 0.000000000000001);
  1336. compare(_Type, V1, V2) -> V1 =:= V2.
  1337. format_hstore({Hstore}) -> Hstore;
  1338. format_hstore(Hstore) ->
  1339. [{format_hstore_key(Key), format_hstore_value(Value)} || {Key, Value} <- Hstore].
  1340. format_hstore_key(Key) -> format_hstore_string(Key).
  1341. format_hstore_value(null) -> null;
  1342. format_hstore_value(undefined) -> null;
  1343. format_hstore_value(Value) -> format_hstore_string(Value).
  1344. format_hstore_string(Num) when is_number(Num) -> iolist_to_binary(io_lib:format("~w", [Num]));
  1345. format_hstore_string(Str) -> iolist_to_binary(io_lib:format("~s", [Str])).