epgsql_tests.erl 35 KB

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