azcosmos

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

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

Go to latest
Published: Sep 13, 2022 License: MIT Imports: 26 Imported by: 0

README

Azure Cosmos DB SDK for Go

Introduction

This client library enables client applications to connect to Azure Cosmos DB via the SQL API. Azure Cosmos DB is a globally distributed, multi-model database service.

Getting Started

Prerequisites
  • Go versions 1.18 or higher
  • An Azure subscription or free Azure Cosmos DB trial account

Note: If you don't have an Azure subscription, create a free account before you begin. You can Try Azure Cosmos DB for free without an Azure subscription, free of charge and commitments, or create an Azure Cosmos DB free tier account, with the first 400 RU/s and 5 GB of storage for free. You can also use the Azure Cosmos DB Emulator with a URI of https://localhost:8081. For the key to use with the emulator, see Authenticating requests.

Create an Azure Cosmos DB account

You can create an Azure Cosmos account using:

Install the package
  • Install the Azure Cosmos DB SDK for Go with go get:

    go get -u github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos
    
Authenticate the client

In order to interact with the Azure Cosmos DB service you'll need to create an instance of the Cosmos client class. To make this possible you will need an URL and key of the Azure Cosmos DB service.

Examples

The following section provides several code snippets covering some of the most common Cosmos DB SQL API tasks, including:

Create Cosmos DB Client

The clients support different forms of authentication. The azcosmos library supports authorization via Azure Active Directory or an account key.

Using Azure Active Directory

import "github.com/Azure/azure-sdk-for-go/sdk/azidentity"

cred, err := azidentity.NewDefaultAzureCredential(nil)
handle(err)
client, err := azcosmos.NewClient("myAccountEndpointURL", cred, nil)
handle(err)

Using account keys

const (
    cosmosDbEndpoint = "someEndpoint"
    cosmosDbKey = "someKey"
)

cred, err := azcosmos.NewKeyCredential(cosmosDbKey)
handle(err)
client, err := azcosmos.NewClientWithKey(cosmosDbEndpoint, cred, nil)
handle(err)
Create Database

Using the client created in previous example, you can create a database like this:

database := azcosmos.DatabaseProperties{Id: dbName}
response, err := client.CreateDatabase(context, database, nil)
handle(err)
database, err := azcosmos.NewDatabase(dbName)
handle(err)
Create Container

Using the above created database for creating a container, like this:

properties := azcosmos.ContainerProperties{
    Id: "aContainer",
    PartitionKeyDefinition: azcosmos.PartitionKeyDefinition{
        Paths: []string{"/id"},
    },
}

throughput := azcosmos.NewManualThroughputProperties(400)
response, err := database.CreateContainer(context, properties, &CreateContainerOptions{ThroughputProperties: &throughput})
handle(err)
CRUD operation on Items
item := map[string]string{
    "id":    "1",
    "value": "2",
}

marshalled, err := json.Marshal(item)
if err != nil {
    log.Fatal(err)
}

container, err := client.NewContainer(dbName, containerName)
handle(err)

pk := azcosmos.NewPartitionKeyString("1")
id := "1"

// Create an item
itemResponse, err := container.CreateItem(context, pk, marshalled, nil)
handle(err)

// Read an item
itemResponse, err = container.ReadItem(context, pk, id, nil)
handle(err)

var itemResponseBody map[string]string
err = json.Unmarshal(itemResponse.Value, &itemResponseBody)
if err != nil {
    log.Fatal(err)
}

itemResponseBody["value"] = "3"
marshalledReplace, err := json.Marshal(itemResponseBody)
if err != nil {
    log.Fatal(err)
}

// Replace an item
itemResponse, err = container.ReplaceItem(context, pk, id, marshalledReplace, nil)
handle(err)

// Delete an item
itemResponse, err = container.DeleteItem(context, pk, id, nil)
handle(err)

Next steps

License

This project is licensed under MIT.

Provide Feedback

If you encounter bugs or have suggestions, please open an issue and assign the Cosmos label.

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

Impressions

Documentation

Overview

Package azcosmos implements the client to interact with the Azure Cosmos DB SQL API.

The azcosmos package is capable of:

  • Creating, deleting, and reading databases in an account
  • Creating, deleting, updating, and reading containers in a database
  • Creating, deleting, replacing, upserting, and reading items in a container

Creating the Client

Types of Credentials The clients support different forms of authentication. The azcosmos library supports authorization via Azure Active Directory or an account key.

Using Azure Active Directory To create a client, you can use any of the TokenCredential implementations provided by `azidentity`.

cred, err := azidentity.NewClientSecretCredential("tenantId", "clientId", "clientSecret")
handle(err)
client, err := azcosmos.NewClient("myAccountEndpointURL", cred, nil)
handle(err)

Using account keys To create a client, you will need the account's endpoint URL and a key credential.

cred, err := azcosmos.NewKeyCredential("myAccountKey")
handle(err)
client, err := azcosmos.NewClientWithKey("myAccountEndpointURL", cred, nil)
handle(err)

Using connection string To create a client, you will need the account's connection string.

client, err := azcosmos.NewClientFromConnectionString("myConnectionString", nil)
handle(err)

Key Concepts

The following are relevant concepts for the usage of the client:

  • A client is a connection to an Azure Cosmos DB account.
  • An account can have multiple databases, and the client allows you to create, read, and delete databases.
  • A database can have multiple containers, and the client allows you to create, read, update, and delete containers, and to modify throughput provision.
  • Information is stored as items inside containers and the client allows you to create, read, update, and delete items in containers.

More Examples

The following sections provide several code snippets covering some of the most common Table tasks, including:

  • Creating a database
  • Creating a container
  • Creating, reading, and deleting items
  • Querying items
  • Using Transactional Batch

Creating a database

Create a database and obtain a `DatabaseClient` to perform operations on your newly created database.

cred, err := azcosmos.NewKeyCredential("myAccountKey")
handle(err)
client, err := azcosmos.NewClientWithKey("myAccountEndpointURL", cred, nil)
handle(err)
database := azcosmos.DatabaseProperties{ID: "myDatabase"}
response, err := client.CreateDatabase(context, database, nil)
handle(err)
database, err := azcosmos.NewDatabase("myDatabase")
handle(err)

Creating a container

Create a container on an existing database and obtain a `ContainerClient` to perform operations on your newly created container.

cred, err := azcosmos.NewKeyCredential("myAccountKey")
handle(err)
client, err := azcosmos.NewClientWithKey("myAccountEndpointURL", cred, nil)
handle(err)
database := azcosmos.NewDatabase("myDatabase")
properties := azcosmos.ContainerProperties{
	ID: "myContainer",
	PartitionKeyDefinition: azcosmos.PartitionKeyDefinition{
		Paths: []string{"/myPartitionKeyProperty"},
	},
}

throughput := azcosmos.NewManualThroughputProperties(400)
response, err := database.CreateContainer(context, properties, &CreateContainerOptions{ThroughputProperties: &throughput})
handle(err)
container, err := database.NewContainer("myContainer")
handle(err)

Creating, reading, and deleting items

item := map[string]string{
	"id":    "1",
	"myPartitionKeyProperty": "myPartitionKeyValue",
	"otherValue": 10
}
marshalled, err := json.Marshal(item)
handle(err)

pk := azcosmos.NewPartitionKeyString("myPartitionKeyValue")
itemResponse, err := container.CreateItem(context, pk, marshalled, nil)
handle(err)

id := "1"
itemResponse, err = container.ReadItem(context, pk, id, nil)
handle(err)

var itemResponseBody map[string]string
err = json.Unmarshal(itemResponse.Value, &itemResponseBody)
handle(err)

itemResponseBody["value"] = "3"
marshalledReplace, err := json.Marshal(itemResponseBody)
handle(err)

itemResponse, err = container.ReplaceItem(context, pk, id, marshalledReplace, nil)
handle(err)

itemResponse, err = container.DeleteItem(context, pk, id, nil)
handle(err)

Querying items

pk := azcosmos.NewPartitionKeyString("myPartitionKeyValue")
queryPager := container.NewQueryItemsPager("select * from docs c", pk, nil)
for queryPager.More() {
	queryResponse, err := queryPager.NextPage(context)
	if err != nil {
		handle(err)
	}

	for _, item := range queryResponse.Items {
		var itemResponseBody map[string]interface{}
		json.Unmarshal(item, &itemResponseBody)
	}
}

Querying items with parametrized queries

