-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.go
More file actions
234 lines (209 loc) · 5.05 KB
/
utils.go
File metadata and controls
234 lines (209 loc) · 5.05 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
package main
import (
"database/sql"
"encoding/json"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"time"
_ "github.com/go-sql-driver/mysql"
"github.com/joho/godotenv"
"github.com/pelletier/go-toml"
"golang.org/x/term"
)
// Common variables
var (
cachedDBNames []string
cachedTableNames = make(map[string][]string)
cachedColumnNames = make(map[string][]string)
)
var KEYWORDS = []string{
"USE", "SELECT", "FROM", "WHERE", "JOIN", "ON", "GROUP BY", "ORDER BY",
"LIMIT", "OFFSET", "AS", "IS", "NULL", "NOT", "IN", "BETWEEN", "LIKE",
"SHOW", "DATABASES", "TABLES", "COLUMNS", "INDEXES", "STATISTICS",
"INSERT", "UPDATE", "DELETE", "DROP", "ALTER", "CREATE", "GRANT", "REVOKE",
"UPDATE", "SET", "WHERE", "ON", "AND", "OR", "XOR", "NOT", "EXISTS",
}
// Output format types
type OutputFormat int
const (
Plain OutputFormat = iota
JSON
Table
CSV
)
func (f OutputFormat) String() string {
return [...]string{"plain", "json", "table", "csv"}[f]
}
func parseOutputFormat(format string) OutputFormat {
switch format {
case "json":
return JSON
case "table":
return Table
case "csv":
return CSV
default:
return Plain
}
}
// Terminal utilities
func isTerminal() bool {
fd := int(os.Stdin.Fd())
return term.IsTerminal(fd)
}
// Value formatting utilities
func formatValue(val interface{}) string {
switch v := val.(type) {
case nil:
return "NULL"
case bool:
return fmt.Sprintf("%t", v)
case int, int64:
return fmt.Sprintf("%d", v)
case float64:
return fmt.Sprintf("%f", v)
case string:
return v
case []byte:
return string(v)
case time.Time:
return v.Format("2006-01-02 15:04:05")
default:
return fmt.Sprintf("%v", v)
}
}
func formatCSVValue(val interface{}) string {
switch v := val.(type) {
case nil:
return ""
case bool:
return fmt.Sprintf("%t", v)
case int, int64:
return fmt.Sprintf("%d", v)
case float64:
return fmt.Sprintf("%f", v)
case string:
return fmt.Sprintf("\"%s\"", strings.ReplaceAll(v, "\"", "\"\""))
case []byte:
return fmt.Sprintf("\"%s\"", strings.ReplaceAll(string(v), "\"", "\"\""))
case time.Time:
return fmt.Sprintf("\"%s\"", v.Format("2006-01-02 15:04:05"))
default:
return fmt.Sprintf("\"%v\"", v)
}
}
// Config utilities
func loadConfigFromFile(configPath string) (map[string]string, error) {
config := make(map[string]string)
file, err := os.ReadFile(configPath)
if err != nil {
return config, err
}
err = toml.Unmarshal(file, &config)
if err != nil {
return config, err
}
return config, nil
}
func loadConfigFromEnv() (string, string, string, string, string, error) {
godotenv.Load(".env") // Optionally load .env file
host := os.Getenv("DB_HOST")
port := os.Getenv("DB_PORT")
user := os.Getenv("DB_USERNAME")
password := os.Getenv("DB_PASSWORD")
defaultDatabase := os.Getenv("DB_DATABASE")
if defaultDatabase == "" {
defaultDatabase = "test"
}
return host, port, user, password, defaultDatabase, nil
}
func getDefaultConfigFilePath() string {
homeDir, err := os.UserHomeDir()
if err != nil {
log.Fatalf("Failed to get user home directory: %v", err)
}
configFile := filepath.Join(homeDir, ".tip/config.toml")
if _, err := os.Stat(configFile); err != nil {
return ""
}
return configFile
}
// Result row structure
type RowResult struct {
colNames []string
colValues []interface{}
}
// MarshalJSON customizes the JSON serialization of RowResult
func (r RowResult) MarshalJSON() ([]byte, error) {
converted := make(map[string]interface{})
for i, col := range r.colNames {
val := r.colValues[i]
if byteVal, ok := val.([]byte); ok {
converted[col] = string(byteVal)
} else {
converted[col] = val
}
}
return json.Marshal(converted)
}
// Get databases and tables
func getDatabases(db *sql.DB) ([]string, error) {
if len(cachedDBNames) > 0 {
return cachedDBNames, nil
}
rows, err := db.Query("SHOW DATABASES")
if err != nil {
return nil, err
}
defer rows.Close()
var databases []string
for rows.Next() {
var dbName string
if err := rows.Scan(&dbName); err == nil {
databases = append(databases, dbName)
}
}
cachedDBNames = databases
return databases, nil
}
func getTableNames(db *sql.DB, dbName string) ([]string, error) {
if cachedTableNames[dbName] != nil {
return cachedTableNames[dbName], nil
}
rows, err := db.Query("SHOW TABLES")
if err != nil {
return nil, err
}
defer rows.Close()
var tables []string
for rows.Next() {
var tableName string
if err := rows.Scan(&tableName); err == nil {
tables = append(tables, tableName)
}
}
cachedTableNames[dbName] = tables
return tables, nil
}
func getAllColumnNames(db *sql.DB, dbName string) ([]string, error) {
if cachedColumnNames[dbName] != nil {
return cachedColumnNames[dbName], nil
}
rows, err := db.Query("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ?", dbName)
if err != nil {
return nil, err
}
defer rows.Close()
var columnNames []string
for rows.Next() {
var columnName string
if err := rows.Scan(&columnName); err == nil {
columnNames = append(columnNames, columnName)
}
}
cachedColumnNames[dbName] = columnNames
return columnNames, nil
}