gRPC Go Client

Go set-up

Add dependencies

To begin, add the required dependency to your project:

go get -u github.com/stargate/stargate-grpc-go-client

The next sections explain the parts of a script to use the Stargate functionality. A full working script is included below.

Go connecting

Authentication

This example assumes that you’re running Stargate locally with the default credentials of cassandra/cassandra. For more information regarding authentication please see the Stargate authentication and authorization docs.

The following code snippet can be used to generate the table-based auth token in the client code:

grpcEndpoint := "localhost:8090"
authEndpoint := "localhost:8081"
username := "cassandra"
passwd := "cassandra"

conn, err := grpc.Dial(grpcEndpoint, grpc.WithInsecure(), grpc.WithBlock(),
  grpc.WithPerRPCCredentials(
    auth.NewTableBasedTokenProviderUnsafe(
      fmt.Sprintf("http://%s/v1/auth", authEndpoint), username, passwd,
    ),
  ),
)

For a secure connection, use:

grpcEndpoint := "localhost:8090"
authEndpoint := "localhost:8081"
username := "cassandra"
passwd := "cassandra"

config := &tls.Config{
 	InsecureSkipVerify: false,
}
conn, err := grpc.Dial(grpcEndpoint, grpc.WithTransportCredentials(credentials.NewTLS(config)),
  grpc.WithBlock(),
  grpc.WithPerRPCCredentials(
    auth.NewTableBasedTokenProvider(
      fmt.Sprintf("http://%s/v1/auth", authEndpoint), username, passwd,
    ),
  ),
)

Set up client

To connect to your Stargate instance, set up the client as follows.

stargateClient, err = client.NewStargateClientWithConn(conn)

if err != nil {
  fmt.Printf("error creating client %v", err)
  os.Exit(1)
}
fmt.Printf("made client\n")

Go querying

A simple query can be performed by passing a CQL query to the client using the ExecuteQuery() function for standard query execution:

selectQuery := &pb.Query{
  Cql: "SELECT firstname, lastname FROM test.users;",
}

response, err := stargateClient.ExecuteQuery(selectQuery)
if err != nil {
  fmt.Printf("error executing query %v", err)
  return
}
fmt.Printf("select executed\n")

Data definition (DDL) queries are supported in the same manner:

// Create a new keyspace
createKeyspaceQuery := &pb.Query{
	Cql: "CREATE KEYSPACE IF NOT EXISTS test WITH REPLICATION = {'class' : 'SimpleStrategy', 'replication_factor' : 1};",
}

_, err = stargateClient.ExecuteQuery(createKeyspaceQuery)
if err != nil {
	fmt.Printf("error creating keyspace %v", err)
	return
}
fmt.Printf("made keyspace\n")

// Create a new table
createTableQuery := &pb.Query{
	Cql: "CREATE TABLE IF NOT EXISTS test.users (firstname text PRIMARY KEY, lastname text);",
}

_, err = stargateClient.ExecuteQuery(createTableQuery)
if err != nil {
	fmt.Printf("error creating table %v", err)
	return
}
fmt.Printf("made table \n")

In general, users will create a keyspace and table first.

Parameterized queries are also supported:

any, err := anypb.New(
	&pb.Values{
		Values: []*pb.Value{
			{Inner: &pb.Value_String_{String_: "system"}},
		},
	},
)
if err != nil {
	return err
}

// read from table
query := &pb.Query{
	Cql: "SELECT * FROM system_schema.keyspaces WHERE keyspace_name = ?",
	Values: &pb.Values{
		Values: []*pb.Value{
			{Inner: &pb.Value_String_{String_: "system"}},
		},
	},
	Parameters: &pb.QueryParameters{
		Tracing:      false,
		SkipMetadata: false,
	},
}
response, err := stargateClient.ExecuteQuery(query)

The ExecuteQuery function can be used to execute a single query.

If you need to group several commands together as a batch statement, the client also provides an ExecuteBatch() function to execute a batch query:

batch := &pb.Batch{
  Type: pb.Batch_LOGGED,
  Queries: []*pb.BatchQuery{
    {
      Cql: "INSERT INTO test.users (firstname, lastname) VALUES ('Lorina', 'Poland');",
    },
    {
      Cql: "INSERT INTO test.users (firstname, lastname) VALUES ('Ronnie', 'Miller');",
    },
  },
}

_, err = stargateClient.ExecuteBatch(batch)
if err != nil {
  fmt.Printf("error creating batch %v", err)
  return
}
fmt.Printf("insert data\n")

This example inserts two values into the keyspace table test.users. Only INSERT, UPDATE, and DELETE operations can be used in a batch query.

Go processing result set

After executing a query, a response returns rows that match the SELECT statement. You can call getResultSet() on the response to grab a ResultSet to process. Note the function may return undefined if no ResultSet is returned; check if it is defined or cast.

result := response.GetResultSet()

