astra

package module
v0.0.0-...-da2d673 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 9, 2022 License: Apache-2.0 Imports: 30 Imported by: 0

README

Datastax Astra Go SDK

License Apache2 Go Report Card Go Reference

Software Development Kit wrapping Astra APIs and drivers.

Overview

TODO

Development

Testing

To run fast unit tests:

go test ./... -run ^Test -test.short

To run all unit tests, integration tests, and examples:

go test ./...

These tests rely on test containers, and require a running Docker daemon to work properly.

To run all tests online:

go test ./... \
  -test_scb_path=<path/to/secure-connect-bundle.zip> \
  -test_token=<AstraCS:...>

Documentation

Overview

Package astra provides the Go SDK for developing applications on the Datastax Astra platform.

Connecting

The Astra Go SDK provides two methods for connecting to Astra:

Use the NewStaticTokenClient method to connect to Astra using a static auth token. See Astra DB Manage application tokens.

c, err := astra.NewStaticTokenClient(
    // URL of the Stargate service to use.
    // Example: "localhost:8090"
    // Example: "<cluster ID>-<cluster region>.apps.astra.datastax.com:443"
    astraURI,
    // Static auth token to use.
    token,
    // Optional deadline for initial connection.
    astra.WithDeadline(time.Second * 10),
    // Optional per-query timeout.
    astra.WithTimeout(time.Second * 5),
    // Optional TLS config. Assumes insecure if not specified.
    astra.WithTLSConfig(tlsConfig)
    // Optional default keyspace in which to run queries that do not specify
    // keyspace.
    astra.WithDefaultKeyspace(keyspace),
)

Use the NewTableBasedTokenClient method to connect to Astra using a Stargate table auth API service URL, username, and password. See Astra DB Table-based authentication/authorization.

c, err := astra.NewTableBasedTokenClient(
    // URL of the Stargate service to use.
    astraURI,
    // Stargate auth endpoint URL.
    authServiceURL,
    // Username and password with which to authenticate.
    username, password,
    ...
)

Querying

Create new queries by calling Client.Query to return a new Query, then execute it with Query.Exec.

rows, err := c.Query("SELECT * FROM table").Exec()
if err != nil {
    // Handle error.
}
for _, r := range rows {
    // Do something with row.
}

Iterate over the returned Rows using a standard for loop. Call Row.Values to inspect the values.

