-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathedit.go
More file actions
216 lines (198 loc) · 4.63 KB
/
edit.go
File metadata and controls
216 lines (198 loc) · 4.63 KB
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
package sqlbless
import (
"context"
"database/sql"
"fmt"
"io"
"regexp"
"strings"
"github.com/nyaosorg/go-box/v3"
"github.com/hymkor/sqlbless/dialect"
"github.com/hymkor/sqlbless/spread"
"github.com/hymkor/sqlbless/internal/misc"
)
const (
_ANSI_CURSOR_OFF = "\x1B[?25l"
_ANSI_CURSOR_ON = "\x1B[?25h"
)
type ErrColumnNotFound string
func (e ErrColumnNotFound) Error() string {
return fmt.Sprintf("%s: column not found", string(e))
}
func askN(msg string, getKey func() (string, error), options ...string) (int, error) {
fmt.Print(msg, _ANSI_CURSOR_ON)
for {
answer, err := getKey()
if err != nil {
return -1, err
}
for i, opt := range options {
if strings.Contains(opt, answer) {
fmt.Println(answer, _ANSI_CURSOR_OFF)
return i, nil
}
}
}
}
func newViewer(ss *session) *spread.Viewer {
var hl int
if ss.Debug {
hl = 3
} else {
hl = 1
}
return &spread.Viewer{
HeaderLines: hl,
Comma: ss.comma(),
Null: ss.Null,
Spool: ss.spool,
}
}
var rxNonQuote = regexp.MustCompile(`^\w+$`)
func chooseTable(ctx context.Context, tables []string, d *dialect.Entry, ttyout io.Writer) (string, error) {
fmt.Fprintln(ttyout, "Select a table:")
table, err := box.SelectString(tables, false, ttyout)
fmt.Println()
if err != nil {
return "", err
}
if len(table) < 1 {
return "", nil
}
targetTable := table[0]
if !rxNonQuote.MatchString(targetTable) {
targetTable = d.EncloseIdentifier(table[0])
}
return targetTable, nil
}
func doEdit(ctx context.Context, ss *session, command string, pilot commandIn) error {
editor := &spread.Editor{
Viewer: &spread.Viewer{
HeaderLines: 1,
Comma: ss.comma(),
Null: ss.Null,
},
Entry: ss.Dialect,
Exec: (&askSqlAndExecute{getKey: pilot.GetKey, session: ss}).Exec,
}
if a, ok := pilot.AutoPilotForCsvi(); ok {
editor.Pilot = misc.AutoCsvi{GetKeyAndSize: a}
}
if ss.tx == nil {
editor.Query = ss.conn.QueryContext
} else {
editor.Query = ss.tx.QueryContext
}
// replace `edit ` to `select * from `
_, tableAndWhere := misc.CutField(command)
if tableAndWhere == "" {
tables, err := ss.Dialect.FetchTables(ctx, ss.conn)
if err != nil {
return err
}
tableAndWhere, err = chooseTable(ctx, tables, ss.Dialect, ss.termOut)
if err != nil || tableAndWhere == "" {
return err
}
}
return editor.Edit(ctx, tableAndWhere, ss.termOut)
}
func joinAny(args []any) string {
if len(args) <= 0 {
return ""
}
var b strings.Builder
for i, v := range args {
if n, ok := v.(sql.NamedArg); ok {
fmt.Fprintf(&b, "(%s) %#v ", n.Name, n.Value)
} else {
fmt.Fprintf(&b, "(%d) %#v ", i+1, v)
}
}
return b.String()
}
type statusValue int
const (
success statusValue = iota
failure
discardAll
applyAll
)
type askSqlAndExecute struct {
status statusValue
getKey func() (string, error)
*session
}
func (ss *askSqlAndExecute) Exec(ctx context.Context, dmlSql string, args ...any) (sql.Result, error) {
fmt.Print("\n---\n")
fmt.Println(dmlSql)
fmt.Println()
argsString := joinAny(args)
if argsString != "" {
fmt.Println(argsString)
}
if ss.status == failure {
if n, _ := askN("Continue or abort [c/a] ", ss.getKey, "cC", "aA"); n == 0 {
ss.status = success
} else {
ss.status = discardAll
}
}
if ss.status == discardAll {
misc.EchoPrefix(ss.stdErr, "(cancel) ", dmlSql)
return nil, nil
}
fmt.Println()
if ss.status == success {
answer, err := askN(`Apply this change? ("y":yes, "n":no, "a":all, "N":none) `, ss.getKey, "y", "n", "aA", "N")
if err != nil {
misc.EchoPrefix(ss.stdErr, "(error) ", err.Error())
ss.status = failure
return nil, err
}
switch answer {
case 1:
// cancel and quit with no error
ss.status = success
misc.EchoPrefix(ss.spool, "(cancel) ", dmlSql)
if argsString != "" {
misc.EchoPrefix(ss.spool, "(args)", argsString)
}
return nil, nil
case 2:
// apply all
ss.status = applyAll
case 3:
// discard all and quit with no error
ss.status = discardAll
misc.EchoPrefix(ss.spool, "(cancel) ", dmlSql)
if argsString != "" {
misc.EchoPrefix(ss.spool, "(args)", argsString)
}
return nil, nil
}
}
isNewTx := (ss.tx == nil)
err := ss.beginTx(ctx, ss.stdErr)
if err != nil {
return nil, err
}
misc.Echo(ss.spool, dmlSql)
if argsString != "" {
misc.Echo(ss.spool, argsString)
}
result, err := ss.tx.ExecContext(ctx, dmlSql, args...)
var count int64
if err == nil {
count, err = result.RowsAffected()
if err == nil && count == 0 {
err = ErrNoDataFound
}
}
if err != nil && isNewTx && ss.tx != nil {
ss.tx.Rollback()
ss.tx = nil
}
fmt.Fprintf(ss.stdOut, "%d record(s) updated.\n", count)
return result, err
}