epgsql_tests.erl 35 KB

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