Debian Codegraph @

internal/internal.go

raw
1 // Package internal contains tblfmt internals.
2 package internal
3
4 import (
5 "bytes"
6 "crypto/md5"
7 "encoding/json/jsontext"
8 json "encoding/json/v2"
9 "fmt"
10 "io"
11 "math/rand"
12 "os/exec"
13 "runtime"
14 "strconv"
15 "strings"
16 "time"
17 "unicode"
18 )
19
20 func init() {
21 if runtime.GOOS == "windows" {
22 newline = []byte("\r\n")
23 } else {
24 newline = []byte("\n")
25 }
26 }
27
28 // Divider is a divider.
29 const Divider = "==============================================="
30
31 // RS is a result set.
32 type RS struct {
33 rs int
34 pos int
35 cols []string
36 vals [][][]any
37 }
38
39 // New creates a new result set.
40 func New(cols []string, vals ...[][]any) *RS {
41 return &RS{
42 cols: cols,
43 vals: vals,
44 }
45 }
46
47 // Multi creates a result set with multiple result sets.
48 func Multi() *RS {
49 s, t := rset(14), rset(38)
50 r := &RS{
51 cols: []string{"author_id", "name", "z"},
52 vals: [][][]any{
53 s[:2], s[2:], t,
54 },
55 }
56 return r
57 }
58
59 // Big creates a random, big result set using the provided seed.
60 func Big(seed int64) *RS {
61 src := rand.New(rand.NewSource(seed))
62 count := src.Intn(1000)
63 // generate rows
64 vals := make([][]any, count)
65 for i := range count {
66 p := newRrow(src)
67 vals[i] = []any{i + 1, p.name, p.dob, p.f, p.hash, p.char, p.z}
68 }
69 return &RS{
70 cols: []string{"id", "name", "dob", "float", "hash", "", "z"},
71 vals: [][][]any{vals},
72 }
73 }
74
75 // Tiny creates a tiny result set.
76 func Tiny() *RS {
77 return &RS{
78 cols: []string{"z"},
79 vals: [][][]any{
80 {
81 {"x"},
82 },
83 },
84 }
85 }
86
87 // Wide creates a wide result set.
88 func Wide() *RS {
89 return &RS{
90 cols: []string{
91 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
92 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
93 "cccccccccccccccccccccccccccccc",
94 "dddddddddddddddddddddddddddddd",
95 "eeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
96 "ffffffffffffffffffffffffffffff",
97 "gggggggggggggggggggggggggggggg",
98 "hhhhhhhhhhhhhhhhhhhhhhhhhhhhhh",
99 "iiiiiiiiiiiiiiiiiiiiiiiiiiiiii",
100 "jjjjjjjjjjjjjjjjjjjjjjjjjjjjjj",
101 },
102 vals: [][][]any{
103 {
104 {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"},
105 },
106 },
107 }
108 }
109
110 // Err satisfies the ResultSet interface.
111 func (*RS) Err() error {
112 return nil
113 }
114
115 // Close satisfies the ResultSet interface.
116 func (*RS) Close() error {
117 return nil
118 }
119
120 // Columns satisfies the ResultSet interface.
121 func (r *RS) Columns() ([]string, error) {
122 return r.cols, nil
123 }
124
125 // Next satisfies the ResultSet interface.
126 func (r *RS) Next() bool {
127 return r.pos < len(r.vals[r.rs])
128 }
129
130 // Scan satisfies the ResultSet interface.
131 func (r *RS) Scan(vals ...any) error {
132 for i := range vals {
133 x, ok := vals[i].(*any)
134 if !ok {
135 return fmt.Errorf("scan for col %d expected *interface{}, got: %T", i, vals[i])
136 }
137 *x = r.vals[r.rs][r.pos][i]
138 }
139 r.pos++
140 return nil
141 }
142
143 // NextResultSet satisfies the ResultSet interface.
144 func (r *RS) NextResultSet() bool {
145 r.rs, r.pos = r.rs+1, 0
146 return r.rs < len(r.vals)
147 }
148
149 // Reset resets the rset so that it can be used repeatedly.
150 func (r *RS) Reset() {
151 r.pos, r.rs = 0, 0
152 }
153
154 // rrow is a random row.
155 type rrow struct {
156 name string
157 dob time.Time
158 f float64
159 hash []byte
160 char []byte
161 z any
162 }
163
164 // newRrow creates a new random row using the rand source.
165 func newRrow(src *rand.Rand) rrow {
166 hash := md5.Sum([]byte(rstr(src)))
167 var char []byte
168 if src.Intn(2) == 1 {
169 char = []byte{byte(int('a') + src.Intn(26))}
170 }
171 var z any
172 switch src.Intn(4) {
173 case 0, 1:
174 case 2:
175 c := 1 + src.Intn(5)
176 m := make(map[string]any, c)
177 for range c {
178 r := []rune(rstr(src))
179 m[string(r[0:3])] = string(r[3:])
180 }
181 z = m
182 case 3:
183 y := make([]any, 1+src.Intn(5))
184 for i := range y {
185 r := []rune(rstr(src))
186 y[i] = string(r[0 : 1+src.Intn(6)])
187 }
188 z = y
189 }
190 return rrow{
191 name: rstr(src),
192 dob: rtime(src),
193 f: src.Float64(),
194 hash: fmt.Appendf(nil, "%x", hash[:]),
195 char: char,
196 z: z,
197 }
198 }
199
200 // rstr creates a random string using the rand source.
201 func rstr(src *rand.Rand) string {
202 l := 6 + src.Intn(32)
203 r := make([]rune, l)
204 for i := range l {
205 r[i] = glyphs[src.Intn(len(glyphs))]
206 }
207 return string(r)
208 }
209
210 // rtime creates a random time using the rand source.
211 func rtime(src *rand.Rand) time.Time {
212 a := time.Date(1970, 1, 0, 0, 0, 0, 0, time.UTC).Unix()
213 b := time.Date(2070, 1, 0, 0, 0, 0, 0, time.UTC).Unix()
214 delta := b - a
215 return time.Unix(src.Int63n(delta)+a, 0).UTC()
216 }
217
218 // rset returns predefined record set values.
219 func rset(i int) [][]any {
220 return [][]any{
221 {float64(i), "a\tb\tc\td", "x"},
222 {float64(i + 1), "aoeu\ntest\n", nil},
223 {float64(i + 2), "foo\bbar", nil},
224 {float64(i + 3), "袈\t袈\t\t袈", nil},
225 {float64(i + 4), "a\tb\t\r\n\ta", "a\n"},
226 {float64(i + 5), "袈\t袈\t\t袈\n", nil},
227 {float64(i + 6), "javascript", map[string]any{
228 fmt.Sprintf("test%d", i+7): "a value",
229 fmt.Sprintf("test%d", i+8): "foo\bbar",
230 }},
231 {float64(i + 9), "slice", []string{"a", "b"}},
232 }
233 }
234
235 // ResultSet is the shared interface for a result set.
236 type ResultSet interface {
237 Next() bool
238 Scan(...any) error
239 Columns() ([]string, error)
240 Close() error
241 Err() error
242 NextResultSet() bool
243 }
244
245 // PsqlEncodeAll does a values query for each of the values in the result set,
246 // writing captured output to the writer.
247 func PsqlEncodeAll(w io.Writer, resultSet ResultSet, params map[string]string, dsn string) error {
248 if err := PsqlEncode(w, resultSet, params, dsn); err != nil {
249 return err
250 }
251 for resultSet.NextResultSet() {
252 if _, err := w.Write(newline); err != nil {
253 return err
254 }
255 if err := PsqlEncode(w, resultSet, params, dsn); err != nil {
256 return err
257 }
258 }
259 if _, err := w.Write(newline); err != nil {
260 return err
261 }
262 return nil
263 }
264
265 // PsqlEncode does a single value query using psql, writing the captured output
266 // to the writer.
267 func PsqlEncode(w io.Writer, resultSet ResultSet, params map[string]string, dsn string) error {
268 // read values
269 var vals strings.Builder
270 var i int
271 for resultSet.Next() {
272 var id, name, z any
273 if err := resultSet.Scan(&id, &name, &z); err != nil {
274 return err
275 }
276 var extra string
277 if i != 0 {
278 extra = ","
279 }
280 n := name.(string)
281 vals.WriteString(fmt.Sprintf("%s\n (%v,E'%s', %s)", extra, id, psqlEsc(n), psqlEnc(n, z)))
282 i++
283 }
284 if err := resultSet.Err(); err != nil {
285 return err
286 }
287 // build pset
288 var pset strings.Builder
289 for k, v := range params {
290 pset.WriteString(fmt.Sprintf("\n\\pset %s '%s'", k, v))
291 }
292 // exec
293 stdout := new(bytes.Buffer)
294 q := fmt.Sprintf(psqlValuesQuery, pset.String(), vals.String())
295 cmd := exec.Command("psql", dsn, "-qX")
296 cmd.Stdin, cmd.Stdout = bytes.NewReader([]byte(q)), stdout
297 if err := cmd.Run(); err != nil {
298 return err
299 }
300 if _, err := w.Write(bytes.TrimRightFunc(stdout.Bytes(), unicode.IsSpace)); err != nil {
301 return err
302 }
303 _, err := w.Write(newline)
304 return err
305 }
306
307 // psqlEsc escapes a string as a psql string.
308 func psqlEsc(s string) string {
309 s = strings.ReplaceAll(s, "\n", `\n`)
310 s = strings.ReplaceAll(s, "\r", `\r`)
311 s = strings.ReplaceAll(s, "\t", `\t`)
312 s = strings.ReplaceAll(s, "\b", `\b`)
313 s = strings.ReplaceAll(s, "袈", `\u8888`)
314 return s
315 }
316
317 // psqlEnc encodes v based on n.
318 func psqlEnc(n string, v any) string {
319 if n != "javascript" && n != "slice" {
320 return "NULL"
321 }
322 buf, err := json.Marshal(v, json.Deterministic(true), jsontext.WithIndent(" "), jsontext.EscapeForHTML(true))
323 if err != nil {
324 panic(err)
325 }
326 s := strconv.QuoteToASCII(string(buf))
327 return "E'" + s[1:len(s)-1] + "'"
328 }
329
330 var glyphs = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 _'\"\t\b\n\rゼ一二三四五六七八九十〇")
331
332 const psqlValuesQuery = `%s
333 SELECT * FROM (
334 VALUES%s
335 ) AS t (author_id, name, z);`
336
337 // newline is the default newline used by the system.
338 var newline []byte