epgsql_tests.erl 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  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. {[{null, undefined}]},
  504. {[{1, null}]},
  505. {[{1.0, null}]},
  506. {[{1, undefined}]},
  507. {[{1.0, undefined}]},
  508. {[{<<"a">>, <<"c">>}, {<<"c">>, <<"d">>}]},
  509. {[{<<"a">>, <<"c">>}, {<<"c">>, null}]},
  510. {[{<<"a">>, <<"c">>}, {<<"c">>, undefined}]}
  511. ],
  512. with_connection(
  513. Module,
  514. fun(_C) ->
  515. check_type(Module, hstore, "''", {[]}, []),
  516. check_type(Module, hstore,
  517. "'a => 1, b => 2.0, c => null'",
  518. {[{<<"c">>, null}, {<<"b">>, <<"2.0">>}, {<<"a">>, <<"1">>}]}, Values)
  519. end).
  520. net_type_test(Module) ->
  521. 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}]),
  522. check_type(Module, inet, "'127.0.0.1'", {127,0,0,1}, [{127,0,0,1}, {0,0,0,0,0,0,0,1}]).
  523. array_type_test(Module) ->
  524. with_connection(
  525. Module,
  526. fun(C) ->
  527. {ok, _, [{[1, 2]}]} = Module:equery(C, "select ($1::int[])[1:2]", [[1, 2, 3]]),
  528. Select = fun(Type, A) ->
  529. Query = "select $1::" ++ atom_to_list(Type) ++ "[]",
  530. {ok, _Cols, [{A2}]} = Module:equery(C, Query, [A]),
  531. case lists:all(fun({V, V2}) -> compare(Type, V, V2) end, lists:zip(A, A2)) of
  532. true -> ok;
  533. false -> ?assertMatch(A, A2)
  534. end
  535. end,
  536. Select(int2, []),
  537. Select(int2, [1, 2, 3, 4]),
  538. Select(int2, [[1], [2], [3], [4]]),
  539. Select(int2, [[[[[[1, 2]]]]]]),
  540. Select(bool, [true]),
  541. Select(char, [$a, $b, $c]),
  542. Select(int4, [[1, 2]]),
  543. Select(int8, [[[[1, 2]], [[3, 4]]]]),
  544. Select(text, [<<"one">>, <<"two>">>]),
  545. Select(varchar, [<<"one">>, <<"two>">>]),
  546. Select(float4, [0.0, 1.0, 0.123]),
  547. Select(float8, [0.0, 1.0, 0.123]),
  548. Select(date, [{2008,1,2}, {2008,1,3}]),
  549. Select(time, [{0,1,2.0}, {0,1,3.0}]),
  550. Select(timetz, [{{0,1,2.0},1*60*60}, {{0,1,3.0},1*60*60}]),
  551. Select(timestamp, [{{2008,1,2},{3,4,5.0}}, {{2008,1,2},{3,4,6.0}}]),
  552. Select(timestamptz, [{{2008,1,2},{3,4,5.0}}, {{2008,1,2},{3,4,6.0}}]),
  553. Select(interval, [{{1,2,3.1},0,0}, {{1,2,3.2},0,0}]),
  554. Select(hstore, [{[{null, null}, {a, 1}, {1, 2}, {b, undefined}]}]),
  555. Select(hstore, [[{[{null, null}, {a, 1}, {1, 2}, {b, undefined}]}, {[]}], [{[{a, 1}]}, {[{null, 2}]}]]),
  556. Select(cidr, [{{127,0,0,1}, 32}, {{0,0,0,0,0,0,0,1}, 128}]),
  557. Select(inet, [{127,0,0,1}, {0,0,0,0,0,0,0,1}])
  558. end).
  559. text_format_test(Module) ->
  560. with_connection(
  561. Module,
  562. fun(C) ->
  563. Select = fun(Type, V) ->
  564. V2 = list_to_binary(V),
  565. Query = "select $1::" ++ Type,
  566. {ok, _Cols, [{V2}]} = Module:equery(C, Query, [V]),
  567. {ok, _Cols, [{V2}]} = Module:equery(C, Query, [V2])
  568. end,
  569. Select("numeric", "123456")
  570. end).
  571. query_timeout_test(Module) ->
  572. with_connection(
  573. Module,
  574. fun(C) ->
  575. {ok, _, _} = Module:squery(C, "SET statement_timeout = 500"),
  576. ?TIMEOUT_ERROR = Module:squery(C, "SELECT pg_sleep(1)"),
  577. ?TIMEOUT_ERROR = Module:equery(C, "SELECT pg_sleep(2)"),
  578. {ok, _Cols, [{1}]} = Module:equery(C, "SELECT 1")
  579. end,
  580. []).
  581. execute_timeout_test(Module) ->
  582. with_connection(
  583. Module,
  584. fun(C) ->
  585. {ok, _, _} = Module:squery(C, "SET statement_timeout = 500"),
  586. {ok, S} = Module:parse(C, "select pg_sleep($1)"),
  587. ok = Module:bind(C, S, [2]),
  588. ?TIMEOUT_ERROR = Module:execute(C, S, 0),
  589. ok = Module:sync(C),
  590. ok = Module:bind(C, S, [0]),
  591. {ok, [{<<>>}]} = Module:execute(C, S, 0),
  592. ok = Module:close(C, S),
  593. ok = Module:sync(C)
  594. end,
  595. []).
  596. connection_closed_test(Module) ->
  597. P = self(),
  598. F = fun() ->
  599. process_flag(trap_exit, true),
  600. {ok, C} = Module:connect(?host, "epgsql_test",
  601. [{port, ?port}, {database, "epgsql_test_db1"}]),
  602. P ! {connected, C},
  603. receive
  604. Any -> P ! Any
  605. end
  606. end,
  607. spawn_link(F),
  608. receive
  609. {connected, C} ->
  610. timer:sleep(100),
  611. Module:close(C),
  612. {'EXIT', C, _} = receive R -> R end
  613. end,
  614. flush().
  615. active_connection_closed_test(Module) ->
  616. P = self(),
  617. F = fun() ->
  618. process_flag(trap_exit, true),
  619. {ok, C} = Module:connect(?host, [{database,
  620. "epgsql_test_db1"}, {port, ?port}]),
  621. P ! {connected, C},
  622. R = Module:squery(C, "select pg_sleep(10)"),
  623. P ! R
  624. end,
  625. spawn_link(F),
  626. receive
  627. {connected, C} ->
  628. timer:sleep(100),
  629. Module:close(C),
  630. {error, closed} = receive R -> R end
  631. end,
  632. flush().
  633. warning_notice_test(Module) ->
  634. with_connection(
  635. Module,
  636. fun(C) ->
  637. Q = "create function pg_temp.raise() returns void as $$
  638. begin
  639. raise warning 'oops';
  640. end;
  641. $$ language plpgsql;
  642. select pg_temp.raise()",
  643. [{ok, _, _}, _] = Module:squery(C, Q),
  644. receive
  645. {epgsql, C, {notice, #error{message = <<"oops">>}}} -> ok
  646. after
  647. 100 -> erlang:error(didnt_receive_notice)
  648. end
  649. end,
  650. [{async, self()}]).
  651. listen_notify_test(Module) ->
  652. with_connection(
  653. Module,
  654. fun(C) ->
  655. {ok, [], []} = Module:squery(C, "listen epgsql_test"),
  656. {ok, _, [{Pid}]} = Module:equery(C, "select pg_backend_pid()"),
  657. {ok, [], []} = Module:squery(C, "notify epgsql_test"),
  658. receive
  659. {epgsql, C, {notification, <<"epgsql_test">>, Pid, <<>>}} -> ok
  660. after
  661. 100 -> erlang:error(didnt_receive_notification)
  662. end
  663. end,
  664. [{async, self()}]).
  665. listen_notify_payload_test(Module) ->
  666. with_min_version(
  667. Module,
  668. 9.0,
  669. fun(C) ->
  670. {ok, [], []} = Module:squery(C, "listen epgsql_test"),
  671. {ok, _, [{Pid}]} = Module:equery(C, "select pg_backend_pid()"),
  672. {ok, [], []} = Module:squery(C, "notify epgsql_test, 'test!'"),
  673. receive
  674. {epgsql, C, {notification, <<"epgsql_test">>, Pid, <<"test!">>}} -> ok
  675. after
  676. 100 -> erlang:error(didnt_receive_notification)
  677. end
  678. end,
  679. [{async, self()}]).
  680. application_test(_Module) ->
  681. lists:foreach(fun application:start/1, ?ssl_apps),
  682. ok = application:start(epgsql),
  683. ok = application:stop(epgsql).
  684. range_type_test(Module) ->
  685. with_min_version(
  686. Module,
  687. 9.2,
  688. fun(_C) ->
  689. check_type(Module, int4range, "int4range(10, 20)", <<"[10,20)">>,
  690. [{1, 58}, {-1, 12}, {-985521, 5412687}, {minus_infinity, 0},
  691. {984655, plus_infinity}, {minus_infinity, plus_infinity}])
  692. end,
  693. []).
  694. %% -- run all tests --
  695. run_tests() ->
  696. Files = filelib:wildcard(filename:dirname(code:which(epgsql_tests))
  697. ++ "/*tests.beam"),
  698. Mods = [list_to_atom(filename:basename(F, ".beam")) || F <- Files],
  699. eunit:test(Mods, []).
  700. all_test_() ->
  701. Version =
  702. erlang:list_to_binary(
  703. re:replace(os:cmd("git rev-parse HEAD"), "\\s+", "")),
  704. with_connection(
  705. epgsql,
  706. fun(C) ->
  707. {ok, _Cols, [{DBVersion}]} = epgsql:squery(C, "SELECT version FROM schema_version"),
  708. case DBVersion == Version of
  709. false ->
  710. 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]),
  711. erlang:exit(1);
  712. _ ->
  713. undefined
  714. end
  715. end),
  716. Tests =
  717. lists:map(
  718. fun({Name, _}) ->
  719. {Name, fun(X) -> ?MODULE:Name(X) end}
  720. end,
  721. lists:filter(
  722. fun({Name, Arity}) ->
  723. case {lists:suffix("_test", atom_to_list(Name)), Arity} of
  724. {true, 1} -> true;
  725. _ -> false
  726. end
  727. end,
  728. ?MODULE:module_info(functions))),
  729. WithModule =
  730. fun(Module) ->
  731. lists:map(
  732. fun({Name, Test}) ->
  733. {lists:flatten(
  734. io_lib:format("~s(~s)", [Name, Module])),
  735. fun() -> Test(Module) end}
  736. end,
  737. Tests)
  738. end,
  739. [WithModule(epgsql),
  740. WithModule(epgsql_cast),
  741. WithModule(epgsql_incremental)].
  742. %% -- internal functions --
  743. connect_only(Module, Args) ->
  744. TestOpts = [{port, ?port}],
  745. case Args of
  746. [User, Opts] -> Args2 = [User, TestOpts ++ Opts];
  747. [User, Pass, Opts] -> Args2 = [User, Pass, TestOpts ++ Opts];
  748. Opts -> Args2 = [TestOpts ++ Opts]
  749. end,
  750. {ok, C} = apply(Module, connect, [?host | Args2]),
  751. Module:close(C),
  752. flush().
  753. with_connection(Module, F) ->
  754. with_connection(Module, F, "epgsql_test", []).
  755. with_connection(Module, F, Args) ->
  756. with_connection(Module, F, "epgsql_test", Args).
  757. with_connection(Module, F, Username, Args) ->
  758. Args2 = [{port, ?port}, {database, "epgsql_test_db1"} | Args],
  759. {ok, C} = Module:connect(?host, Username, Args2),
  760. try
  761. F(C)
  762. after
  763. Module:close(C)
  764. end,
  765. flush().
  766. with_rollback(Module, F) ->
  767. with_connection(
  768. Module,
  769. fun(C) ->
  770. try
  771. Module:squery(C, "begin"),
  772. F(C)
  773. after
  774. Module:squery(C, "rollback")
  775. end
  776. end).
  777. with_min_version(Module, Min, F, Args) ->
  778. with_connection(
  779. Module,
  780. fun(C) ->
  781. {ok, Bin} = Module:get_parameter(C, <<"server_version">>),
  782. {ok, [{float, 1, Ver} | _], _} = erl_scan:string(binary_to_list(Bin)),
  783. case Ver >= Min of
  784. true -> F(C);
  785. false -> ?debugFmt("skipping test requiring PostgreSQL >= ~.2f~n", [Min])
  786. end
  787. end,
  788. Args).
  789. check_type(Module, Type, In, Out, Values) ->
  790. Column = "c_" ++ atom_to_list(Type),
  791. check_type(Module, Type, In, Out, Values, Column).
  792. check_type(Module, Type, In, Out, Values, Column) ->
  793. with_connection(
  794. Module,
  795. fun(C) ->
  796. Select = io_lib:format("select ~s::~w", [In, Type]),
  797. Res = Module:equery(C, Select),
  798. {ok, [#column{type = Type}], [{Out}]} = Res,
  799. Sql = io_lib:format("insert into test_table2 (~s) values ($1) returning ~s", [Column, Column]),
  800. {ok, #statement{columns = [#column{type = Type}]} = S} = Module:parse(C, Sql),
  801. Insert = fun(V) ->
  802. ok = Module:bind(C, S, [V]),
  803. {ok, 1, [{V2}]} = Module:execute(C, S),
  804. case compare(Type, V, V2) of
  805. true -> ok;
  806. false -> ?debugFmt("~p =/= ~p~n", [V, V2]), ?assert(false)
  807. end,
  808. ok = Module:sync(C)
  809. end,
  810. lists:foreach(Insert, [null, undefined | Values])
  811. end).
  812. compare(_Type, null, null) -> true;
  813. compare(_Type, undefined, null) -> true;
  814. compare(float4, V1, V2) -> abs(V2 - V1) < 0.000001;
  815. compare(float8, V1, V2) -> abs(V2 - V1) < 0.000000000000001;
  816. compare(hstore, {V1}, V2) -> compare(hstore, V1, V2);
  817. compare(hstore, V1, {V2}) -> compare(hstore, V1, V2);
  818. compare(hstore, V1, V2) ->
  819. orddict:from_list(format_hstore(V1)) =:= orddict:from_list(format_hstore(V2));
  820. compare(Type, V1 = {_, _, MS}, {D2, {H2, M2, S2}}) when Type == timestamp;
  821. Type == timestamptz ->
  822. {D1, {H1, M1, S1}} = calendar:now_to_universal_time(V1),
  823. ({D1, H1, M1} =:= {D2, H2, M2}) and (abs(S1 + MS/1000000 - S2) < 0.000000000000001);
  824. compare(int4range, {Lower, Upper}, Result) ->
  825. translate_infinities(Lower, Upper) =:= Result;
  826. compare(_Type, V1, V2) -> V1 =:= V2.
  827. translate_infinities(Lower, Upper) ->
  828. iolist_to_binary([lower(Lower), [","], upper(Upper)]).
  829. lower(minus_infinity) ->
  830. "(";
  831. lower(Val) ->
  832. io_lib:format("[~p", [Val]).
  833. upper(plus_infinity) ->
  834. ")";
  835. upper(Val) ->
  836. io_lib:format("~p)", [Val]).
  837. format_hstore({Hstore}) -> Hstore;
  838. format_hstore(Hstore) ->
  839. [{format_hstore_key(Key), format_hstore_value(Value)} || {Key, Value} <- Hstore].
  840. format_hstore_key(Key) -> format_hstore_string(Key).
  841. format_hstore_value(null) -> null;
  842. format_hstore_value(undefined) -> null;
  843. format_hstore_value(Value) -> format_hstore_string(Value).
  844. format_hstore_string(Num) when is_number(Num) -> iolist_to_binary(io_lib:format("~w", [Num]));
  845. format_hstore_string(Str) -> iolist_to_binary(io_lib:format("~s", [Str])).
  846. %% flush mailbox
  847. flush() ->
  848. ?assertEqual([], flush([])).
  849. flush(Acc) ->
  850. receive
  851. {'EXIT', _Pid, normal} -> flush(Acc);
  852. M -> flush([M | Acc])
  853. after
  854. 0 -> lists:reverse(Acc)
  855. end.