Skip to content

Commit

Permalink
client/tailsql: add a convenience type for string-wrapped JSON text
Browse files Browse the repository at this point in the history
  • Loading branch information
creachadair committed Oct 27, 2023
1 parent bf55ea3 commit 713b6cd
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
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 to be decoded 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)
}
})
}

0 comments on commit 713b6cd

Please sign in to comment.