v4 / vlib / db / pg / pg_result_test.v
84 lines · 70 sloc · 2.02 KB · f581cbb1c964f89133439f4e303136998ddcfcfb
Raw
1// vtest build: started_postgres?
2module main
3
4import db.pg
5
6struct Info {
7 table_schema string
8 relname string
9 attname string
10 typename string
11 typealign string
12 typlen int
13}
14
15fn deref(val ?string) string {
16 return val or { panic('no value') }
17}
18
19fn row_mapper(res pg.Result, row pg.Row) !Info {
20 return Info{
21 table_schema: deref(row.vals[res.cols['table_schema']])
22 relname: deref(row.vals[res.cols['relname']])
23 attname: deref(row.vals[res.cols['attname']])
24 typename: deref(row.vals[res.cols['typename']])
25 typealign: deref(row.vals[res.cols['typealign']])
26 typlen: deref(row.vals[res.cols['typlen']]).int()
27 }
28}
29
30fn test_large_exec() {
31 $if !network ? {
32 eprintln('> Skipping test ${@FN}, since `-d network` is not passed.')
33 eprintln('> This test requires a working postgres server running on localhost.')
34 return
35 }
36
37 mut db := pg.connect(pg.Config{ user: 'postgres', password: '12345678', dbname: 'postgres' })!
38 defer {
39 db.close() or {}
40 }
41
42 result := db.exec_result('
43SELECT ischema.table_schema, c.relname, a.attname, t.typname, t.typalign, t.typlen
44 FROM pg_class c
45 JOIN information_schema.tables ischema on ischema.table_name = c.relname
46 JOIN pg_attribute a ON (a.attrelid = c.oid)
47 JOIN pg_type t ON (t.oid = a.atttypid)
48WHERE
49 a.attnum >= 0
50 ')!
51
52 infos := result.as_structs(row_mapper)!
53
54 assert result.rows.len > 0 && infos.len == result.rows.len
55
56 // println(infos)
57}
58
59fn test_empty_result_set_returns_col_names() {
60 $if !network ? {
61 eprintln('> Skipping test ${@FN}, since `-d network` is not passed.')
62 eprintln('> This test requires a working postgres server running on localhost.')
63 return
64 }
65
66 mut db := pg.connect(pg.Config{
67 user: 'postgres'
68 password: '12345678'
69 dbname: 'postgres'
70 })!
71 defer {
72 db.close() or {}
73 }
74
75 // Query that returns column metadata but zero tuples
76 result := db.exec_result('SELECT 1 AS id WHERE false')!
77
78 assert result.names.len == 1
79 assert result.names[0] == 'id'
80 assert result.cols == {
81 'id': 0
82 }
83 assert result.rows.len == 0
84}
85