for _, r := range rows {
    vals := r.Values()
    someText := vals[0].(string)
    someNumber := vals[1].(int64)
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BatchQuery

type BatchQuery struct {
	// contains filtered or unexported fields
}

BatchQuery is a configurable and executable Stargate batch query. Use Client.Batch to create a BatchQuery.

func (*BatchQuery) BatchType

func (b *BatchQuery) BatchType(batchType BatchType) *BatchQuery

BatchType sets the batch type to use for the batch query.

func (*BatchQuery) Exec

func (b *BatchQuery) Exec() error

Exec executes the BatchQuery using the client that created it.

func (*BatchQuery) Keyspace

func (b *BatchQuery) Keyspace(value string) *BatchQuery

Keyspace sets the keyspace to use for the batch query.

type BatchType

type BatchType uint8
const (
	BatchLogged BatchType = iota
	BatchUnlogged
	BatchCounter
)

Batch types for BatchQuery. See https://docs.datastax.com/en/cql-oss/3.x/cql/cql_reference/cqlBatch.html

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is a client for Stargate.ø

func NewStaticTokenClient

func NewStaticTokenClient(token string, connection StaticTokenConnectConfig, opts ...ClientOption) (*Client, error)

NewStaticTokenClient creates a new Client which uses the specified static auth token for requests.

Example
astraURI := "<ASTRA_CLUSTER_ID>-<ASTRA_REGION>.apps.astra.datastax.com:443"
token := "AstraCS:<...>"
c, err := NewStaticTokenClient(token,
	WithAstraURI(astraURI),
	WithDefaultKeyspace("example"),
	// other options
)
if err != nil {
	log.Fatalf("failed to initialize client: %v", err)
}

_, err = c.Query(`<some query>`).Exec()
if err != nil {
	log.Fatalf("failed to execute query: %v", err)
}
Output:

Example (WithSecureConnectBundle)
c, err := NewStaticTokenClient(token,
	WithSecureConnectBundle("path/to/secure-connect-bundle.zip"),
	WithDefaultKeyspace("example"),
	// other options
)
if err != nil {
	log.Fatalf("failed to initialize client: %v", err)
}

_, err = c.Query(`<some query>`).Exec()
if err != nil {
	log.Fatalf("failed to execute query: %v", err)
}
Output:

func NewTableBasedTokenClient

func NewTableBasedTokenClient(astraURI, authServiceURI, username, password string, opts ...ClientOption) (*Client, error)

NewTableBasedTokenClient creates a new Client which uses the specified Stargate table auth API service URL, username, and password to obtain an auth token for requests.

Example
astraURI := "<ASTRA_CLUSTER_ID>-<ASTRA_REGION>.apps.astra.datastax.com:443"
authServiceURI := fmt.Sprintf("http://%s/v1/auth", astraURI)
c, err := NewTableBasedTokenClient(
	astraURI, authServiceURI,
	"username", "password",
	WithDefaultKeyspace("example"),
	// other options
)
if err != nil {
	log.Fatalf("failed to initialize client: %v", err)
}

_, err = c.Query(`<some query>`).Exec()
if err != nil {
	log.Fatalf("failed to execute query: %v", err)
}
Output:

func (*Client) Batch

func (c *Client) Batch(queries ...*Query) *BatchQuery

Batch creates a new Astra batch query.

Example
c, err := NewStaticTokenClient(
	token, WithAstraURI(endpoint),
	WithDefaultKeyspace("example"),
)
if err != nil {
	log.Fatalf("failed to initialize client: %v", err)
}

err = c.Batch(
	// Table already contains a user named 'Alice'.
	c.Query(
		`INSERT INTO users (id, name, age) VALUES (12345678-1234-5678-1234-56781234567B,'Bob',31)`),
	c.Query(
		`INSERT INTO users (id, name, age) VALUES (12345678-1234-5678-1234-56781234567C,'Charles',32)`),
).
	BatchType(BatchUnlogged).
	Exec()
if err != nil {
	log.Fatalf("failed to insert new example users: %v", err)
}

rows, err := c.Query(`SELECT * FROM users`).Exec()
if err != nil {
	log.Fatalf("failed to execute query: %v", err)
}

fmt.Printf("rows returned: %v", len(rows))
Output:

rows returned: 3
Example (WithOptions)
c, err := NewStaticTokenClient(token, WithAstraURI(endpoint))
if err != nil {
	log.Fatalf("failed to initialize client: %v", err)
}

err = c.Batch(
	// Table already contains a user named 'Alice'.
	c.Query(
		`INSERT INTO users (id, name, age) VALUES (12345678-1234-5678-1234-56781234567B,'Bob',31)`),
	c.Query(
		`INSERT INTO users (id, name, age) VALUES (12345678-1234-5678-1234-56781234567C,'Charles',32)`),
).
	Keyspace("example").
	BatchType(BatchUnlogged).
	Exec()
if err != nil {
	log.Fatalf("failed to insert new example users: %v", err)
}

rows, err := c.Query(`SELECT * FROM users`).Keyspace("example").Exec()
if err != nil {
	log.Fatalf("failed to execute query: %v", err)
}

fmt.Printf("rows returned: %v", len(rows))
Output:

rows returned: 3

func (*Client) Query

func (c *Client) Query(cql string, values ...any) *Query

Query creates a new Astra query.

Example (Cast)
c, err := NewStaticTokenClient(
	token, WithAstraURI(endpoint),
	WithDefaultKeyspace("example"),
)
if err != nil {
	log.Fatalf("failed to initialize client: %v", err)
}

rows, err := c.Query(
	`SELECT id, name, age 
		 FROM users 
		 WHERE id = ?`,
	uuid.MustParse("12345678-1234-5678-1234-567812345678"),
).Exec()
if err != nil {
	log.Fatalf("failed to execute query: %v", err)
}

for _, row := range rows {
	vals := row.Values()
	id := vals[0].(uuid.UUID)
	name := vals[1].(string)
	age := vals[2].(int64)
	fmt.Printf("id: %s, name: %s, age: %d\n", id, name, age)
}
Output:

id: 12345678-1234-5678-1234-567812345678, name: Alice, age: 30
Example (Scan)
c, err := NewStaticTokenClient(
	token, WithAstraURI(endpoint),
	WithDefaultKeyspace("example"),
)
if err != nil {
	log.Fatalf("failed to initialize client: %v", err)
}

rows, err := c.Query(
	`SELECT id, name, age 
		 FROM users 
		 WHERE id = ?`,
	uuid.MustParse("12345678-1234-5678-1234-567812345678"),
).Exec()
if err != nil {
	log.Fatalf("failed to execute query: %v", err)
}

type User struct {
	ID   uuid.UUID
	Name string
	Age  int16
}

for _, row := range rows {
	u := &User{}
	err := row.Scan(&u.ID, &u.Name, &u.Age)
	if err != nil {
		log.Fatalf("failed to scan row: %v", err)
	}
	fmt.Printf("%+v\n", u)
}
Output:

&{ID:12345678-1234-5678-1234-567812345678 Name:Alice Age:30}
Example (WithOptions)
c, err := NewStaticTokenClient(token, WithAstraURI(endpoint))
if err != nil {
	log.Fatalf("failed to initialize client: %v", err)
}

rows, err := c.Query(
	`SELECT * FROM users WHERE id = ?`,
	uuid.MustParse("12345678-1234-5678-1234-567812345678"),
).
	Keyspace("example").
	Exec()
if err != nil {
	log.Fatalf("failed to execute query: %v", err)
}

fmt.Printf("rows returned: %v", len(rows))
Output:

rows returned: 1

type ClientOption

type ClientOption func(*Client)

ClientOption is an option for a Client.

func WithDeadline

func WithDeadline(deadline time.Duration) ClientOption

WithDeadline sets the deadline for the initial connection.

func WithDefaultKeyspace

func WithDefaultKeyspace(keyspace string) ClientOption

WithDefaultKeyspace specifies the default keyspace for client queries.

func WithGRPCConnParams

func WithGRPCConnParams(params *grpc.ConnectParams) ClientOption

WithGRPCConnParams specifies other connection parameters to use for the gRPC connection.

func WithInsecure

func WithInsecure(insecure bool) ClientOption

WithInsecure specifies whether to use an insecure connection. Intended localhost testing only.

func WithTLSConfig

func WithTLSConfig(config *tls.Config) ClientOption

WithTLSConfig specifies the TLS configuration to use for the gRPC connection.

func WithTimeout

func WithTimeout(timeout time.Duration) ClientOption

WithTimeout sets the timeout for queries.

type Query

type Query struct {
	// contains filtered or unexported fields
}

Query is a configurable and executable Stargate query. Use Client.Query to create a Query.

func (*Query) Exec

func (q *Query) Exec() (Rows, error)

Exec executes the Query using the client that created it and returns the resultant rows.

func (*Query) Keyspace

func (q *Query) Keyspace(value string) *Query

Keyspace sets the keyspace to use for the query.

type Row

type Row struct {
	// contains filtered or unexported fields
}

Row represents a row of data from an Astra table.

func (*Row) Scan

func (r *Row) Scan(dest ...any) error

Scan copies the values from the row into the provided pointers.

func (*Row) String

func (r *Row) String() string

String returns a string representation of the values in the row.

func (*Row) Values

func (r *Row) Values() []any

Values returns the values in the row.

type Rows

type Rows []Row

Rows represents a list of Astra table rows.

type StaticTokenConnectConfig

type StaticTokenConnectConfig func(*Client)

StaticTokenConnectConfig describes a connection method to use in a call to NewStaticTokenClient.

func WithAstraURI

func WithAstraURI(uri string) StaticTokenConnectConfig

WithAstraURI specifies the Astra URI to use for the gRPC connection.

func WithSecureConnectBundle

func WithSecureConnectBundle(path string) StaticTokenConnectConfig

WithSecureConnectBundle specifies the secure connect bundle to use for the gRPC connection.

type TestContainer

type TestContainer struct {
	// contains filtered or unexported fields
}

func NewStargateTestContainer

func NewStargateTestContainer() (*TestContainer, error)

func (*TestContainer) CreateClientWithStaticToken

func (stc *TestContainer) CreateClientWithStaticToken() (*Client, error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL