forked from wgliang/pgproxy
/
cmd.go
94 lines (87 loc) · 2.07 KB
/
cmd.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
// Copyright 2017 wgliang. All rights reserved.
// Use of this source code is governed by Apache
// license that can be found in the LICENSE file.
// Package cli provides virtual command-line access
// in pgproxy include start,cli and stop action.
package cli
import (
"bufio"
"fmt"
"os"
"strings"
"time"
"github.com/golang/glog"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
"github.com/wgliang/pgproxy/proxy"
)
type Client struct {
db *sqlx.DB
timestamp int64
}
// Command line access to pgproxy and provide a friendly display
// interface.
func Command() {
client := new(Client)
var err error
client.db, err = sqlx.Open("postgres", connStr)
if err != nil {
glog.Fatalln(err)
}
client.timestamp = time.Now().Unix()
// Set connections num
client.db.SetMaxIdleConns(1)
client.db.SetMaxOpenConns(10)
client.db.SetConnMaxLifetime(60 * time.Second)
defer func() {
client.db.Close()
if err != nil {
glog.Errorln(err)
}
}()
fmt.Printf(" pgproxy (%s)\n", VERSION)
fmt.Println(" Login in:", time.Unix(client.timestamp, 0).Format("2006-01-02 03:04:05 PM"))
fmt.Println(` Type "help" for help.`)
running := true
reader := bufio.NewReader(os.Stdin)
for running {
// Sleep some Nanoseconds wait for event have been deal.
time.Sleep(300000 * time.Nanosecond)
fmt.Print("pgproxy#")
data, _, _ := reader.ReadLine()
command := string(data)
if command == "quit" {
fmt.Println("pgproxy Exit!")
return
}
client.Request(command)
}
return
}
// Client request switcher,for different types of sql statement
// calls different requests.
func (c *Client) Request(sql string) {
index := strings.Index(sql, " ")
if index == -1 {
index = len(sql)
}
// Choose right function for requests.
switch strings.ToLower(sql[0:index]) {
case "select":
rows, err := c.db.Query(sql)
if err != nil {
glog.Errorln(err)
} else {
proxy.RowsFormater(rows)
}
case "insert", "delete", "update":
res, err := c.db.Exec(sql)
if err != nil {
glog.Errorln(err)
} else {
proxy.ResultFormater(res)
}
case `\d`, `\l`, `\q`:
// res := c.db.Exec(sql)
}
}