&opt := azcosmos.QueryOptions{
	azcosmos.QueryParameters: []QueryParameter{
		{"@value", "2"},
	},
}
pk := azcosmos.NewPartitionKeyString("myPartitionKeyValue")
queryPager := container.NewQueryItemsPager("select * from docs c where c.value = @value", pk, opt)
for queryPager.More() {
	queryResponse, err := queryPager.NextPage(context)
	if err != nil {
		handle(err)
	}

	for _, item := range queryResponse.Items {
		var itemResponseBody map[string]interface{}
		json.Unmarshal(item, &itemResponseBody)
	}
}

Using Transactional batch

pk := azcosmos.NewPartitionKeyString("myPartitionKeyValue")
batch := container.NewTransactionalBatch(pk)

item := map[string]string{
	"id":    "1",
	"myPartitionKeyProperty": "myPartitionKeyValue",
	"otherValue": 10
}
marshalled, err := json.Marshal(item)
handle(err)

batch.CreateItem(marshalled, nil)
batch.ReadItem("otherExistingId", nil)
batch.DeleteItem("yetAnotherExistingId", nil)

batchResponse, err  := container.ExecuteTransactionalBatch(context, batch, nil)
handle(err)

if batchResponse.Success {
	// Transaction succeeded
	// We can inspect the individual operation results
	for index, operation := range batchResponse.OperationResults {
		fmt.Printf("Operation %v completed with status code %v consumed %v RU", index, operation.StatusCode, operation.RequestCharge)
		if index == 1 {
			// Read operation would have body available
			var itemResponseBody map[string]string
			err = json.Unmarshal(operation.ResourceBody, &itemResponseBody)
			if err != nil {
				panic(err)
			}
		}
	}
} else {
	// Transaction failed, look for the offending operation
	for index, operation := range batchResponse.OperationResults {
		if operation.StatusCode != http.StatusFailedDependency {
			fmt.Printf("Transaction failed due to operation %v which failed with status code %v", index, operation.StatusCode)
		}
	}
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

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

Client is used to interact with the Azure Cosmos DB database service.

func NewClient

func NewClient(endpoint string, cred azcore.TokenCredential, o *ClientOptions) (*Client, error)

NewClient creates a new instance of Cosmos client with Azure AD access token authentication. It uses the default pipeline configuration. endpoint - The cosmos service endpoint to use. cred - The credential used to authenticate with the cosmos service. options - Optional Cosmos client options. Pass nil to accept default values.

Example
package main

import (
	"fmt"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
	"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
)

func main() {
	endpoint, ok := os.LookupEnv("AZURE_COSMOS_ENDPOINT")
	if !ok {
		panic("AZURE_COSMOS_ENDPOINT could not be found")
	}

	// Obtain a TokenCredential for the current environment
	// Alternatively, you could use any of the other credential types
	// For example, azidentity.NewClientSecretCredential("tenantId", "clientId", "clientSecret")
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		panic(err)
	}

	client, err := azcosmos.NewClient(endpoint, cred, nil)
	if err != nil {
		panic(err)
	}

	fmt.Println(client)
}
Output:

func NewClientFromConnectionString

func NewClientFromConnectionString(connectionString string, o *ClientOptions) (*Client, error)

NewClientFromConnectionString creates a new instance of Cosmos client from connection string. It uses the default pipeline configuration. connectionString - The cosmos service connection string. options - Optional Cosmos client options. Pass nil to accept default values.

Example
package main

import (
	"fmt"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
)

func main() {
	connectionString, ok := os.LookupEnv("AZURE_COSMOS_CONNECTION_STRING")
	if !ok {
		panic("AZURE_COSMOS_CONNECTION_STRING could not be found")
	}

	client, err := azcosmos.NewClientFromConnectionString(connectionString, nil)
	if err != nil {
		panic(err)
	}

	fmt.Println(client)
}
Output:

func NewClientWithKey

func NewClientWithKey(endpoint string, cred KeyCredential, o *ClientOptions) (*Client, error)

NewClientWithKey creates a new instance of Cosmos client with shared key authentication. It uses the default pipeline configuration. endpoint - The cosmos service endpoint to use. cred - The credential used to authenticate with the cosmos service. options - Optional Cosmos client options. Pass nil to accept default values.

Example
package main

import (
	"fmt"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
)

func main() {
	endpoint, ok := os.LookupEnv("AZURE_COSMOS_ENDPOINT")
	if !ok {
		panic("AZURE_COSMOS_ENDPOINT could not be found")
	}

	key, ok := os.LookupEnv("AZURE_COSMOS_KEY")
	if !ok {
		panic("AZURE_COSMOS_KEY could not be found")
	}

	// Create new Cosmos DB client.
	cred, err := azcosmos.NewKeyCredential(key)
	if err != nil {
		panic(err)
	}

	client, err := azcosmos.NewClientWithKey(endpoint, cred, nil)
	if err != nil {
		panic(err)
	}

	fmt.Println(client)
}
Output:

func (*Client) CreateDatabase

func (c *Client) CreateDatabase(
	ctx context.Context,
	databaseProperties DatabaseProperties,
	o *CreateDatabaseOptions) (DatabaseResponse, error)

CreateDatabase creates a new database. ctx - The context for the request. databaseProperties - The definition of the database o - Options for the create database operation.

Example
package main

import (
	"context"
	"errors"
	"fmt"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
)

func main() {
	endpoint, ok := os.LookupEnv("AZURE_COSMOS_ENDPOINT")
	if !ok {
		panic("AZURE_COSMOS_ENDPOINT could not be found")
	}

	key, ok := os.LookupEnv("AZURE_COSMOS_KEY")
	if !ok {
		panic("AZURE_COSMOS_KEY could not be found")
	}

	cred, err := azcosmos.NewKeyCredential(key)
	if err != nil {
		panic(err)
	}

	client, err := azcosmos.NewClientWithKey(endpoint, cred, nil)
	if err != nil {
		panic(err)
	}

	databaseProperties := azcosmos.DatabaseProperties{ID: "databaseName"}
	databaseResponse, err := client.CreateDatabase(context.Background(), databaseProperties, nil)
	if err != nil {
		var responseErr *azcore.ResponseError
		errors.As(err, &responseErr)
		panic(responseErr)
	}

	fmt.Printf("Database created. ActivityId %s", databaseResponse.ActivityID)
}
Output:

func (*Client) Endpoint

func (c *Client) Endpoint() string

Endpoint used to create the client.

func (*Client) NewContainer

func (c *Client) NewContainer(databaseId string, containerId string) (*ContainerClient, error)

NewContainer returns a struct that represents a container and allows container level operations. databaseId - The id of the database. containerId - The id of the container.

func (*Client) NewDatabase

func (c *Client) NewDatabase(id string) (*DatabaseClient, error)

NewDatabase returns a struct that represents a database and allows database level operations. id - The id of the database.

type ClientOptions

type ClientOptions struct {
	azcore.ClientOptions
	// When EnableContentResponseOnWrite is false will cause the response to have a null resource. This reduces networking and CPU load by not sending the resource back over the network and serializing it on the client.
	// The default is false.
	EnableContentResponseOnWrite bool
}

ClientOptions defines the options for the Cosmos client.

type CompositeIndex

type CompositeIndex struct {
	// Path for the index.
	Path string `json:"path"`
	// Order represents the order of the composite index.
	// For example if you want to run the query "SELECT * FROM c ORDER BY c.age asc, c.height desc",
	// then you need to make the order for "/age" "ascending" and the order for "/height" "descending".
	Order CompositeIndexOrder `json:"order"`
}

CompositeIndex is used when queries have an ORDER BY clause with two or more properties

type CompositeIndexOrder

type CompositeIndexOrder string

CompositeIndexOrder are the ordering values available for composite indexes in the Azure Cosmos DB database service. For more information see https://docs.microsoft.com/azure/cosmos-db/index-policy

const (
	// Ascending sort order for composite paths.
	CompositeIndexAscending CompositeIndexOrder = "ascending"
	// Descending sort order for composite paths.
	CompositeIndexDescending CompositeIndexOrder = "descending"
)

func CompositeIndexOrderValues

func CompositeIndexOrderValues() []CompositeIndexOrder

Returns a list of available consistency levels

func (CompositeIndexOrder) ToPtr

ToPtr returns a *CompositeIndexOrder

type ConflictResolutionMode

type ConflictResolutionMode string

ConflictResolutionMode defines the conflict resolution mode in the Azure Cosmos DB service.

