Passed
Pull Request — main (#3)
by Adriano
02:14
created

jsonl.*jsonlExport.Export   C

Complexity

Conditions 10

Size

Total Lines 46
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 28
dl 0
loc 46
c 0
b 0
f 0
rs 5.9999
nop 0

How to fix   Complexity   

Complexity

Complex classes like jsonl.*jsonlExport.Export often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
package jsonl
2
3
import (
4
	"adrianolaselva.github.io/csvql/pkg/exportdata"
5
	"bytes"
6
	"database/sql"
7
	"encoding/json"
8
	"fmt"
9
	"github.com/schollz/progressbar/v3"
10
	"os"
11
	"path/filepath"
12
)
13
14
const (
15
	fileModeDefault os.FileMode = 0644
16
)
17
18
type jsonlExport struct {
19
	rows       *sql.Rows
20
	bar        *progressbar.ProgressBar
21
	exportPath string
22
}
23
24
func NewJsonlExport(rows *sql.Rows, exportPath string, bar *progressbar.ProgressBar) exportdata.Export {
25
	return &jsonlExport{rows: rows, exportPath: exportPath, bar: bar}
26
}
27
28
func (j *jsonlExport) Export() error {
29
	columns, err := j.rows.Columns()
30
	if err != nil {
31
		return err
32
	}
33
34
	if err = os.MkdirAll(filepath.Dir(j.exportPath), os.ModePerm); err != nil {
35
		return err
36
	}
37
38
	bufferRx, err := os.OpenFile(j.exportPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, fileModeDefault)
39
	defer bufferRx.Close()
40
41
	for j.rows.Next() {
42
		j.bar.Add(1)
43
		values := make([]interface{}, len(columns))
44
		pointers := make([]interface{}, len(columns))
45
		for i := range values {
46
			pointers[i] = &values[i]
47
		}
48
49
		if err := j.rows.Scan(pointers...); err != nil {
50
			return err
51
		}
52
53
		attr := map[string]interface{}{}
54
		for i, c := range columns {
55
			attr[c] = pointers[i]
56
		}
57
58
		payload, err := json.Marshal(attr)
59
		if err != nil {
60
			return err
61
		}
62
63
		buffer := new(bytes.Buffer)
64
		if err := json.Compact(buffer, payload); err != nil {
65
			return err
66
		}
67
68
		if _, err := bufferRx.WriteString(fmt.Sprintf("%s\n", buffer.String())); err != nil {
69
			return err
70
		}
71
	}
72
73
	return nil
74
}
75