epgsql_SUITE.erl 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474
  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, _}] =
  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. ])
  439. end).
  440. single_batch(Config) ->
  441. Module = ?config(module, Config),
  442. epgsql_ct:with_connection(Config, fun(C) ->
  443. {ok, S1} = Module:parse(C, "one", "select $1", [int4]),
  444. [{ok, [{1}]}] = Module:execute_batch(C, [{S1, [1]}])
  445. end).
  446. extended_select(Config) ->
  447. Module = ?config(module, Config),
  448. epgsql_ct:with_connection(Config, fun(C) ->
  449. {ok, Cols, Rows} = Module:equery(C, "select * from test_table1", []),
  450. [#column{name = <<"id">>, type = int4, size = 4},
  451. #column{name = <<"value">>, type = text, size = -1}] = Cols,
  452. [{1, <<"one">>}, {2, <<"two">>}] = Rows
  453. end).
  454. extended_sync_ok(Config) ->
  455. Module = ?config(module, Config),
  456. epgsql_ct:with_connection(Config, fun(C) ->
  457. {ok, _Cols, [{<<"one">>}]} = Module:equery(C, "select value from test_table1 where id = $1", [1]),
  458. {ok, _Cols, [{<<"two">>}]} = Module:equery(C, "select value from test_table1 where id = $1", [2])
  459. end).
  460. extended_sync_error(Config) ->
  461. Module = ?config(module, Config),
  462. epgsql_ct:with_connection(Config, fun(C) ->
  463. {error, #error{}} = Module:equery(C, "select _alue from test_table1 where id = $1", [1]),
  464. {ok, _Cols, [{<<"one">>}]} = Module:equery(C, "select value from test_table1 where id = $1", [1])
  465. end).
  466. returning_from_insert(Config) ->
  467. Module = ?config(module, Config),
  468. epgsql_ct:with_rollback(Config, fun(C) ->
  469. {ok, 1, _Cols, [{3}]} = Module:equery(C, "insert into test_table1 (id) values (3) returning id")
  470. end).
  471. returning_from_update(Config) ->
  472. Module = ?config(module, Config),
  473. epgsql_ct:with_rollback(Config, fun(C) ->
  474. {ok, 2, _Cols, [{1}, {2}]} = Module:equery(C, "update test_table1 set value = 'hi' returning id"),
  475. ?assertMatch({ok, 0, [#column{}], []},
  476. Module:equery(C, "update test_table1 set value = 'hi' where false returning id")),
  477. ?assertMatch([{ok, 2, [#column{}], [{<<"1">>}, {<<"2">>}]},
  478. {ok, 0, [#column{}], []}],
  479. Module:squery(C,
  480. "update test_table1 set value = 'hi2' returning id; "
  481. "update test_table1 set value = 'hi' where false returning id"))
  482. end).
  483. returning_from_delete(Config) ->
  484. Module = ?config(module, Config),
  485. epgsql_ct:with_rollback(Config, fun(C) ->
  486. {ok, 2, _Cols, [{1}, {2}]} = Module:equery(C, "delete from test_table1 returning id"),
  487. ?assertMatch({ok, 0, [#column{}], []},
  488. Module:equery(C, "delete from test_table1 returning id"))
  489. end).
  490. parse(Config) ->
  491. Module = ?config(module, Config),
  492. epgsql_ct:with_connection(Config, fun(C) ->
  493. {ok, S} = Module:parse(C, "select * from test_table1"),
  494. [#column{name = <<"id">>}, #column{name = <<"value">>}] = S#statement.columns,
  495. ok = Module:close(C, S),
  496. ok = Module:sync(C)
  497. end).
  498. parse_column_format(Config) ->
  499. Module = ?config(module, Config),
  500. epgsql_ct:with_connection(Config, fun(C) ->
  501. {ok, S} = Module:parse(C, "select 1::int4, false::bool, 2.0::float4"),
  502. [#column{type = int4, table_oid = 0, table_attr_number = 0},
  503. #column{type = bool, table_oid = 0, table_attr_number = 0},
  504. #column{type = float4, table_oid = 0, table_attr_number = 0}] = S#statement.columns,
  505. ok = Module:bind(C, S, []),
  506. {ok, [{1, false, 2.0}]} = Module:execute(C, S, 0),
  507. ok = Module:close(C, S),
  508. ok = Module:sync(C)
  509. end).
  510. parse_error(Config) ->
  511. Module = ?config(module, Config),
  512. epgsql_ct:with_connection(Config, fun(C) ->
  513. {error, #error{
  514. extra = [{file, _}, {line, _}, {position, <<"8">>}, {routine, _} | _]
  515. }} = Module:parse(C, "select _ from test_table1"),
  516. {ok, S} = Module:parse(C, "select * from test_table1"),
  517. [#column{name = <<"id">>}, #column{name = <<"value">>}] = S#statement.columns,
  518. ok = Module:close(C, S),
  519. ok = Module:sync(C)
  520. end).
  521. parse_and_close(Config) ->
  522. Module = ?config(module, Config),
  523. epgsql_ct:with_connection(Config, fun(C) ->
  524. Parse = fun() -> Module:parse(C, "test", "select * from test_table1", []) end,
  525. {ok, S} = Parse(),
  526. {error, #error{code = <<"42P05">>, codename = duplicate_prepared_statement}} = Parse(),
  527. Module:close(C, S),
  528. {ok, S} = Parse(),
  529. ok = Module:sync(C)
  530. end).
  531. bind(Config) ->
  532. Module = ?config(module, Config),
  533. epgsql_ct:with_connection(Config, fun(C) ->
  534. {ok, S} = Module:parse(C, "select value from test_table1 where id = $1"),
  535. ok = Module:bind(C, S, [1]),
  536. ok = Module:close(C, S),
  537. ok = Module:sync(C)
  538. end).
  539. bind_parameter_format(Config) ->
  540. Module = ?config(module, Config),
  541. epgsql_ct:with_connection(Config, fun(C) ->
  542. {ok, S} = Module:parse(C, "select $1, $2, $3", [int2, text, bool]),
  543. [int2, text, bool] = S#statement.types,
  544. ok = Module:bind(C, S, [1, "hi", true]),
  545. {ok, [{1, <<"hi">>, true}]} = Module:execute(C, S, 0),
  546. ok = Module:close(C, S),
  547. ok = Module:sync(C)
  548. end).
  549. bind_error(Config) ->
  550. Module = ?config(module, Config),
  551. epgsql_ct:with_connection(Config, fun(C) ->
  552. {ok, S} = Module:parse(C, "select $1::char"),
  553. {error, #error{}} = Module:bind(C, S, [0]),
  554. ok = Module:bind(C, S, [$A]),
  555. ok = Module:close(C, S),
  556. ok = Module:sync(C)
  557. end).
  558. bind_and_close(Config) ->
  559. Module = ?config(module, Config),
  560. epgsql_ct:with_connection(Config, fun(C) ->
  561. {ok, S} = Module:parse(C, "select * from test_table1"),
  562. ok = Module:bind(C, S, "one", []),
  563. {error, #error{code = <<"42P03">>, codename = duplicate_cursor}} = Module:bind(C, S, "one", []),
  564. ok = Module:close(C, portal, "one"),
  565. ok = Module:bind(C, S, "one", []),
  566. ok = Module:sync(C)
  567. end).
  568. execute_error(Config) ->
  569. Module = ?config(module, Config),
  570. epgsql_ct:with_connection(Config, fun(C) ->
  571. {ok, S} = Module:parse(C, "insert into test_table1 (id, value) values ($1, $2)"),
  572. ok = Module:bind(C, S, [1, <<"foo">>]),
  573. {error, #error{
  574. code = <<"23505">>, codename = unique_violation,
  575. extra = [
  576. {constraint_name, <<"test_table1_pkey">>},
  577. {detail, _},
  578. {file, _},
  579. {line, _},
  580. {routine, _},
  581. {schema_name, <<"public">>} | _%,
  582. %{table_name, <<"test_table1">>}
  583. ]
  584. }} = Module:execute(C, S, 0),
  585. {error, sync_required} = Module:bind(C, S, [3, <<"quux">>]),
  586. ok = Module:sync(C),
  587. ok = Module:bind(C, S, [3, <<"quux">>]),
  588. {ok, _} = Module:execute(C, S, 0),
  589. {ok, 1} = Module:squery(C, "delete from test_table1 where id = 3")
  590. end).
  591. describe(Config) ->
  592. Module = ?config(module, Config),
  593. epgsql_ct:with_connection(Config, fun(C) ->
  594. {ok, S} = Module:parse(C, "select * from test_table1"),
  595. [#column{name = <<"id">>}, #column{name = <<"value">>}] = S#statement.columns,
  596. {ok, S} = Module:describe(C, S),
  597. ok = Module:close(C, S),
  598. ok = Module:sync(C)
  599. end).
  600. describe_with_param(Config) ->
  601. Module = ?config(module, Config),
  602. epgsql_ct:with_connection(Config, fun(C) ->
  603. {ok, S} = Module:parse(C, "select id from test_table1 where id = $1"),
  604. ?assertEqual([int4], S#statement.types),
  605. ?assertMatch([#column{name = <<"id">>}], S#statement.columns),
  606. {ok, S} = Module:describe(C, S),
  607. ok = Module:close(C, S),
  608. ok = Module:sync(C)
  609. end).
  610. describe_named(Config) ->
  611. Module = ?config(module, Config),
  612. epgsql_ct:with_connection(Config, fun(C) ->
  613. {ok, S} = Module:parse(C, "name", "select * from test_table1", []),
  614. [#column{name = <<"id">>}, #column{name = <<"value">>}] = S#statement.columns,
  615. {ok, S} = Module:describe(C, S),
  616. ok = Module:close(C, S),
  617. ok = Module:sync(C)
  618. end).
  619. describe_error(Config) ->
  620. Module = ?config(module, Config),
  621. epgsql_ct:with_connection(Config, fun(C) ->
  622. {error, #error{}} = Module:describe(C, statement, ""),
  623. {ok, S} = Module:parse(C, "select * from test_table1"),
  624. {ok, S} = Module:describe(C, statement, ""),
  625. ok = Module:sync(C)
  626. end).
  627. describe_portal(Config) ->
  628. Module = ?config(module, Config),
  629. epgsql_ct:with_connection(Config, fun(C) ->
  630. {ok, Stmt} = Module:parse(C, "my_stmt", "select * from test_table1 WHERE id = $1", []),
  631. ok = Module:bind(C, Stmt, "my_portal", [1]),
  632. {ok, Columns} = Module:describe(C, portal, "my_portal"),
  633. ?assertMatch(
  634. [#column{name = <<"id">>,
  635. type = int4},
  636. #column{name = <<"value">>,
  637. type = text}],
  638. Columns
  639. ),
  640. ok = Module:close(C, Stmt),
  641. ok = Module:sync(C)
  642. end).
  643. portal(Config) ->
  644. Module = ?config(module, Config),
  645. epgsql_ct:with_connection(Config, fun(C) ->
  646. {ok, S} = Module:parse(C, "select value from test_table1"),
  647. ok = Module:bind(C, S, []),
  648. {partial, [{<<"one">>}]} = Module:execute(C, S, 1),
  649. {partial, [{<<"two">>}]} = Module:execute(C, S, 1),
  650. {ok, []} = Module:execute(C, S,1),
  651. ok = Module:close(C, S),
  652. ok = Module:sync(C)
  653. end).
  654. returning(Config) ->
  655. Module = ?config(module, Config),
  656. epgsql_ct:with_rollback(Config, fun(C) ->
  657. {ok, S} = Module:parse(C, "update test_table1 set value = $1 returning id"),
  658. ok = Module:bind(C, S, ["foo"]),
  659. {ok, 2, [{1}, {2}]} = Module:execute(C, S),
  660. ok = Module:sync(C)
  661. end).
  662. multiple_statement(Config) ->
  663. Module = ?config(module, Config),
  664. epgsql_ct:with_connection(Config, fun(C) ->
  665. {ok, S1} = Module:parse(C, "one", "select value from test_table1 where id = 1", []),
  666. ok = Module:bind(C, S1, []),
  667. {partial, [{<<"one">>}]} = Module:execute(C, S1, 1),
  668. {ok, S2} = Module:parse(C, "two", "select value from test_table1 where id = 2", []),
  669. ok = Module:bind(C, S2, []),
  670. {partial, [{<<"two">>}]} = Module:execute(C, S2, 1),
  671. {ok, []} = Module:execute(C, S1, 1),
  672. {ok, []} = Module:execute(C, S2, 1),
  673. ok = Module:close(C, S1),
  674. ok = Module:close(C, S2),
  675. ok = Module:sync(C)
  676. end).
  677. multiple_portal(Config) ->
  678. Module = ?config(module, Config),
  679. epgsql_ct:with_connection(Config, fun(C) ->
  680. {ok, S} = Module:parse(C, "select value from test_table1 where id = $1"),
  681. ok = Module:bind(C, S, "one", [1]),
  682. ok = Module:bind(C, S, "two", [2]),
  683. {ok, [{<<"one">>}]} = Module:execute(C, S, "one", 0),
  684. {ok, [{<<"two">>}]} = Module:execute(C, S, "two", 0),
  685. ok = Module:close(C, S),
  686. ok = Module:sync(C)
  687. end).
  688. execute_function(Config) ->
  689. Module = ?config(module, Config),
  690. epgsql_ct:with_rollback(Config, fun(C) ->
  691. {ok, _Cols1, [{3}]} = Module:equery(C, "select insert_test1(3, 'three')"),
  692. {ok, _Cols2, [{<<>>}]} = Module:equery(C, "select do_nothing()")
  693. end).
  694. parameter_get(Config) ->
  695. Module = ?config(module, Config),
  696. epgsql_ct:with_connection(Config, fun(C) ->
  697. {ok, <<"off">>} = Module:get_parameter(C, "is_superuser")
  698. end).
  699. parameter_set(Config) ->
  700. Module = ?config(module, Config),
  701. epgsql_ct:with_connection(Config, fun(C) ->
  702. {ok, [], []} = Module:squery(C, "set DateStyle = 'ISO, MDY'"),
  703. {ok, <<"ISO, MDY">>} = Module:get_parameter(C, "DateStyle"),
  704. {ok, _Cols, [{<<"2000-01-02">>}]} = Module:squery(C, "select '2000-01-02'::date"),
  705. {ok, [], []} = Module:squery(C, "set DateStyle = 'German'"),
  706. {ok, <<"German, DMY">>} = Module:get_parameter(C, "DateStyle"),
  707. {ok, _Cols, [{<<"02.01.2000">>}]} = Module:squery(C, "select '2000-01-02'::date")
  708. end).
  709. numeric_type(Config) ->
  710. check_type(Config, int2, "1", 1, [0, 256, -32768, +32767]),
  711. check_type(Config, int4, "1", 1, [0, 512, -2147483648, +2147483647]),
  712. check_type(Config, int8, "1", 1, [0, 1024, -9223372036854775808, +9223372036854775807]),
  713. check_type(Config, float4, "1.0", 1.0, [0.0, 1.23456, -1.23456]),
  714. check_type(Config, float4, "'-Infinity'", minus_infinity, [minus_infinity, plus_infinity, nan]),
  715. check_type(Config, float8, "1.0", 1.0, [0.0, 1.23456789012345, -1.23456789012345]),
  716. check_type(Config, float8, "'nan'", nan, [minus_infinity, plus_infinity, nan]),
  717. %% Check overflow protection. Connection just crashes for now instead of silently
  718. %% truncating the data. Some cleaner behaviour can be introduced later.
  719. epgsql_ct:with_connection(Config, fun(C) ->
  720. Module = ?config(module, Config),
  721. Trap = process_flag(trap_exit, true),
  722. try Module:equery(C, "SELECT $1::int2", [32768]) of
  723. {error, closed} ->
  724. %% epgsqla/epgsqli
  725. ok
  726. catch exit:Reason ->
  727. %% epgsql
  728. ?assertMatch({{{integer_overflow, int2, _}, _}, _}, Reason),
  729. receive {'EXIT', C, _} -> ok
  730. after 1000 -> error(timeout)
  731. end
  732. end,
  733. process_flag(trap_exit, Trap)
  734. end).
  735. character_type(Config) ->
  736. Alpha = unicode:characters_to_binary([16#03B1]),
  737. Ka = unicode:characters_to_binary([16#304B]),
  738. One = unicode:characters_to_binary([16#10D360]),
  739. check_type(Config, bpchar, "'A'", $A, [1, $1, 16#7F, Alpha, Ka, One], "c_char"),
  740. check_type(Config, text, "'hi'", <<"hi">>, [<<"">>, <<"hi">>]),
  741. check_type(Config, varchar, "'hi'", <<"hi">>, [<<"">>, <<"hi">>]),
  742. epgsql_ct:with_connection(
  743. Config,
  744. fun(C) ->
  745. Module = ?config(module, Config),
  746. %% IOlists
  747. ?assertMatch({ok, _, [{<<1087/utf8, 1088/utf8, 1080/utf8,
  748. 1074/utf8, 1077/utf8, 1090/utf8>>}]},
  749. Module:equery(C, "SELECT $1::text", [[1087,1088,1080,1074,1077,1090]])),
  750. %% Deprecated casts
  751. ?assertMatch({ok, _, [{<<"my_atom">>}]},
  752. Module:equery(C, "SELECT $1::varchar", [my_atom])),
  753. ?assertMatch({ok, _, [{<<"12345">>}]},
  754. Module:equery(C, "SELECT $1::varchar", [12345])),
  755. FloatBin = erlang:float_to_binary(1.2345),
  756. ?assertMatch({ok, _, [{FloatBin}]},
  757. Module:equery(C, "SELECT $1::varchar", [1.2345])),
  758. %% String bpchar
  759. ?assertMatch({ok, _, [{<<"hello world">>}]},
  760. Module:equery(C, "SELECT $1::bpchar", ["hello world"]))
  761. end).
  762. uuid_type(Config) ->
  763. check_type(Config, uuid,
  764. io_lib:format("'~s'", [uuid_to_bin_string(?UUID1)]),
  765. uuid_to_bin_string(?UUID1), []).
  766. point_type(Config) ->
  767. check_type(Config, point, "'(23.15, 100)'", {23.15, 100.0}, []).
  768. geometry_type(Config) ->
  769. check_type(Config, geometry, "'COMPOUNDCURVE(CIRCULARSTRING(0 0,1 1,1 0),(1 0,0 1))'",
  770. {compound_curve,'2d', [
  771. {circular_string,'2d', [
  772. {point,'2d',0.0,0.0,undefined,undefined},
  773. {point,'2d',1.0,1.0,undefined,undefined},
  774. {point,'2d',1.0,0.0,undefined,undefined}
  775. ]},
  776. {line_string,'2d', [
  777. {point,'2d',1.0,0.0,undefined,undefined},
  778. {point,'2d',0.0,1.0,undefined,undefined}
  779. ]}
  780. ]}, []).
  781. uuid_select(Config) ->
  782. Module = ?config(module, Config),
  783. epgsql_ct:with_rollback(Config, fun(C) ->
  784. U1 = uuid_to_bin_string(?UUID1),
  785. U2 = uuid_to_bin_string(?UUID2),
  786. U3 = uuid_to_bin_string(?UUID3),
  787. {ok, 1} =
  788. Module:equery(C, "insert into test_table2 (c_varchar, c_uuid) values ('UUID1', $1)",
  789. [U1]),
  790. {ok, 1} =
  791. Module:equery(C, "insert into test_table2 (c_varchar, c_uuid) values ('UUID2', $1)",
  792. [U2]),
  793. {ok, 1} =
  794. Module:equery(C, "insert into test_table2 (c_varchar, c_uuid) values ('UUID3', $1)",
  795. [U3]),
  796. Res = Module:equery(C, "select c_varchar, c_uuid from test_table2 where c_uuid = any($1)",
  797. [[U1, U2]]),
  798. ?assertMatch(
  799. {ok,[#column{name = <<"c_varchar">>, type = varchar},
  800. #column{name = <<"c_uuid">>, type = uuid}],
  801. [{<<"UUID1">>, U1},
  802. {<<"UUID2">>, U2}]}, Res)
  803. end).
  804. date_time_type(Config) ->
  805. Module = ?config(module, Config),
  806. epgsql_ct:with_connection(Config, fun(C) ->
  807. case Module:get_parameter(C, "integer_datetimes") of
  808. {ok, <<"on">>} -> MaxTsDate = 294276;
  809. {ok, <<"off">>} -> MaxTsDate = 5874897
  810. end,
  811. check_type(Config, date, "'2008-01-02'", {2008,1,2}, [{-4712,1,1}, {5874897,1,1}]),
  812. check_type(Config, time, "'00:01:02'", {0,1,2.0}, [{0,0,0.0}, {24,0,0.0}]),
  813. check_type(Config, timetz, "'00:01:02-01'", {{0,1,2.0},1*60*60},
  814. [{{0,0,0.0},0}, {{24,0,0.0},-13*60*60}]),
  815. check_type(Config, timestamp, "'2008-01-02 03:04:05'", {{2008,1,2},{3,4,5.0}},
  816. [{{-4712,1,1},{0,0,0.0}}, {{MaxTsDate,12,31}, {23,59,59.0}}, {1322,334285,440966}]),
  817. check_type(Config, timestamptz, "'2011-01-02 03:04:05+3'", {{2011, 1, 2}, {0, 4, 5.0}}, [{1324,875970,286983}]),
  818. check_type(Config, interval, "'1 hour 2 minutes 3.1 seconds'", {{1,2,3.1},0,0},
  819. [{{0,0,0.0},0,-178000000 * 12}, {{0,0,0.0},0,178000000 * 12}])
  820. end).
  821. json_type(Config) ->
  822. Module = ?config(module, Config),
  823. epgsql_ct:with_connection(Config, fun(C) ->
  824. check_type(Config, json, "'{}'", <<"{}">>,
  825. [<<"{}">>, <<"[]">>, <<"1">>, <<"1.0">>, <<"true">>, <<"\"string\"">>, <<"{\"key\": []}">>],
  826. get_type_col(json), C),
  827. check_type(Config, jsonb, "'{}'", <<"{}">>,
  828. [<<"{}">>, <<"[]">>, <<"1">>, <<"1.0">>, <<"true">>, <<"\"string\"">>, <<"{\"key\": []}">>],
  829. get_type_col(jsonb), C),
  830. epgsql:update_type_cache(C, [{epgsql_codec_json, epgsql_fake_json_mod}]),
  831. RowId = "json_type_custom_mod_" ++ atom_to_list(Module),
  832. {ok, 1} = Module:equery(C, "insert into test_table2 (c_varchar, c_json, c_jsonb) values ($1, $2, $3)", [RowId, {"{}"}, {"{}"}]),
  833. Res = Module:equery(C, "select c_json, c_jsonb from test_table2 where c_varchar = $1", [RowId]),
  834. ?assertMatch(
  835. {ok, [#column{name = <<"c_json">>, type = json}, #column{name = <<"c_jsonb">>, type = jsonb}],
  836. [{{<<"{}">>}, {<<"{}">>}}]},
  837. Res
  838. )
  839. end).
  840. misc_type(Config) ->
  841. check_type(Config, bool, "true", true, [true, false]),
  842. check_type(Config, bytea, "E'\001\002'", <<1,2>>, [<<>>, <<0,128,255>>]).
  843. hstore_type(Config) ->
  844. Module = ?config(module, Config),
  845. Values = [
  846. {[]},
  847. {[{null, null}]},
  848. {[{null, undefined}]},
  849. {[{1, null}]},
  850. {[{1.0, null}]},
  851. {[{1, undefined}]},
  852. {[{1.0, undefined}]},
  853. {[{<<"a">>, <<"c">>}, {<<"c">>, <<"d">>}]},
  854. {[{<<"a">>, <<"c">>}, {<<"c">>, null}]},
  855. {[{<<"a">>, <<"c">>}, {<<"c">>, undefined}]}
  856. ],
  857. check_type(Config, hstore, "''", {[]}, []),
  858. check_type(Config, hstore,
  859. "'a => 1, b => 2.0, c => null'",
  860. {[{<<"a">>, <<"1">>}, {<<"b">>, <<"2.0">>}, {<<"c">>, null}]}, Values),
  861. epgsql_ct:with_connection(
  862. Config,
  863. fun(C) ->
  864. %% Maps as input
  865. [begin
  866. {ok, _, [{Res}]} = Module:equery(C, "select $1::hstore", [maps:from_list(KV)]),
  867. ?assert(compare(hstore, Res, Jiffy))
  868. end || {KV} = Jiffy <- Values],
  869. %% Maps as output
  870. {ok, [hstore]} = epgsql:update_type_cache(
  871. C, [{epgsql_codec_hstore, #{return => map}}]),
  872. [begin
  873. {ok, _, [{Res}]} = Module:equery(C, "select $1::hstore", [maps:from_list(KV)]),
  874. HstoreMap = maps:from_list([{format_hstore_key(K), format_hstore_value(V)} || {K, V} <- KV]),
  875. ?assertEqual(HstoreMap, Res)
  876. end || {KV} <- Values],
  877. %% Proplist as output
  878. {ok, [hstore]} = epgsql:update_type_cache(
  879. C, [{epgsql_codec_hstore, #{return => proplist}}]),
  880. [begin
  881. {ok, _, [{Res}]} = Module:equery(C, "select $1::hstore", [Jiffy]),
  882. HstoreProplist = [{format_hstore_key(K), format_hstore_value(V)} || {K, V} <- KV],
  883. ?assertEqual(lists:sort(HstoreProplist), lists:sort(Res))
  884. end || {KV} = Jiffy <- Values],
  885. %% Custom nulls
  886. Nulls = [nil, 'NULL', aaaa],
  887. {ok, [hstore]} = epgsql:update_type_cache(
  888. C, [{epgsql_codec_hstore, #{return => map,
  889. nulls => Nulls}}]),
  890. K = <<"k">>,
  891. [begin
  892. {ok, _, [{Res}]} = Module:equery(C, "select $1::hstore", [#{K => V}]),
  893. ?assertEqual(#{K => nil}, Res)
  894. end || V <- Nulls]
  895. end).
  896. net_type(Config) ->
  897. 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}]),
  898. check_type(Config, inet, "'127.0.0.1'", {127,0,0,1}, [{127,0,0,1}, {0,0,0,0,0,0,0,1}]),
  899. %% macaddr8 available only on PG>=10
  900. check_type(Config, macaddr,
  901. "'FF:FF:FF:FF:FF:FF'", {255, 255, 255, 255, 255, 255},
  902. [{255, 255, 255, 255, 255, 255},
  903. {6, 0, 0, 0, 0, 0}]).
  904. array_type(Config) ->
  905. Module = ?config(module, Config),
  906. epgsql_ct:with_connection(Config, fun(C) ->
  907. {ok, _, [{[1, 2]}]} = Module:equery(C, "select ($1::int[])[1:2]", [[1, 2, 3]]),
  908. {ok, _, [{[{1, <<"one">>}, {2, <<"two">>}]}]} =
  909. Module:equery(C, "select Array(select (id, value) from test_table1)", []),
  910. {ok, _, [{ [[1], [null], [3], [null]] }]} =
  911. Module:equery(C, "select $1::int2[]", [ [[1], [null], [3], [undefined]] ]),
  912. Select = fun(Type, AIn) ->
  913. Query = "select $1::" ++ atom_to_list(Type) ++ "[]",
  914. {ok, _Cols, [{AOut}]} = Module:equery(C, Query, [AIn]),
  915. case lists:all(fun({VIn, VOut}) ->
  916. compare(Type, VIn, VOut)
  917. end, lists:zip(AIn, AOut)) of
  918. true -> ok;
  919. false -> ?assertEqual(AIn, AOut)
  920. end
  921. end,
  922. Select(int2, []),
  923. Select(int2, [1, 2, 3, 4]),
  924. Select(int2, [[1], [2], [3], [4]]),
  925. Select(int2, [[[[[[1, 2]]]]]]),
  926. Select(int2, [1, null, 3, undefined]),
  927. Select(int2, [[1], [null], [3], [null]]),
  928. Select(bool, [true]),
  929. Select(char, [$a, $b, $c]),
  930. Select(int4, [[1, 2]]),
  931. Select(int8, [[[[1, 2]], [[3, 4]]]]),
  932. Select(text, [<<"one">>, <<"two>">>]),
  933. Select(varchar, [<<"one">>, <<"two>">>]),
  934. Select(float4, [0.0, 1.0, 0.123]),
  935. Select(float8, [0.0, 1.0, 0.123]),
  936. Select(date, [{2008,1,2}, {2008,1,3}]),
  937. Select(time, [{0,1,2.0}, {0,1,3.0}]),
  938. Select(timetz, [{{0,1,2.0},1*60*60}, {{0,1,3.0},1*60*60}]),
  939. Select(timestamp, [{{2008,1,2},{3,4,5.0}}, {{2008,1,2},{3,4,6.0}}]),
  940. Select(timestamptz, [{{2008,1,2},{3,4,5.0}}, {{2008,1,2},{3,4,6.0}}]),
  941. Select(interval, [{{1,2,3.1},0,0}, {{1,2,3.2},0,0}]),
  942. Select(hstore, [{[{null, null}, {a, 1}, {1, 2}, {b, undefined}]}]),
  943. Select(hstore, [[{[{null, null}, {a, 1}, {1, 2}, {b, undefined}]}, {[]}], [{[{a, 1}]}, {[{null, 2}]}]]),
  944. Select(cidr, [{{127,0,0,1}, 32}, {{0,0,0,0,0,0,0,1}, 128}]),
  945. Select(inet, [{127,0,0,1}, {0,0,0,0,0,0,0,1}]),
  946. Select(json, [<<"{}">>, <<"[]">>, <<"1">>, <<"1.0">>, <<"true">>, <<"\"string\"">>, <<"{\"key\": []}">>]),
  947. Select(jsonb, [<<"{}">>, <<"[]">>, <<"1">>, <<"1.0">>, <<"true">>, <<"\"string\"">>, <<"{\"key\": []}">>])
  948. end).
  949. record_type(Config) ->
  950. Module = ?config(module, Config),
  951. epgsql_ct:with_connection(Config, fun(C) ->
  952. Select = fun(Sql, Expected) ->
  953. {ok, _Columns, [Row]} = Module:equery(C, Sql, []),
  954. ?assertMatch(Expected, Row)
  955. end,
  956. %% Simple record
  957. Select("select (1,2)", {{1, 2}}),
  958. %% Record inside other record
  959. Select("select (1, (select (2,3)))", {{1, {2, 3}}}),
  960. %% Array inside record
  961. Select("select (1, '{2,3}'::int[])", {{1, [2, 3]}}),
  962. %% Array of records inside record
  963. Select("select (0, ARRAY(select (id, value) from test_table1))", {{0,[{1,<<"one">>},{2,<<"two">>}]}}),
  964. %% Record with NULLs
  965. Select("select (1, NULL::integer, 2)", {{1, null, 2}})
  966. end).
  967. custom_types(Config) ->
  968. Module = ?config(module, Config),
  969. epgsql_ct:with_connection(Config, fun(C) ->
  970. Module:squery(C, "drop table if exists t_foo;"),
  971. Module:squery(C, "drop type if exists my_type;"),
  972. {ok, [], []} = Module:squery(C, "create type my_type as enum('foo', 'bar');"),
  973. {ok, [my_type]} = epgsql:update_type_cache(C, [{epgsql_codec_test_enum, [foo, bar]}]),
  974. {ok, [], []} = Module:squery(C, "create table t_foo (col my_type);"),
  975. {ok, S} = Module:parse(C, "insert_foo", "insert into t_foo values ($1)", [my_type]),
  976. ok = Module:bind(C, S, [bar]),
  977. {ok, 1} = Module:execute(C, S),
  978. ?assertMatch({ok, _, [{bar}]}, Module:equery(C, "SELECT col FROM t_foo"))
  979. end).
  980. custom_null(Config) ->
  981. Module = ?config(module, Config),
  982. epgsql_ct:with_connection(Config, fun(C) ->
  983. Test3 = fun(Type, In, Out) ->
  984. Q = ["SELECT $1::", Type],
  985. {ok, _, [{Res}]} = Module:equery(C, Q, [In]),
  986. ?assertEqual(Out, Res)
  987. end,
  988. Test = fun(Type, In) ->
  989. Test3(Type, In, In)
  990. end,
  991. Test("int2", nil),
  992. Test3("int2", 'NULL', nil),
  993. Test("text", nil),
  994. Test3("text", 'NULL', nil),
  995. Test3("text", null, <<"null">>),
  996. Test("int2[]", [nil, 1, nil, 2]),
  997. Test3("text[]", [null, <<"ok">>], [<<"null">>, <<"ok">>]),
  998. Test3("int2[]", ['NULL', 1, nil, 2], [nil, 1, nil, 2]),
  999. Test("int2[]", [[nil], [1], [nil], [2]]),
  1000. Test3("int2[]", [['NULL'], [1], [nil], [2]], [[nil], [1], [nil], [2]]),
  1001. ?assertMatch(
  1002. {ok, _, [{ {1, nil, {2, nil, 3}} }]},
  1003. Module:equery(C, "SELECT (1, NULL, (2, NULL, 3))", []))
  1004. end,
  1005. [{nulls, [nil, 'NULL']}]).
  1006. text_format(Config) ->
  1007. Module = ?config(module, Config),
  1008. epgsql_ct:with_connection(Config, fun(C) ->
  1009. Select = fun(Type, V) ->
  1010. V2 = list_to_binary(V),
  1011. Query = "select $1::" ++ Type,
  1012. ?assertMatch({ok, _Cols, [{V2}]}, Module:equery(C, Query, [V])),
  1013. ?assertMatch({ok, _Cols, [{V2}]}, Module:equery(C, Query, [V2]))
  1014. end,
  1015. Select("numeric", "123456")
  1016. end).
  1017. query_timeout(Config) ->
  1018. Module = ?config(module, Config),
  1019. epgsql_ct:with_connection(Config, fun(C) ->
  1020. {ok, _, _} = Module:squery(C, "SET statement_timeout = 500"),
  1021. ?assertMatch(?TIMEOUT_ERROR, Module:squery(C, "SELECT pg_sleep(1)")),
  1022. ?assertMatch(?TIMEOUT_ERROR, Module:equery(C, "SELECT pg_sleep(2)")),
  1023. {ok, _Cols, [{1}]} = Module:equery(C, "SELECT 1")
  1024. end, []).
  1025. execute_timeout(Config) ->
  1026. Module = ?config(module, Config),
  1027. epgsql_ct:with_connection(Config, fun(C) ->
  1028. {ok, _, _} = Module:squery(C, "SET statement_timeout = 500"),
  1029. {ok, S} = Module:parse(C, "select pg_sleep($1)"),
  1030. ok = Module:bind(C, S, [2]),
  1031. ?assertMatch(?TIMEOUT_ERROR, Module:execute(C, S, 0)),
  1032. ok = Module:sync(C),
  1033. ok = Module:bind(C, S, [0]),
  1034. {ok, [{<<>>}]} = Module:execute(C, S, 0),
  1035. ok = Module:close(C, S),
  1036. ok = Module:sync(C)
  1037. end, []).
  1038. connection_closed(Config) ->
  1039. {Host, Port} = epgsql_ct:connection_data(Config),
  1040. Module = ?config(module, Config),
  1041. P = self(),
  1042. spawn_link(fun() ->
  1043. process_flag(trap_exit, true),
  1044. {ok, C} = Module:connect(Host, "epgsql_test",[
  1045. {port, Port},
  1046. {database, "epgsql_test_db1"}
  1047. ]),
  1048. P ! {connected, C},
  1049. receive
  1050. Any -> P ! Any
  1051. end
  1052. end),
  1053. receive
  1054. {connected, C} ->
  1055. timer:sleep(100),
  1056. Module:close(C),
  1057. {'EXIT', C, _} = receive R -> R end
  1058. end,
  1059. epgsql_ct:flush().
  1060. connection_closed_by_server(Config) ->
  1061. Module = ?config(module, Config),
  1062. epgsql_ct:with_connection(Config, fun(C1) ->
  1063. P = self(),
  1064. spawn_link(fun() ->
  1065. process_flag(trap_exit, true),
  1066. epgsql_ct:with_connection(Config, fun(C2) ->
  1067. {ok, _, [{Pid}]} = Module:equery(C2, "select pg_backend_pid()"),
  1068. % emulate of disconnection
  1069. {ok, _, [{true}]} = Module:equery(C1,
  1070. "select pg_terminate_backend($1)", [Pid]),
  1071. receive
  1072. {'EXIT', C2, {shutdown, #error{code = <<"57P01">>}}} ->
  1073. P ! ok;
  1074. Other ->
  1075. ct:pal("Unexpected msg: ~p~n", [Other]),
  1076. P ! error
  1077. end
  1078. end)
  1079. end),
  1080. receive ok -> ok end
  1081. end).
  1082. active_connection_closed(Config) ->
  1083. {Host, Port} = epgsql_ct:connection_data(Config),
  1084. Module = ?config(module, Config),
  1085. P = self(),
  1086. F = fun() ->
  1087. process_flag(trap_exit, true),
  1088. {ok, C} = Module:connect(Host, [
  1089. {database, "epgsql_test_db1"},
  1090. {port, Port}
  1091. ]),
  1092. P ! {connected, C},
  1093. R = Module:squery(C, "select pg_sleep(10)"),
  1094. P ! R
  1095. end,
  1096. spawn_link(F),
  1097. receive
  1098. {connected, C} ->
  1099. timer:sleep(100),
  1100. Module:close(C),
  1101. {error, closed} = receive R -> R end
  1102. end,
  1103. epgsql_ct:flush().
  1104. warning_notice(Config) ->
  1105. Module = ?config(module, Config),
  1106. epgsql_ct:with_connection(Config, fun(C) ->
  1107. Q = "create function pg_temp.raise() returns void as $$
  1108. begin
  1109. raise warning 'oops';
  1110. end;
  1111. $$ language plpgsql;
  1112. select pg_temp.raise()",
  1113. [{ok, _, _}, _] = Module:squery(C, Q),
  1114. receive
  1115. {epgsql, C, {notice, #error{message = <<"oops">>, extra = Extra}}} ->
  1116. ?assertMatch([{file, _},{line, _},{routine, _} | _], Extra),
  1117. ok
  1118. after
  1119. 100 -> erlang:error(didnt_receive_notice)
  1120. end
  1121. end, [{async, self()}]).
  1122. listen_notify(Config) ->
  1123. Module = ?config(module, Config),
  1124. epgsql_ct:with_connection(Config, fun(C) ->
  1125. {ok, [], []} = Module:squery(C, "listen epgsql_test"),
  1126. {ok, _, [{Pid}]} = Module:equery(C, "select pg_backend_pid()"),
  1127. {ok, [], []} = Module:squery(C, "notify epgsql_test"),
  1128. receive
  1129. {epgsql, C, {notification, <<"epgsql_test">>, Pid, <<>>}} -> ok
  1130. after
  1131. 100 -> erlang:error(didnt_receive_notification)
  1132. end
  1133. end, [{async, self()}]).
  1134. listen_notify_payload(Config) ->
  1135. Module = ?config(module, Config),
  1136. epgsql_ct:with_min_version(Config, [9, 0], fun(C) ->
  1137. {ok, [], []} = Module:squery(C, "listen epgsql_test"),
  1138. {ok, _, [{Pid}]} = Module:equery(C, "select pg_backend_pid()"),
  1139. {ok, [], []} = Module:squery(C, "notify epgsql_test, 'test!'"),
  1140. receive
  1141. {epgsql, C, {notification, <<"epgsql_test">>, Pid, <<"test!">>}} -> ok
  1142. after
  1143. 100 -> erlang:error(didnt_receive_notification)
  1144. end
  1145. end, [{async, self()}]).
  1146. set_notice_receiver(Config) ->
  1147. Module = ?config(module, Config),
  1148. epgsql_ct:with_min_version(Config, [9, 0], fun(C) ->
  1149. {ok, [], []} = Module:squery(C, "listen epgsql_test"),
  1150. {ok, _, [{Pid}]} = Module:equery(C, "select pg_backend_pid()"),
  1151. EnsureNoNotification = fun(Payload) ->
  1152. {ok, [], []} = Module:squery(C, ["notify epgsql_test, '", Payload, "'"]),
  1153. receive
  1154. {epgsql, _, _} -> erlang:error(got_unexpected_notification)
  1155. after
  1156. 10 -> ok
  1157. end
  1158. end,
  1159. EnsureNotification = fun(Payload) ->
  1160. {ok, [], []} = Module:squery(C, ["notify epgsql_test, '", Payload, "'"]),
  1161. receive
  1162. {epgsql, C, {notification, <<"epgsql_test">>, Pid, Payload}} -> ok
  1163. after
  1164. 100 -> erlang:error(didnt_receive_notification)
  1165. end
  1166. end,
  1167. Self = self(),
  1168. EnsureNoNotification(<<"test1">>),
  1169. % Set pid()
  1170. {ok, undefined} = Module:set_notice_receiver(C, Self),
  1171. EnsureNotification(<<"test2">>),
  1172. %% test PL/PgSQL NOTICE
  1173. {ok, [], []} = Module:squery(C, ["DO $$ BEGIN RAISE WARNING 'test notice'; END $$;"]),
  1174. receive
  1175. {epgsql, C, {notice, #error{severity = warning,
  1176. code = <<"01000">>,
  1177. message = <<"test notice">>,
  1178. extra = _}}} -> ok
  1179. after
  1180. 100 -> erlang:error(didnt_receive_notice)
  1181. end,
  1182. % set registered pid
  1183. Receiver = pg_notification_receiver,
  1184. register(Receiver, Self),
  1185. {ok, Self} = Module:set_notice_receiver(C, Receiver),
  1186. EnsureNotification(<<"test3">>),
  1187. % make registered name invalid
  1188. unregister(Receiver),
  1189. EnsureNoNotification(<<"test4">>),
  1190. % disable
  1191. {ok, Receiver} = Module:set_notice_receiver(C, undefined),
  1192. EnsureNoNotification(<<"test5">>)
  1193. end, []).
  1194. get_cmd_status(Config) ->
  1195. Module = ?config(module, Config),
  1196. epgsql_ct:with_connection(Config, fun(C) ->
  1197. {ok, [], []} = Module:squery(C, "BEGIN"),
  1198. ?assertEqual({ok, 'begin'}, Module:get_cmd_status(C)),
  1199. {ok, [], []} = epgsql:equery(C, "CREATE TEMPORARY TABLE cmd_status_t(col INTEGER)"),
  1200. ?assertEqual({ok, 'create'}, Module:get_cmd_status(C)),
  1201. %% Some commands have number of affected rows in status
  1202. {ok, N} = Module:squery(C, "INSERT INTO cmd_status_t (col) VALUES (1), (2)"),
  1203. ?assertEqual({ok, {'insert', N}}, Module:get_cmd_status(C)),
  1204. {ok, 1} = Module:squery(C, "UPDATE cmd_status_t SET col=3 WHERE col=1"),
  1205. ?assertEqual({ok, {'update', 1}}, Module:get_cmd_status(C)),
  1206. %% Failed queries have no status
  1207. {error, _} = Module:squery(C, "DELETE FROM cmd_status_t WHERE not_col=2"),
  1208. ?assertEqual({ok, undefined}, Module:get_cmd_status(C)),
  1209. %% if COMMIT failed, status will be 'rollback'
  1210. {ok, [], []} = Module:squery(C, "COMMIT"),
  1211. ?assertEqual({ok, 'rollback'}, Module:get_cmd_status(C)),
  1212. %% Only last command's status returned
  1213. [_, _, _] = Module:squery(C, "BEGIN; SELECT 1; COMMIT"),
  1214. ?assertEqual({ok, 'commit'}, Module:get_cmd_status(C))
  1215. end).
  1216. range_type(Config) ->
  1217. epgsql_ct:with_min_version(Config, [9, 2], fun(_C) ->
  1218. check_type(Config, int4range, "int4range(10, 20)", {10, 20}, [
  1219. {1, 58}, {-1, 12}, {-985521, 5412687}, {minus_infinity, 0},
  1220. {984655, plus_infinity}, {minus_infinity, plus_infinity}
  1221. ]),
  1222. check_type(Config, int4range, "int4range(10, 10)", empty, [])
  1223. end, []).
  1224. range8_type(Config) ->
  1225. epgsql_ct:with_min_version(Config, [9, 2], fun(_C) ->
  1226. check_type(Config, int8range, "int8range(10, 20)", {10, 20}, [
  1227. {1, 58}, {-1, 12}, {-9223372036854775808, 5412687},
  1228. {minus_infinity, 9223372036854775807},
  1229. {984655, plus_infinity}, {minus_infinity, plus_infinity}
  1230. ]),
  1231. check_type(Config, int8range, "int8range(10, 10)", empty, [])
  1232. end, []).
  1233. date_time_range_type(Config) ->
  1234. epgsql_ct:with_min_version(Config, [9, 2], fun(_C) ->
  1235. 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}}}, []),
  1236. 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}}}, []),
  1237. 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}}}, []),
  1238. 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}}}, []),
  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-01-02 03:04:05')", empty, []),
  1241. check_type(Config, daterange, "daterange('2008-01-02', '2008-02-02')", {{2008,1,2}, {2008, 2, 2}}, [{{-4712,1,1}, {5874897,1,1}}]),
  1242. 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}}}]),
  1243. check_type(Config, tstzrange, "tstzrange('2008-01-02 03:04:05', null)", {{{2008,1,2},{3,4,5.0}}, plus_infinity}, []),
  1244. check_type(Config, tstzrange, "tstzrange('2008-01-02 03:04:05', null, '[]')", {{{2008,1,2},{3,4,5.0}}, plus_infinity}, []),
  1245. check_type(Config, tstzrange, "tstzrange('2008-01-02 03:04:05', null, '()')", {{{2008,1,2},{3,4,5.0}}, plus_infinity}, []),
  1246. check_type(Config, tstzrange, "tstzrange(null, '2008-01-02 03:04:05')", {minus_infinity, {{2008,1,2},{3,4,5.0}}}, []),
  1247. check_type(Config, tstzrange, "tstzrange(null, '2008-01-02 03:04:05', '[]')", {minus_infinity, {{2008,1,2},{3,4,5.0}}}, []),
  1248. check_type(Config, tstzrange, "tstzrange(null, '2008-01-02 03:04:05', '()')", {minus_infinity, {{2008,1,2},{3,4,5.0}}}, [])
  1249. end, []).
  1250. with_transaction(Config) ->
  1251. Module = ?config(module, Config),
  1252. epgsql_ct:with_connection(
  1253. Config,
  1254. fun(C) ->
  1255. %% Success case
  1256. ?assertEqual(
  1257. success, Module:with_transaction(C, fun(_) -> success end)),
  1258. ?assertEqual(
  1259. success, Module:with_transaction(C, fun(_) -> success end,
  1260. [{ensure_committed, true}])),
  1261. %% begin_opts
  1262. ?assertMatch(
  1263. [{ok, _, [{<<"serializable">>}]},
  1264. {ok, _, [{<<"on">>}]}],
  1265. Module:with_transaction(
  1266. C, fun(C1) ->
  1267. Module:squery(C1, ("SHOW transaction_isolation; "
  1268. "SHOW transaction_read_only"))
  1269. end,
  1270. [{begin_opts, "READ ONLY ISOLATION LEVEL SERIALIZABLE"}])),
  1271. %% ensure_committed failure
  1272. ?assertError(
  1273. {ensure_committed_failed, rollback},
  1274. Module:with_transaction(
  1275. C, fun(C1) ->
  1276. {error, _} = Module:squery(C1, "SELECT col FROM _nowhere_"),
  1277. ok
  1278. end,
  1279. [{ensure_committed, true}])),
  1280. %% reraise
  1281. ?assertEqual(
  1282. {rollback, my_err},
  1283. Module:with_transaction(
  1284. C, fun(_) -> error(my_err) end,
  1285. [{reraise, false}])),
  1286. ?assertError(
  1287. my_err,
  1288. Module:with_transaction(
  1289. C, fun(_) -> error(my_err) end, []))
  1290. end, []).
  1291. %% =============================================================================
  1292. %% Internal functions
  1293. %% ============================================================================
  1294. get_type_col(Type) ->
  1295. "c_" ++ atom_to_list(Type).
  1296. check_type(Config, Type, In, Out, Values) ->
  1297. Column = get_type_col(Type),
  1298. check_type(Config, Type, In, Out, Values, Column).
  1299. check_type(Config, Type, In, Out, Values, Column) ->
  1300. epgsql_ct:with_connection(Config, fun(C) ->
  1301. check_type(Config, Type, In, Out, Values, Column, C)
  1302. end).
  1303. check_type(Config, Type, In, Out, Values, Column, C) ->
  1304. Module = ?config(module, Config),
  1305. Select = io_lib:format("select ~s::~w", [In, Type]),
  1306. Res = Module:equery(C, Select),
  1307. ?assertMatch({ok, [#column{type = Type}], [{Out}]}, Res),
  1308. Sql = io_lib:format("insert into test_table2 (~s) values ($1) returning ~s", [Column, Column]),
  1309. {ok, #statement{columns = [#column{type = Type}]} = S} = Module:parse(C, Sql),
  1310. Insert = fun(V) ->
  1311. ok = Module:bind(C, S, [V]),
  1312. {ok, 1, [{V2}]} = Module:execute(C, S),
  1313. case compare(Type, V, V2) of
  1314. true -> ok;
  1315. false -> error({write_read_compare_failed, io_lib:format("~p =/= ~p", [V, V2])})
  1316. end,
  1317. ok = Module:sync(C)
  1318. end,
  1319. lists:foreach(Insert, [null, undefined | Values]).
  1320. compare(_Type, null, null) -> true;
  1321. compare(_Type, undefined, null) -> true;
  1322. compare(float4, V1, V2) when is_float(V1) -> abs(V2 - V1) < 0.000001;
  1323. compare(float8, V1, V2) when is_float(V1) -> abs(V2 - V1) < 0.000000000000001;
  1324. compare(hstore, {V1}, V2) -> compare(hstore, V1, V2);
  1325. compare(hstore, V1, {V2}) -> compare(hstore, V1, V2);
  1326. compare(hstore, V1, V2) ->
  1327. orddict:from_list(format_hstore(V1)) =:= orddict:from_list(format_hstore(V2));
  1328. compare(Type, V1 = {_, _, MS}, {D2, {H2, M2, S2}}) when Type == timestamp;
  1329. Type == timestamptz ->
  1330. {D1, {H1, M1, S1}} = calendar:now_to_universal_time(V1),
  1331. ({D1, H1, M1} =:= {D2, H2, M2}) and (abs(S1 + MS/1000000 - S2) < 0.000000000000001);
  1332. compare(_Type, V1, V2) -> V1 =:= V2.
  1333. format_hstore({Hstore}) -> Hstore;
  1334. format_hstore(Hstore) ->
  1335. [{format_hstore_key(Key), format_hstore_value(Value)} || {Key, Value} <- Hstore].
  1336. format_hstore_key(Key) -> format_hstore_string(Key).
  1337. format_hstore_value(null) -> null;
  1338. format_hstore_value(undefined) -> null;
  1339. format_hstore_value(Value) -> format_hstore_string(Value).
  1340. format_hstore_string(Num) when is_number(Num) -> iolist_to_binary(io_lib:format("~w", [Num]));
  1341. format_hstore_string(Str) -> iolist_to_binary(io_lib:format("~s", [Str])).