const (
	// Conflict resolution that uses the highest value of the conflicting documents property values.
	ConflictResolutionModeLastWriteWins ConflictResolutionMode = "LastWriterWins"
	// Custom conflict resolution mode that requires the definition of a stored procedure.
	ConflictResolutionModeCustom ConflictResolutionMode = "Custom"
)

func ConflictResolutionModeValues

func ConflictResolutionModeValues() []ConflictResolutionMode

Returns a list of available consistency levels

func (ConflictResolutionMode) ToPtr

ToPtr returns a *ConflictResolution(mode)

type ConflictResolutionPolicy

type ConflictResolutionPolicy struct {
	// Conflict resolution mode. By default, the conflict resolution mode is LastWriteWins.
	Mode ConflictResolutionMode `json:"mode"`
	// The path which is present in each item in the container to be used on LastWriteWins conflict resolution.
	// It must be an integer value.
	ResolutionPath string `json:"conflictResolutionPath,omitempty"`
	// The stored procedure path on Custom conflict.
	// The path should be the full path to the procedure
	ResolutionProcedure string `json:"conflictResolutionProcedure,omitempty"`
}

ConflictResolutionPolicy represents a conflict resolution policy for a container. For more information see https://docs.microsoft.com/azure/cosmos-db/unique-keys

type ConsistencyLevel

type ConsistencyLevel string

ConsistencyLevel supported by the Azure Cosmos DB service.

const (
	ConsistencyLevelStrong           ConsistencyLevel = "Strong"
	ConsistencyLevelBoundedStaleness ConsistencyLevel = "BoundedStaleness"
	ConsistencyLevelSession          ConsistencyLevel = "Session"
	ConsistencyLevelEventual         ConsistencyLevel = "Eventual"
	ConsistencyLevelConsistentPrefix ConsistencyLevel = "ConsistentPrefix"
)

func ConsistencyLevelValues

func ConsistencyLevelValues() []ConsistencyLevel

Returns a list of available consistency levels

func (ConsistencyLevel) ToPtr

ToPtr returns a *ConsistencyLevel

type ContainerClient

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

ContainerClient lets you perform read, update, change throughput, and delete container operations. It also lets you perform read, update, change throughput, and delete item operations.

func (*ContainerClient) CreateItem

func (c *ContainerClient) CreateItem(
	ctx context.Context,
	partitionKey PartitionKey,
	item []byte,
	o *ItemOptions) (ItemResponse, error)

CreateItem creates an item in a Cosmos container. ctx - The context for the request. partitionKey - The partition key for the item. item - The item to create. o - Options for the operation.

Example
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
)

func main() {
	endpoint, ok := os.LookupEnv("AZURE_COSMOS_ENDPOINT")
	if !ok {
		panic("AZURE_COSMOS_ENDPOINT could not be found")
	}

	key, ok := os.LookupEnv("AZURE_COSMOS_KEY")
	if !ok {
		panic("AZURE_COSMOS_KEY could not be found")
	}

	cred, err := azcosmos.NewKeyCredential(key)
	if err != nil {
		panic(err)
	}

	client, err := azcosmos.NewClientWithKey(endpoint, cred, nil)
	if err != nil {
		panic(err)
	}

	container, err := client.NewContainer("databaseName", "aContainer")
	if err != nil {
		panic(err)
	}

	pk := azcosmos.NewPartitionKeyString("newPartitionKey")

	item := map[string]string{
		"id":             "anId",
		"value":          "2",
		"myPartitionKey": "newPartitionKey",
	}

	marshalled, err := json.Marshal(item)
	if err != nil {
		panic(err)
	}

	itemResponse, err := container.CreateItem(context.Background(), pk, marshalled, nil)
	if err != nil {
		var responseErr *azcore.ResponseError
		errors.As(err, &responseErr)
		panic(responseErr)
	}

	fmt.Printf("Item created. ActivityId %s consuming %v RU", itemResponse.ActivityID, itemResponse.RequestCharge)
}
Output:

func (*ContainerClient) Delete

Delete a Cosmos container. ctx - The context for the request. o - Options for the operation.

func (*ContainerClient) DeleteItem

func (c *ContainerClient) DeleteItem(
	ctx context.Context,
	partitionKey PartitionKey,
	itemId string,
	o *ItemOptions) (ItemResponse, error)

DeleteItem deletes an item in a Cosmos container. ctx - The context for the request. partitionKey - The partition key for the item. itemId - The id of the item to delete. o - Options for the operation.

Example
package main

import (
	"context"
	"errors"
	"fmt"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
)

func main() {
	endpoint, ok := os.LookupEnv("AZURE_COSMOS_ENDPOINT")
	if !ok {
		panic("AZURE_COSMOS_ENDPOINT could not be found")
	}

	key, ok := os.LookupEnv("AZURE_COSMOS_KEY")
	if !ok {
		panic("AZURE_COSMOS_KEY could not be found")
	}

	cred, err := azcosmos.NewKeyCredential(key)
	if err != nil {
		panic(err)
	}

	client, err := azcosmos.NewClientWithKey(endpoint, cred, nil)
	if err != nil {
		panic(err)
	}

	container, err := client.NewContainer("databaseName", "aContainer")
	if err != nil {
		panic(err)
	}

	pk := azcosmos.NewPartitionKeyString("newPartitionKey")

	id := "anId"
	itemResponse, err := container.DeleteItem(context.Background(), pk, id, nil)
	if err != nil {
		var responseErr *azcore.ResponseError
		errors.As(err, &responseErr)
		panic(responseErr)
	}

	fmt.Printf("Item deleted. ActivityId %s consuming %v RU", itemResponse.ActivityID, itemResponse.RequestCharge)
}
Output:

func (*ContainerClient) ExecuteTransactionalBatch

ExecuteTransactionalBatch executes a transactional batch. Once executed, verify the Success property of the response to determine if the batch was committed

func (*ContainerClient) ID

func (c *ContainerClient) ID() string

ID returns the identifier of the Cosmos container.

func (*ContainerClient) NewQueryItemsPager

func (c *ContainerClient) NewQueryItemsPager(query string, partitionKey PartitionKey, o *QueryOptions) *runtime.Pager[QueryItemsResponse]

NewQueryItemsPager executes a single partition query in a Cosmos container. ctx - The context for the request. query - The SQL query to execute. partitionKey - The partition key to scope the query on. o - Options for the operation.

Example
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
)

func main() {
	endpoint, ok := os.LookupEnv("AZURE_COSMOS_ENDPOINT")
	if !ok {
		panic("AZURE_COSMOS_ENDPOINT could not be found")
	}

	key, ok := os.LookupEnv("AZURE_COSMOS_KEY")
	if !ok {
		panic("AZURE_COSMOS_KEY could not be found")
	}

	cred, err := azcosmos.NewKeyCredential(key)
	if err != nil {
		panic(err)
	}

	client, err := azcosmos.NewClientWithKey(endpoint, cred, nil)
	if err != nil {
		panic(err)
	}

	container, err := client.NewContainer("databaseName", "aContainer")
	if err != nil {
		panic(err)
	}

	pk := azcosmos.NewPartitionKeyString("newPartitionKey")

	queryPager := container.NewQueryItemsPager("select * from docs c", pk, nil)
	for queryPager.More() {
		queryResponse, err := queryPager.NextPage(context.Background())
		if err != nil {
			var responseErr *azcore.ResponseError
			errors.As(err, &responseErr)
			panic(responseErr)
		}

		for _, item := range queryResponse.Items {
			var itemResponseBody map[string]interface{}
			err = json.Unmarshal(item, &itemResponseBody)
			if err != nil {
				panic(err)
			}
		}

		fmt.Printf("Query page received with %v items. ActivityId %s consuming %v RU", len(queryResponse.Items), queryResponse.ActivityID, queryResponse.RequestCharge)
	}
}
Output:

Example (ParametrizedQueries)

Azure Cosmos DB supports queries with parameters expressed by the familiar @ notation. Parameterized SQL provides robust handling and escaping of user input, and prevents accidental exposure of data through SQL injection.

package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
)

