epgsql_tests.erl 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  1. -module(epgsql_tests).
  2. -export([run_tests/0]).
  3. -compile([export_all]).
  4. -include_lib("eunit/include/eunit.hrl").
  5. -include_lib("public_key/include/public_key.hrl").
  6. -include("epgsql.hrl").
  7. -define(host, "localhost").
  8. -define(port, 5432).
  9. -define(ssl_apps, [crypto, asn1, public_key, ssl]).
  10. -define(UUID1,
  11. <<163,189,240,40,149,151,17,227,141,6,112,24,139,130,16,73>>).
  12. -define(UUID2,
  13. <<183,55,22,52,149,151,17,227,187,167,112,24,139,130,16,73>>).
  14. -define(UUID3,
  15. <<198,188,155,66,149,151,17,227,138,98,112,24,139,130,16,73>>).
  16. %% From uuid.erl in http://gitorious.org/avtobiff/erlang-uuid
  17. uuid_to_string(<<U0:32, U1:16, U2:16, U3:16, U4:48>>) ->
  18. lists:flatten(io_lib:format(
  19. "~8.16.0b-~4.16.0b-~4.16.0b-~4.16.0b-~12.16.0b",
  20. [U0, U1, U2, U3, U4])).
  21. connect_test(Module) ->
  22. connect_only(Module, []).
  23. connect_to_db_test(Module) ->
  24. connect_only(Module, [{database, "epgsql_test_db1"}]).
  25. connect_as_test(Module) ->
  26. connect_only(Module, ["epgsql_test", [{database, "epgsql_test_db1"}]]).
  27. connect_with_cleartext_test(Module) ->
  28. connect_only(Module, ["epgsql_test_cleartext",
  29. "epgsql_test_cleartext",
  30. [{database, "epgsql_test_db1"}]]).
  31. connect_with_md5_test(Module) ->
  32. connect_only(Module, ["epgsql_test_md5",
  33. "epgsql_test_md5",
  34. [{database, "epgsql_test_db1"}]]).
  35. connect_with_invalid_user_test(Module) ->
  36. {error, Why} =
  37. Module:connect(?host,
  38. "epgsql_test_invalid",
  39. "epgsql_test_invalid",
  40. [{port, ?port}, {database, "epgsql_test_db1"}]),
  41. case Why of
  42. invalid_authorization_specification -> ok; % =< 8.4
  43. invalid_password -> ok % >= 9.0
  44. end.
  45. connect_with_invalid_password_test(Module) ->
  46. {error, Why} =
  47. Module:connect(?host,
  48. "epgsql_test_md5",
  49. "epgsql_test_invalid",
  50. [{port, ?port}, {database, "epgsql_test_db1"}]),
  51. case Why of
  52. invalid_authorization_specification -> ok; % =< 8.4
  53. invalid_password -> ok % >= 9.0
  54. end.
  55. connect_with_ssl_test(Module) ->
  56. lists:foreach(fun application:start/1, ?ssl_apps),
  57. with_connection(
  58. Module,
  59. fun(C) ->
  60. {ok, _Cols, [{true}]} = Module:equery(C, "select ssl_is_used()")
  61. end,
  62. "epgsql_test",
  63. [{ssl, true}]).
  64. connect_with_client_cert_test(Module) ->
  65. lists:foreach(fun application:start/1, ?ssl_apps),
  66. Dir = filename:join(filename:dirname(code:which(epgsql_tests)), "../test_data"),
  67. File = fun(Name) -> filename:join(Dir, Name) end,
  68. {ok, Pem} = file:read_file(File("epgsql.crt")),
  69. [{'Certificate', Der, not_encrypted}] = public_key:pem_decode(Pem),
  70. Cert = public_key:pkix_decode_cert(Der, plain),
  71. #'TBSCertificate'{serialNumber = Serial} = Cert#'Certificate'.tbsCertificate,
  72. Serial2 = list_to_binary(integer_to_list(Serial)),
  73. with_connection(
  74. Module,
  75. fun(C) ->
  76. {ok, _, [{true}]} = Module:equery(C, "select ssl_is_used()"),
  77. {ok, _, [{Serial2}]} = Module:equery(C, "select ssl_client_serial()")
  78. end,
  79. "epgsql_test_cert",
  80. [{ssl, true}, {keyfile, File("epgsql.key")}, {certfile, File("epgsql.crt")}]).
  81. select_test(Module) ->
  82. with_connection(
  83. Module,
  84. fun(C) ->
  85. {ok, Cols, Rows} = Module:squery(C, "select * from test_table1"),
  86. [#column{name = <<"id">>, type = int4, size = 4},
  87. #column{name = <<"value">>, type = text, size = -1}] = Cols,
  88. [{<<"1">>, <<"one">>}, {<<"2">>, <<"two">>}] = Rows
  89. end).
  90. insert_test(Module) ->
  91. with_rollback(
  92. Module,
  93. fun(C) ->
  94. {ok, 1} = Module:squery(C, "insert into test_table1 (id, value) values (3, 'three')")
  95. end).
  96. update_test(Module) ->
  97. with_rollback(
  98. Module,
  99. fun(C) ->
  100. {ok, 1} = Module:squery(C, "insert into test_table1 (id, value) values (3, 'three')"),
  101. {ok, 1} = Module:squery(C, "insert into test_table1 (id, value) values (4, 'four')"),
  102. {ok, 2} = Module:squery(C, "update test_table1 set value = 'foo' where id > 2"),
  103. {ok, _, [{<<"2">>}]} = Module:squery(C, "select count(*) from test_table1 where value = 'foo'")
  104. end).
  105. delete_test(Module) ->
  106. with_rollback(
  107. Module,
  108. fun(C) ->
  109. {ok, 1} = Module:squery(C, "insert into test_table1 (id, value) values (3, 'three')"),
  110. {ok, 1} = Module:squery(C, "insert into test_table1 (id, value) values (4, 'four')"),
  111. {ok, 2} = Module:squery(C, "delete from test_table1 where id > 2"),
  112. {ok, _, [{<<"2">>}]} = Module:squery(C, "select count(*) from test_table1")
  113. end).
  114. create_and_drop_table_test(Module) ->
  115. with_rollback(
  116. Module,
  117. fun(C) ->
  118. {ok, [], []} = Module:squery(C, "create table test_table3 (id int4)"),
  119. {ok, [#column{type = int4}], []} = Module:squery(C, "select * from test_table3"),
  120. {ok, [], []} = Module:squery(C, "drop table test_table3")
  121. end).
  122. cursor_test(Module) ->
  123. with_connection(
  124. Module,
  125. fun(C) ->
  126. {ok, [], []} = Module:squery(C, "begin"),
  127. {ok, [], []} = Module:squery(C, "declare c cursor for select id from test_table1"),
  128. {ok, 2} = Module:squery(C, "move forward 2 from c"),
  129. {ok, 1} = Module:squery(C, "move backward 1 from c"),
  130. {ok, 1, _Cols, [{<<"2">>}]} = Module:squery(C, "fetch next from c"),
  131. {ok, [], []} = Module:squery(C, "close c")
  132. end).
  133. multiple_result_test(Module) ->
  134. with_connection(
  135. Module,
  136. fun(C) ->
  137. [{ok, _, [{<<"1">>}]}, {ok, _, [{<<"2">>}]}] = Module:squery(C, "select 1; select 2"),
  138. [{ok, _, [{<<"1">>}]}, {error, #error{}}] = Module:squery(C, "select 1; select foo;")
  139. end).
  140. execute_batch_test(Module) ->
  141. with_connection(
  142. Module,
  143. fun(C) ->
  144. {ok, S1} = Module:parse(C, "one", "select $1", [int4]),
  145. {ok, S2} = Module:parse(C, "two", "select $1 + $2", [int4, int4]),
  146. [{ok, [{1}]}, {ok, [{3}]}] =
  147. Module:execute_batch(C, [{S1, [1]}, {S2, [1, 2]}])
  148. end).
  149. batch_error_test(Module) ->
  150. with_rollback(
  151. Module,
  152. fun(C) ->
  153. {ok, S} = Module:parse(C, "insert into test_table1(id, value) values($1, $2)"),
  154. [{ok, 1}, {error, _}] =
  155. Module:execute_batch(
  156. C,
  157. [{S, [3, "batch_error 3"]},
  158. {S, [2, "batch_error 2"]}, % duplicate key error
  159. {S, [5, "batch_error 5"]} % won't be executed
  160. ])
  161. end).
  162. single_batch_test(Module) ->
  163. with_connection(
  164. Module,
  165. fun(C) ->
  166. {ok, S1} = Module:parse(C, "one", "select $1", [int4]),
  167. [{ok, [{1}]}] = Module:execute_batch(C, [{S1, [1]}])
  168. end).
  169. extended_select_test(Module) ->
  170. with_connection(
  171. Module,
  172. fun(C) ->
  173. {ok, Cols, Rows} = Module:equery(C, "select * from test_table1", []),
  174. [#column{name = <<"id">>, type = int4, size = 4},
  175. #column{name = <<"value">>, type = text, size = -1}] = Cols,
  176. [{1, <<"one">>}, {2, <<"two">>}] = Rows
  177. end).
  178. extended_sync_ok_test(Module) ->
  179. with_connection(
  180. Module,
  181. fun(C) ->
  182. {ok, _Cols, [{<<"one">>}]} = Module:equery(C, "select value from test_table1 where id = $1", [1]),
  183. {ok, _Cols, [{<<"two">>}]} = Module:equery(C, "select value from test_table1 where id = $1", [2])
  184. end).
  185. extended_sync_error_test(Module) ->
  186. with_connection(
  187. Module,
  188. fun(C) ->
  189. {error, #error{}} = Module:equery(C, "select _alue from test_table1 where id = $1", [1]),
  190. {ok, _Cols, [{<<"one">>}]} = Module:equery(C, "select value from test_table1 where id = $1", [1])
  191. end).
  192. returning_from_insert_test(Module) ->
  193. with_rollback(
  194. Module,
  195. fun(C) ->
  196. {ok, 1, _Cols, [{3}]} = Module:equery(C, "insert into test_table1 (id) values (3) returning id")
  197. end).
  198. returning_from_update_test(Module) ->
  199. with_rollback(
  200. Module,
  201. fun(C) ->
  202. {ok, 2, _Cols, [{1}, {2}]} = Module:equery(C, "update test_table1 set value = 'hi' returning id")
  203. end).
  204. returning_from_delete_test(Module) ->
  205. with_rollback(
  206. Module,
  207. fun(C) ->
  208. {ok, 2, _Cols, [{1}, {2}]} = Module:equery(C, "delete from test_table1 returning id")
  209. end).
  210. parse_test(Module) ->
  211. with_connection(
  212. Module,
  213. fun(C) ->
  214. {ok, S} = Module:parse(C, "select * from test_table1"),
  215. [#column{name = <<"id">>}, #column{name = <<"value">>}] = S#statement.columns,
  216. ok = Module:close(C, S),
  217. ok = Module:sync(C)
  218. end).
  219. parse_column_format_test(Module) ->
  220. with_connection(
  221. Module,
  222. fun(C) ->
  223. {ok, S} = Module:parse(C, "select 1::int4, false::bool, 2.0::float4"),
  224. [#column{type = int4},
  225. #column{type = bool},
  226. #column{type = float4}] = S#statement.columns,
  227. ok = Module:bind(C, S, []),
  228. {ok, [{1, false, 2.0}]} = Module:execute(C, S, 0),
  229. ok = Module:close(C, S),
  230. ok = Module:sync(C)
  231. end).
  232. parse_error_test(Module) ->
  233. with_connection(
  234. Module,
  235. fun(C) ->
  236. {error, #error{}} = Module:parse(C, "select _ from test_table1"),
  237. {ok, S} = Module:parse(C, "select * from test_table1"),
  238. [#column{name = <<"id">>}, #column{name = <<"value">>}] = S#statement.columns,
  239. ok = Module:close(C, S),
  240. ok = Module:sync(C)
  241. end).
  242. parse_and_close_test(Module) ->
  243. with_connection(
  244. Module,
  245. fun(C) ->
  246. Parse = fun() -> Module:parse(C, "test", "select * from test_table1", []) end,
  247. {ok, S} = Parse(),
  248. {error, #error{code = <<"42P05">>}} = Parse(),
  249. Module:close(C, S),
  250. {ok, S} = Parse(),
  251. ok = Module:sync(C)
  252. end).
  253. bind_test(Module) ->
  254. with_connection(
  255. Module,
  256. fun(C) ->
  257. {ok, S} = Module:parse(C, "select value from test_table1 where id = $1"),
  258. ok = Module:bind(C, S, [1]),
  259. ok = Module:close(C, S),
  260. ok = Module:sync(C)
  261. end).
  262. bind_parameter_format_test(Module) ->
  263. with_connection(
  264. Module,
  265. fun(C) ->
  266. {ok, S} = Module:parse(C, "select $1, $2, $3", [int2, text, bool]),
  267. [int2, text, bool] = S#statement.types,
  268. ok = Module:bind(C, S, [1, "hi", true]),
  269. {ok, [{1, <<"hi">>, true}]} = Module:execute(C, S, 0),
  270. ok = Module:close(C, S),
  271. ok = Module:sync(C)
  272. end).
  273. bind_error_test(Module) ->
  274. with_connection(
  275. Module,
  276. fun(C) ->
  277. {ok, S} = Module:parse(C, "select $1::char"),
  278. {error, #error{}} = Module:bind(C, S, [0]),
  279. ok = Module:bind(C, S, [$A]),
  280. ok = Module:close(C, S),
  281. ok = Module:sync(C)
  282. end).
  283. bind_and_close_test(Module) ->
  284. with_connection(
  285. Module,
  286. fun(C) ->
  287. {ok, S} = Module:parse(C, "select * from test_table1"),
  288. ok = Module:bind(C, S, "one", []),
  289. {error, #error{code = <<"42P03">>}} = Module:bind(C, S, "one", []),
  290. ok = Module:close(C, portal, "one"),
  291. ok = Module:bind(C, S, "one", []),
  292. ok = Module:sync(C)
  293. end).
  294. execute_error_test(Module) ->
  295. with_connection(
  296. Module,
  297. fun(C) ->
  298. {ok, S} = Module:parse(C, "insert into test_table1 (id, value) values ($1, $2)"),
  299. ok = Module:bind(C, S, [1, <<"foo">>]),
  300. {error, #error{code = <<"23505">>}} = Module:execute(C, S, 0),
  301. {error, sync_required} = Module:bind(C, S, [3, <<"quux">>]),
  302. ok = Module:sync(C),
  303. ok = Module:bind(C, S, [3, <<"quux">>]),
  304. {ok, _} = Module:execute(C, S, 0),
  305. {ok, 1} = Module:squery(C, "delete from test_table1 where id = 3")
  306. end).
  307. describe_test(Module) ->
  308. with_connection(
  309. Module,
  310. fun(C) ->
  311. {ok, S} = Module:parse(C, "select * from test_table1"),
  312. [#column{name = <<"id">>}, #column{name = <<"value">>}] = S#statement.columns,
  313. {ok, S} = Module:describe(C, S),
  314. ok = Module:close(C, S),
  315. ok = Module:sync(C)
  316. end).
  317. describe_with_param_test(Module) ->
  318. with_connection(
  319. Module,
  320. fun(C) ->
  321. {ok, S} = Module:parse(C, "select id from test_table1 where id = $1"),
  322. [int4] = S#statement.types,
  323. [#column{name = <<"id">>}] = S#statement.columns,
  324. {ok, S} = Module:describe(C, S),
  325. ok = Module:close(C, S),
  326. ok = Module:sync(C)
  327. end).
  328. describe_named_test(Module) ->
  329. with_connection(
  330. Module,
  331. fun(C) ->
  332. {ok, S} = Module:parse(C, "name", "select * from test_table1", []),
  333. [#column{name = <<"id">>}, #column{name = <<"value">>}] = S#statement.columns,
  334. {ok, S} = Module:describe(C, S),
  335. ok = Module:close(C, S),
  336. ok = Module:sync(C)
  337. end).
  338. describe_error_test(Module) ->
  339. with_connection(
  340. Module,
  341. fun(C) ->
  342. {error, #error{}} = Module:describe(C, statement, ""),
  343. {ok, S} = Module:parse(C, "select * from test_table1"),
  344. {ok, S} = Module:describe(C, statement, ""),
  345. ok = Module:sync(C)
  346. end).
  347. portal_test(Module) ->
  348. with_connection(
  349. Module,
  350. fun(C) ->
  351. {ok, S} = Module:parse(C, "select value from test_table1"),
  352. ok = Module:bind(C, S, []),
  353. {partial, [{<<"one">>}]} = Module:execute(C, S, 1),
  354. {partial, [{<<"two">>}]} = Module:execute(C, S, 1),
  355. {ok, []} = Module:execute(C, S,1),
  356. ok = Module:close(C, S),
  357. ok = Module:sync(C)
  358. end).
  359. returning_test(Module) ->
  360. with_rollback(
  361. Module,
  362. fun(C) ->
  363. {ok, S} = Module:parse(C, "update test_table1 set value = $1 returning id"),
  364. ok = Module:bind(C, S, ["foo"]),
  365. {ok, 2, [{1}, {2}]} = Module:execute(C, S),
  366. ok = Module:sync(C)
  367. end).
  368. multiple_statement_test(Module) ->
  369. with_connection(
  370. Module,
  371. fun(C) ->
  372. {ok, S1} = Module:parse(C, "one", "select value from test_table1 where id = 1", []),
  373. ok = Module:bind(C, S1, []),
  374. {partial, [{<<"one">>}]} = Module:execute(C, S1, 1),
  375. {ok, S2} = Module:parse(C, "two", "select value from test_table1 where id = 2", []),
  376. ok = Module:bind(C, S2, []),
  377. {partial, [{<<"two">>}]} = Module:execute(C, S2, 1),
  378. {ok, []} = Module:execute(C, S1, 1),
  379. {ok, []} = Module:execute(C, S2, 1),
  380. ok = Module:close(C, S1),
  381. ok = Module:close(C, S2),
  382. ok = Module:sync(C)
  383. end).
  384. multiple_portal_test(Module) ->
  385. with_connection(
  386. Module,
  387. fun(C) ->
  388. {ok, S} = Module:parse(C, "select value from test_table1 where id = $1"),
  389. ok = Module:bind(C, S, "one", [1]),
  390. ok = Module:bind(C, S, "two", [2]),
  391. {ok, [{<<"one">>}]} = Module:execute(C, S, "one", 0),
  392. {ok, [{<<"two">>}]} = Module:execute(C, S, "two", 0),
  393. ok = Module:close(C, S),
  394. ok = Module:sync(C)
  395. end).
  396. execute_function_test(Module) ->
  397. with_rollback(
  398. Module,
  399. fun(C) ->
  400. {ok, _Cols1, [{3}]} = Module:equery(C, "select insert_test1(3, 'three')"),
  401. {ok, _Cols2, [{<<>>}]} = Module:equery(C, "select do_nothing()")
  402. end).
  403. parameter_get_test(Module) ->
  404. with_connection(
  405. Module,
  406. fun(C) ->
  407. {ok, <<"off">>} = Module:get_parameter(C, "is_superuser")
  408. end).
  409. parameter_set_test(Module) ->
  410. with_connection(
  411. Module,
  412. fun(C) ->
  413. {ok, [], []} = Module:squery(C, "set DateStyle = 'ISO, MDY'"),
  414. {ok, <<"ISO, MDY">>} = Module:get_parameter(C, "DateStyle"),
  415. {ok, _Cols, [{<<"2000-01-02">>}]} = Module:squery(C, "select '2000-01-02'::date"),
  416. {ok, [], []} = Module:squery(C, "set DateStyle = 'German'"),
  417. {ok, <<"German, DMY">>} = Module:get_parameter(C, "DateStyle"),
  418. {ok, _Cols, [{<<"02.01.2000">>}]} = Module:squery(C, "select '2000-01-02'::date")
  419. end).
  420. numeric_type_test(Module) ->
  421. check_type(Module, int2, "1", 1, [0, 256, -32768, +32767]),
  422. check_type(Module, int4, "1", 1, [0, 512, -2147483648, +2147483647]),
  423. check_type(Module, int8, "1", 1, [0, 1024, -9223372036854775808, +9223372036854775807]),
  424. check_type(Module, float4, "1.0", 1.0, [0.0, 1.23456, -1.23456]),
  425. check_type(Module, float8, "1.0", 1.0, [0.0, 1.23456789012345, -1.23456789012345]).
  426. character_type_test(Module) ->
  427. Alpha = unicode:characters_to_binary([16#03B1]),
  428. Ka = unicode:characters_to_binary([16#304B]),
  429. One = unicode:characters_to_binary([16#10D360]),
  430. check_type(Module, bpchar, "'A'", $A, [1, $1, 16#7F, Alpha, Ka, One], "c_char"),
  431. check_type(Module, text, "'hi'", <<"hi">>, [<<"">>, <<"hi">>]),
  432. check_type(Module, varchar, "'hi'", <<"hi">>, [<<"">>, <<"hi">>]).
  433. uuid_type_test(Module) ->
  434. check_type(Module, uuid,
  435. io_lib:format("'~s'", [uuid_to_string(?UUID1)]),
  436. list_to_binary(uuid_to_string(?UUID1)), []).
  437. point_type_test(Module) ->
  438. check_type(Module, point, "'(23.15, 100)'", {23.15, 100.0}, []).
  439. geometry_type_test(Module) ->
  440. check_type(Module, geometry, "'COMPOUNDCURVE(CIRCULARSTRING(0 0,1 1,1 0),(1 0,0 1))'",
  441. {compound_curve,'2d',
  442. [{circular_string,'2d',
  443. [{point,'2d',0.0,0.0,undefined,undefined},
  444. {point,'2d',1.0,1.0,undefined,undefined},
  445. {point,'2d',1.0,0.0,undefined,undefined}]},
  446. {line_string,'2d',
  447. [{point,'2d',1.0,0.0,undefined,undefined},
  448. {point,'2d',0.0,1.0,undefined,undefined}]}]},
  449. []).
  450. uuid_select_test(Module) ->
  451. with_rollback(
  452. Module,
  453. fun(C) ->
  454. U1 = uuid_to_string(?UUID1),
  455. U2 = uuid_to_string(?UUID2),
  456. U3 = uuid_to_string(?UUID3),
  457. {ok, 1} =
  458. Module:equery(C, "insert into test_table2 (c_varchar, c_uuid) values ('UUID1', $1)",
  459. [U1]),
  460. {ok, 1} =
  461. Module:equery(C, "insert into test_table2 (c_varchar, c_uuid) values ('UUID2', $1)",
  462. [U2]),
  463. {ok, 1} =
  464. Module:equery(C, "insert into test_table2 (c_varchar, c_uuid) values ('UUID3', $1)",
  465. [U3]),
  466. Res = Module:equery(C, "select c_varchar, c_uuid from test_table2 where c_uuid = any($1)",
  467. [[U1, U2]]),
  468. U1Bin = list_to_binary(U1),
  469. U2Bin = list_to_binary(U2),
  470. {ok,[{column,<<"c_varchar">>,varchar,_,_,_},
  471. {column,<<"c_uuid">>,uuid,_,_,_}],
  472. [{<<"UUID1">>, U1Bin},
  473. {<<"UUID2">>, U2Bin}]} = Res
  474. end).
  475. date_time_type_test(Module) ->
  476. with_connection(
  477. Module,
  478. fun(C) ->
  479. case Module:get_parameter(C, "integer_datetimes") of
  480. {ok, <<"on">>} -> MaxTsDate = 294276;
  481. {ok, <<"off">>} -> MaxTsDate = 5874897
  482. end,
  483. check_type(Module, date, "'2008-01-02'", {2008,1,2}, [{-4712,1,1}, {5874897,1,1}]),
  484. check_type(Module, time, "'00:01:02'", {0,1,2.0}, [{0,0,0.0}, {24,0,0.0}]),
  485. check_type(Module, timetz, "'00:01:02-01'", {{0,1,2.0},1*60*60},
  486. [{{0,0,0.0},0}, {{24,0,0.0},-13*60*60}]),
  487. check_type(Module, timestamp, "'2008-01-02 03:04:05'", {{2008,1,2},{3,4,5.0}},
  488. [{{-4712,1,1},{0,0,0.0}}, {{MaxTsDate,12,31}, {23,59,59.0}}, {1322,334285,440966}]),
  489. check_type(Module, timestamptz, "'2011-01-02 03:04:05+3'", {{2011, 1, 2}, {0, 4, 5.0}}, [{1324,875970,286983}]),
  490. check_type(Module, interval, "'1 hour 2 minutes 3.1 seconds'", {{1,2,3.1},0,0},
  491. [{{0,0,0.0},0,-178000000 * 12}, {{0,0,0.0},0,178000000 * 12}])
  492. end).
  493. misc_type_test(Module) ->
  494. check_type(Module, bool, "true", true, [true, false]),
  495. check_type(Module, bytea, "E'\001\002'", <<1,2>>, [<<>>, <<0,128,255>>]).
  496. hstore_type_test(Module) ->
  497. Values = [
  498. {[]},
  499. {[{null, null}]},
  500. {[{1, null}]},
  501. {[{1.0, null}]},
  502. {[{<<"a">>, <<"c">>}, {<<"c">>, <<"d">>}]},
  503. {[{<<"a">>, <<"c">>}, {<<"c">>, null}]}
  504. ],
  505. check_type(Module, hstore, "''", {[]}, []),
  506. check_type(Module, hstore, "'a => 1, b => 2.0, c => null'",
  507. {[{<<"c">>, null}, {<<"b">>, <<"2.0">>}, {<<"a">>, <<"1">>}]}, Values).
  508. array_type_test(Module) ->
  509. with_connection(
  510. Module,
  511. fun(C) ->
  512. {ok, _, [{[1, 2]}]} = Module:equery(C, "select ($1::int[])[1:2]", [[1, 2, 3]]),
  513. Select = fun(Type, A) ->
  514. Query = "select $1::" ++ atom_to_list(Type) ++ "[]",
  515. {ok, _Cols, [{A2}]} = Module:equery(C, Query, [A]),
  516. case lists:all(fun({V, V2}) -> compare(Type, V, V2) end, lists:zip(A, A2)) of
  517. true -> ok;
  518. false -> ?assertMatch(A, A2)
  519. end
  520. end,
  521. Select(int2, []),
  522. Select(int2, [1, 2, 3, 4]),
  523. Select(int2, [[1], [2], [3], [4]]),
  524. Select(int2, [[[[[[1, 2]]]]]]),
  525. Select(bool, [true]),
  526. Select(char, [$a, $b, $c]),
  527. Select(int4, [[1, 2]]),
  528. Select(int8, [[[[1, 2]], [[3, 4]]]]),
  529. Select(text, [<<"one">>, <<"two>">>]),
  530. Select(varchar, [<<"one">>, <<"two>">>]),
  531. Select(float4, [0.0, 1.0, 0.123]),
  532. Select(float8, [0.0, 1.0, 0.123]),
  533. Select(date, [{2008,1,2}, {2008,1,3}]),
  534. Select(time, [{0,1,2.0}, {0,1,3.0}]),
  535. Select(timetz, [{{0,1,2.0},1*60*60}, {{0,1,3.0},1*60*60}]),
  536. Select(timestamp, [{{2008,1,2},{3,4,5.0}}, {{2008,1,2},{3,4,6.0}}]),
  537. Select(timestamptz, [{{2008,1,2},{3,4,5.0}}, {{2008,1,2},{3,4,6.0}}]),
  538. Select(interval, [{{1,2,3.1},0,0}, {{1,2,3.2},0,0}]),
  539. Select(hstore, [{[{null, null}, {a, 1}, {1, 2}]}]),
  540. Select(hstore, [[{[{null, null}, {a, 1}, {1, 2}]}, {[]}], [{[{a, 1}]}, {[{null, 2}]}]])
  541. end).
  542. text_format_test(Module) ->
  543. with_connection(
  544. Module,
  545. fun(C) ->
  546. Select = fun(Type, V) ->
  547. V2 = list_to_binary(V),
  548. Query = "select $1::" ++ Type,
  549. {ok, _Cols, [{V2}]} = Module:equery(C, Query, [V]),
  550. {ok, _Cols, [{V2}]} = Module:equery(C, Query, [V2])
  551. end,
  552. Select("inet", "127.0.0.1"),
  553. Select("numeric", "123456")
  554. end).
  555. connect_timeout_test(Module) ->
  556. {error, timeout} = Module:connect(?host, [{port, ?port}, {timeout, 0}]).
  557. query_timeout_test(Module) ->
  558. with_connection(
  559. Module,
  560. fun(C) ->
  561. {error, timeout} = Module:squery(C, "select pg_sleep(1)"),
  562. {error, timeout} = Module:equery(C, "select pg_sleep(2)"),
  563. {ok, _Cols, [{1}]} = Module:equery(C, "select 1")
  564. end,
  565. [{timeout, 10}]).
  566. execute_timeout_test(Module) ->
  567. with_connection(
  568. Module,
  569. fun(C) ->
  570. {ok, S} = Module:parse(C, "select pg_sleep($1)"),
  571. ok = Module:bind(C, S, [2]),
  572. {error, timeout} = Module:execute(C, S, 0),
  573. ok = Module:bind(C, S, [0]),
  574. {ok, [{<<>>}]} = Module:execute(C, S, 0),
  575. ok = Module:close(C, S),
  576. ok = Module:sync(C)
  577. end,
  578. [{timeout, 10}]).
  579. connection_closed_test(Module) ->
  580. P = self(),
  581. F = fun() ->
  582. process_flag(trap_exit, true),
  583. {ok, C} = Module:connect(?host, [{port, ?port}]),
  584. P ! {connected, C},
  585. receive
  586. Any -> P ! Any
  587. end
  588. end,
  589. spawn_link(F),
  590. receive
  591. {connected, C} ->
  592. timer:sleep(100),
  593. Module:close(C),
  594. {'EXIT', C, _} = receive R -> R end
  595. end,
  596. flush().
  597. active_connection_closed_test(Module) ->
  598. P = self(),
  599. F = fun() ->
  600. process_flag(trap_exit, true),
  601. {ok, C} = Module:connect(?host, [{port, ?port}]),
  602. P ! {connected, C},
  603. R = Module:squery(C, "select pg_sleep(10)"),
  604. P ! R
  605. end,
  606. spawn_link(F),
  607. receive
  608. {connected, C} ->
  609. timer:sleep(100),
  610. Module:close(C),
  611. {error, closed} = receive R -> R end
  612. end,
  613. flush().
  614. warning_notice_test(Module) ->
  615. with_connection(
  616. Module,
  617. fun(C) ->
  618. Q = "create function pg_temp.raise() returns void as $$
  619. begin
  620. raise warning 'oops';
  621. end;
  622. $$ language plepgsql;
  623. select pg_temp.raise()",
  624. [{ok, _, _}, _] = Module:squery(C, Q),
  625. receive
  626. {epgsql, C, {notice, #error{message = <<"oops">>}}} -> ok
  627. after
  628. 100 -> erlang:error(didnt_receive_notice)
  629. end
  630. end,
  631. [{async, self()}]).
  632. listen_notify_test(Module) ->
  633. with_connection(
  634. Module,
  635. fun(C) ->
  636. {ok, [], []} = Module:squery(C, "listen epgsql_test"),
  637. {ok, _, [{Pid}]} = Module:equery(C, "select pg_backend_pid()"),
  638. {ok, [], []} = Module:squery(C, "notify epgsql_test"),
  639. receive
  640. {epgsql, C, {notification, <<"epgsql_test">>, Pid, <<>>}} -> ok
  641. after
  642. 100 -> erlang:error(didnt_receive_notification)
  643. end
  644. end,
  645. [{async, self()}]).
  646. listen_notify_payload_test(Module) ->
  647. with_min_version(
  648. Module,
  649. 9.0,
  650. fun(C) ->
  651. {ok, [], []} = Module:squery(C, "listen epgsql_test"),
  652. {ok, _, [{Pid}]} = Module:equery(C, "select pg_backend_pid()"),
  653. {ok, [], []} = Module:squery(C, "notify epgsql_test, 'test!'"),
  654. receive
  655. {epgsql, C, {notification, <<"epgsql_test">>, Pid, <<"test!">>}} -> ok
  656. after
  657. 100 -> erlang:error(didnt_receive_notification)
  658. end
  659. end,
  660. [{async, self()}]).
  661. application_test(_Module) ->
  662. lists:foreach(fun application:start/1, ?ssl_apps),
  663. ok = application:start(epgsql),
  664. ok = application:stop(epgsql).
  665. %% -- run all tests --
  666. run_tests() ->
  667. Files = filelib:wildcard(filename:dirname(code:which(epgsql_tests))
  668. ++ "/*tests.beam"),
  669. Mods = [list_to_atom(filename:basename(F, ".beam")) || F <- Files],
  670. eunit:test(Mods, []).
  671. all_test_() ->
  672. Tests =
  673. lists:map(
  674. fun({Name, _}) ->
  675. {Name, fun(X) -> ?MODULE:Name(X) end}
  676. end,
  677. lists:filter(
  678. fun({Name, Arity}) ->
  679. case {lists:suffix("_test", atom_to_list(Name)), Arity} of
  680. {true, 1} -> true;
  681. _ -> false
  682. end
  683. end,
  684. ?MODULE:module_info(functions))),
  685. WithModule =
  686. fun(Module) ->
  687. lists:map(
  688. fun({Name, Test}) ->
  689. {lists:flatten(
  690. io_lib:format("~s(~s)", [Name, Module])),
  691. fun() -> Test(Module) end}
  692. end,
  693. Tests)
  694. end,
  695. [WithModule(epgsql),
  696. WithModule(epgsql_cast),
  697. WithModule(epgsql_incremental)].
  698. %% -- internal functions --
  699. connect_only(Module, Args) ->
  700. TestOpts = [{port, ?port}],
  701. case Args of
  702. [User, Opts] -> Args2 = [User, TestOpts ++ Opts];
  703. [User, Pass, Opts] -> Args2 = [User, Pass, TestOpts ++ Opts];
  704. Opts -> Args2 = [TestOpts ++ Opts]
  705. end,
  706. {ok, C} = apply(Module, connect, [?host | Args2]),
  707. Module:close(C),
  708. flush().
  709. with_connection(Module, F) ->
  710. with_connection(Module, F, "epgsql_test", []).
  711. with_connection(Module, F, Args) ->
  712. with_connection(Module, F, "epgsql_test", Args).
  713. with_connection(Module, F, Username, Args) ->
  714. Args2 = [{port, ?port}, {database, "epgsql_test_db1"} | Args],
  715. {ok, C} = Module:connect(?host, Username, Args2),
  716. try
  717. F(C)
  718. after
  719. Module:close(C)
  720. end,
  721. flush().
  722. with_rollback(Module, F) ->
  723. with_connection(
  724. Module,
  725. fun(C) ->
  726. try
  727. Module:squery(C, "begin"),
  728. F(C)
  729. after
  730. Module:squery(C, "rollback")
  731. end
  732. end).
  733. with_min_version(Module, Min, F, Args) ->
  734. with_connection(
  735. Module,
  736. fun(C) ->
  737. {ok, Bin} = Module:get_parameter(C, <<"server_version">>),
  738. {ok, [{float, 1, Ver} | _], _} = erl_scan:string(binary_to_list(Bin)),
  739. case Ver >= Min of
  740. true -> F(C);
  741. false -> ?debugFmt("skipping test requiring PostgreSQL >= ~.2f~n", [Min])
  742. end
  743. end,
  744. Args).
  745. check_type(Module, Type, In, Out, Values) ->
  746. Column = "c_" ++ atom_to_list(Type),
  747. check_type(Module, Type, In, Out, Values, Column).
  748. check_type(Module, Type, In, Out, Values, Column) ->
  749. with_connection(
  750. Module,
  751. fun(C) ->
  752. Select = io_lib:format("select ~s::~w", [In, Type]),
  753. Res = Module:equery(C, Select),
  754. {ok, [#column{type = Type}], [{Out}]} = Res,
  755. Sql = io_lib:format("insert into test_table2 (~s) values ($1) returning ~s", [Column, Column]),
  756. {ok, #statement{columns = [#column{type = Type}]} = S} = Module:parse(C, Sql),
  757. Insert = fun(V) ->
  758. ok = Module:bind(C, S, [V]),
  759. {ok, 1, [{V2}]} = Module:execute(C, S),
  760. case compare(Type, V, V2) of
  761. true -> ok;
  762. false -> ?debugFmt("~p =/= ~p~n", [V, V2]), ?assert(false)
  763. end,
  764. ok = Module:sync(C)
  765. end,
  766. lists:foreach(Insert, [null | Values])
  767. end).
  768. compare(_Type, null, null) -> true;
  769. compare(float4, V1, V2) -> abs(V2 - V1) < 0.000001;
  770. compare(float8, V1, V2) -> abs(V2 - V1) < 0.000000000000001;
  771. compare(hstore, {V1}, V2) -> compare(hstore, V1, V2);
  772. compare(hstore, V1, {V2}) -> compare(hstore, V1, V2);
  773. compare(hstore, V1, V2) ->
  774. orddict:from_list(format_hstore(V1)) =:= orddict:from_list(format_hstore(V2));
  775. compare(Type, V1 = {_, _, MS}, {D2, {H2, M2, S2}}) when Type == timestamp;
  776. Type == timestamptz ->
  777. {D1, {H1, M1, S1}} = calendar:now_to_universal_time(V1),
  778. ({D1, H1, M1} =:= {D2, H2, M2}) and (abs(S1 + MS/1000000 - S2) < 0.000000000000001);
  779. compare(_Type, V1, V2) -> V1 =:= V2.
  780. format_hstore({Hstore}) -> Hstore;
  781. format_hstore(Hstore) ->
  782. [{format_hstore_key(Key), format_hstore_value(Value)} || {Key, Value} <- Hstore].
  783. format_hstore_key(Key) -> format_hstore_string(Key).
  784. format_hstore_value(null) -> null;
  785. format_hstore_value(Value) -> format_hstore_string(Value).
  786. format_hstore_string(Num) when is_number(Num) -> iolist_to_binary(io_lib:format("~w", [Num]));
  787. format_hstore_string(Str) -> iolist_to_binary(io_lib:format("~s", [Str])).
  788. %% flush mailbox
  789. flush() ->
  790. ?assertEqual([], flush([])).
  791. flush(Acc) ->
  792. receive
  793. {'EXIT', _Pid, normal} -> flush(Acc);
  794. M -> flush([M | Acc])
  795. after
  796. 0 -> lists:reverse(Acc)
  797. end.