-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprequel.go
More file actions
324 lines (255 loc) · 6.16 KB
/
prequel.go
File metadata and controls
324 lines (255 loc) · 6.16 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
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
package main
import (
"errors"
"fmt"
"io/ioutil"
"encoding/json"
"database/sql"
"github.com/nsf/termbox-go"
"github.com/briansteffens/escapebox"
"github.com/briansteffens/tui"
_ "github.com/go-sql-driver/mysql"
)
const minColumnWidth int = 5
const maxColumnWidth int = 25
const cursorStatementColor termbox.Attribute = termbox.Attribute(237)
const tempSqlFile string = "prequel.sql"
type Connection struct {
Driver string `json:"driver"`
Host string `json:"host"`
Port int `json:"port"`
User string `json:"user"`
Password string `json:"password"`
Database string `json:"database"`
}
type Statement struct {
start int
length int
}
var db *sql.DB
var editor tui.EditBox
var results tui.DetailView
var container tui.Container
var status tui.Label
var statements []Statement
var statement Statement
func resizeHandler() {
editor.Bounds.Width = container.Width
editor.Bounds.Height = container.Height / 2
results.Bounds.Top = editor.Bounds.Height
results.Bounds.Width = container.Width
results.Bounds.Height = container.Height - editor.Bounds.Height - 1
status.Bounds.Top = results.Bounds.Bottom() + 1
status.Bounds.Width = container.Width
}
func connect(conn Connection) (*sql.DB, error) {
dsn := conn.User
if conn.Password != "" {
dsn += ":" + conn.Password
}
if dsn != "" {
dsn += "@"
}
dsn += fmt.Sprintf("tcp(%s:%d)", conn.Host, conn.Port)
if conn.Database != "" {
dsn += "/" + conn.Database
}
return sql.Open(conn.Driver, dsn)
}
func cursorInWhichStatement(cur int, ss []Statement) (Statement, error) {
for _, s := range ss {
if cur > s.start + s.length - 1 {
continue
}
return s, nil
}
// Default to last statement if there is one
if len(ss) > 0 {
return ss[len(ss) - 1], nil
}
return Statement {}, errors.New("Cursor not in statement")
}
func editorTextChanged(e *tui.EditBox) {
err := ioutil.WriteFile(tempSqlFile, []byte(e.GetText()), 0644)
if err != nil {
panic(err)
}
lineHighlighter(e)
}
func lineHighlighter(e *tui.EditBox) {
var cur, next *tui.Char
statements = []Statement {}
statementStart := 0
chars := e.AllChars()
for i := 0; i <= len(chars); i++ {
cur = next
if i < len(chars) {
next = chars[i]
} else {
next = nil
}
// Skip first iteration because cur won't be set yet.
if cur == nil {
continue
}
// Statements end at unquoted semi-colons and EOF
if next == nil ||
cur.Quote == tui.QuoteNone && cur.Char == ';' {
newStatement := Statement {
start: statementStart,
length: i - statementStart,
}
statementStart = i
// Statements should include a trailing newline if
// present.
if next != nil && next.Char == '\n' {
newStatement.length++
statementStart++
}
statements = append(statements, newStatement)
}
}
statement, _ = cursorInWhichStatement(e.GetCursor(), statements)
for i := 0; i < len(chars); i++ {
if i >= statement.start &&
i < statement.start + statement.length {
chars[i].Bg = cursorStatementColor
} else {
chars[i].Bg = termbox.ColorBlack
}
}
}
func handleContainerEvent(c *tui.Container, ev escapebox.Event) bool {
if ev.Type == termbox.EventKey && ev.Key == termbox.KeyF5 {
runQuery()
return true
}
return false
}
func runQuery() {
results.Reset()
status.Text = ""
query := ""
for i := statement.start; i < statement.start + statement.length; i++ {
ch, err := editor.GetChar(i)
if err != nil {
panic(err)
}
query += string(ch.Char)
}
res, err := db.Query(query)
if err != nil {
status.Text = fmt.Sprintf("%s", err)
return
}
defer res.Close()
columnNames, err := res.Columns()
if err != nil {
panic(err)
}
values := make([]interface{}, len(columnNames))
valuePointers := make([]interface{}, len(columnNames))
for i := 0; i < len(columnNames); i++ {
valuePointers[i] = &values[i]
}
rows := make([][]string, 0)
for res.Next() {
if err := res.Scan(valuePointers...); err != nil {
panic(err)
}
row := make([]string, len(columnNames))
for i := 0; i < len(columnNames); i++ {
val := "null"
if values[i] != nil {
val = fmt.Sprintf("%s", values[i])
}
row[i] = val
}
rows = append(rows, row)
}
columns := make([]tui.Column, len(columnNames))
for i := 0; i < len(columnNames); i++ {
columns[i].Name = columnNames[i]
width := len(columns[i].Name)
for _, row := range rows {
if len(row[i]) > width {
width = len(row[i])
}
}
width++
if width < minColumnWidth {
width = minColumnWidth
}
if width > maxColumnWidth {
width = maxColumnWidth
}
columns[i].Width = width
}
results.Columns = columns
results.Rows = rows
}
func main() {
configBytes, err := ioutil.ReadFile("config.json")
if err != nil {
panic(err)
}
connection := Connection{}
err = json.Unmarshal(configBytes, &connection)
if err != nil {
fmt.Println("Error: config.json, invalid json")
panic(err)
}
if connection.Driver == "" {
fmt.Println("Error: config.json is missing the 'driver' " +
"field");
return;
}
if connection.Database == "" {
fmt.Println("Error: config.json is missing the 'database' " +
"field");
return;
}
db, err = connect(connection)
if err != nil {
panic(err)
}
defer db.Close()
err = db.Ping()
if err != nil {
panic(err)
}
tempSql := "show tables;"
tempSqlBytes, err := ioutil.ReadFile(tempSqlFile)
if err == nil {
tempSql = string(tempSqlBytes);
}
tui.Init()
defer tui.Close()
editor = tui.EditBox {
Highlighter: tui.BasicHighlighter,
Dialect: tui.DialectMySQL,
OnTextChanged: editorTextChanged,
OnCursorMoved: lineHighlighter,
}
editor.SetText(tempSql)
results = tui.DetailView {
Columns: []tui.Column {},
Rows: [][]string {},
RowBg: termbox.Attribute(0),
RowBgAlt: termbox.Attribute(236),
SelectedBg: termbox.Attribute(22),
}
status = tui.Label {
}
container = tui.Container {
Controls: []tui.Control {&results, &editor, &status},
ResizeHandler: resizeHandler,
KeyBindingExit: tui.KeyBinding { Key: termbox.KeyCtrlC },
KeyBindingFocusNext: tui.KeyBinding { Key: termbox.KeyTab },
KeyBindingFocusPrevious: tui.KeyBinding {
Seq: tui.SeqShiftTab,
},
HandleEvent: handleContainerEvent,
}
tui.MainLoop(&container)
}