func main() {
	endpoint, ok := os.LookupEnv("AZURE_COSMOS_ENDPOINT")
	if !ok {
		panic("AZURE_COSMOS_ENDPOINT could not be found")
	}

	key, ok := os.LookupEnv("AZURE_COSMOS_KEY")
	if !ok {
		panic("AZURE_COSMOS_KEY could not be found")
	}

	cred, err := azcosmos.NewKeyCredential(key)
	if err != nil {
		panic(err)
	}

	client, err := azcosmos.NewClientWithKey(endpoint, cred, nil)
	if err != nil {
		panic(err)
	}

	container, err := client.NewContainer("databaseName", "aContainer")
	if err != nil {
		panic(err)
	}

	opt := &azcosmos.QueryOptions{
		QueryParameters: []azcosmos.QueryParameter{
			{"@value", "2"},
		},
	}

	pk := azcosmos.NewPartitionKeyString("newPartitionKey")

	queryPager := container.NewQueryItemsPager("select * from docs c where c.value = @value", pk, opt)
	for queryPager.More() {
		queryResponse, err := queryPager.NextPage(context.Background())
		if err != nil {
			var responseErr *azcore.ResponseError
			errors.As(err, &responseErr)
			panic(responseErr)
		}

		for _, item := range queryResponse.Items {
			var itemResponseBody map[string]interface{}
			err = json.Unmarshal(item, &itemResponseBody)
			if err != nil {
				panic(err)
			}
		}

		fmt.Printf("Query page received with %v items. ActivityId %s consuming %v RU", len(queryResponse.Items), queryResponse.ActivityID, queryResponse.RequestCharge)
	}
}
Output:

func (*ContainerClient) NewTransactionalBatch

func (c *ContainerClient) NewTransactionalBatch(partitionKey PartitionKey) TransactionalBatch

NewTransactionalBatch creates a batch of operations to be committed as a single unit. See https://docs.microsoft.com/azure/cosmos-db/sql/transactional-batch

Example
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
)

func main() {
	endpoint, ok := os.LookupEnv("AZURE_COSMOS_ENDPOINT")
	if !ok {
		panic("AZURE_COSMOS_ENDPOINT could not be found")
	}

	key, ok := os.LookupEnv("AZURE_COSMOS_KEY")
	if !ok {
		panic("AZURE_COSMOS_KEY could not be found")
	}

	cred, err := azcosmos.NewKeyCredential(key)
	if err != nil {
		panic(err)
	}

	client, err := azcosmos.NewClientWithKey(endpoint, cred, nil)
	if err != nil {
		panic(err)
	}

	container, err := client.NewContainer("databaseName", "aContainer")
	if err != nil {
		panic(err)
	}

	pk := azcosmos.NewPartitionKeyString("newPartitionKey")

	batch := container.NewTransactionalBatch(pk)

	item := map[string]string{
		"id":             "anId",
		"value":          "2",
		"myPartitionKey": "newPartitionKey",
	}

	marshalledItem, err := json.Marshal(item)
	if err != nil {
		panic(err)
	}

	batch.CreateItem(marshalledItem, nil)
	batch.ReadItem("anIdThatExists", nil)
	batch.DeleteItem("yetAnotherExistingId", nil)

	batchResponse, err := container.ExecuteTransactionalBatch(context.Background(), batch, nil)
	if err != nil {
		panic(err)
	}

	if batchResponse.Success {
		// Transaction succeeded
		// We can inspect the individual operation results
		for index, operation := range batchResponse.OperationResults {
			fmt.Printf("Operation %v completed with status code %v consumed %v RU", index, operation.StatusCode, operation.RequestCharge)
			if index == 1 {
				// Read operation would have body available
				var itemResponseBody map[string]string
				err = json.Unmarshal(operation.ResourceBody, &itemResponseBody)
				if err != nil {
					panic(err)
				}
			}
		}
	} else {
		// Transaction failed, look for the offending operation
		for index, operation := range batchResponse.OperationResults {
			if operation.StatusCode != http.StatusFailedDependency {
				fmt.Printf("Transaction failed due to operation %v which failed with status code %v", index, operation.StatusCode)
			}
		}
	}
}
Output:

func (*ContainerClient) Read

Read obtains the information for a Cosmos container. ctx - The context for the request. o - Options for the operation.

func (*ContainerClient) ReadItem

func (c *ContainerClient) ReadItem(
	ctx context.Context,
	partitionKey PartitionKey,
	itemId string,
	o *ItemOptions) (ItemResponse, error)

ReadItem reads an item in a Cosmos container. ctx - The context for the request. partitionKey - The partition key for the item. itemId - The id of the item to read. o - Options for the operation.

Example
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
)

func main() {
	endpoint, ok := os.LookupEnv("AZURE_COSMOS_ENDPOINT")
	if !ok {
		panic("AZURE_COSMOS_ENDPOINT could not be found")
	}

	key, ok := os.LookupEnv("AZURE_COSMOS_KEY")
	if !ok {
		panic("AZURE_COSMOS_KEY could not be found")
	}

	cred, err := azcosmos.NewKeyCredential(key)
	if err != nil {
		panic(err)
	}

	client, err := azcosmos.NewClientWithKey(endpoint, cred, nil)
	if err != nil {
		panic(err)
	}

	container, err := client.NewContainer("databaseName", "aContainer")
	if err != nil {
		panic(err)
	}

	pk := azcosmos.NewPartitionKeyString("newPartitionKey")

	id := "anId"
	itemResponse, err := container.ReadItem(context.Background(), pk, id, nil)
	if err != nil {
		var responseErr *azcore.ResponseError
		errors.As(err, &responseErr)
		panic(responseErr)
	}

	var itemResponseBody map[string]string
	err = json.Unmarshal(itemResponse.Value, &itemResponseBody)
	if err != nil {
		panic(err)
	}

	fmt.Printf("Item read. ActivityId %s consuming %v RU", itemResponse.ActivityID, itemResponse.RequestCharge)
}
Output:

Example (SessionConsistency)
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
)

func main() {
	endpoint, ok := os.LookupEnv("AZURE_COSMOS_ENDPOINT")
	if !ok {
		panic("AZURE_COSMOS_ENDPOINT could not be found")
	}

	key, ok := os.LookupEnv("AZURE_COSMOS_KEY")
	if !ok {
		panic("AZURE_COSMOS_KEY could not be found")
	}

	cred, err := azcosmos.NewKeyCredential(key)
	if err != nil {
		panic(err)
	}

	client, err := azcosmos.NewClientWithKey(endpoint, cred, nil)
	if err != nil {
		panic(err)
	}

	container, err := client.NewContainer("databaseName", "aContainer")
	if err != nil {
		panic(err)
	}

	pk := azcosmos.NewPartitionKeyString("newPartitionKey")
	id := "anId"
	item := map[string]string{
		"id":             "anId",
		"value":          "2",
		"myPartitionKey": "newPartitionKey",
	}

	marshalled, err := json.Marshal(item)
	if err != nil {
		panic(err)
	}

	itemResponse, err := container.CreateItem(context.Background(), pk, marshalled, nil)
	if err != nil {
		panic(err)
	}

	itemSessionToken := itemResponse.SessionToken
	fmt.Printf("Create response contained session %s", itemSessionToken)

	// In another client, maintain the session by passing the session token
	itemResponse, err = container.ReadItem(context.Background(), pk, id, &azcosmos.ItemOptions{SessionToken: itemSessionToken})
	if err != nil {
		var responseErr *azcore.ResponseError
		errors.As(err, &responseErr)
		panic(responseErr)
	}

	fmt.Printf("Item read. ActivityId %s consuming %v RU", itemResponse.ActivityID, itemResponse.RequestCharge)
}
Output:

func (*ContainerClient) ReadThroughput

ReadThroughput obtains the provisioned throughput information for the container. ctx - The context for the request. o - Options for the operation.

func (*ContainerClient) Replace

Replace a Cosmos container. ctx - The context for the request. o - Options for the operation.

Example
package main

import (
	"context"
	"errors"
	"fmt"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
)

func main() {
	endpoint, ok := os.LookupEnv("AZURE_COSMOS_ENDPOINT")
	if !ok {
		panic("AZURE_COSMOS_ENDPOINT could not be found")
	}

	key, ok := os.LookupEnv("AZURE_COSMOS_KEY")
	if !ok {
		panic("AZURE_COSMOS_KEY could not be found")
	}

	cred, err := azcosmos.NewKeyCredential(key)
	if err != nil {
		panic(err)
	}

	client, err := azcosmos.NewClientWithKey(endpoint, cred, nil)
	if err != nil {
		panic(err)
	}

	container, err := client.NewContainer("databaseName", "aContainer")
	if err != nil {
		panic(err)
	}

	containerResponse, err := container.Read(context.Background(), nil)
	if err != nil {
		panic(err)
	}

	// Changing the indexing policy
	containerResponse.ContainerProperties.IndexingPolicy = &azcosmos.IndexingPolicy{
		IncludedPaths: []azcosmos.IncludedPath{},
		ExcludedPaths: []azcosmos.ExcludedPath{},
		Automatic:     false,
		IndexingMode:  azcosmos.IndexingModeNone,
	}

	// Replace container properties
	replaceResponse, err := container.Replace(context.Background(), *containerResponse.ContainerProperties, nil)
	if err != nil {
		var responseErr *azcore.ResponseError
		errors.As(err, &responseErr)
		panic(responseErr)
	}

	fmt.Printf("Container updated. ActivityId %s", replaceResponse.ActivityID)
}
Output:

