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