• Glossary
  • Support
  • Downloads
  • DataStax Home
Get Live Help
Expand All
Collapse All

DataStax Astra DB Serverless Documentation

    • Overview
      • Release notes
      • Astra DB FAQs
      • Astra DB glossary
      • Get support
    • Getting Started
      • Grant a user access
      • Load and retrieve data
        • Use DSBulk to load data
        • Use Data Loader in Astra Portal
      • Connect a driver
      • Build sample apps
      • Use integrations
        • Connect with DataGrip
        • Connect with DBSchema
        • Connect with JanusGraph
        • Connect with Strapi
    • Planning
      • Plan options
      • Database regions
    • Securing
      • Security highlights
      • Security guidelines
      • Default user permissions
      • Change your password
      • Reset your password
      • Authentication and Authorization
      • Astra DB Plugin for HashiCorp Vault
    • Connecting
      • Connecting private endpoints
        • AWS Private Link
        • Azure Private Link
        • GCP Private Endpoints
        • Connecting custom DNS
      • Connecting Change Data Capture (CDC)
      • Connecting CQL console
      • Connect the Spark Cassandra Connector to Astra
      • Drivers for Astra DB
        • Connecting C++ driver
        • Connecting C# driver
        • Connecting Java driver
        • Connecting Node.js driver
        • Connecting Python driver
        • Drivers retry policies
      • Connecting Legacy drivers
      • Get Secure Connect Bundle
    • Migrating
      • FAQs
      • Preliminary steps
        • Feasibility checks
        • Deployment and infrastructure considerations
        • Create target environment for migration
        • Understand rollback options
      • Phase 1: Deploy ZDM Proxy and connect client applications
        • Set up the ZDM Automation with ZDM Utility
        • Deploy the ZDM Proxy and monitoring
          • Configure Transport Layer Security
        • Connect client applications to ZDM Proxy
        • Manage your ZDM Proxy instances
      • Phase 2: Migrate and validate data
      • Phase 3: Enable asynchronous dual reads
      • Phase 4: Change read routing to Target
      • Phase 5: Connect client applications directly to Target
      • Troubleshooting
        • Troubleshooting tips
        • Troubleshooting scenarios
      • Additional resources
        • Glossary
        • Contribution guidelines
        • Release Notes
    • Managing
      • Managing your organization
        • User permissions
        • Pricing and billing
        • Audit Logs
        • Bring Your Own Key
          • BYOK AWS Astra DB console
          • BYOK GCP Astra DB console
          • BYOK AWS DevOps API
          • BYOK GCP DevOps API
        • Configuring SSO
          • Configure SSO for Microsoft Azure AD
          • Configure SSO for Okta
          • Configure SSO for OneLogin
      • Managing your database
        • Create your database
        • View your databases
        • Database statuses
        • Use DSBulk to load data
        • Use Data Loader in Astra Portal
        • Monitor your databases
        • Export metrics to third party
          • Export metrics via Astra Portal
          • Export metrics via DevOps API
        • Manage access lists
        • Manage multiple keyspaces
        • Using multiple regions
        • Terminate your database
      • Managing with DevOps API
        • Managing database lifecycle
        • Managing roles
        • Managing users
        • Managing tokens
        • Managing BYOK AWS
        • Managing BYOK GCP
        • Managing access list
        • Managing multiple regions
        • Get private endpoints
        • AWS PrivateLink
        • Azure PrivateLink
        • GCP Private Service
    • Astra CLI
    • DataStax Astra Block
      • FAQs
      • About NFTs
      • DataStax Astra Block for Ethereum quickstart
    • Developing with Stargate APIs
      • Develop with REST
      • Develop with Document
      • Develop with GraphQL
        • Develop with GraphQL (CQL-first)
        • Develop with GraphQL (Schema-first)
      • Develop with gRPC
        • gRPC Rust client
        • gRPC Go client
        • gRPC Node.js client
        • gRPC Java client
      • Develop with CQL
      • Tooling Resources
      • Node.js Document API client
      • Node.js REST API client
    • Stargate QuickStarts
      • Document API QuickStart
      • REST API QuickStart
      • GraphQL API CQL-first QuickStart
    • API References
      • DevOps REST API v2
      • Stargate Document API v2
      • Stargate REST API v2
  • DataStax Astra DB Serverless Documentation
  • Developing with Stargate APIs
  • Develop with gRPC
  • gRPC Go client

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.

gRPC Rust client gRPC Node.js client

General Inquiries: +1 (650) 389-6000 info@datastax.com

© DataStax | Privacy policy | Terms of use

DataStax, Titan, and TitanDB are registered trademarks of DataStax, Inc. and its subsidiaries in the United States and/or other countries.

Apache, Apache Cassandra, Cassandra, Apache Tomcat, Tomcat, Apache Lucene, Apache Solr, Apache Hadoop, Hadoop, Apache Pulsar, Pulsar, Apache Spark, Spark, Apache TinkerPop, TinkerPop, Apache Kafka and Kafka are either registered trademarks or trademarks of the Apache Software Foundation or its subsidiaries in Canada, the United States and/or other countries.

Kubernetes is the registered trademark of the Linux Foundation.

landing_page landingpage