epgsql_tests.erl 34 KB

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