-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.go
232 lines (218 loc) · 6.09 KB
/
main.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
package main
import (
"errors"
"fmt"
"os"
"os/signal"
"strings"
"time"
"github.com/FrontMage/dynamo.cli/db"
"github.com/FrontMage/dynamo.cli/executors"
"github.com/FrontMage/dynamo.cli/sqlparser"
"github.com/FrontMage/dynamo.cli/tables"
"github.com/briandowns/spinner"
prompt "github.com/c-bata/go-prompt"
"golang.org/x/net/context"
cli "gopkg.in/urfave/cli.v2"
)
// TODO better suggest, suggest based on hash key and range key
var tableNameSuggestions []prompt.Suggest
// Key bindings, reserved, might use them oneday
var keyBindings = []prompt.KeyBind{
{
Key: prompt.ControlK,
Fn: func(buf *prompt.Buffer) {},
},
}
func sqlRunner(sql string, resultCh chan string, errCh chan error) (chan string, chan error) {
if sqlparser.SelectRegexp.MatchString(sql) {
// add surfix "END" for rexexp matching
if r, err := executors.Select(sql + " END"); err == nil {
resultCh <- r
} else {
errCh <- err
}
} else if sqlparser.DescRegexp.MatchString(sql) && sqlparser.TableRegexp.MatchString(sql) {
if r, err := executors.DescribeTable(sql + " END"); err == nil {
resultCh <- r
} else {
errCh <- err
}
} else if sqlparser.UpdateRegexp.MatchString(sql) {
// TODO require WHERE field, update all seems not so safe?
if r, err := executors.Update(sql + " END"); err == nil {
resultCh <- r
} else {
errCh <- err
}
} else {
resultCh <- ""
errCh <- nil
}
// TODO support SHOW TABLE
return resultCh, errCh
}
// executor executes command and print the output.
func executor(in string) {
s := strings.TrimSpace(in)
s = strings.TrimSuffix(in, ";")
if s == "" {
return
} else if s == "quit" || s == "exit" {
os.Exit(0)
} else {
spin := spinner.New(spinner.CharSets[14], 100*time.Millisecond)
spin.Start()
defer spin.Stop()
ctx, cancel := context.WithCancel(context.Background())
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt) // sigCh only listens to os.Interrupt
// Listen to the os interrupt signal which is ctrl+c
// when ctrl+c is pressed, cancel current query
go func() {
select {
case <-sigCh:
cancel()
return
}
}()
resultCh := make(chan string, 1)
errCh := make(chan error, 1)
go sqlRunner(s, resultCh, errCh)
// The main executor function will have to wait until the query is done or canceled
// so that new prompts won't popup
select {
case <-ctx.Done():
return
case r := <-resultCh:
fmt.Println(r)
case e := <-errCh:
fmt.Println(e)
}
}
}
func runPrompt(tablePrefix string) {
spin := spinner.New(spinner.CharSets[14], 100*time.Millisecond)
spin.Start()
// load some table names for auto complete
tableNames, _ := db.ListTable([]*string{}, nil)
for _, name := range tableNames {
// filter certain table name
if tablePrefix != "" {
if strings.HasPrefix(*name, tablePrefix) {
tableNameSuggestions = append(tableNameSuggestions, prompt.Suggest{
Text: *name,
Description: "table",
})
go func(tableName *string) {
if _, err := tables.GetTableDesc(tableName); err != nil {
fmt.Println(err)
}
}(name)
}
} else {
tableNameSuggestions = append(tableNameSuggestions, prompt.Suggest{
Text: *name,
Description: "table",
})
go func(tableName *string) {
if _, err := tables.GetTableDesc(tableName); err != nil {
fmt.Println(err)
}
}(name)
}
}
spin.Stop()
p := prompt.New(
executor,
completer,
prompt.OptionPrefix(">>> "),
prompt.OptionTitle("DynamoDB prompt"),
prompt.OptionAddKeyBind(keyBindings...),
)
p.Run()
}
// completer returns the completion items from user input.
func completer(d prompt.Document) []prompt.Suggest {
keywords := []prompt.Suggest{
{Text: "SELECT", Description: "keyword"},
{Text: "FROM", Description: "keyword"},
{Text: "WHERE", Description: "keyword"},
{Text: "LIMIT", Description: "keyword"},
{Text: "DESC", Description: "keyword"},
{Text: "TABLE", Description: "keyword"},
{Text: "LIKE", Description: "keyword"},
{Text: "ALL", Description: "keyword"},
{Text: "AND", Description: "keyword"},
{Text: "UPDATE", Description: "keyword"},
{Text: "SET", Description: "keyword"},
{Text: "RETRUNING", Description: "keyword"},
}
wordBefore := d.GetWordBeforeCursor()
if wordBefore == "" {
return []prompt.Suggest{}
}
if d.TextBeforeCursor() == " " {
return tableNameSuggestions
}
if wordBefore == strings.ToUpper(wordBefore) && wordBefore != "_" && wordBefore != "-" && wordBefore != " " {
return prompt.FilterHasPrefix(keywords, d.GetWordBeforeCursor(), true)
}
return prompt.FilterHasPrefix(tableNameSuggestions, d.GetWordBeforeCursor(), true)
}
func main() {
// grmon.Start()
defer recover()
var accessKeyID string
var secretAccessKey string
var region string
var tablePrefix string
app := &cli.App{
Name: "dynamo.cli",
Usage: "DynamoDB command line prompt",
Version: "0.1.1",
Authors: []*cli.Author{&cli.Author{
Name: "xinbg",
Email: "[email protected]",
}},
Flags: []cli.Flag{
&cli.StringFlag{
Name: "key",
Usage: "specify aws config access key id",
Aliases: []string{"k"},
Destination: &accessKeyID,
},
&cli.StringFlag{
Name: "secret",
Usage: "specify aws config secret access key",
Aliases: []string{"s"},
Destination: &secretAccessKey,
},
&cli.StringFlag{
Name: "region",
Usage: "specify aws config region",
Aliases: []string{"r"},
Destination: ®ion,
},
&cli.StringFlag{
Name: "tablePrefix",
Usage: "specify certain prefix string for table names auto completion",
Aliases: []string{"p"},
Destination: &tablePrefix,
},
},
Action: func(c *cli.Context) error {
if !((accessKeyID == "" && secretAccessKey == "") || (accessKeyID != "" && secretAccessKey != "")) {
return errors.New("Must provide access key id and secret access key at the same time")
} else if _, err := db.GetDynamoSession(accessKeyID, secretAccessKey, region); err == nil {
runPrompt(tablePrefix)
return nil
} else {
return err
}
},
}
if err := app.Run(os.Args); err != nil {
fmt.Println(err.Error())
}
}