diff --git a/client.go b/client.go new file mode 100644 index 0000000..065f280 --- /dev/null +++ b/client.go @@ -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)) +} diff --git a/config.go b/config.go new file mode 100644 index 0000000..665c270 --- /dev/null +++ b/config.go @@ -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 +} diff --git a/config_test.go b/config_test.go new file mode 100644 index 0000000..306cbb3 --- /dev/null +++ b/config_test.go @@ -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:bar@example.com/", Config{"example.com", "foo", "bar"}}, + {"mysql://foo@example.com/", Config{"example.com", "foo", ""}}, + {"mysql://foo:bar@example.com: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) + }) + } +}