var i, j int
for i = 0; i < 2; i++ {
  valueToPrint := ""
  for j = 0; j < 2; j++ {
    value, err := client.ToString(result.Rows[i].Values[j])
    if err != nil {
      fmt.Printf("error getting value %v", err)
      os.Exit(1)
    }
    valueToPrint += " "
    valueToPrint += value
  }
  fmt.Printf("%v \n", valueToPrint)
}
}

Since the result type is known, the ToString function transforms the value into a native string. Additional functions also exist for other types such as int, map, and blob. The full list can be found in values.go.

Go full sample script

To put all the pieces together, here is a sample script that combines all the pieces shown above:

  • Sample script

  • Result

package main

import (
	"fmt"
	"os"

	"github.com/stargate/stargate-grpc-go-client/stargate/pkg/auth"
	"github.com/stargate/stargate-grpc-go-client/stargate/pkg/client"
	pb "github.com/stargate/stargate-grpc-go-client/stargate/pkg/proto"

	"google.golang.org/grpc"
)

var stargateClient *client.StargateClient

func main() {

	grpcEndpoint := "localhost:8090"
	authEndpoint := "localhost:8081"
	username := "cassandra"
	passwd := "cassandra"

	conn, err := grpc.Dial(grpcEndpoint, grpc.WithInsecure(), grpc.WithBlock(),
		grpc.WithPerRPCCredentials(
			auth.NewTableBasedTokenProviderUnsafe(
				fmt.Sprintf("http://%s/v1/auth", authEndpoint), username, passwd,
			),
		),
	)

	// config := &tls.Config{
	// 	InsecureSkipVerify: false,
	// }
	//conn, err := grpc.Dial(grpcEndpoint, grpc.WithTransportCredentials(credentials.NewTLS(config)),
	//   grpc.WithBlock(),
	//   grpc.WithPerRPCCredentials(
	//     auth.NewTableBasedTokenProvider(
	//       fmt.Sprintf("http://%s/v1/auth", authEndpoint), username, passwd,
	//     ),
	//   ),
	// )

	stargateClient, err = client.NewStargateClientWithConn(conn)

	if err != nil {
		fmt.Printf("error creating client %v", err)
		os.Exit(1)
	}
	fmt.Printf("made client\n")

	// Create a new keyspace
	createKeyspaceQuery := &pb.Query{
		Cql: "CREATE KEYSPACE IF NOT EXISTS test WITH REPLICATION = {'class' : 'SimpleStrategy', 'replication_factor' : 1};",
	}

	_, err = stargateClient.ExecuteQuery(createKeyspaceQuery)
	if err != nil {
		fmt.Printf("error creating keyspace %v", err)
		return
	}
	fmt.Printf("made keyspace\n")

	// Create a new table
	createTableQuery := &pb.Query{
		Cql: "CREATE TABLE IF NOT EXISTS test.users (firstname text PRIMARY KEY, lastname text);",
	}

	_, err = stargateClient.ExecuteQuery(createTableQuery)
	if err != nil {
		fmt.Printf("error creating table %v", err)
		return
	}
	fmt.Printf("made table \n")

	batch := &pb.Batch{
		Type: pb.Batch_LOGGED,
		Queries: []*pb.BatchQuery{
			{
				Cql: "INSERT INTO test.users (firstname, lastname) VALUES ('Jane', 'Doe');",
			},
			{
				Cql: "INSERT INTO test.users (firstname, lastname) VALUES ('Serge', 'Provencio');",
			},
		},
	}

	_, err = stargateClient.ExecuteBatch(batch)
	if err != nil {
		fmt.Printf("error creating batch %v", err)
		return
	}
	fmt.Printf("insert data\n")

	selectQuery := &pb.Query{
		Cql: "SELECT firstname, lastname FROM test.users;",
	}

	response, err := stargateClient.ExecuteQuery(selectQuery)
	if err != nil {
		fmt.Printf("error executing query %v", err)
		return
	}
	fmt.Printf("select executed\n")

	result := response.GetResultSet()

	var i, j int
	for i = 0; i < 2; i++ {
		valueToPrint := ""
		for j = 0; j < 2; j++ {
			value, err := client.ToString(result.Rows[i].Values[j])
			if err != nil {
				fmt.Printf("error getting value %v", err)
				os.Exit(1)
			}
			valueToPrint += " "
			valueToPrint += value
		}
		fmt.Printf("%v \n", valueToPrint)
	}
}
[ ~/CLONES/grpc-go ] (main ✏️ 1) $go run connect-sgoss.go
made client
made keyspace
made table
insert data
select executed
 Jane Doe
 Serge Provencio

Go developing

Getting started

Clone the repo, then install dependencies:

go mod download

Testing

The tests for this project can be run from the root using the following command:

go test ./... -v -tags integration

The addition of -tags integration also runs the integration tests.

Generating gRPC code stubs

To update the protobuf files being used, add the new files to the top level proto directory and then run make proto from the root of the project. After running, you will find the new generated `*.pb.go files in stargate/pkg/proto.

Coding style

This project uses golangci-lint to lint code. These standards are enforced automatically in the CI pipeline.

The Stargate gRPC Go Client repository is located at https://github.com/stargate/stargate-grpc-go-client.