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

client/tailsql: add a convenience type for string-wrapped JSON text #19

Closed
wants to merge 1 commit into from
Closed
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
13 changes: 13 additions & 0 deletions client/tailsql/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,19 @@ func QueryJSON[T any](ctx context.Context, c Client, dataSrc, sql string) ([]T,
}
}

// JSONString is a wrapper type that decodes JSON text encoded as a string
// value into plain JSON text.
type JSONString []byte

// UnmarshalText implements the encoding.TextUnmarshaler interface for JSON
// text encoded inside a JSON string value.
func (js *JSONString) UnmarshalText(data []byte) error {
return json.Unmarshal(data, (*json.RawMessage)(js))
}

// MarshalText encodes a JSON text into a JSON string value.
func (js JSONString) MarshalText() ([]byte, error) { return []byte(js), nil }

// Rows is the result of a successful Query call.
type Rows struct {
Columns []string // column names
Expand Down
47 changes: 47 additions & 0 deletions client/tailsql/client_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package tailsql_test

import (
"bytes"
"context"
"database/sql"
"encoding/json"
"net/http/httptest"
"path/filepath"
"testing"
Expand Down Expand Up @@ -143,3 +145,48 @@ func TestClient(t *testing.T) {
}
})
}

func TestJSONString(t *testing.T) {
var tdata = struct {
S string `json:"foo"`
Z int `json:"bar"`
B bool `json:"baz"`
}{S: "hello", Z: 1337, B: true}

tjson, err := json.Marshal(tdata)
if err != nil {
t.Fatalf("Encode test data: %v", err)
}

t.Run("Encode", func(t *testing.T) {
const want = `"{\"foo\":\"hello\",\"bar\":1337,\"baz\":true}"`
enc, err := json.Marshal(tailsql.JSONString(tjson))
if err != nil {
t.Fatalf("Encode failed: %v", err)
}
if got := string(enc); got != want {
t.Errorf("Encode: got %#q, want %#q", got, want)
}
})

// Verify that we can round-trip through a string.
t.Run("RoundTrip", func(t *testing.T) {
enc, err := json.Marshal(struct {
V tailsql.JSONString
}{V: tjson})
if err != nil {
t.Fatalf("Encode wrapper: %v", err)
}

var dec struct {
V tailsql.JSONString
}
if err := json.Unmarshal(enc, &dec); err != nil {
t.Fatalf("Decode wrapper: %v", err)
}

if !bytes.Equal(dec.V, tjson) {
t.Fatalf("Decoded string: got %#q, want %#q", dec.V, tjson)
}
})
}