Skip to content

Commit

Permalink
psdb client
Browse files Browse the repository at this point in the history
  • Loading branch information
mattrobenolt committed Feb 27, 2023
1 parent 79303c6 commit 0c5b82c
Show file tree
Hide file tree
Showing 3 changed files with 88 additions and 0 deletions.
42 changes: 42 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package psdb

import (
"context"

"github.com/bufbuild/connect-go"
"github.com/planetscale/psdb/auth"
coreclient "github.com/planetscale/psdb/core/client"
psdbv1 "github.com/planetscale/psdb/types/psdb/v1"
"github.com/planetscale/psdb/types/psdb/v1/psdbv1connect"
)

type (
TableCursor = psdbv1.TableCursor
SyncStream = connect.ServerStreamForClient[psdbv1.SyncResponse]
SyncRequest = psdbv1.SyncRequest
)

const (
Primary = psdbv1.TabletType_primary
Replica = psdbv1.TabletType_replica
)

// Client is a PlanetScale Database client
type Client struct {
core psdbv1connect.DatabaseClient
}

// New creates a new Client with the provided Config
func New(cfg Config) *Client {
return &Client{
core: coreclient.New(
cfg.Host,
psdbv1connect.NewDatabaseClient,
auth.NewBasicAuth(cfg.User, cfg.Password),
),
}
}

func (c *Client) Sync(ctx context.Context, r *SyncRequest) (*SyncStream, error) {
return c.core.Sync(ctx, connect.NewRequest(r))
}
20 changes: 20 additions & 0 deletions config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package psdb

import "net/url"

// Config is a PlanetScale connection configuration
type Config struct {
Host string
User string
Password string
}

func ConfigFromURL(rawURL string) Config {
var cfg Config
if u, err := url.Parse(rawURL); err == nil {
cfg.Host = u.Host
cfg.User = u.User.Username()
cfg.Password, _ = u.User.Password()
}
return cfg
}
26 changes: 26 additions & 0 deletions config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package psdb

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestConfigFromURL(t *testing.T) {
cases := []struct {
in string
cfg Config
}{
{"mysql://foo:[email protected]/", Config{"example.com", "foo", "bar"}},
{"mysql://[email protected]/", Config{"example.com", "foo", ""}},
{"mysql://foo:[email protected]:9999", Config{"example.com:9999", "foo", "bar"}},
{"", Config{}},
}

for _, c := range cases {
t.Run(c.in, func(t *testing.T) {
cfg := ConfigFromURL(c.in)
assert.Equal(t, cfg, c.cfg)
})
}
}

0 comments on commit 0c5b82c

Please sign in to comment.