Debian Codegraph @

view.go

raw
1 package tblfmt
2
3 import (
4 "slices"
5 "sort"
6 "strconv"
7 "strings"
8 )
9
10 // CrosstabView is a crosstab view for result sets.
11 //
12 // CAUTION:
13 //
14 // A design decision was made to not support multiple result sets, and to force
15 // the user to create a new crosstab view for each result set. As such,
16 // NextResultSet always returns false, and any use of this view should take
17 // care when using inside a loop or passing to other code that calls
18 // NextResultSet.
19 type CrosstabView struct {
20 // resultSet is the wrapped result set.
21 resultSet ResultSet
22 // formatter is the formatter.
23 formatter Formatter
24 // empty is the empty value.
25 empty *Value
26 // headerTransformer is the column header transformer.
27 headerTransformer Transformer
28 // columnTypes is used to build column types for a result set.
29 columnTypes func(ResultSet, []any, int) error
30 // v is the vertical header column.
31 v string
32 // h is the horizontal header column.
33 h string
34 // d is the data column.
35 d string
36 // s is the horizontal header sort column.
37 s string
38 // vmap is the map of vertical rows.
39 vkeys []string
40 // hmap is the map of horizontal columns.
41 hkeys []hkey
42 // vals are the result values.
43 vals map[string]map[string]any
44 // pos is the index for the result.
45 pos int
46 // err is the last encountered error.
47 err error
48 }
49
50 // NewCrosstabView creates a new crosstab view.
51 func NewCrosstabView(resultSet ResultSet, opts ...Option) (ResultSet, error) {
52 view := &CrosstabView{
53 resultSet: resultSet,
54 formatter: NewEscapeFormatter(WithIsRaw(true, 0, 0)),
55 empty: &Value{
56 Tabs: make([][][2]int, 1),
57 },
58 }
59 for _, o := range opts {
60 if err := o.apply(view); err != nil {
61 return nil, err
62 }
63 }
64 if view.v != "" && view.h != "" && view.v == view.h {
65 return nil, ErrCrosstabVerticalAndHorizontalColumnsMustNotBeSame
66 }
67 if err := view.build(); err != nil {
68 return nil, err
69 }
70 return view, nil
71 }
72
73 // build builds the crosstab view.
74 func (view *CrosstabView) build() error {
75 // reset
76 view.pos = -1
77 view.vals = make(map[string]map[string]any)
78 // get columns
79 clen, cols, err := buildColNames(view.resultSet, view.headerTransformer)
80 switch {
81 case err != nil:
82 return view.fail(err)
83 case clen < 3:
84 return view.fail(ErrCrosstabResultMustHaveAtLeast3Columns)
85 case clen > 3 && view.d == "":
86 return view.fail(ErrCrosstabDataColumnMustBeSpecifiedWhenQueryReturnsMoreThanThreeColumns)
87 }
88 vindex := findIndex(cols, view.v, 0)
89 if vindex == -1 {
90 return view.fail(ErrCrosstabVerticalColumnNotInResult)
91 }
92 view.v = cols[vindex]
93 hindex := findIndex(cols, view.h, 1)
94 if hindex == -1 {
95 return view.fail(ErrCrosstabHorizontalColumnNotInResult)
96 }
97 view.h = cols[hindex]
98 // this complicated bit of code is used to find the 'unused' column for d
99 // (ie, when number of columns == 3, and v and h are specified)
100 //
101 // psql manual states (colD == d):
102 //
103 // " If colD is not specified, then there must be exactly three columns
104 // in the query result, and the column that is neither colV nor colH is
105 // taken to be colD."
106 ddef := 2
107 if view.d == "" {
108 used := map[int]bool{
109 vindex: true,
110 hindex: true,
111 }
112 for i := range 3 {
113 if !used[i] {
114 ddef = i
115 }
116 }
117 }
118 dindex := findIndex(cols, view.d, ddef)
119 if dindex == -1 {
120 return view.fail(ErrCrosstabDataColumnNotInResult)
121 }
122 view.d = cols[dindex]
123 sindex := -1
124 if view.s != "" {
125 if sidx := indexOf(cols, view.s); sidx != -1 {
126 sindex = sidx
127 } else {
128 return view.fail(ErrCrosstabHorizontalSortColumnNotInResult)
129 }
130 }
131 // process results
132 for view.resultSet.Next() {
133 r, err := buildColumnTypes(view.resultSet, clen, view.columnTypes)
134 if err != nil {
135 return view.fail(err)
136 }
137 if err := view.resultSet.Scan(r...); err != nil {
138 return view.fail(err)
139 }
140 // raw format values
141 vals := []any{r[vindex], r[hindex]}
142 if sindex != -1 {
143 vals = append(vals, r[sindex])
144 }
145 v, err := view.formatter.Format(vals)
146 if err != nil {
147 return view.fail(err)
148 }
149 var s *Value
150 if sindex != -1 {
151 s = v[2]
152 }
153 d := deref(r[dindex])
154 if err := view.add(d, v[0], v[1], s); err != nil {
155 return view.fail(err)
156 }
157 }
158 if err := view.resultSet.Err(); err != nil {
159 return view.fail(err)
160 }
161 // sort
162 if sindex != -1 {
163 sort.Slice(view.hkeys, func(i, j int) bool {
164 return view.hkeys[i].s < view.hkeys[j].s
165 })
166 }
167 return nil
168 }
169
170 // fail sets the internal error to the passed error and returns it.
171 func (view *CrosstabView) fail(err error) error {
172 view.err = err
173 return err
174 }
175
176 // add processes and adds a val.
177 func (view *CrosstabView) add(d any, v, h, s *Value) error {
178 if v == nil {
179 v = view.empty
180 }
181 if h == nil {
182 h = view.empty
183 }
184 // determine sort value
185 var sval int
186 if s != nil {
187 var err error
188 sval, err = strconv.Atoi(s.String())
189 if err != nil {
190 return ErrCrosstabHorizontalSortColumnIsNotANumber
191 }
192 }
193 // add v and h keys
194 vk, hk := v.String(), h.String()
195 view.vkeys = vkeyAppend(view.vkeys, vk)
196 view.hkeys = hkeyAppend(view.hkeys, hkey{v: hk, s: sval})
197 // store
198 if _, ok := view.vals[vk]; !ok {
199 view.vals[vk] = make(map[string]any)
200 }
201 if _, ok := view.vals[vk][hk]; ok {
202 return ErrCrosstabDuplicateVerticalAndHorizontalValue
203 }
204 view.vals[vk][hk] = d
205 return nil
206 }
207
208 // Next satisfies the ResultSet interface.
209 func (view *CrosstabView) Next() bool {
210 if view.err != nil {
211 return false
212 }
213 view.pos++
214 return view.pos < len(view.vkeys)
215 }
216
217 // Scan satisfies the ResultSet interface.
218 func (view *CrosstabView) Scan(v ...any) error {
219 vkey := view.vkeys[view.pos]
220 if len(v) > 0 {
221 *(v[0].(*any)) = vkey
222 }
223 row := view.vals[vkey]
224 for i := 0; i < len(view.hkeys) && i < len(v)-1; i++ {
225 if z, ok := row[view.hkeys[i].v]; ok {
226 *(v[i+1].(*any)) = z
227 } else {
228 *(v[i+1].(*any)) = nil
229 }
230 }
231 return nil
232 }
233
234 // Columns satisfies the ResultSet interface.
235 func (view *CrosstabView) Columns() ([]string, error) {
236 if view.err != nil {
237 return nil, view.err
238 }
239 cols := make([]string, len(view.hkeys)+1)
240 cols[0] = view.v
241 for i := range len(view.hkeys) {
242 cols[i+1] = view.hkeys[i].v
243 }
244 return cols, nil
245 }
246
247 // Close satisfies the ResultSet interface.
248 func (view *CrosstabView) Close() error {
249 return view.resultSet.Close()
250 }
251
252 // Err satisfies the ResultSet interface.
253 func (view *CrosstabView) Err() error {
254 return view.err
255 }
256
257 // NextResultSet satisfies the ResultSet interface.
258 func (view *CrosstabView) NextResultSet() bool {
259 return false
260 }
261
262 // vkeyAppend determines if k is in v, if so it returns the unmodified v.
263 // Otherwise, appends k to v.
264 func vkeyAppend(v []string, k string) []string {
265 if slices.Contains(v, k) {
266 return v
267 }
268 return append(v, k)
269 }
270
271 // hkey wraps a horizontal column.
272 type hkey struct {
273 v string
274 s int
275 }
276
277 // hkeyAppend determines if k is in v, if so it returns the unmodified v.
278 // Otherwise, appends k to v.
279 func hkeyAppend(v []hkey, k hkey) []hkey {
280 for _, z := range v {
281 if z.v == k.v {
282 return v
283 }
284 }
285 return append(v, k)
286 }
287
288 // indexOf returns the index of s in v. If s is a integer, then it returns the
289 // converted value of s. If s is an integer, it needs to be 1-based.
290 func indexOf(v []string, s string) int {
291 s = strings.TrimSpace(s)
292 if i, err := strconv.Atoi(s); err == nil {
293 i--
294 if i >= 0 && i < len(v) {
295 return i
296 }
297 return -1
298 }
299 for i, vv := range v {
300 if strings.EqualFold(s, strings.TrimSpace(vv)) {
301 return i
302 }
303 }
304 return -1
305 }
306
307 // findIndex returns the index of s in v.
308 func findIndex(v []string, s string, i int) int {
309 if s == "" {
310 if i < len(v) {
311 return i
312 }
313 return -1
314 }
315 return indexOf(v, s)
316 }