-
Notifications
You must be signed in to change notification settings - Fork 72
/
repl.go
270 lines (231 loc) · 5.1 KB
/
repl.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
package gosql
import (
"fmt"
"io"
"os"
"strings"
"github.com/chzyer/readline"
"github.com/olekukonko/tablewriter"
)
func doSelect(mb Backend, slct *SelectStatement) error {
results, err := mb.Select(slct)
if err != nil {
return err
}
if len(results.Rows) == 0 {
fmt.Println("(no results)")
return nil
}
table := tablewriter.NewWriter(os.Stdout)
header := []string{}
for _, col := range results.Columns {
header = append(header, col.Name)
}
table.SetHeader(header)
table.SetAutoFormatHeaders(false)
rows := [][]string{}
for _, result := range results.Rows {
row := []string{}
for i, cell := range result {
typ := results.Columns[i].Type
r := ""
switch typ {
case IntType:
i := cell.AsInt()
if i != nil {
r = fmt.Sprintf("%d", *i)
}
case TextType:
s := cell.AsText()
if s != nil {
r = *s
}
case BoolType:
b := cell.AsBool()
if b != nil {
r = "t"
if !*b {
r = "f"
}
}
}
row = append(row, r)
}
rows = append(rows, row)
}
table.SetBorder(false)
table.AppendBulk(rows)
table.Render()
if len(rows) == 1 {
fmt.Println("(1 result)")
} else {
fmt.Printf("(%d results)\n", len(rows))
}
return nil
}
func debugTable(b Backend, name string) {
// psql behavior is to display all if no name is specified.
if name == "" {
debugTables(b)
return
}
var tm *TableMetadata = nil
for _, t := range b.GetTables() {
if t.Name == name {
tm = &t
}
}
if tm == nil {
fmt.Printf(`Did not find any relation named "%s".\n`, name)
return
}
fmt.Printf("Table \"%s\"\n", name)
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Column", "Type", "Nullable"})
table.SetAutoFormatHeaders(false)
table.SetBorder(false)
rows := [][]string{}
for _, c := range tm.Columns {
typeString := "integer"
switch c.Type {
case TextType:
typeString = "text"
case BoolType:
typeString = "boolean"
}
nullable := ""
if c.NotNull {
nullable = "not null"
}
rows = append(rows, []string{c.Name, typeString, nullable})
}
table.AppendBulk(rows)
table.Render()
if len(tm.Indexes) > 0 {
fmt.Println("Indexes:")
}
for _, index := range tm.Indexes {
attributes := []string{}
if index.PrimaryKey {
attributes = append(attributes, "PRIMARY KEY")
} else if index.Unique {
attributes = append(attributes, "UNIQUE")
}
attributes = append(attributes, index.Type)
fmt.Printf("\t\"%s\" %s (%s)\n", index.Name, strings.Join(attributes, ", "), index.Exp)
}
fmt.Println("")
}
func debugTables(b Backend) {
tables := b.GetTables()
if len(tables) == 0 {
fmt.Println("Did not find any relations.")
return
}
fmt.Println("List of relations")
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Name", "Type"})
table.SetAutoFormatHeaders(false)
table.SetBorder(false)
rows := [][]string{}
for _, t := range tables {
rows = append(rows, []string{t.Name, "table"})
}
table.AppendBulk(rows)
table.Render()
fmt.Println("")
}
func RunRepl(b Backend) {
l, err := readline.NewEx(&readline.Config{
Prompt: "# ",
HistoryFile: "/tmp/tmp",
InterruptPrompt: "^C",
EOFPrompt: "exit",
})
if err != nil {
panic(err)
}
defer l.Close()
fmt.Println("Welcome to gosql.")
repl:
for {
fmt.Print("# ")
line, err := l.Readline()
if err == readline.ErrInterrupt {
if len(line) == 0 {
break
} else {
continue repl
}
} else if err == io.EOF {
break
}
if err != nil {
fmt.Println("Error while reading line:", err)
continue repl
}
parser := Parser{}
trimmed := strings.TrimSpace(line)
if trimmed == "quit" || trimmed == "exit" || trimmed == "\\q" {
break
}
if trimmed == "\\dt" {
debugTables(b)
continue
}
if strings.HasPrefix(trimmed, "\\d") {
name := strings.TrimSpace(trimmed[len("\\d"):])
debugTable(b, name)
continue
}
parseOnly := false
if strings.HasPrefix(trimmed, "\\p") {
line = strings.TrimSpace(trimmed[len("\\p"):])
parseOnly = true
}
ast, err := parser.Parse(line)
if err != nil {
fmt.Println("Error while parsing:", err)
continue repl
}
for _, stmt := range ast.Statements {
if parseOnly {
fmt.Println(stmt.GenerateCode())
continue
}
switch stmt.Kind {
case CreateIndexKind:
err = b.CreateIndex(ast.Statements[0].CreateIndexStatement)
if err != nil {
fmt.Println("Error adding index on table:", err)
continue repl
}
case CreateTableKind:
err = b.CreateTable(ast.Statements[0].CreateTableStatement)
if err != nil {
fmt.Println("Error creating table:", err)
continue repl
}
case DropTableKind:
err = b.DropTable(ast.Statements[0].DropTableStatement)
if err != nil {
fmt.Println("Error dropping table:", err)
continue repl
}
case InsertKind:
err = b.Insert(stmt.InsertStatement)
if err != nil {
fmt.Println("Error inserting values:", err)
continue repl
}
case SelectKind:
err := doSelect(b, stmt.SelectStatement)
if err != nil {
fmt.Println("Error selecting values:", err)
continue repl
}
}
}
fmt.Println("ok")
}
}