func (*ContainerClient) ReplaceItem

func (c *ContainerClient) ReplaceItem(
	ctx context.Context,
	partitionKey PartitionKey,
	itemId string,
	item []byte,
	o *ItemOptions) (ItemResponse, error)

ReplaceItem replaces an item in a Cosmos container. ctx - The context for the request. partitionKey - The partition key of the item to replace. itemId - The id of the item to replace. item - The content to be used to replace. o - Options for the operation.

Example
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
)

func main() {
	endpoint, ok := os.LookupEnv("AZURE_COSMOS_ENDPOINT")
	if !ok {
		panic("AZURE_COSMOS_ENDPOINT could not be found")
	}

	key, ok := os.LookupEnv("AZURE_COSMOS_KEY")
	if !ok {
		panic("AZURE_COSMOS_KEY could not be found")
	}

	cred, err := azcosmos.NewKeyCredential(key)
	if err != nil {
		panic(err)
	}

	client, err := azcosmos.NewClientWithKey(endpoint, cred, nil)
	if err != nil {
		panic(err)
	}

	container, err := client.NewContainer("databaseName", "aContainer")
	if err != nil {
		panic(err)
	}

	pk := azcosmos.NewPartitionKeyString("newPartitionKey")

	id := "anId"
	itemResponse, err := container.ReadItem(context.Background(), pk, id, nil)
	if err != nil {
		panic(err)
	}

	var itemResponseBody map[string]string
	err = json.Unmarshal(itemResponse.Value, &itemResponseBody)
	if err != nil {
		panic(err)
	}

	// Modify some property
	itemResponseBody["value"] = "newValue"
	marshalledReplace, err := json.Marshal(itemResponseBody)
	if err != nil {
		panic(err)
	}

	itemResponse, err = container.ReplaceItem(context.Background(), pk, id, marshalledReplace, nil)
	if err != nil {
		var responseErr *azcore.ResponseError
		errors.As(err, &responseErr)
		panic(responseErr)
	}

	fmt.Printf("Item replaced. ActivityId %s consuming %v RU", itemResponse.ActivityID, itemResponse.RequestCharge)
}
Output:

Example (OptimisticConcurrency)

Azure Cosmos DB supports optimistic concurrency control to prevent lost updates or deletes and detection of conflicting operations. Check the item response status code. If an error is emitted and the response code is 412 then retry operation.

package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"os"
	"time"

	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
)

func main() {
	endpoint, ok := os.LookupEnv("AZURE_COSMOS_ENDPOINT")
	if !ok {
		panic("AZURE_COSMOS_ENDPOINT could not be found")
	}

	key, ok := os.LookupEnv("AZURE_COSMOS_KEY")
	if !ok {
		panic("AZURE_COSMOS_KEY could not be found")
	}

	cred, err := azcosmos.NewKeyCredential(key)
	if err != nil {
		panic(err)
	}

	client, err := azcosmos.NewClientWithKey(endpoint, cred, nil)
	if err != nil {
		panic(err)
	}

	container, err := client.NewContainer("databaseName", "aContainer")
	if err != nil {
		panic(err)
	}

	pk := azcosmos.NewPartitionKeyString("newPartitionKey")
	id := "anId"

	numberRetry := 3 // Defining a limit on retries
	err = retryOptimisticConcurrency(numberRetry, 10*time.Millisecond, func() (bool, error) {
		itemResponse, err := container.ReadItem(context.Background(), pk, id, nil)
		if err != nil {
			panic(err)
		}

		var itemResponseBody map[string]string
		err = json.Unmarshal(itemResponse.Value, &itemResponseBody)
		if err != nil {
			panic(err)
		}

		// Change a value in the item response body.
		itemResponseBody["value"] = "newValue"

		marshalledReplace, err := json.Marshal(itemResponseBody)
		if err != nil {
			panic(err)
		}

		// Replace with Etag
		etag := itemResponse.ETag
		itemResponse, err = container.ReplaceItem(context.Background(), pk, id, marshalledReplace, &azcosmos.ItemOptions{IfMatchEtag: &etag})
		var responseErr *azcore.ResponseError

		return (errors.As(err, &responseErr) && responseErr.StatusCode == 412), err
	})
	if err != nil {
		panic(err)
	}
}

func retryOptimisticConcurrency(retryAttempts int, wait time.Duration, retry func() (bool, error)) (result error) {
	for i := 0; ; i++ {
		retryResult, err := retry()
		if err != nil {
			break
		}

		if !(retryResult) {
			break
		}

		if i >= (retryAttempts - 1) {
			break
		}

		fmt.Printf("retrying after error: %v", err)

		time.Sleep(wait)
	}
	return fmt.Errorf("Cosmos DB retry attempts %d, error: %s", retryAttempts, result)
}
Output:

func (*ContainerClient) ReplaceThroughput

func (c *ContainerClient) ReplaceThroughput(
	ctx context.Context,
	throughputProperties ThroughputProperties,
	o *ThroughputOptions) (ThroughputResponse, error)

ReplaceThroughput updates the provisioned throughput for the container. ctx - The context for the request. throughputProperties - The throughput configuration of the container. o - Options for the operation.

Example
package main

import (
	"context"
	"errors"
	"fmt"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
)

func main() {
	endpoint, ok := os.LookupEnv("AZURE_COSMOS_ENDPOINT")
	if !ok {
		panic("AZURE_COSMOS_ENDPOINT could not be found")
	}

	key, ok := os.LookupEnv("AZURE_COSMOS_KEY")
	if !ok {
		panic("AZURE_COSMOS_KEY could not be found")
	}

	cred, err := azcosmos.NewKeyCredential(key)
	if err != nil {
		panic(err)
	}

	client, err := azcosmos.NewClientWithKey(endpoint, cred, nil)
	if err != nil {
		panic(err)
	}

	container, err := client.NewContainer("databaseName", "aContainer")
	if err != nil {
		panic(err)
	}

	throughputResponse, err := container.ReadThroughput(context.Background(), nil)
	if err != nil {
		panic(err)
	}

	manualThroughput, hasManual := throughputResponse.ThroughputProperties.ManualThroughput()
	if !hasManual {
		panic("Expected to have manual throughput")
	}
	fmt.Printf("Container is provisioned with %v RU/s", manualThroughput)

	// Replace manual throughput
	newScale := azcosmos.NewManualThroughputProperties(500)
	replaceThroughputResponse, err := container.ReplaceThroughput(context.Background(), newScale, nil)
	if err != nil {
		var responseErr *azcore.ResponseError
		errors.As(err, &responseErr)
		panic(responseErr)
	}

	fmt.Printf("Throughput updated. ActivityId %s", replaceThroughputResponse.ActivityID)
}
Output:

func (*ContainerClient) UpsertItem

func (c *ContainerClient) UpsertItem(
	ctx context.Context,
	partitionKey PartitionKey,
	item []byte,
	o *ItemOptions) (ItemResponse, error)

UpsertItem creates or replaces an item in a Cosmos container. ctx - The context for the request. partitionKey - The partition key for the item. item - The item to upsert. o - Options for the operation.

type ContainerProperties

