epgsql_SUITE.erl 68 KB

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