epgsql_tests.erl 39 KB

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