type ContainerProperties struct {
	// ID contains the unique id of the container.
	ID string
	// ETag contains the entity etag of the container.
	ETag *azcore.ETag
	// SelfLink contains the self-link of the container.
	SelfLink string
	// ResourceID contains the resource id of the container.
	ResourceID string
	// LastModified contains the last modified time of the container.
	LastModified time.Time
	// DefaultTimeToLive contains the default time to live in seconds for items in the container.
	// For more information see https://docs.microsoft.com/azure/cosmos-db/time-to-live#time-to-live-configurations
	DefaultTimeToLive *int32
	// AnalyticalStoreTimeToLiveInSeconds contains the default time to live in seconds for analytical store in the container.
	// For more information see https://docs.microsoft.com/azure/cosmos-db/analytical-store-introduction#analytical-ttl
	AnalyticalStoreTimeToLiveInSeconds *int32
	// PartitionKeyDefinition contains the partition key definition of the container.
	PartitionKeyDefinition PartitionKeyDefinition
	// IndexingPolicy contains the indexing definition of the container.
	IndexingPolicy *IndexingPolicy
	// UniqueKeyPolicy contains the unique key policy of the container.
	UniqueKeyPolicy *UniqueKeyPolicy
	// ConflictResolutionPolicy contains the conflict resolution policy of the container.
	ConflictResolutionPolicy *ConflictResolutionPolicy
}

ContainerProperties represents the properties of a container.

func (ContainerProperties) MarshalJSON

func (tp ContainerProperties) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface

func (*ContainerProperties) UnmarshalJSON

func (tp *ContainerProperties) UnmarshalJSON(b []byte) error

UnmarshalJSON implements the json.Unmarshaler interface

type ContainerResponse

type ContainerResponse struct {
	// ContainerProperties contains the unmarshalled response body in ContainerProperties format.
	ContainerProperties *ContainerProperties
	Response
}

ContainerResponse represents the response from a container request.

type CreateContainerOptions

type CreateContainerOptions struct {
	// ThroughputProperties: Optional throughput configuration of the container
	ThroughputProperties *ThroughputProperties
}

CreateContainerOptions are options for the CreateContainer operation

type CreateDatabaseOptions

type CreateDatabaseOptions struct {
	// ThroughputProperties: Optional throughput configuration of the database
	ThroughputProperties *ThroughputProperties
}

CreateDatabaseOptions are options for the CreateDatabase operation

type DataType

type DataType string

DataType defines supported values for data types in Spatial Indexes

const (
	// Represents a line.
	DataTypeString DataType = "String"
	// Represents a number.
	DataTypeNumber DataType = "Number"
	// Represents a point.
	DataTypePoint DataType = "Point"
	// Represents a polygon.
	DataTypePolygon DataType = "Polygon"
	// Represents a line string.
	DataTypeLineString DataType = "LineString"
	// Represents a multi polygon.
	DataTypeMultiPolygon DataType = "MultiPolygon"
)

func DataTypeValues

func DataTypeValues() []DataType

Returns a list of available data types

func (DataType) ToPtr

func (c DataType) ToPtr() *DataType

ToPtr returns a *DataType

type DatabaseClient

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

DatabaseClient lets you perform read, update, change throughput, and delete database operations.

func (*DatabaseClient) CreateContainer

func (db *DatabaseClient) CreateContainer(
	ctx context.Context,
	containerProperties ContainerProperties,
	o *CreateContainerOptions) (ContainerResponse, error)

CreateContainer creates a container in the Cosmos database. ctx - The context for the request. containerProperties - The properties for the container. o - Options for the create container operation.

Example
package main

import (
	"context"
	"errors"
	"fmt"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
)

func main() {
	endpoint, ok := os.LookupEnv("AZURE_COSMOS_ENDPOINT")
	if !ok {
		panic("AZURE_COSMOS_ENDPOINT could not be found")
	}

	key, ok := os.LookupEnv("AZURE_COSMOS_KEY")
	if !ok {
		panic("AZURE_COSMOS_KEY could not be found")
	}

	cred, err := azcosmos.NewKeyCredential(key)
	if err != nil {
		panic(err)
	}

	client, err := azcosmos.NewClientWithKey(endpoint, cred, nil)
	if err != nil {
		panic(err)
	}

	database, err := client.NewDatabase("databaseName")
	if err != nil {
		panic(err)
	}

	properties := azcosmos.ContainerProperties{
		ID: "aContainer",
		PartitionKeyDefinition: azcosmos.PartitionKeyDefinition{
			Paths: []string{"/myPartitionKey"},
		},
	}

	throughput := azcosmos.NewManualThroughputProperties(400)

	resp, err := database.CreateContainer(context.Background(), properties, &azcosmos.CreateContainerOptions{ThroughputProperties: &throughput})
	if err != nil {
		var responseErr *azcore.ResponseError
		errors.As(err, &responseErr)
		panic(responseErr)
	}

	fmt.Printf("Container created. ActivityId %s", resp.ActivityID)
}
Output:

func (*DatabaseClient) Delete

Delete a Cosmos database. ctx - The context for the request. o - Options for Read operation.

func (*DatabaseClient) ID

func (db *DatabaseClient) ID() string

ID returns the identifier of the Cosmos database.

func (*DatabaseClient) NewContainer

func (db *DatabaseClient) NewContainer(id string) (*ContainerClient, error)

NewContainer returns a struct that represents the container and allows container level operations. id - The id of the container.

func (*DatabaseClient) Read

Read obtains the information for a Cosmos database. ctx - The context for the request. o - Options for Read operation.

func (*DatabaseClient) ReadThroughput

func (db *DatabaseClient) ReadThroughput(
	ctx context.Context,
	o *ThroughputOptions) (ThroughputResponse, error)

ReadThroughput obtains the provisioned throughput information for the database. ctx - The context for the request. o - Options for the operation.

func (*DatabaseClient) ReplaceThroughput

func (db *DatabaseClient) ReplaceThroughput(
	ctx context.Context,
	throughputProperties ThroughputProperties,
	o *ThroughputOptions) (ThroughputResponse, error)

ReplaceThroughput updates the provisioned throughput for the database. ctx - The context for the request. throughputProperties - The throughput configuration of the database. o - Options for the operation.

type DatabaseProperties

type DatabaseProperties struct {
	// ID contains the unique id of the database.
	ID string `json:"id"`
	// ETag contains the entity etag of the database
	ETag *azcore.ETag `json:"_etag,omitempty"`
	// SelfLink contains the self-link of the database
	SelfLink string `json:"_self,omitempty"`
	// ResourceID contains the resource id of the database
	ResourceID string `json:"_rid,omitempty"`
	// LastModified contains the last modified time of the database
	LastModified time.Time `json:"_ts,omitempty"`
}

DatabaseProperties represents the properties of a database.

func (DatabaseProperties) MarshalJSON

func (tp DatabaseProperties) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface

func (*DatabaseProperties) UnmarshalJSON

func (tp *DatabaseProperties) UnmarshalJSON(b []byte) error

UnmarshalJSON implements the json.Unmarshaler interface

type DatabaseResponse

type DatabaseResponse struct {
	// DatabaseProperties contains the unmarshalled response body in DatabaseProperties format.
	DatabaseProperties *DatabaseProperties
	Response
}

DatabaseResponse represents the response from a database request.

type DeleteContainerOptions

type DeleteContainerOptions struct{}

DeleteContainerOptions are options for the DeleteContainer operation

type DeleteDatabaseOptions

type DeleteDatabaseOptions struct {
	IfMatchEtag     *azcore.ETag
	IfNoneMatchEtag *azcore.ETag
}

DeleteDatabaseOptions includes options DeleteDatabase operation.

type ExcludedPath

type ExcludedPath struct {
	// Path to be excluded.
	Path string `json:"path"`
}

ExcludedPath represents a json path to be excluded from indexing.

type IncludedPath

type IncludedPath struct {
	// Path to be included.
	Path string `json:"path"`
}

IncludedPath represents a json path to be included in indexing.

type IndexingDirective

type IndexingDirective string

IndexingDirective specifies whether the resource in the Azure Cosmos DB database is to be indexed.

const (
	// Use any pre-defined/pre-configured defaults.
	IndexingDirectiveDefault IndexingDirective = "Default"
	// Index the resource.
	IndexingDirectiveInclude IndexingDirective = "Include"
	// Do not index the resource.
	IndexingDirectiveExclude IndexingDirective = "Exclude"
)

func IndexingDirectives

func IndexingDirectives() []IndexingDirective

Returns a list of available indexing directives

func (IndexingDirective) ToPtr

ToPtr returns a *IndexingDirective

type IndexingMode

type IndexingMode string

IndexingMode defines the supported indexing modes in the Azure Cosmos DB service.

const (
	// IndexingModeConsistent Index is updated synchronously with a create, update or delete operation.
	IndexingModeConsistent IndexingMode = "Consistent"
	// No index is provided.
	IndexingModeNone IndexingMode = "None"
)

func IndexingModeValues

func IndexingModeValues() []IndexingMode

Returns a list of available consistency levels

