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

psdbconnect client #18

Draft
wants to merge 1 commit into
base: psdb-namespace
Choose a base branch
from
Draft
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
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)
})
}
}