epgsql_SUITE.erl 58 KB

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