func (IndexingMode) ToPtr

func (c IndexingMode) ToPtr() *IndexingMode

ToPtr returns a *IndexingMode

type IndexingPolicy

type IndexingPolicy struct {
	// Automatic defines if the indexing policy is automatic or manual.
	Automatic bool `json:"automatic"`
	// IndexingMode for the container.
	IndexingMode IndexingMode `json:"indexingMode,omitempty"`
	// Paths to be indexed.
	IncludedPaths []IncludedPath `json:"includedPaths,omitempty"`
	// Paths to be excluded.
	ExcludedPaths []ExcludedPath `json:"excludedPaths,omitempty"`
	// Spatial indexes.
	SpatialIndexes []SpatialIndex `json:"spatialIndexes,omitempty"`
	// Spatial indexes.
	CompositeIndexes [][]CompositeIndex `json:"compositeIndexes,omitempty"`
}

IndexingPolicy represents an indexing policy for a container. For more information see https://docs.microsoft.com/azure/cosmos-db/index-policy

type ItemOptions

type ItemOptions struct {
	// Triggers to be invoked before the operation.
	PreTriggers []string
	// Triggers to be invoked after the operation.
	PostTriggers []string
	// SessionToken to be used when using Session consistency on the account.
	// When working with Session consistency, each new write request to Azure Cosmos DB is assigned a new SessionToken.
	// The client instance will use this token internally with each read/query request to ensure that the set consistency level is maintained.
	// In some scenarios you need to manage this Session yourself: Consider a web application with multiple nodes, each node will have its own client instance.
	// If you wanted these nodes to participate in the same session (to be able read your own writes consistently across web tiers),
	// you would have to send the SessionToken from the response of the write action on one node to the client tier, using a cookie or some other mechanism, and have that token flow back to the web tier for subsequent reads.
	// If you are using a round-robin load balancer which does not maintain session affinity between requests, such as the Azure Load Balancer,the read could potentially land on a different node to the write request, where the session was created.
	SessionToken string
	// ConsistencyLevel overrides the account defined consistency level for this operation.
	// Consistency can only be relaxed.
	ConsistencyLevel *ConsistencyLevel
	// Indexing directive to be applied to the operation.
	IndexingDirective *IndexingDirective
	// When EnableContentResponseOnWrite is false will cause the response on write operations to have a null resource. This reduces networking and CPU load by not sending the resource back over the network and serializing it on the client.
	// The default is false.
	EnableContentResponseOnWrite bool
	// IfMatchEtag is used to ensure optimistic concurrency control.
	// https://docs.microsoft.com/azure/cosmos-db/sql/database-transactions-optimistic-concurrency#optimistic-concurrency-control
	IfMatchEtag *azcore.ETag
}

ItemOptions includes options for operations on items.

type ItemResponse

type ItemResponse struct {
	// The byte content of the operation response.
	Value []byte
	Response
	// SessionToken contains the value from the session token header to be used on session consistency.
	SessionToken string
}

ItemResponse represents the response from an item request.

type KeyCredential

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

KeyCredential contains an account's name and its primary or secondary key. It is immutable making it shareable and goroutine-safe.

func NewKeyCredential

func NewKeyCredential(accountKey string) (KeyCredential, error)

NewKeyCredential creates an KeyCredential containing the account's primary or secondary key.

func (*KeyCredential) Update

func (c *KeyCredential) Update(accountKey string) error

Update replaces the existing account key with the specified account key.

type PartitionKey

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

PartitionKey represents a logical partition key value.

func NewPartitionKeyBool

func NewPartitionKeyBool(value bool) PartitionKey

NewPartitionKeyBool creates a partition key with a boolean value.

func NewPartitionKeyNumber

func NewPartitionKeyNumber(value float64) PartitionKey

NewPartitionKeyNumber creates a partition key with a numeric value.

func NewPartitionKeyString

func NewPartitionKeyString(value string) PartitionKey

NewPartitionKeyString creates a partition key with a string value.

type PartitionKeyDefinition

type PartitionKeyDefinition struct {
	// Paths returns the list of partition key paths of the container.
	Paths []string `json:"paths"`
	// Version returns the version of the hash partitioning of the container.
	Version int `json:"version,omitempty"`
}

PartitionKeyDefinition represents a partition key definition in the Azure Cosmos DB database service. A partition key definition defines the path for the partition key property.

type QueryItemsResponse

type QueryItemsResponse struct {
	Response
	// ContinuationToken contains the value of the x-ms-continuation header in the response.
	// It can be used to stop a query and resume it later.
	ContinuationToken string
	// Contains the query metrics related to the query execution
	QueryMetrics *string
	// IndexMetrics contains the index utilization metrics if QueryOptions.PopulateIndexMetrics = true
	IndexMetrics *string
	// List of items.
	Items [][]byte
}

QueryItemsResponse contains response from the query operation.

type QueryOptions

type QueryOptions struct {
	// SessionToken to be used when using Session consistency on the account.
	// When working with Session consistency, each new write request to Azure Cosmos DB is assigned a new SessionToken.
	// The client instance will use this token internally with each read/query request to ensure that the set consistency level is maintained.
	// In some scenarios you need to manage this Session yourself: Consider a web application with multiple nodes, each node will have its own client instance.
	// If you wanted these nodes to participate in the same session (to be able read your own writes consistently across web tiers),
	// you would have to send the SessionToken from the response of the write action on one node to the client tier, using a cookie or some other mechanism, and have that token flow back to the web tier for subsequent reads.
	// If you are using a round-robin load balancer which does not maintain session affinity between requests, such as the Azure Load Balancer,the read could potentially land on a different node to the write request, where the session was created.
	SessionToken string
	// ConsistencyLevel overrides the account defined consistency level for this operation.
	// Consistency can only be relaxed.
	ConsistencyLevel *ConsistencyLevel
	// PopulateIndexMetrics is used to obtain the index metrics to understand how the query engine used existing indexes and how it could use potential new indexes.
	// Please note that this options will incur overhead, so it should be enabled only when debugging slow queries and not in production.
	PopulateIndexMetrics bool
	// ResponseContinuationTokenLimitInKB is used to limit the length of continuation token in the query response. Valid values are >= 0.
	ResponseContinuationTokenLimitInKB int32
	// PageSizeHint determines the maximum number of items to be retrieved in a query result page.
	// '-1' Used for dynamic page size. This is a maximum. Query can return 0 items in the page.
	PageSizeHint int32
	// EnableScanInQuery Allow scan on the queries which couldn't be served as indexing was opted out on the requested paths.
	EnableScanInQuery bool
	// ContinuationToken to be used to continue a previous query execution.
	// Obtained from QueryItemsResponse.ContinuationToken.
	ContinuationToken string
	// QueryParameters allows execution of parametrized queries.
	// See https://docs.microsoft.com/azure/cosmos-db/sql/sql-query-parameterized-queries
	QueryParameters []QueryParameter
}

QueryOptions includes options for query operations on items.

type QueryParameter

type QueryParameter struct {
	// Name represents the name of the parameter in the parametrized query.
	Name string `json:"name"`
	// Value represents the value of the parameter in the parametrized query.
	Value any `json:"value"`
}

QueryParameter represents a parameter for a parametrized query.

type ReadContainerOptions

type ReadContainerOptions struct {
	// PopulateQuotaInfo indicates whether to populate quota info in response headers.
	PopulateQuotaInfo bool
}

ReadContainerOptions includes options for Read

type ReadDatabaseOptions

type ReadDatabaseOptions struct {
	IfMatchEtag     *azcore.ETag
	IfNoneMatchEtag *azcore.ETag
}

ReadDatabaseOptions includes options ReadDatabase operation.

type ReplaceContainerOptions

type ReplaceContainerOptions struct{}

ReplaceContainerOptions are options for the ReplaceContainer operation

type Response

type Response struct {
	// RawResponse contains the underlying HTTP response.
	RawResponse *http.Response
	// RequestCharge contains the value from the request charge header.
	RequestCharge float32
	// ActivityID contains the value from the activity header.
	ActivityID string
	// ETag contains the value from the ETag header.
	ETag azcore.ETag
}

Response is the base response type for all responses from the Azure Cosmos DB database service. It contains base methods and properties that are common to all responses.

type SpatialIndex

type SpatialIndex struct {
	// Path for the index.
	Path string `json:"path"`
	// SpatialType of the spatial index.
	SpatialTypes []SpatialType `json:"types"`
}

