epgsql_tests.erl 33 KB

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