-
Notifications
You must be signed in to change notification settings - Fork 356
/
handler.go
1693 lines (1622 loc) · 43.7 KB
/
handler.go
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package handler provides a input process handler implementation for usql.
package handler
import (
"bufio"
"bytes"
"context"
"database/sql"
"errors"
"fmt"
"io"
"log"
"maps"
"net/url"
"os"
"os/exec"
"os/signal"
"os/user"
"path"
"path/filepath"
"regexp"
"slices"
"strconv"
"strings"
"syscall"
"time"
"unicode"
"github.com/alecthomas/chroma/v2"
"github.com/alecthomas/chroma/v2/formatters"
"github.com/alecthomas/chroma/v2/styles"
"github.com/go-git/go-billy/v5"
"github.com/xo/dburl"
"github.com/xo/dburl/passfile"
"github.com/xo/echartsgoja"
"github.com/xo/resvg"
"github.com/xo/tblfmt"
"github.com/xo/usql/drivers"
"github.com/xo/usql/drivers/completer"
"github.com/xo/usql/drivers/metadata"
"github.com/xo/usql/env"
"github.com/xo/usql/metacmd"
"github.com/xo/usql/metacmd/charts"
"github.com/xo/usql/rline"
"github.com/xo/usql/stmt"
ustyles "github.com/xo/usql/styles"
"github.com/xo/usql/text"
)
// Handler is a input process handler.
//
// Glues together usql's components to provide a "read-eval-print loop" (REPL)
// for usql's interactive command-line and manages most of the core/high-level logic.
//
// Manages the active statement buffer, application IO, executing/querying SQL
// statements, and handles backslash (\) meta commands encountered in the input
// stream.
type Handler struct {
// l is the readline handler.
l rline.IO
// user is the user.
user *user.User
// wd is the working directory.
wd string
// charts is the charts filesystem.
charts billy.Filesystem
// nopw indicates not asking for password.
nopw bool
// timing of every command executed.
timing bool
// singleLineMode is single line mode.
singleLineMode bool
// buf is the query statement buffer.
buf *stmt.Stmt
// lastExec is the last executed query statement.
lastExec string
// lastExecPrefix is the last executed query statement prefix.
lastExecPrefix string
// lastPrint is the last executed printable query statement.
lastPrint string
// lastRaw is the last executed raw query statement.
lastRaw string
// batch indicates a batch has been started.
batch bool
// batchEnd is the batch end string.
batchEnd string
// bind are bound values for that will be used for statement execution.
bind []interface{}
// u is the active connection information.
u *dburl.URL
// db is the active database connection.
db *sql.DB
// tx is the active transaction, if any.
tx *sql.Tx
// out file or pipe
out io.WriteCloser
}
// New creates a new input handler.
func New(l rline.IO, user *user.User, wd string, charts billy.Filesystem, nopw bool) *Handler {
f, iactive := l.Next, l.Interactive()
if iactive {
f = func() ([]rune, error) {
// next line
r, err := l.Next()
if err != nil {
return nil, err
}
// save history
_ = l.Save(string(r))
return r, nil
}
}
h := &Handler{
l: l,
user: user,
wd: wd,
charts: charts,
nopw: nopw,
buf: stmt.New(f),
}
if iactive {
l.SetOutput(h.outputHighlighter)
l.Completer(completer.NewDefaultCompleter(completer.WithConnStrings(h.connStrings())))
}
return h
}
// GetTiming gets the timing toggle.
func (h *Handler) GetTiming() bool {
return h.timing
}
// SetTiming sets the timing toggle.
func (h *Handler) SetTiming(timing bool) {
h.timing = timing
}
// SetSingleLineMode sets the single line mode toggle.
func (h *Handler) SetSingleLineMode(singleLineMode bool) {
h.singleLineMode = singleLineMode
}
// Run executes queries and commands.
func (h *Handler) Run() error {
stdout, stderr, iactive := h.l.Stdout(), h.l.Stderr(), h.l.Interactive()
// display welcome info
if iactive && env.Get("QUIET") == "off" {
// logo
if typ := env.TermGraphics(); typ.Available() {
if err := typ.Encode(stdout, text.Logo); err != nil {
return err
}
}
// welcome text
fmt.Fprintln(stdout, text.WelcomeDesc)
fmt.Fprintln(stdout)
}
var cmd string
var paramstr string
var err error
var opt metacmd.Option
var cont bool
var lastErr error
var execute bool
for {
execute = false
// set prompt
if iactive {
h.l.Prompt(h.Prompt(env.Get("PROMPT1")))
}
// read next statement/command
switch cmd, paramstr, err = h.buf.Next(env.Untick(h.user, env.Vars(), false)); {
case h.singleLineMode && err == nil:
execute = h.buf.Len != 0
case err == rline.ErrInterrupt:
h.buf.Reset(nil)
continue
case err == io.EOF:
return lastErr
case err != nil:
return err
case cmd != "":
opt, cont, lastErr = h.apply(stdout, stderr, strings.TrimPrefix(cmd, `\`), paramstr)
}
if cont {
continue
}
// help, exit, quit intercept
if iactive && len(h.buf.Buf) >= 4 {
i, first := lastIndex(h.buf.Buf, '\n'), false
if i == -1 {
i, first = 0, true
}
if s := strings.ToLower(helpQuitExitRE.FindString(string(h.buf.Buf[i:]))); s != "" {
switch s {
case "help":
s = text.HelpDescShort
if first {
s = text.HelpDesc
h.buf.Reset(nil)
}
case "quit", "exit":
s = text.QuitDesc
if first {
return nil
}
}
fmt.Fprintln(stdout, s)
}
}
// quit
if opt.Quit {
if h.out != nil {
h.out.Close()
}
return nil
}
// execute buf
if execute || h.buf.Ready() || opt.Exec != metacmd.ExecNone {
// intercept batch query
if h.u != nil {
typ, end, batch := drivers.IsBatchQueryPrefix(h.u, h.buf.Prefix)
switch {
case h.batch && batch:
err = fmt.Errorf("cannot perform %s in existing batch", typ)
lastErr = WrapErr(h.buf.String(), err)
fmt.Fprintln(stderr, "error:", err)
continue
// cannot use \g* while accumulating statements for batch queries
case h.batch && typ != h.batchEnd && opt.Exec != metacmd.ExecNone:
err = errors.New("cannot force batch execution")
lastErr = WrapErr(h.buf.String(), err)
fmt.Fprintln(stderr, "error:", err)
continue
case batch:
h.batch, h.batchEnd = true, end
case h.batch:
var lend string
if len(h.lastExec) != 0 {
lend = "\n"
}
// append to last
h.lastExec += lend + h.buf.String()
h.lastExecPrefix = h.buf.Prefix
h.lastPrint += lend + h.buf.PrintString()
h.lastRaw += lend + h.buf.RawString()
h.buf.Reset(nil)
// break
if h.batchEnd != typ {
continue
}
h.lastExecPrefix = h.batchEnd
h.batch, h.batchEnd = false, ""
}
}
if h.buf.Len != 0 {
h.lastExec, h.lastExecPrefix, h.lastPrint, h.lastRaw = h.buf.String(), h.buf.Prefix, h.buf.PrintString(), h.buf.RawString()
h.buf.Reset(nil)
}
// log.Printf(">> PROCESS EXECUTE: (%s) `%s`", h.lastPrefix, h.last)
if !h.batch && h.lastExec != "" && h.lastExec != ";" {
// force a transaction for batched queries for certain drivers
var forceBatch bool
if h.u != nil {
_, _, forceBatch = drivers.IsBatchQueryPrefix(h.u, stmt.FindPrefix(h.lastExec, true, true, true))
forceBatch = forceBatch && drivers.BatchAsTransaction(h.u)
}
// execute
out := stdout
if h.out != nil {
out = h.out
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
if err = h.Execute(ctx, out, opt, h.lastExecPrefix, h.lastExec, forceBatch, h.unbind()...); err != nil {
lastErr = WrapErr(h.lastExec, err)
if env.Get("ON_ERROR_STOP") == "on" {
if iactive {
fmt.Fprintln(stderr, "error:", err)
h.buf.Reset([]rune{}) // empty the buffer so no other statements are run
continue
} else {
stop()
return err
}
} else {
fmt.Fprintln(stderr, "error:", err)
}
}
stop()
}
}
}
}
// apply applies the command against the handler.
func (h *Handler) apply(stdout, stderr io.Writer, cmd, paramstr string) (metacmd.Option, bool, error) {
// cmd = strings.TrimPrefix(cmd, `\`)
params := stmt.NewParams(paramstr)
// decode
f, err := metacmd.Decode(cmd, params)
if err != nil {
switch err = WrapErr(cmd, err); {
case err == text.ErrUnknownCommand:
fmt.Fprintln(stderr, fmt.Sprintf(text.InvalidCommand, cmd))
case err == text.ErrMissingRequiredArgument:
fmt.Fprintln(stderr, fmt.Sprintf(text.MissingRequiredArg, cmd))
default:
fmt.Fprintln(stderr, "error:", err)
}
return metacmd.Option{}, true, err
}
// run
opt, err := f(h)
if err != nil && err != rline.ErrInterrupt {
fmt.Fprintln(stderr, "error:", err)
return metacmd.Option{}, true, WrapErr(cmd, err)
}
loop:
// print unused command parameters
for {
switch arg, ok, err := params.Arg(); {
case err != nil:
fmt.Fprintln(stderr, "error:", err)
case !ok:
break loop
default:
fmt.Fprintln(stdout, fmt.Sprintf(text.ExtraArgumentIgnored, cmd, arg))
}
}
return opt, false, nil
}
// outputHighlighter returns s as a highlighted string, based on the current
// buffer and syntax highlighting settings.
func (h *Handler) outputHighlighter(s string) string {
// bail when string is empty (ie, contains no printable, non-space
// characters) or if syntax highlighting is not enabled
if empty(s) || env.Get("SYNTAX_HL") != "true" {
return s
}
// count end lines
var endl string
if m := lineendRE.FindStringSubmatch(s); m != nil {
s = strings.TrimSuffix(s, m[0])
endl += m[0]
}
// leading whitespace
var leading string
// capture current query statement buffer
orig := h.buf.RawString()
full := orig
if full != "" {
full += "\n"
} else {
// get leading whitespace
if i := strings.IndexFunc(s, func(r rune) bool {
return !isSpaceOrControl(r)
}); i != -1 {
leading = s[:i]
}
}
full += s
// setup statement parser
st := drivers.NewStmt(h.u, func() func() ([]rune, error) {
y := strings.Split(orig, "\n")
if y[0] == "" {
y[0] = s
} else {
y = append(y, s)
}
return func() ([]rune, error) {
if len(y) > 0 {
z := y[0]
y = y[1:]
return []rune(z), nil
}
return nil, io.EOF
}
}())
// accumulate all "active" statements in buffer, breaking either at
// EOF or when a \ cmd has been encountered
var err error
var cmd, final string
loop:
for {
cmd, _, err = st.Next(env.Untick(h.user, env.Vars(), false))
switch {
case err != nil && err != io.EOF:
return s + endl
case err == io.EOF:
break loop
}
if st.Ready() || cmd != "" {
final += st.RawString()
st.Reset(nil)
// grab remaining whitespace to add to final
l := len(final)
// find first non empty character
if i := strings.IndexFunc(full[l:], func(r rune) bool {
return !isSpaceOrControl(r)
}); i != -1 {
final += full[l : l+i]
}
}
}
if !st.Ready() && cmd == "" {
final += st.RawString()
}
final = leading + final
// determine whatever is remaining after "active"
var remaining string
if fnl := len(final); fnl < len(full) {
remaining = full[fnl:]
}
// this happens when a read line is empty and/or has only
// whitespace and a \ cmd
if s == remaining {
return s + endl
}
// highlight entire final accumulated buffer
b := new(bytes.Buffer)
if err := h.Highlight(b, final); err != nil {
return s + endl
}
colored := b.String()
// return only last line plus whatever remaining string (ie, after
// a \ cmd) and the end line count
ss := strings.Split(colored, "\n")
return lastcolor(colored) + ss[len(ss)-1] + remaining + endl
}
// Execute executes a query against the connected database.
func (h *Handler) Execute(ctx context.Context, w io.Writer, opt metacmd.Option, prefix, sqlstr string, forceTrans bool, bind ...interface{}) error {
if h.db == nil {
return text.ErrNotConnected
}
// determine type and pre process string
prefix, sqlstr, qtyp, err := drivers.Process(h.u, prefix, sqlstr)
if err != nil {
return drivers.WrapErr(h.u.Driver, err)
}
// start a transaction if forced
if forceTrans {
if err = h.BeginTx(ctx, nil); err != nil {
return err
}
}
f := h.doExecSingle
switch opt.Exec {
case metacmd.ExecExec:
f = h.doExecExec
case metacmd.ExecSet:
f = h.doExecSet
case metacmd.ExecWatch:
f = h.doExecWatch
case metacmd.ExecChart:
f = h.doExecChart
}
if err = drivers.WrapErr(h.u.Driver, f(ctx, w, opt, prefix, sqlstr, qtyp, bind)); err != nil {
if forceTrans {
defer h.tx.Rollback()
h.tx = nil
}
return err
}
if forceTrans {
return h.Commit()
}
return nil
}
// Reset resets the handler's query statement buffer.
func (h *Handler) Reset(r []rune) {
h.buf.Reset(r)
h.lastExec, h.lastExecPrefix, h.lastPrint, h.lastRaw, h.batch, h.batchEnd = "", "", "", "", false, ""
}
// Bind sets the bind parameters for the next query execution.
func (h *Handler) Bind(bind []interface{}) {
h.bind = bind
}
// unbind returns the bind parameters.
func (h *Handler) unbind() []interface{} {
v := h.bind
h.bind = nil
return v
}
// Prompt parses a prompt.
//
// NOTE: the documentation below is INCORRECT, as it is just copied from
// https://www.postgresql.org/docs/current/app-psql.html#APP-PSQL-PROMPTING
//
// TODO/FIXME: complete this functionality (from psql documentation):
//
// %M - The full host name (with domain name) of the database server, or
// [local] if the connection is over a Unix domain socket, or
// [local:/dir/name], if the Unix domain socket is not at the compiled in
// default location.
//
// %m - The host name of the database server, truncated at the first dot, or
// [local] if the connection is over a Unix domain socket.
//
// %> - The port number at which the database server is listening.
//
// %n - The database session user name. (The expansion of this value might
// change during a database session as the result of the command SET SESSION
// AUTHORIZATION.)
//
// %/ - The name of the current database.
//
// %~ - Like %/, but the output is ~ (tilde) if the database is your default
// database.
//
// %# - If the session user is a database superuser, then a #, otherwise a >.
// (The expansion of this value might change during a database session as the
// result of the command SET SESSION AUTHORIZATION.)
//
// %p - The process ID of the backend currently connected to.
//
// %R - In prompt 1 normally =, but @ if the session is in an inactive branch
// of a conditional block, or ^ if in single-line mode, or ! if the session is
// disconnected from the database (which can happen if \connect fails). In
// prompt 2 %R is replaced by a character that depends on why psql expects
// more input: - if the command simply wasn't terminated yet, but * if there
// is an unfinished /* ... */ comment, a single quote if there is an
// unfinished quoted string, a double quote if there is an unfinished quoted
// identifier, a dollar sign if there is an unfinished dollar-quoted string,
// or ( if there is an unmatched left parenthesis. In prompt 3 %R doesn't
// produce anything.
//
// %x - Transaction status: an empty string when not in a transaction block,
// or * when in a transaction block, or ! when in a failed transaction block,
// or ? when the transaction state is indeterminate (for example, because
// there is no connection).
//
// %l - The line number inside the current statement, starting from 1.
//
// %digits - The character with the indicated octal code is substituted.
//
// %:name: - The value of the psql variable name. See Variables, above, for
// details.
//
// %`command` - The output of command, similar to ordinary “back-tick”
// substitution.
//
// %[ ... %] - Prompts can contain terminal control characters which, for
// example, change the color, background, or style of the prompt text, or
// change the title of the terminal window. In order for the line editing
// features of Readline to work properly, these non-printing control
// characters must be designated as invisible by surrounding them with %[ and
// %]. Multiple pairs of these can occur within the prompt. For example:
//
// testdb=> \set PROMPT1 '%[%033[1;33;40m%]%n@%/%R%[%033[0m%]%# '
//
// results in a boldfaced (1;) yellow-on-black (33;40) prompt on
// VT100-compatible, color-capable terminals.
//
// %w - Whitespace of the same width as the most recent output of PROMPT1.
// This can be used as a PROMPT2 setting, so that multi-line statements are
// aligned with the first line, but there is no visible secondary prompt.
//
// To insert a percent sign into your prompt, write %%. The default prompts are
// '%/%R%x%# ' for prompts 1 and 2, and '>> ' for prompt 3.
func (h *Handler) Prompt(prompt string) string {
r, connected := []rune(prompt), h.db != nil
end := len(r)
var buf []byte
for i := 0; i < end; i++ {
if r[i] != '%' {
buf = append(buf, string(r[i])...)
continue
}
switch grab(r, i+1, end) {
case '%': // literal
buf = append(buf, '%')
case 'S': // short driver name
if connected {
s := dburl.ShortAlias(h.u.Scheme)
if s == "" {
s = dburl.ShortAlias(h.u.Driver)
}
if s == "" {
s = text.UnknownShortAlias
}
buf = append(buf, s+":"...)
} else {
buf = append(buf, text.NotConnected...)
}
case 'u': // dburl short
if connected {
buf = append(buf, h.u.Short()...)
} else {
buf = append(buf, text.NotConnected...)
}
case 'M': // full host name with domain
if connected {
buf = append(buf, h.u.Hostname()...)
}
case 'm': // host name truncated at first dot, or [local] if it's a domain socket
if connected {
s := h.u.Hostname()
if i := strings.Index(s, "."); i != -1 {
s = s[:i]
}
buf = append(buf, s...)
}
case '>': // the port number
if connected {
s := h.u.Port()
if s != "" {
s = ":" + s
}
buf = append(buf, s...)
}
case 'N': // database user
if connected && h.u.User != nil {
s := h.u.User.Username()
if s != "" {
buf = append(buf, s+"@"...)
}
}
case 'n': // database user
if connected && h.u.User != nil {
buf = append(buf, h.u.User.Username()...)
}
case '/': // database name
switch {
case connected && h.u.Opaque != "":
buf = append(buf, h.u.Opaque...)
case connected && h.u.Path != "" && h.u.Path != "/":
buf = append(buf, h.u.Path...)
}
case 'O':
if connected {
buf = append(buf, h.u.Opaque...)
}
case 'o':
if connected {
buf = append(buf, filepath.Base(h.u.Opaque)...)
}
case 'P':
if connected {
buf = append(buf, h.u.Path...)
}
case 'p':
if connected {
buf = append(buf, path.Base(h.u.Path)...)
}
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
j := i + 1
base := 10
if grab(r, j, end) == '0' {
j++
base = 8
}
if grab(r, j, end) == 'x' {
j++
base = 16
}
i = j
for unicode.IsDigit(grab(r, i+1, end)) {
i++
}
n, err := strconv.ParseInt(string(r[j:i+1]), base, 16)
if err == nil {
buf = append(buf, byte(n))
}
i--
case '~': // like %/ but ~ when default database
case '#': // when superuser, a #, otherwise >
if h.tx != nil || h.batch {
buf = append(buf, '~')
} else {
buf = append(buf, '>')
}
// case 'p': // the process id of the connected backend -- never going to be supported
case 'R': // statement state
buf = append(buf, h.buf.State()...)
case 'x': // empty when not in a transaction block, * in transaction block, ! in failed transaction block, or ? when indeterminate
case 'l': // line number
case ':': // variable value
case '`': // value of the evaluated command
case '[', ']':
case 'w':
}
i++
}
return string(buf)
}
// IO returns the io for the handler.
func (h *Handler) IO() rline.IO {
return h.l
}
// User returns the user for the handler.
func (h *Handler) User() *user.User {
return h.user
}
// URL returns the URL for the handler.
func (h *Handler) URL() *dburl.URL {
return h.u
}
// DB returns the sql.DB for the handler.
func (h *Handler) DB() drivers.DB {
if h.tx != nil {
return h.tx
}
return h.db
}
// LastExec returns the last executed statement.
func (h *Handler) LastExec() string {
return h.lastExec
}
// LastPrint returns the last printable statement.
func (h *Handler) LastPrint() string {
return h.lastPrint
}
// LastRaw returns the last raw (non-interpolated) executed statement.
func (h *Handler) LastRaw() string {
return h.lastRaw
}
// Buf returns the current query statement buffer.
func (h *Handler) Buf() *stmt.Stmt {
return h.buf
}
// Highlight highlights using the current environment settings.
func (h *Handler) Highlight(w io.Writer, buf string) error {
// create lexer, formatter, styler
l := chroma.Coalesce(drivers.Lexer(h.u))
f := formatters.Get(env.Get("SYNTAX_HL_FORMAT"))
s := styles.Get(env.Get("SYNTAX_HL_STYLE"))
// override background
if env.Get("SYNTAX_HL_OVERRIDE_BG") != "false" {
s = ustyles.Get(env.Get("SYNTAX_HL_STYLE"))
}
// tokenize stream
it, err := l.Tokenise(nil, buf)
if err != nil {
return err
}
// write formatted output
return f.Format(w, s, it)
}
// Open handles opening a specified database URL, passing either a single
// string in the form of a URL, or more than one string, in which case the
// first string is treated as a driver name, and the remaining strings are
// joined (with a space) and passed as a DSN to sql.Open.
//
// If there is only one parameter, and it is not a well formatted URL, but
// appears to be a file on disk, then an attempt will be made to open it with
// an appropriate driver (mysql, postgres, sqlite3) depending on the type (unix
// domain socket, directory, or regular file, respectively).
func (h *Handler) Open(ctx context.Context, params ...string) error {
if len(params) == 0 || params[0] == "" {
return nil
}
if h.tx != nil {
return text.ErrPreviousTransactionExists
}
if len(params) == 1 {
if v, ok := env.Vars().GetConn(params[0]); ok {
params = v
}
}
if len(params) < 2 {
dsn := params[0]
// parse dsn
u, err := dburl.Parse(dsn)
if err != nil {
return err
}
h.u = u
// force parameters
h.forceParams(h.u)
} else {
h.u = &dburl.URL{
Driver: params[0],
DSN: strings.Join(params[1:], " "),
}
}
// open connection
var err error
h.db, err = drivers.Open(ctx, h.u, h.GetOutput, h.l.Stderr)
if err != nil && !drivers.IsPasswordErr(h.u, err) {
defer h.Close()
return err
}
// set buffer options
drivers.ConfigStmt(h.u, h.buf)
// force error/check connection
if err == nil {
if err = drivers.Ping(ctx, h.u, h.db); err == nil {
return h.Version(ctx)
}
}
// bail without getting password
if h.nopw || !drivers.IsPasswordErr(h.u, err) || len(params) > 1 || !h.l.Interactive() {
defer h.Close()
return err
}
// print the error
fmt.Fprintln(h.l.Stderr(), "error:", err)
// otherwise, try to collect a password ...
dsn, err := h.Password(params[0])
if err != nil {
// close connection
defer h.Close()
return err
}
// reconnect
return h.Open(ctx, dsn)
}
func (h *Handler) connStrings() []string {
entries, err := passfile.Entries(h.user.HomeDir, text.PassfileName)
if err != nil {
// ignore the error as this is only used for completer
// and it'll be reported again when trying to force params before opening a conn
entries = nil
}
available := drivers.Available()
names := make([]string, 0, len(available)+len(entries))
for schema := range available {
_, aliases := dburl.SchemeDriverAndAliases(schema)
// TODO should we create all combinations of space, :, :// and +transport ?
names = append(names, schema)
names = append(names, aliases...)
}
for _, entry := range entries {
if entry.Protocol == "*" {
continue
}
user, host, port, dbname := "", "", "", ""
if entry.Username != "*" {
user = entry.Username + "@"
if entry.Host != "*" {
host = entry.Host
if entry.Port != "*" {
port = ":" + entry.Port
}
if entry.DBName != "*" {
dbname = "/" + entry.DBName
}
}
}
names = append(names, entry.Protocol+"://"+user+host+port+dbname)
}
return append(names, slices.Sorted(maps.Keys(env.Vars().Conn()))...)
}
// forceParams forces connection parameters on a database URL, adding any
// driver specific required parameters, and the username/password when a
// matching entry exists in the PASS file.
func (h *Handler) forceParams(u *dburl.URL) {
// force driver parameters
drivers.ForceParams(u)
// see if password entry is present
user, err := passfile.Match(u, h.user.HomeDir, text.PassfileName)
switch {
case err != nil:
fmt.Fprintln(h.l.Stderr(), "error:", err)
case user != nil:
u.User = user
}
// copy back to u
z, _ := dburl.Parse(u.String())
*u = *z
}
// Password collects a password from input, and returns a modified DSN
// including the collected password.
func (h *Handler) Password(dsn string) (string, error) {
switch conn, ok := env.Vars().GetConn(dsn); {
case dsn == "":
return "", text.ErrMissingDSN
case ok && len(conn) < 2:
return "", text.ErrNamedConnectionIsNotAURL
case ok:
dsn = conn[0]
}
u, err := dburl.Parse(dsn)
if err != nil {
return "", err
}
user := h.user.Username
if u.User != nil {
user = u.User.Username()
}
pass, err := h.l.Password(text.EnterPassword)
if err != nil {
return "", err
}
u.User = url.UserPassword(user, pass)
return u.String(), nil
}
// Close closes the database connection if it is open.
func (h *Handler) Close() error {
if h.tx != nil {
return text.ErrPreviousTransactionExists
}
if h.db != nil {
err := h.db.Close()
drv := h.u.Driver
h.db, h.u = nil, nil
return drivers.WrapErr(drv, err)
}
return nil
}
// ReadVar reads a variable from the interactive prompt, saving it to
// environment variables.
func (h *Handler) ReadVar(typ, prompt string) (string, error) {
var masked bool
// check type
switch typ {
case "password":
masked = true
case "string", "int", "uint", "float", "bool":
default:
return "", text.ErrInvalidType
}
var v string
var err error
if masked {
if prompt == "" {
prompt = text.EnterPassword
}
v, err = h.l.Password(prompt)
} else {
h.l.Prompt(prompt)
var r []rune
r, err = h.l.Next()
v = string(r)
}
switch typ {
case "int":
_, err = strconv.ParseInt(v, 10, 64)
case "uint":
_, err = strconv.ParseUint(v, 10, 64)
case "float":
_, err = strconv.ParseFloat(v, 64)
case "bool":
var b bool
if b, err = strconv.ParseBool(v); err == nil {
v = fmt.Sprintf("%t", b)
}
}
if err != nil {
errstr := err.Error()
if i := strings.LastIndex(errstr, ":"); i != -1 {
errstr = strings.TrimSpace(errstr[i+1:])
}
return "", fmt.Errorf(text.InvalidValue, typ, v, errstr)
}
return v, nil
}
// ChangePassword changes a password for the user.
func (h *Handler) ChangePassword(user string) (string, error) {
if h.db == nil {
return "", text.ErrNotConnected
}
if !h.l.Interactive() {
return "", text.ErrNotInteractive
}
var err error
if err = drivers.CanChangePassword(h.u); err != nil {
return "", err
}
var newpw, newpw2, oldpw string
// ask for previous password
if user == "" && drivers.RequirePreviousPassword(h.u) {
oldpw, err = h.l.Password(text.EnterPreviousPassword)
if err != nil {
return "", err
}
}
// attempt to get passwords
for i := 0; i < 3; i++ {
if newpw, err = h.l.Password(text.NewPassword); err != nil {
return "", err
}
if newpw2, err = h.l.Password(text.ConfirmPassword); err != nil {
return "", err
}
if newpw == newpw2 {