Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for SQL #131

Merged
merged 1 commit into from
Mar 9, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions version.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package semver

import (
"bytes"
"database/sql/driver"
"encoding/json"
"errors"
"fmt"
Expand Down Expand Up @@ -435,6 +436,28 @@ func (v Version) MarshalJSON() ([]byte, error) {
return json.Marshal(v.String())
}

// Scan implements the SQL.Scanner interface.
func (v *Version) Scan(value interface{}) error {
var s string
s, _ = value.(string)
temp, err := NewVersion(s)
if err != nil {
return err
}
v.major = temp.major
v.minor = temp.minor
v.patch = temp.patch
v.pre = temp.pre
v.metadata = temp.metadata
v.original = temp.original
return nil
}

// Value implements the Driver.Valuer interface.
func (v Version) Value() (driver.Value, error) {
return v.String(), nil
}

func compareSegment(v, o uint64) int {
if v < o {
return -1
Expand Down
36 changes: 36 additions & 0 deletions version_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package semver

import (
"database/sql"
"encoding/json"
"fmt"
"testing"
Expand Down Expand Up @@ -541,6 +542,41 @@ func TestJsonUnmarshal(t *testing.T) {
}
}

func TestSQLScanner(t *testing.T) {
sVer := "1.1.1"
x, err := StrictNewVersion(sVer)
if err != nil {
t.Errorf("Error creating version: %s", err)
}
var s sql.Scanner = x
var out *Version
var ok bool
if out, ok = s.(*Version); !ok {
t.Errorf("Error expected Version type, got=%T want=%T", s, Version{})
}
got := out.String()
want := sVer
if got != want {
t.Errorf("Error sql scanner unexpected scan content: got=%q want=%q", got, want)
}
}

func TestDriverValuer(t *testing.T) {
sVer := "1.1.1"
x, err := StrictNewVersion(sVer)
if err != nil {
t.Errorf("Error creating version: %s", err)
}
got, err := x.Value()
if err != nil {
t.Fatalf("Error getting value, got %v", err)
}
want := sVer
if got != want {
t.Errorf("Error driver valuer unexpected value content: got=%q want=%q", got, want)
}
}

func TestValidatePrerelease(t *testing.T) {
tests := []struct {
pre string
Expand Down