-
Notifications
You must be signed in to change notification settings - Fork 10
/
srv.go
78 lines (67 loc) · 1.66 KB
/
srv.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
package pgsrv
import (
"context"
"database/sql/driver"
nodes "github.com/lfittl/pg_query_go/nodes"
"net"
)
// implements the Server interface
type server struct {
queryer Queryer
authenticator authenticator
}
// New creates a Server object capable of handling postgres client connections.
// It delegates query execution to the provided Queryer. If the provided Queryer
// also implements Execer, the returned server will also be able to handle
// executing SQL commands (see Execer).
//
// If queryer implements passwordProvider interface, a new server will be protected
// with a new md5Authenticator.
func New(queryer Queryer) Server {
var auth authenticator
auth = &noPasswordAuthenticator{}
pp, ok := queryer.(PasswordProvider)
if ok {
switch pp.Type() {
case MD5:
auth = &md5Authenticator{pp}
case Plain:
auth = &clearTextAuthenticator{pp}
}
}
return &server{queryer, auth}
}
// implements Queryer
func (s *server) Query(ctx context.Context, n nodes.Node) (driver.Rows, error) {
return s.queryer.Query(ctx, n)
}
// implements Execer
func (s *server) Exec(ctx context.Context, n nodes.Node) (driver.Result, error) {
execer, ok := s.queryer.(Execer)
if !ok {
return nil, Unsupported("commands execution. Read-only mode.")
}
return execer.Exec(ctx, n)
}
func (s *server) Listen(laddr string) error {
ln, err := net.Listen("tcp", laddr)
if err != nil {
return err
}
for {
conn, err := ln.Accept()
if err != nil {
return err
}
go s.Serve(conn)
}
}
func (s *server) Serve(conn net.Conn) error {
defer conn.Close()
sess := &session{Server: s, Conn: conn}
err := sess.Serve()
if err != nil {
// TODO: Log it?
}
return err
}