|
3 | 3 | [clojure.core.async :refer [<!! go]] |
4 | 4 | [postgres.async :refer :all])) |
5 | 5 |
|
6 | | -(def ^:private ^:dynamic *db*) |
| 6 | +(def ^:dynamic *db*) |
7 | 7 | (def table "clj_pg_test") |
8 | 8 |
|
9 | | -(defn- wait [channel] |
| 9 | +(defn wait [channel] |
10 | 10 | (let [r (<!! channel)] |
11 | 11 | (if (instance? Throwable r) |
12 | 12 | (throw r)) |
|
17 | 17 | (wait (execute! db [(str "create table " table " ( |
18 | 18 | id serial, t varchar(10))")]))) |
19 | 19 |
|
20 | | -(defn- db-fixture [f] |
| 20 | +(defn db-fixture [f] |
21 | 21 | (letfn [(env [name default] |
22 | 22 | (or (System/getenv name) default))] |
23 | 23 | (binding [*db* (open-db {:hostname (env "PG_HOST" "localhost") |
|
34 | 34 | (use-fixtures :each db-fixture) |
35 | 35 |
|
36 | 36 | (deftest queries |
| 37 | + |
37 | 38 | (testing "query returns rows as map" |
38 | 39 | (let [rs (wait (query! *db* ["select 1 as x"]))] |
39 | 40 | (is (= 1 (get-in rs [0 :x])))))) |
40 | 41 |
|
41 | 42 | (deftest query-for-array |
| 43 | + |
42 | 44 | (testing "arrays are converted to vectors" |
43 | 45 | (let [rs (wait (query! *db* ["select '{1,2}'::INT[] as a"]))] |
44 | 46 | (is (= [1 2] (get-in rs [0 :a]))))) |
| 47 | + |
45 | 48 | (testing "nested arrays are converted to vectors" |
46 | 49 | (let [rs (wait (query! *db* ["select '{{1,2},{3,4},{5,NULL}}'::INT[][] as a"]))] |
47 | 50 | (is (= [[1 2] [3 4] [5 nil]] (get-in rs [0 :a])))))) |
48 | 51 |
|
49 | 52 | (deftest inserts |
| 53 | + |
50 | 54 | (testing "insert returns row count" |
51 | 55 | (let [rs (wait (insert! *db* {:table table} {:t "x"}))] |
52 | 56 | (is (= 1 (:updated rs))))) |
| 57 | + |
53 | 58 | (testing "insert with returning returns generated keys" |
54 | 59 | (let [rs (wait (insert! *db* {:table table :returning "id"} {:t "y"}))] |
55 | 60 | (is (get-in rs [:rows 0 :id])))) |
| 61 | + |
56 | 62 | (testing "multiple rows can be inserted" |
57 | 63 | (let [rs (wait (insert! *db* |
58 | 64 | {:table table :returning "id"} |
|
61 | 67 | (is (= 2 (count (:rows rs))))))) |
62 | 68 |
|
63 | 69 | (deftest updates |
| 70 | + |
64 | 71 | (testing "update returns row count" |
65 | 72 | (let [rs (wait (insert! *db* |
66 | 73 | {:table table :returning "id"} |
|
73 | 80 | (is (= 2 (:updated rs)))))) |
74 | 81 |
|
75 | 82 | (deftest sql-macro |
| 83 | + |
76 | 84 | (testing "dosql returns last form" |
77 | 85 | (is (= "123" (wait (go (dosql |
78 | 86 | [tx (begin! *db*) |
79 | 87 | rs (query! tx ["select 123 as x"]) |
80 | 88 | rs (query! tx ["select $1::text as t" (:x (first rs))]) |
81 | 89 | _ (commit! tx)] |
82 | 90 | (:t (first rs)))))))) |
| 91 | + |
83 | 92 | (testing "dosql short-circuits on errors" |
84 | 93 | (let [e (Exception. "Oops!") |
85 | 94 | executed (atom 0)] |
|
0 commit comments