pgsql_tests.erl 31 KB

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