epgsql_SUITE.erl 53 KB

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