Skip to content

Commit

Permalink
get the sql driver version
Browse files Browse the repository at this point in the history
  • Loading branch information
shogo82148 committed Apr 26, 2022
1 parent a13045e commit fe8f9d8
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 16 deletions.
1 change: 1 addition & 0 deletions xray/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ func getVersion() string {
// search the most specific module
if strings.HasPrefix(pkg, dep.Path) && len(dep.Path) > depth {
version = dep.Version
depth = len(dep.Path)
}
}
return version
Expand Down
4 changes: 3 additions & 1 deletion xray/plugin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ func TestAddPlugin(t *testing.T) {
var wg sync.WaitGroup
wg.Add(n)
for i := 0; i < n; i++ {
go AddPlugin(&xrayPlugin{})
go AddPlugin(&xrayPlugin{
sdkVersion: getVersion(),
})
go getPlugins()
}

Expand Down
46 changes: 31 additions & 15 deletions xraysql/connector.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ import (
"fmt"
"io"
"reflect"
"runtime/debug"
"strconv"
"strings"
"sync"
"time"

Expand Down Expand Up @@ -172,21 +174,7 @@ func newDBAttribute(ctx context.Context, driverName string, d driver.Driver, con
}
}

// There's no standard to get SQL driver version information
// So we invent an interface by which drivers can provide us this data
type versionedDriver interface {
Version() string
}

if vd, ok := d.(versionedDriver); ok {
attr.driverVersion = vd.Version()
} else {
t := reflect.TypeOf(d)
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
attr.driverVersion = t.PkgPath()
}
attr.driverVersion = getDriverVersion(d)
if driverName != "" {
attr.name = attr.dbname + "@" + driverName
} else {
Expand All @@ -205,6 +193,34 @@ func newDBAttribute(ctx context.Context, driverName string, d driver.Driver, con
return &attr, nil
}

func getDriverVersion(d driver.Driver) string {
t := reflect.TypeOf(d)
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
pkg := t.PkgPath()

info, ok := debug.ReadBuildInfo()
if !ok {
return pkg
}

version := ""
depth := 0
for _, dep := range info.Deps {
// search the most specific module
if strings.HasPrefix(pkg, dep.Path) && len(dep.Path) > depth {
version = dep.Version
depth = len(dep.Path)
}
}

if version == "" {
return pkg
}
return pkg + "@" + version
}

func postgresDetector(ctx context.Context, conn driver.Conn, attr *dbAttribute) error {
var databaseVersion, user, dbname string
err := queryRow(
Expand Down

0 comments on commit fe8f9d8

Please sign in to comment.