SpatialIndex represents a spatial index.

type SpatialType

type SpatialType string

SpatialType defines supported values for spatial index types in Spatial Indexes

const (
	// Represents a point.
	SpatialTypePoint SpatialType = "Point"
	// Represents a polygon.
	SpatialTypePolygon SpatialType = "Polygon"
	// Represents a line string.
	SpatialTypeLineString SpatialType = "LineString"
	// Represents a multi polygon.
	SpatialTypeMultiPolygon SpatialType = "MultiPolygon"
)

func SpatialTypeValues

func SpatialTypeValues() []SpatialType

Returns a list of available data types

func (SpatialType) ToPtr

func (c SpatialType) ToPtr() *SpatialType

ToPtr returns a *SpatialType

type ThroughputOptions

type ThroughputOptions struct {
	// IfMatchEtag If-Match (ETag) associated with the request.
	IfMatchEtag *azcore.ETag
	// IfNoneMatchEtag If-None-Match (ETag) associated with the request.
	IfNoneMatchEtag *azcore.ETag
}

ThroughputOptions includes options for throughput operations.

type ThroughputProperties

type ThroughputProperties struct {
	// ETag contains the entity etag of the throughput information.
	ETag *azcore.ETag
	// LastModified contains the last modified time of the throughput information.
	LastModified time.Time
	// contains filtered or unexported fields
}

ThroughputProperties describes the throughput configuration of a resource. It must be initialized through the available constructors.

func NewAutoscaleThroughputProperties

func NewAutoscaleThroughputProperties(startingMaxThroughput int32) ThroughputProperties

NewAutoscaleThroughputProperties returns a ThroughputProperties object with the given max throughput on autoscale mode. maxThroughput - the max throughput in RU/s

func NewAutoscaleThroughputPropertiesWithIncrement

func NewAutoscaleThroughputPropertiesWithIncrement(startingMaxThroughput int32, incrementPercentage int32) ThroughputProperties

NewAutoscaleThroughputPropertiesWithIncrement returns a ThroughputProperties object with the given max throughput on autoscale mode. maxThroughput - the max throughput in RU/s incrementPercentage - the auto upgrade max throughput increment percentage

func NewManualThroughputProperties

func NewManualThroughputProperties(throughput int32) ThroughputProperties

NewManualThroughputProperties returns a ThroughputProperties object with the given throughput in manual mode. throughput - the throughput in RU/s

func (*ThroughputProperties) AutoscaleIncrement

func (tp *ThroughputProperties) AutoscaleIncrement() (int32, bool)

AutoscaleIncrement returns the configured percent increment on autoscale mode.

func (*ThroughputProperties) AutoscaleMaxThroughput

func (tp *ThroughputProperties) AutoscaleMaxThroughput() (int32, bool)

AutoscaleMaxThroughput returns the configured max throughput on autoscale mode.

func (*ThroughputProperties) ManualThroughput

func (tp *ThroughputProperties) ManualThroughput() (int32, bool)

ManualThroughput returns the provisioned throughput in manual mode.

func (*ThroughputProperties) MarshalJSON

func (tp *ThroughputProperties) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface

func (*ThroughputProperties) UnmarshalJSON

func (tp *ThroughputProperties) UnmarshalJSON(b []byte) error

UnmarshalJSON implements the json.Unmarshaler interface

type ThroughputResponse

type ThroughputResponse struct {
	// ThroughputProperties contains the unmarshalled response body in ThroughputProperties format.
	ThroughputProperties *ThroughputProperties
	Response
	// IsReplacePending returns the state of a throughput update.
	IsReplacePending bool
	// MinThroughput is minimum throughput in measurement of request units per second in the Azure Cosmos service.
	MinThroughput *int32
}

ThroughputResponse represents the response from a throughput request.

type TransactionalBatch

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

TransactionalBatch is a batch of operations to be executed in a single transaction. See https://docs.microsoft.com/azure/cosmos-db/sql/transactional-batch

func (*TransactionalBatch) CreateItem

func (b *TransactionalBatch) CreateItem(item []byte, o *TransactionalBatchItemOptions)

CreateItem adds a create operation to the batch.

func (*TransactionalBatch) DeleteItem

func (b *TransactionalBatch) DeleteItem(itemID string, o *TransactionalBatchItemOptions)

DeleteItem adds a delete operation to the batch.

func (*TransactionalBatch) ReadItem

ReadItem adds a read operation to the batch.

func (*TransactionalBatch) ReplaceItem

func (b *TransactionalBatch) ReplaceItem(itemID string, item []byte, o *TransactionalBatchItemOptions)

ReplaceItem adds a replace operation to the batch.

func (*TransactionalBatch) UpsertItem

func (b *TransactionalBatch) UpsertItem(item []byte, o *TransactionalBatchItemOptions)

UpsertItem adds an upsert operation to the batch.

type TransactionalBatchItemOptions

type TransactionalBatchItemOptions struct {
	// IfMatchETag is used to ensure optimistic concurrency control.
	// https://docs.microsoft.com/azure/cosmos-db/sql/database-transactions-optimistic-concurrency#optimistic-concurrency-control
	IfMatchETag *azcore.ETag
}

TransactionalBatchItemOptions includes options for the specific operation inside a TransactionalBatch

type TransactionalBatchOptions

type TransactionalBatchOptions struct {
	// SessionToken to be used when using Session consistency on the account.
	// When working with Session consistency, each new write request to Azure Cosmos DB is assigned a new SessionToken.
	// The client instance will use this token internally with each read/query request to ensure that the set consistency level is maintained.
	// In some scenarios you need to manage this Session yourself: Consider a web application with multiple nodes, each node will have its own client instance.
	// If you wanted these nodes to participate in the same session (to be able read your own writes consistently across web tiers),
	// you would have to send the SessionToken from the response of the write action on one node to the client tier, using a cookie or some other mechanism, and have that token flow back to the web tier for subsequent reads.
	// If you are using a round-robin load balancer which does not maintain session affinity between requests, such as the Azure Load Balancer,the read could potentially land on a different node to the write request, where the session was created.
	SessionToken string
	// ConsistencyLevel overrides the account defined consistency level for this operation.
	// Consistency can only be relaxed.
	ConsistencyLevel *ConsistencyLevel
	// When EnableContentResponseOnWrite is false, the operations in the batch response will have no body, except when they are Read operations.
	// The default is false.
	EnableContentResponseOnWrite bool
}

TransactionalBatchOptions includes options for transactional batch operations.

type TransactionalBatchResponse

type TransactionalBatchResponse struct {
	Response
	// SessionToken contains the value from the session token header to be used on session consistency.
	SessionToken string
	// OperationResults contains the individual batch operation results.
	// The order of the results is the same as the order of the operations in the batch.
	OperationResults []TransactionalBatchResult
	// Success indicates if the transaction was successfully committed.
	// If false, one of the operations in the batch failed.
	// Inspect the OperationResults, any operation with status code http.StatusFailedDependency is a dependency failure.
	// The cause of the batch failure is the first operation with status code different from http.StatusFailedDependency.
	Success bool
}

TransactionalBatchResponse contains response from a transactional batch operation.

type TransactionalBatchResult

type TransactionalBatchResult struct {
	// StatusCode contains the status code of the operation.
	StatusCode int32
	// RequestCharge contains the request charge for the operation.
	RequestCharge float32
	// ResourceBody contains the body response of the operation.
	// This property is available depending on the EnableContentResponseOnWrite option.
	ResourceBody []byte
	// ETag contains the ETag of the operation.
	ETag azcore.ETag
}

TransactionalBatchResult represents the result of a single operation in a batch.

func (*TransactionalBatchResult) UnmarshalJSON

func (or *TransactionalBatchResult) UnmarshalJSON(b []byte) error

UnmarshalJSON implements the json.Unmarshaler interface

type UniqueKey

type UniqueKey struct {
	// Paths define a sets of paths which must be unique for each document.
	Paths []string `json:"paths"`
}

UniqueKey represents a unique key for a container. For more information see https://docs.microsoft.com/azure/cosmos-db/unique-keys

type UniqueKeyPolicy

type UniqueKeyPolicy struct {
	// Automatic defines if the indexing policy is automatic or manual.
	UniqueKeys []UniqueKey `json:"uniqueKeys"`
}

UniqueKeyPolicy represents a unique key policy for a container. For more information see https://docs.microsoft.com/azure/cosmos-db/unique-keys

Jump to

Keyboard shortcuts

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