feat(nebula): add NebulaGraph 3.x browser support
This commit is contained in:
1 parent
e59a8c1bd4
commit
ef05a6a19b
69 files changed
+1737
-41
No files matched your search
@@ -0,0 +1,11 @@
|
||||
module github.com/t8y2/dbx/agents/drivers/nebula-go
|
||||
|
||||
go 1.24
|
||||
|
||||
require github.com/vesoft-inc/nebula-go/v3 v3.8.0
|
||||
|
||||
require (
|
||||
github.com/vesoft-inc/fbthrift v0.0.0-20230214024353-fa2f34755b28 // indirect
|
||||
golang.org/x/net v0.17.0 // indirect
|
||||
golang.org/x/text v0.13.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,55 @@
|
||||
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/vesoft-inc/fbthrift v0.0.0-20230214024353-fa2f34755b28 h1:gpoPCGeOEuk/TnoY9nLVK1FoBM5ie7zY3BPVG8q43ME=
|
||||
github.com/vesoft-inc/fbthrift v0.0.0-20230214024353-fa2f34755b28/go.mod h1:xu7e9za8StcJhBZmCDwK1Hyv4/Y0xFsjS+uqp10ECJg=
|
||||
github.com/vesoft-inc/nebula-go/v3 v3.8.0 h1:ecB87KMnMUcuKbgFESKIscdxA7Y1TcX7XEVqZQ1UqlA=
|
||||
github.com/vesoft-inc/nebula-go/v3 v3.8.0/go.mod h1:YTNAQzimjXLXUaEDOzty/eCCye+9zkZRuUzXz9LQUpU=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
||||
golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM=
|
||||
golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
|
||||
golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=
|
||||
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,347 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
nebula "github.com/vesoft-inc/nebula-go/v3"
|
||||
)
|
||||
|
||||
const (
|
||||
legacySessionID = "__legacy__"
|
||||
maxSessions = 256
|
||||
)
|
||||
|
||||
type request struct {
|
||||
ID json.RawMessage `json:"id"`
|
||||
Method string `json:"method"`
|
||||
Params map[string]json.RawMessage `json:"params"`
|
||||
}
|
||||
|
||||
type response struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID json.RawMessage `json:"id,omitempty"`
|
||||
Result any `json:"result,omitempty"`
|
||||
Error *rpcError `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type connectParams struct {
|
||||
DriverProfile string `json:"driver_profile"`
|
||||
Host string `json:"host"`
|
||||
Port int `json:"port"`
|
||||
Database string `json:"database"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
SSL bool `json:"ssl"`
|
||||
CACertPath string `json:"ca_cert_path"`
|
||||
ClientCertPath string `json:"client_cert_path"`
|
||||
ClientKeyPath string `json:"client_key_path"`
|
||||
ConnectTimeoutSecs int `json:"connect_timeout_secs"`
|
||||
}
|
||||
|
||||
type agentSession struct {
|
||||
mu sync.Mutex
|
||||
pool *nebula.ConnectionPool
|
||||
conn *nebula.Session
|
||||
params connectParams
|
||||
cursors map[string]*queryCursor
|
||||
nextCursorID uint64
|
||||
closed bool
|
||||
canceled atomic.Bool
|
||||
closePool sync.Once
|
||||
}
|
||||
|
||||
type runtimeServer struct {
|
||||
mu sync.RWMutex
|
||||
sessions map[string]*agentSession
|
||||
}
|
||||
|
||||
func main() {
|
||||
runtime := &runtimeServer{sessions: make(map[string]*agentSession)}
|
||||
encoder := json.NewEncoder(os.Stdout)
|
||||
var output sync.Mutex
|
||||
var running sync.WaitGroup
|
||||
fmt.Fprintln(os.Stdout, `{"ready":true}`)
|
||||
scanner := bufio.NewScanner(os.Stdin)
|
||||
scanner.Buffer(make([]byte, 0, 64*1024), 512*1024*1024)
|
||||
for scanner.Scan() {
|
||||
line := strings.TrimSpace(scanner.Text())
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
var envelope request
|
||||
if json.Unmarshal([]byte(line), &envelope) == nil && envelope.Method == "shutdown" {
|
||||
running.Wait()
|
||||
result := runtime.handleLine(line)
|
||||
output.Lock()
|
||||
_ = encoder.Encode(result)
|
||||
output.Unlock()
|
||||
return
|
||||
}
|
||||
running.Add(1)
|
||||
go func(line string) {
|
||||
defer running.Done()
|
||||
result := runtime.handleLine(line)
|
||||
output.Lock()
|
||||
defer output.Unlock()
|
||||
if err := encoder.Encode(result); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
}
|
||||
}(line)
|
||||
}
|
||||
running.Wait()
|
||||
if err := scanner.Err(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
}
|
||||
_ = runtime.closeAll()
|
||||
}
|
||||
|
||||
func (r *runtimeServer) handleLine(line string) response {
|
||||
var req request
|
||||
if err := json.Unmarshal([]byte(line), &req); err != nil {
|
||||
return errorResponse(nil, "", "", err)
|
||||
}
|
||||
if len(req.ID) == 0 {
|
||||
req.ID = json.RawMessage("1")
|
||||
}
|
||||
result, err := r.dispatch(req.Method, req.Params)
|
||||
if err != nil {
|
||||
return errorResponse(req.ID, req.Method, stringParam(req.Params, "agentSessionId"), err)
|
||||
}
|
||||
return response{JSONRPC: "2.0", ID: req.ID, Result: result}
|
||||
}
|
||||
|
||||
func (r *runtimeServer) dispatch(method string, params map[string]json.RawMessage) (any, error) {
|
||||
switch method {
|
||||
case "handshake":
|
||||
return map[string]any{
|
||||
"protocolVersion": 2, "agentProtocolVersion": 2,
|
||||
"capabilities": []string{"connect", "test_connection", "metadata", "query", "paged_query", "ddl", "multi_session", "structured_error_v1"},
|
||||
}, nil
|
||||
case "open_session", "connect":
|
||||
var options connectParams
|
||||
if err := decodeParams(params, &options); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id := stringParam(params, "agentSessionId")
|
||||
if method == "connect" {
|
||||
id = legacySessionID
|
||||
_ = r.closeSession(id)
|
||||
}
|
||||
if id == "" {
|
||||
return nil, errors.New("agentSessionId is required")
|
||||
}
|
||||
return map[string]bool{"ok": true}, r.openSession(id, options)
|
||||
case "test_connection":
|
||||
var options connectParams
|
||||
if err := decodeParams(params, &options); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
session, err := newAgentSession(options)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer session.close()
|
||||
return map[string]bool{"ok": true}, nil
|
||||
case "close_session", "disconnect":
|
||||
id := stringParam(params, "agentSessionId")
|
||||
if method == "disconnect" {
|
||||
id = legacySessionID
|
||||
}
|
||||
return map[string]bool{"ok": true}, r.closeSession(id)
|
||||
case "shutdown":
|
||||
return map[string]bool{"ok": true}, r.closeAll()
|
||||
case "cancel_session":
|
||||
session, err := r.session(stringParam(params, "agentSessionId"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
session.cancel()
|
||||
return map[string]bool{"ok": true}, nil
|
||||
}
|
||||
|
||||
id := stringParam(params, "agentSessionId")
|
||||
if id == "" {
|
||||
id = legacySessionID
|
||||
}
|
||||
session, err := r.session(id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
session.mu.Lock()
|
||||
defer session.mu.Unlock()
|
||||
if session.closed || session.canceled.Load() {
|
||||
return nil, errors.New("agent session is closed")
|
||||
}
|
||||
if method == "validate_session" || method == "validate_connection" {
|
||||
_, err := session.execute("SHOW SPACES", "")
|
||||
return map[string]bool{"ok": err == nil}, err
|
||||
}
|
||||
return session.dispatch(method, params)
|
||||
}
|
||||
|
||||
func (r *runtimeServer) openSession(id string, options connectParams) error {
|
||||
r.mu.Lock()
|
||||
if _, exists := r.sessions[id]; exists {
|
||||
r.mu.Unlock()
|
||||
return fmt.Errorf("agent session already exists: %s", id)
|
||||
}
|
||||
if len(r.sessions) >= maxSessions {
|
||||
r.mu.Unlock()
|
||||
return errors.New("agent session limit reached")
|
||||
}
|
||||
r.mu.Unlock()
|
||||
session, err := newAgentSession(options)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if _, exists := r.sessions[id]; exists {
|
||||
session.close()
|
||||
return fmt.Errorf("agent session already exists: %s", id)
|
||||
}
|
||||
if len(r.sessions) >= maxSessions {
|
||||
session.close()
|
||||
return errors.New("agent session limit reached")
|
||||
}
|
||||
r.sessions[id] = session
|
||||
return nil
|
||||
}
|
||||
|
||||
func newAgentSession(options connectParams) (*agentSession, error) {
|
||||
if options.DriverProfile != "" && !strings.EqualFold(options.DriverProfile, "nebula") && !strings.EqualFold(options.DriverProfile, "nebula-v3") {
|
||||
return nil, fmt.Errorf("unsupported NebulaGraph driver profile %q; only NebulaGraph 3.x is supported", options.DriverProfile)
|
||||
}
|
||||
if strings.TrimSpace(options.Host) == "" {
|
||||
return nil, errors.New("NebulaGraph graphd host is required")
|
||||
}
|
||||
if options.Port <= 0 || options.Port > 65535 {
|
||||
return nil, errors.New("NebulaGraph graphd port is invalid")
|
||||
}
|
||||
config := nebula.GetDefaultConf()
|
||||
config.MaxConnPoolSize = 1
|
||||
config.MinConnPoolSize = 1
|
||||
if options.ConnectTimeoutSecs > 0 {
|
||||
config.TimeOut = time.Duration(options.ConnectTimeoutSecs) * time.Second
|
||||
} else {
|
||||
config.TimeOut = 15 * time.Second
|
||||
}
|
||||
hosts := []nebula.HostAddress{{Host: options.Host, Port: options.Port}}
|
||||
var pool *nebula.ConnectionPool
|
||||
var err error
|
||||
if options.SSL {
|
||||
if options.CACertPath == "" || options.ClientCertPath == "" || options.ClientKeyPath == "" {
|
||||
return nil, errors.New("NebulaGraph TLS requires CA, client certificate and client key paths")
|
||||
}
|
||||
tlsConfig, tlsErr := nebula.GetDefaultSSLConfig(options.CACertPath, options.ClientCertPath, options.ClientKeyPath)
|
||||
if tlsErr != nil {
|
||||
return nil, tlsErr
|
||||
}
|
||||
pool, err = nebula.NewSslConnectionPool(hosts, config, tlsConfig, nebula.DefaultLogger{})
|
||||
} else {
|
||||
pool, err = nebula.NewConnectionPool(hosts, config, nebula.DefaultLogger{})
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conn, err := pool.GetSession(options.Username, options.Password)
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
return nil, err
|
||||
}
|
||||
session := &agentSession{pool: pool, conn: conn, params: options, cursors: make(map[string]*queryCursor)}
|
||||
if _, err := session.execute("SHOW SPACES", ""); err != nil {
|
||||
session.close()
|
||||
return nil, err
|
||||
}
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func (r *runtimeServer) session(id string) (*agentSession, error) {
|
||||
r.mu.RLock()
|
||||
session := r.sessions[id]
|
||||
r.mu.RUnlock()
|
||||
if session == nil {
|
||||
return nil, fmt.Errorf("agent session not found: %s", id)
|
||||
}
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func (r *runtimeServer) closeSession(id string) error {
|
||||
r.mu.Lock()
|
||||
session := r.sessions[id]
|
||||
delete(r.sessions, id)
|
||||
r.mu.Unlock()
|
||||
if session != nil {
|
||||
session.mu.Lock()
|
||||
session.close()
|
||||
session.mu.Unlock()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *runtimeServer) closeAll() error {
|
||||
r.mu.Lock()
|
||||
sessions := r.sessions
|
||||
r.sessions = make(map[string]*agentSession)
|
||||
r.mu.Unlock()
|
||||
for _, session := range sessions {
|
||||
session.mu.Lock()
|
||||
session.close()
|
||||
session.mu.Unlock()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *agentSession) cancel() {
|
||||
s.canceled.Store(true)
|
||||
s.closePool.Do(func() { s.pool.Close() })
|
||||
}
|
||||
|
||||
func (s *agentSession) close() {
|
||||
if s.closed {
|
||||
return
|
||||
}
|
||||
s.closed = true
|
||||
s.cursors = nil
|
||||
s.closePool.Do(func() {
|
||||
if !s.canceled.Load() {
|
||||
s.conn.Release()
|
||||
}
|
||||
s.pool.Close()
|
||||
})
|
||||
}
|
||||
|
||||
func decodeParams(params map[string]json.RawMessage, target any) error {
|
||||
data, err := json.Marshal(params)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return json.Unmarshal(data, target)
|
||||
}
|
||||
|
||||
func stringParam(params map[string]json.RawMessage, key string) string {
|
||||
var value string
|
||||
_ = json.Unmarshal(params[key], &value)
|
||||
return value
|
||||
}
|
||||
|
||||
func intParam(params map[string]json.RawMessage, key string) int {
|
||||
var value int
|
||||
_ = json.Unmarshal(params[key], &value)
|
||||
return value
|
||||
}
|
||||
|
||||
func stringSliceParam(params map[string]json.RawMessage, key string) []string {
|
||||
var values []string
|
||||
_ = json.Unmarshal(params[key], &values)
|
||||
return values
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
nebula "github.com/vesoft-inc/nebula-go/v3"
|
||||
wire "github.com/vesoft-inc/nebula-go/v3/nebula"
|
||||
"github.com/vesoft-inc/nebula-go/v3/nebula/graph"
|
||||
)
|
||||
|
||||
func resultSet(t *testing.T, names []string, rows [][]*wire.Value) *nebula.ResultSet {
|
||||
t.Helper()
|
||||
columns := make([][]byte, len(names))
|
||||
for index, name := range names {
|
||||
columns[index] = []byte(name)
|
||||
}
|
||||
data := &wire.DataSet{ColumnNames: columns}
|
||||
for _, row := range rows {
|
||||
data.Rows = append(data.Rows, &wire.Row{Values: row})
|
||||
}
|
||||
result, err := nebula.GenResultSet(&graph.ExecutionResponse{ErrorCode: wire.ErrorCode_SUCCEEDED, Data: data})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func TestHandshakeMatchesAgentProtocol(t *testing.T) {
|
||||
runtime := &runtimeServer{sessions: make(map[string]*agentSession)}
|
||||
response := runtime.handleLine(`{"jsonrpc":"2.0","id":7,"method":"handshake","params":{}}`)
|
||||
if response.Error != nil {
|
||||
t.Fatalf("unexpected handshake error: %#v", response.Error)
|
||||
}
|
||||
result := response.Result.(map[string]any)
|
||||
if result["protocolVersion"] != 2 {
|
||||
t.Fatalf("unexpected protocol: %#v", result)
|
||||
}
|
||||
capabilities := result["capabilities"].([]string)
|
||||
if !strings.Contains(strings.Join(capabilities, ","), "multi_session") {
|
||||
t.Fatalf("missing multi-session capability: %#v", capabilities)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDriverProfileSupportsV3AndLegacyConnections(t *testing.T) {
|
||||
for _, profile := range []string{"", "nebula", "nebula-v3"} {
|
||||
_, err := newAgentSession(connectParams{DriverProfile: profile})
|
||||
if err == nil || !strings.Contains(err.Error(), "graphd host is required") {
|
||||
t.Fatalf("profile %q unexpectedly rejected: %v", profile, err)
|
||||
}
|
||||
}
|
||||
_, err := newAgentSession(connectParams{DriverProfile: "nebula-v5"})
|
||||
if err == nil || !strings.Contains(err.Error(), "only NebulaGraph 3.x is supported") {
|
||||
t.Fatalf("unsupported profile was not rejected: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMissingSessionReturnsValidErrorContract(t *testing.T) {
|
||||
runtime := &runtimeServer{sessions: make(map[string]*agentSession)}
|
||||
response := runtime.handleLine(`{"jsonrpc":"2.0","id":7,"method":"execute_query","params":{"agentSessionId":"missing","sql":"SHOW SPACES"}}`)
|
||||
if response.Error == nil || response.Error.Data == nil {
|
||||
t.Fatalf("missing structured error: %#v", response)
|
||||
}
|
||||
data := response.Error.Data
|
||||
if data.ContractVersion != 1 || data.Stage != "execute" || data.OperationOutcome != "unknown" || data.AgentSessionID != "missing" || data.Category != "protocol" {
|
||||
t.Fatalf("invalid error contract: %#v", data)
|
||||
}
|
||||
if _, err := json.Marshal(response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQueryErrorClassifiesAsSQLWithoutSQLState(t *testing.T) {
|
||||
response := errorResponse(json.RawMessage("1"), "execute_query", "session-1", &nebulaQueryError{code: "-1004", message: "syntax error"})
|
||||
if response.Error.Data.Category != "sql" || response.Error.Data.SessionDisposition != "keep" {
|
||||
t.Fatalf("unexpected SQL error: %#v", response.Error)
|
||||
}
|
||||
if !strings.Contains(response.Error.Message, "-1004") {
|
||||
t.Fatalf("NebulaGraph error code missing: %q", response.Error.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuoteNebulaIdentifier(t *testing.T) {
|
||||
quoted, err := quoteNebulaIdentifier("edge`name\\part")
|
||||
if err != nil || quoted != "`edge\\`name\\\\part`" {
|
||||
t.Fatalf("quoted = %q, err = %v", quoted, err)
|
||||
}
|
||||
if _, err := quoteNebulaIdentifier("a\nb"); err == nil {
|
||||
t.Fatal("control characters must not be accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadRowsPreservesScalarAndGraphValues(t *testing.T) {
|
||||
count := int64(42)
|
||||
nullValue := wire.NullType___NULL__
|
||||
value := resultSet(t, []string{"name", "count", "missing"}, [][]*wire.Value{{
|
||||
{SVal: []byte("Ada")}, {IVal: &count}, {NVal: &nullValue},
|
||||
}})
|
||||
rows, types, err := readRows(value, 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(rows, [][]any{{"Ada", "42", nil}}) || !reflect.DeepEqual(types, []string{"string", "int", "Unknown"}) {
|
||||
t.Fatalf("rows=%#v types=%#v", rows, types)
|
||||
}
|
||||
metadata, err := metadataRows(value)
|
||||
if err != nil || metadata[0]["name"] != "Ada" || metadata[0]["count"] != "42" {
|
||||
t.Fatalf("metadata=%#v err=%v", metadata, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchQueryPageAdvancesWithoutReexecuting(t *testing.T) {
|
||||
session := &agentSession{cursors: map[string]*queryCursor{
|
||||
"page-1": {result: queryResult{Columns: []string{"n"}, ColumnTypes: []string{"int"}, Rows: [][]any{{"1"}, {"2"}, {"3"}}}, offset: 1},
|
||||
}}
|
||||
page, err := session.fetchQueryPage("page-1", 1)
|
||||
if err != nil || !page.HasMore || !reflect.DeepEqual(page.Rows, [][]any{{"2"}}) {
|
||||
t.Fatalf("page=%#v err=%v", page, err)
|
||||
}
|
||||
last, err := session.fetchQueryPage("page-1", 1)
|
||||
if err != nil || last.HasMore || !reflect.DeepEqual(last.Rows, [][]any{{"3"}}) || len(session.cursors) != 0 {
|
||||
t.Fatalf("last=%#v err=%v cursors=%d", last, err, len(session.cursors))
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetadataKindsRemainSeparate(t *testing.T) {
|
||||
if !acceptsObjectType([]string{"TABLE"}, "TABLE") || acceptsObjectType([]string{"TABLE"}, "VIEW") {
|
||||
t.Fatal("tag and edge types were mixed")
|
||||
}
|
||||
if !acceptsObjectType([]string{"EDGE"}, "VIEW") || !acceptsObjectType(nil, "TABLE") {
|
||||
t.Fatal("edge alias or unrestricted metadata lookup failed")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
nebula "github.com/vesoft-inc/nebula-go/v3"
|
||||
)
|
||||
|
||||
type databaseInfo struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type tableInfo struct {
|
||||
Name string `json:"name"`
|
||||
TableType string `json:"table_type"`
|
||||
Comment *string `json:"comment"`
|
||||
}
|
||||
|
||||
type objectInfo struct {
|
||||
Name string `json:"name"`
|
||||
ObjectType string `json:"object_type"`
|
||||
Schema string `json:"schema"`
|
||||
Comment *string `json:"comment"`
|
||||
}
|
||||
|
||||
type columnInfo struct {
|
||||
Name string `json:"name"`
|
||||
DataType string `json:"data_type"`
|
||||
IsNullable bool `json:"is_nullable"`
|
||||
ColumnDefault *string `json:"column_default"`
|
||||
IsPrimaryKey bool `json:"is_primary_key"`
|
||||
Extra *string `json:"extra"`
|
||||
Comment *string `json:"comment"`
|
||||
NumericPrecision *int `json:"numeric_precision"`
|
||||
NumericScale *int `json:"numeric_scale"`
|
||||
CharacterMaximumLength *int `json:"character_maximum_length"`
|
||||
}
|
||||
|
||||
type objectSource struct {
|
||||
Name string `json:"name"`
|
||||
ObjectType string `json:"object_type"`
|
||||
Schema *string `json:"schema"`
|
||||
Source string `json:"source"`
|
||||
}
|
||||
|
||||
func (s *agentSession) listDatabases() ([]databaseInfo, error) {
|
||||
result, err := s.execute("SHOW SPACES", "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows, err := metadataRows(result)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
spaces := make([]databaseInfo, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
name := firstMetadataValue(row, "Name")
|
||||
if name != "" {
|
||||
spaces = append(spaces, databaseInfo{Name: name})
|
||||
}
|
||||
}
|
||||
sort.Slice(spaces, func(i, j int) bool { return spaces[i].Name < spaces[j].Name })
|
||||
return spaces, nil
|
||||
}
|
||||
|
||||
func (s *agentSession) listTables(params map[string]json.RawMessage) ([]tableInfo, error) {
|
||||
space := selectedSpace(stringParam(params, "database"), s.params.Database)
|
||||
if space == "" {
|
||||
return []tableInfo{}, nil
|
||||
}
|
||||
filter := strings.ToLower(strings.TrimSpace(stringParam(params, "filter")))
|
||||
requestedTypes := stringSliceParam(params, "object_types")
|
||||
if len(requestedTypes) == 0 {
|
||||
requestedTypes = stringSliceParam(params, "objectTypes")
|
||||
}
|
||||
tables := make([]tableInfo, 0)
|
||||
for _, kind := range []struct{ typeName, statement string }{{"TABLE", "SHOW TAGS"}, {"VIEW", "SHOW EDGES"}} {
|
||||
if !acceptsObjectType(requestedTypes, kind.typeName) {
|
||||
continue
|
||||
}
|
||||
result, err := s.execute(kind.statement, space)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows, err := metadataRows(result)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, row := range rows {
|
||||
name := firstMetadataValue(row, "Name")
|
||||
if name != "" && strings.Contains(strings.ToLower(name), filter) {
|
||||
tables = append(tables, tableInfo{Name: name, TableType: kind.typeName})
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Slice(tables, func(i, j int) bool {
|
||||
if tables[i].TableType != tables[j].TableType {
|
||||
return tables[i].TableType < tables[j].TableType
|
||||
}
|
||||
return tables[i].Name < tables[j].Name
|
||||
})
|
||||
offset, limit := intParam(params, "offset"), intParam(params, "limit")
|
||||
if offset < 0 {
|
||||
offset = 0
|
||||
}
|
||||
if offset >= len(tables) {
|
||||
return []tableInfo{}, nil
|
||||
}
|
||||
tables = tables[offset:]
|
||||
if limit > 0 && limit < len(tables) {
|
||||
tables = tables[:limit]
|
||||
}
|
||||
return tables, nil
|
||||
}
|
||||
|
||||
func (s *agentSession) listObjects(params map[string]json.RawMessage) ([]objectInfo, error) {
|
||||
tables, err := s.listTables(params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
objects := make([]objectInfo, 0, len(tables))
|
||||
for _, table := range tables {
|
||||
objects = append(objects, objectInfo{Name: table.Name, ObjectType: table.TableType, Schema: ""})
|
||||
}
|
||||
return objects, nil
|
||||
}
|
||||
|
||||
func (s *agentSession) getColumns(database, name string) ([]columnInfo, error) {
|
||||
space := selectedSpace(database, s.params.Database)
|
||||
if space == "" {
|
||||
return nil, errors.New("select a NebulaGraph space before reading object columns")
|
||||
}
|
||||
quoted, err := quoteNebulaIdentifier(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, err := s.execute("DESCRIBE TAG "+quoted, space)
|
||||
if err != nil {
|
||||
result, err = s.execute("DESCRIBE EDGE "+quoted, space)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
rows, err := metadataRows(result)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
columns := make([]columnInfo, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
field := firstMetadataValue(row, "Field")
|
||||
if field == "" {
|
||||
continue
|
||||
}
|
||||
columns = append(columns, columnInfo{
|
||||
Name: field, DataType: firstMetadataValue(row, "Type"),
|
||||
IsNullable: !strings.EqualFold(firstMetadataValue(row, "Null"), "NO"),
|
||||
ColumnDefault: optionalMetadataValue(row, "Default"), Comment: optionalMetadataValue(row, "Comment"),
|
||||
})
|
||||
}
|
||||
return columns, nil
|
||||
}
|
||||
|
||||
func (s *agentSession) getTableDDL(database, name, objectType string) (string, error) {
|
||||
space := selectedSpace(database, s.params.Database)
|
||||
if space == "" {
|
||||
return "", errors.New("select a NebulaGraph space before reading object DDL")
|
||||
}
|
||||
quoted, err := quoteNebulaIdentifier(name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
kinds := []string{"TAG", "EDGE"}
|
||||
if strings.EqualFold(objectType, "VIEW") || strings.EqualFold(objectType, "EDGE") {
|
||||
kinds = []string{"EDGE"}
|
||||
}
|
||||
for _, kind := range kinds {
|
||||
result, queryErr := s.execute("SHOW CREATE "+kind+" "+quoted, space)
|
||||
if queryErr != nil {
|
||||
if kind == kinds[len(kinds)-1] {
|
||||
return "", queryErr
|
||||
}
|
||||
continue
|
||||
}
|
||||
rows, readErr := metadataRows(result)
|
||||
if readErr != nil {
|
||||
return "", readErr
|
||||
}
|
||||
if len(rows) > 0 {
|
||||
for key, value := range rows[0] {
|
||||
if strings.HasPrefix(strings.ToLower(key), "create ") {
|
||||
return value, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func (s *agentSession) getObjectSource(params map[string]json.RawMessage) (objectSource, error) {
|
||||
name := stringParam(params, "name")
|
||||
objectType := strings.ToUpper(stringParam(params, "object_type"))
|
||||
if objectType == "" {
|
||||
objectType = strings.ToUpper(stringParam(params, "objectType"))
|
||||
}
|
||||
source, err := s.getTableDDL(stringParam(params, "database"), name, objectType)
|
||||
if err != nil {
|
||||
return objectSource{}, err
|
||||
}
|
||||
return objectSource{Name: name, ObjectType: objectType, Source: source}, nil
|
||||
}
|
||||
|
||||
func selectedSpace(requested, configured string) string {
|
||||
if strings.TrimSpace(requested) != "" {
|
||||
return strings.TrimSpace(requested)
|
||||
}
|
||||
return strings.TrimSpace(configured)
|
||||
}
|
||||
|
||||
func quoteNebulaIdentifier(name string) (string, error) {
|
||||
if name == "" || strings.IndexFunc(name, unicode.IsControl) >= 0 {
|
||||
return "", fmt.Errorf("invalid NebulaGraph identifier: %q", name)
|
||||
}
|
||||
escaped := strings.ReplaceAll(strings.ReplaceAll(name, `\`, `\\`), "`", "\\`")
|
||||
return "`" + escaped + "`", nil
|
||||
}
|
||||
|
||||
func acceptsObjectType(requested []string, kind string) bool {
|
||||
if len(requested) == 0 {
|
||||
return true
|
||||
}
|
||||
for _, candidate := range requested {
|
||||
if strings.EqualFold(candidate, kind) || (kind == "TABLE" && strings.EqualFold(candidate, "TAG")) || (kind == "VIEW" && strings.EqualFold(candidate, "EDGE")) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func metadataRows(result *nebula.ResultSet) ([]map[string]string, error) {
|
||||
columns := result.GetColNames()
|
||||
rows := make([]map[string]string, 0, len(result.GetRows()))
|
||||
for index := range result.GetRows() {
|
||||
record, err := result.GetRowValuesByIndex(index)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
row := make(map[string]string, len(columns))
|
||||
for column, name := range columns {
|
||||
value, err := record.GetValueByIndex(column)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if normalized := normalizeValue(value); normalized != nil {
|
||||
row[name] = fmt.Sprint(normalized)
|
||||
}
|
||||
}
|
||||
rows = append(rows, row)
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
func firstMetadataValue(row map[string]string, name string) string {
|
||||
for key, value := range row {
|
||||
if strings.EqualFold(key, name) {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func optionalMetadataValue(row map[string]string, name string) *string {
|
||||
value := firstMetadataValue(row, name)
|
||||
if value == "" || strings.EqualFold(value, "NULL") {
|
||||
return nil
|
||||
}
|
||||
return &value
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type rpcError struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Data *rpcErrorData `json:"data"`
|
||||
}
|
||||
|
||||
type rpcErrorData struct {
|
||||
ContractVersion int `json:"contractVersion"`
|
||||
Category string `json:"category"`
|
||||
Retryable bool `json:"retryable"`
|
||||
SessionDisposition string `json:"sessionDisposition"`
|
||||
Stage string `json:"stage"`
|
||||
OperationOutcome string `json:"operationOutcome"`
|
||||
AgentSessionID string `json:"agentSessionId,omitempty"`
|
||||
}
|
||||
|
||||
func errorResponse(id json.RawMessage, method, sessionID string, err error) response {
|
||||
stage := errorStage(method)
|
||||
data := &rpcErrorData{
|
||||
ContractVersion: 1, Category: "protocol", SessionDisposition: "keep",
|
||||
Stage: stage, OperationOutcome: errorOutcome(stage), AgentSessionID: strings.TrimSpace(sessionID),
|
||||
}
|
||||
var queryError *nebulaQueryError
|
||||
if errors.As(err, &queryError) {
|
||||
if stage == "execute" || stage == "fetch" {
|
||||
data.Category = "sql"
|
||||
} else {
|
||||
data.Category = "connection"
|
||||
}
|
||||
} else if errors.Is(err, io.EOF) || isNetworkError(err) {
|
||||
data.Category = "connection"
|
||||
data.Retryable = stage == "connect" || stage == "validate"
|
||||
if stage == "execute" || stage == "fetch" {
|
||||
data.SessionDisposition = "quarantine"
|
||||
}
|
||||
}
|
||||
return response{JSONRPC: "2.0", ID: id, Error: &rpcError{Code: -1, Message: err.Error(), Data: data}}
|
||||
}
|
||||
|
||||
func errorStage(method string) string {
|
||||
switch method {
|
||||
case "open_session", "connect", "test_connection":
|
||||
return "connect"
|
||||
case "validate_session", "validate_connection":
|
||||
return "validate"
|
||||
case "fetch_query_page", "fetch_table_read_page":
|
||||
return "fetch"
|
||||
case "cancel_session":
|
||||
return "cancel"
|
||||
case "close_session", "disconnect", "close_query_session", "close_table_read_session", "shutdown":
|
||||
return "close"
|
||||
case "handshake", "":
|
||||
return "request"
|
||||
default:
|
||||
return "execute"
|
||||
}
|
||||
}
|
||||
|
||||
func errorOutcome(stage string) string {
|
||||
if stage == "request" || stage == "connect" || stage == "validate" {
|
||||
return "not_started"
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
func isNetworkError(err error) bool {
|
||||
var networkError net.Error
|
||||
return errors.As(err, &networkError)
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
nebula "github.com/vesoft-inc/nebula-go/v3"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultMaxRows = 10000
|
||||
maxQueryRows = 100000
|
||||
defaultPage = 1000
|
||||
)
|
||||
|
||||
type queryOptions struct {
|
||||
SQL string `json:"sql"`
|
||||
Database string `json:"database"`
|
||||
MaxRows int `json:"maxRows"`
|
||||
TimeoutSecs int `json:"timeoutSecs"`
|
||||
}
|
||||
|
||||
type queryResult struct {
|
||||
Columns []string `json:"columns"`
|
||||
ColumnTypes []string `json:"column_types"`
|
||||
Rows [][]any `json:"rows"`
|
||||
AffectedRows int64 `json:"affected_rows"`
|
||||
ExecutionTimeMS int64 `json:"execution_time_ms"`
|
||||
Truncated bool `json:"truncated"`
|
||||
}
|
||||
|
||||
type queryPageResult struct {
|
||||
queryResult
|
||||
SessionID *string `json:"session_id"`
|
||||
HasMore bool `json:"has_more"`
|
||||
}
|
||||
|
||||
type queryCursor struct {
|
||||
result queryResult
|
||||
offset int
|
||||
}
|
||||
|
||||
func (s *agentSession) dispatch(method string, params map[string]json.RawMessage) (any, error) {
|
||||
switch method {
|
||||
case "connection_info":
|
||||
return map[string]any{
|
||||
"database": s.params.Database, "schema": "", "username": s.params.Username,
|
||||
"identifierQuote": "`", "compatibilityMode": "ngql",
|
||||
"databaseInfo": map[string]string{
|
||||
"productName": "NebulaGraph", "driverName": "NebulaGraph Go Client", "driverVersion": "3.8.0",
|
||||
"unquotedIdentifierCase": "mixed", "quotedIdentifierCase": "mixed",
|
||||
},
|
||||
}, nil
|
||||
case "list_databases":
|
||||
return s.listDatabases()
|
||||
case "list_schemas":
|
||||
return []string{}, nil
|
||||
case "list_tables":
|
||||
return s.listTables(params)
|
||||
case "list_objects":
|
||||
return s.listObjects(params)
|
||||
case "list_data_types":
|
||||
return []string{"bool", "int8", "int16", "int32", "int64", "float", "double", "string", "fixed_string", "date", "time", "datetime", "timestamp", "duration", "geography"}, nil
|
||||
case "get_columns":
|
||||
return s.getColumns(stringParam(params, "database"), stringParam(params, "table"))
|
||||
case "get_table_ddl":
|
||||
return s.getTableDDL(stringParam(params, "database"), stringParam(params, "table"), "")
|
||||
case "get_object_source":
|
||||
return s.getObjectSource(params)
|
||||
case "get_table_comment":
|
||||
return nil, nil
|
||||
case "list_indexes", "list_foreign_keys", "list_triggers", "list_constraints", "list_partitions", "list_subpartitions":
|
||||
return []any{}, nil
|
||||
case "get_explain_info":
|
||||
return map[string]any{"plan": "", "has_actual_stats": false}, nil
|
||||
case "execute_query":
|
||||
var options queryOptions
|
||||
if err := decodeParams(params, &options); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.executeQuery(options)
|
||||
case "execute_query_page", "start_table_read":
|
||||
var options queryOptions
|
||||
if err := decodeParams(params, &options); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.executeQueryPage(options, intParam(params, "pageSize"))
|
||||
case "fetch_query_page", "fetch_table_read_page":
|
||||
return s.fetchQueryPage(stringParam(params, "sessionId"), intParam(params, "pageSize"))
|
||||
case "close_query_session", "close_table_read_session":
|
||||
delete(s.cursors, stringParam(params, "sessionId"))
|
||||
return map[string]bool{"ok": true}, nil
|
||||
case "execute_batch":
|
||||
started := time.Now()
|
||||
for _, statement := range stringSliceParam(params, "statements") {
|
||||
_, err := s.executeQuery(queryOptions{SQL: statement, Database: stringParam(params, "database")})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return queryResult{Columns: []string{}, ColumnTypes: []string{}, Rows: [][]any{}, ExecutionTimeMS: time.Since(started).Milliseconds()}, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported NebulaGraph agent method: %s", method)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *agentSession) execute(statement, space string) (*nebula.ResultSet, error) {
|
||||
if s.canceled.Load() {
|
||||
return nil, errors.New("agent session was canceled")
|
||||
}
|
||||
if space = strings.TrimSpace(space); space != "" {
|
||||
quoted, err := quoteNebulaIdentifier(space)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
selected, err := s.conn.Execute("USE " + quoted)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := resultError(selected); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
result, err := s.conn.Execute(statement)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := resultError(result); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *agentSession) executeQuery(options queryOptions) (queryResult, error) {
|
||||
started := time.Now()
|
||||
statement := strings.TrimSpace(options.SQL)
|
||||
if statement == "" {
|
||||
return queryResult{Columns: []string{}, ColumnTypes: []string{}, Rows: [][]any{}}, nil
|
||||
}
|
||||
space := options.Database
|
||||
if space == "" {
|
||||
space = s.params.Database
|
||||
}
|
||||
result, err := s.execute(statement, space)
|
||||
if err != nil {
|
||||
return queryResult{}, err
|
||||
}
|
||||
rows, types, err := readRows(result, effectiveMaxRows(options.MaxRows))
|
||||
if err != nil {
|
||||
return queryResult{}, err
|
||||
}
|
||||
return queryResult{
|
||||
Columns: result.GetColNames(), ColumnTypes: types, Rows: rows,
|
||||
ExecutionTimeMS: time.Since(started).Milliseconds(), Truncated: len(result.GetRows()) > len(rows),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *agentSession) executeQueryPage(options queryOptions, pageSize int) (queryPageResult, error) {
|
||||
result, err := s.executeQuery(options)
|
||||
if err != nil {
|
||||
return queryPageResult{}, err
|
||||
}
|
||||
if pageSize <= 0 {
|
||||
pageSize = defaultPage
|
||||
}
|
||||
if pageSize >= len(result.Rows) {
|
||||
return queryPageResult{queryResult: result}, nil
|
||||
}
|
||||
s.nextCursorID++
|
||||
id := fmt.Sprintf("nebula-query-%d", s.nextCursorID)
|
||||
s.cursors[id] = &queryCursor{result: result, offset: pageSize}
|
||||
result.Rows = result.Rows[:pageSize]
|
||||
return queryPageResult{queryResult: result, SessionID: &id, HasMore: true}, nil
|
||||
}
|
||||
|
||||
func (s *agentSession) fetchQueryPage(id string, pageSize int) (queryPageResult, error) {
|
||||
cursor := s.cursors[id]
|
||||
if cursor == nil {
|
||||
return queryPageResult{}, fmt.Errorf("query session not found: %s", id)
|
||||
}
|
||||
if pageSize <= 0 {
|
||||
pageSize = defaultPage
|
||||
}
|
||||
end := min(cursor.offset+pageSize, len(cursor.result.Rows))
|
||||
result := cursor.result
|
||||
result.Rows = result.Rows[cursor.offset:end]
|
||||
cursor.offset = end
|
||||
if end == len(cursor.result.Rows) {
|
||||
delete(s.cursors, id)
|
||||
return queryPageResult{queryResult: result}, nil
|
||||
}
|
||||
return queryPageResult{queryResult: result, SessionID: &id, HasMore: true}, nil
|
||||
}
|
||||
|
||||
func effectiveMaxRows(requested int) int {
|
||||
if requested <= 0 {
|
||||
return defaultMaxRows
|
||||
}
|
||||
return min(requested, maxQueryRows)
|
||||
}
|
||||
|
||||
func readRows(result *nebula.ResultSet, limit int) ([][]any, []string, error) {
|
||||
columns := result.GetColNames()
|
||||
rows := make([][]any, 0, min(len(result.GetRows()), limit))
|
||||
types := make([]string, len(columns))
|
||||
for i := range types {
|
||||
types[i] = "Unknown"
|
||||
}
|
||||
for index := 0; index < len(result.GetRows()) && index < limit; index++ {
|
||||
record, err := result.GetRowValuesByIndex(index)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
row := make([]any, len(columns))
|
||||
for column := range columns {
|
||||
value, err := record.GetValueByIndex(column)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if types[column] == "Unknown" && value.GetType() != "null" {
|
||||
types[column] = value.GetType()
|
||||
}
|
||||
row[column] = normalizeValue(value)
|
||||
}
|
||||
rows = append(rows, row)
|
||||
}
|
||||
return rows, types, nil
|
||||
}
|
||||
|
||||
func normalizeValue(value *nebula.ValueWrapper) any {
|
||||
if value == nil || value.GetType() == "null" {
|
||||
return nil
|
||||
}
|
||||
if value.GetType() == "string" {
|
||||
if text, err := value.AsString(); err == nil {
|
||||
return text
|
||||
}
|
||||
}
|
||||
return value.String()
|
||||
}
|
||||
|
||||
type nebulaQueryError struct {
|
||||
code string
|
||||
message string
|
||||
}
|
||||
|
||||
func (err *nebulaQueryError) Error() string {
|
||||
return fmt.Sprintf("NebulaGraph error %s: %s", err.code, err.message)
|
||||
}
|
||||
|
||||
func resultError(result *nebula.ResultSet) error {
|
||||
if result == nil {
|
||||
return errors.New("NebulaGraph returned no result")
|
||||
}
|
||||
if !result.IsSucceed() {
|
||||
return &nebulaQueryError{code: fmt.Sprint(result.GetErrorCode()), message: result.GetErrorMsg()}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in new issue
Block a user