aztables

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Jan 12, 2022 License: MIT Imports: 31 Imported by: 23

README

Azure Tables client library for Go

Azure Tables is a NoSQL data storage service that can be accessed from anywhere in the world via authenticated calls using HTTP or HTTPS. Tables scales as needed to support the amount of data inserted, and allows for the storing of data with non-complex accessing. The Azure Tables client can be used to access Azure Storage or Cosmos accounts.

Source code | API reference documentation

Getting started

The Azure Tables SDK can access an Azure Storage or CosmosDB account.

Prerequisites
Create account
Install the package

Install the Azure Tables client library for Go with go get:

go get github.com/Azure/azure-sdk-for-go/sdk/data/aztables
Create the client

The Azure Tables library allows you to interact with two types of resources:

  • the tables in your account
  • the entities within those tables. Interaction with these resources starts with an instance of a client. To create a client object, you will need the account's table service endpoint URL and a credential that allows you to access the account. The endpoint can be found on the page for your storage account in the Azure Portal under the "Access Keys" section or by running the following Azure CLI command:
# Log in to Azure CLI first, this opens a browser window
az login
# Get the table service URL for the account
az storage account show -n mystorageaccount -g MyResourceGroup --query "primaryEndpoints.table"

Once you have the account URL, it can be used to create the service client:

cred, err := aztables.NewSharedKeyCredential("myAccountName", "myAccountKey")
handle(err)
serviceClient, err := aztables.NewServiceClientWithSharedKeyCredential("https://<myAccountName>.table.core.windows.net/", cred, nil)
handle(err)

For more information about table service URL's and how to configure custom domain names for Azure Storage check out the official documentation

Types of credentials

The clients support different forms of authentication. Cosmos accounts can use a Shared Key Credential, Connection String, or an Shared Access Signature Token for authentication. Storage account can use the same credentials as a Cosmos account and can use the credentials in azidentity like azidentity.NewDefaultAzureCredential().

The aztables package supports any of the types that implement the azcore.TokenCredential interface, authorization via a Connection String, or authorization with a Shared Access Signature Token.

Creating the client with an AAD credential

Use AAD authentication as the credential parameter to authenticate the client:

cred, err := azidentity.NewDefaultAzureCredential(nil)
handle(err)
serviceClient, err := aztables.NewServiceClient("https://<myAccountName>.table.core.windows.net/", cred, nil)
handle(err)
Creating the client from a shared key

To use an account shared key (aka account key or access key), provide the key as a string. This can be found in your storage account in the Azure Portal under the "Access Keys" section or by running the following Azure CLI command:

az storage account keys list -g MyResourceGroup -n MyStorageAccount
cred, err := aztables.NewSharedKeyCredential("<accountName>", "<accountKey>")
handle(err)
client, err := aztables.NewServiceClientWithSharedKey(serviceURL, cred, nil)
handle(err)
Creating the client from a connection string

Depending on your use case and authorization method, you may prefer to initialize a client instance with a connection string instead of providing the account URL and credential separately. To do this, pass the connection string to the client's NewServiceClientFromConnectionString method. The connection string can be found in your storage account in the Azure Portal under the "Access Keys" section or with the following Azure CLI command:

az storage account show-connection-string -g MyResourceGroup -n MyStorageAccount
connStr := "DefaultEndpointsProtocol=https;AccountName=<myAccountName>;AccountKey=<myAccountKey>;EndpointSuffix=core.windows.net"
serviceClient, err := aztables.NewServiceClientFromConnectionString(connStr, nil)
Creating the client from a SAS token

To use a shared access signature (SAS) token, provide the token as a string. If your account URL includes the SAS token, omit the credential parameter. You can generate a SAS token from the Azure Portal under Shared access signature or use the ServiceClient.GetAccountSASToken or Client.GetTableSASToken() methods.

cred, err := aztables.NewSharedKeyCredential("myAccountName", "myAccountKey")
handle(err)
service, err := aztables.NewServiceClient("https://<myAccountName>.table.core.windows.net", cred, nil)

resources := aztables.AccountSASResourceTypes{Service: true}
permission := aztables.AccountSASPermissions{Read: true}
start := time.Now()
expiry := start.AddDate(1, 0, 0)
sasUrl, err := service.GetAccountSASToken(resources, permission, start, expiry)
handle(err)

sasService, err := aztables.NewServiceClient(sasUrl, azcore.AnonymousCredential(), nil)
handle(err)
Creating the client for Azurite

If you are using the Azurite emulator you can authenticate a client with the default connection string:

connStr := "DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;TableEndpoint=http://127.0.0.1:10002/devstoreaccount1;"
svc, err := NewServiceClientFromConnectionString(connStr, nil)
handle(err)

client, err := svc.CreateTable(context.TODO(), "AzuriteTable", nil)
handle(err)

Key concepts

Common uses of the table service include:

  • Storing TBs of structured data capable of serving web scale applications
  • Storing datasets that do not require complex joins, foreign keys, or stored procedures and can be de-normalized for fast access
  • Quickly querying data using a clustered index
  • Accessing data using the OData protocol filter expressions

The following components make up the Azure Tables Service:

  • The account
  • A table within the account, which contains a set of entities
  • An entity within a table, as a dictionary

The Azure Tables client library for Go allows you to interact with each of these components through the use of a dedicated client object.

Clients

Two different clients are provided to interact with the various components of the Table Service:

  1. Client -
    • Interacts with a specific table (which need not exist yet).
    • Create, delete, query, and upsert entities within the specified table.
    • Create or delete the specified table itself.
  2. ServiceClient -
    • Get and set account settings
    • Query, create, and delete tables within the account.
    • Get a Client to access a specific table using the NewClient method.
Entities

Entities are similar to rows. An entity has a PartitionKey, a RowKey, and a set of properties. A property is a name value pair, similar to a column. Every entity in a table does not need to have the same properties. Entities are returned as JSON, allowing developers to use JSON marshalling and unmarshalling techniques. Additionally, you can use the aztables.EDMEntity to ensure proper round-trip serialization of all properties.

aztables.EDMEntity{
    Entity: aztables.Entity{
        PartitionKey: "pencils",
        RowKey: "Wooden Pencils",
    },
    Properties: map[string]interface{}{
        "Product": "Ticonderoga Pencils",
        "Price": 5.00,
        "Count": aztables.EDMInt64(12345678901234),
        "ProductGUID": aztables.EDMGUID("some-guid-value"),
        "DateReceived": aztables.EDMDateTime(time.Date{....})
    }
}

Examples

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

Creating a table

Create a table in your account and get a Client to perform operations on the newly created table:

cred, err := aztables.NewSharedKeyCredential("myAccountName", "myAccountKey")
handle(err)
service, err := aztables.NewServiceClient("https://<myAccountName>.table.core.windows.net", cred, nil)
handle(err)
resp, err := service.CreateTable("myTable")
Creating entities

Create entities in the table:

cred, err := aztables.NewSharedKeyCredential("myAccountName", "myAccountKey")
handle(err)

service, err := aztables.NewServiceClient("https://<myAccountName>.table.core.windows.net", cred, nil)
handle(err)

client, err := service.NewClient("myTable")
handle(err)

myEntity := aztables.EDMEntity{
    Entity: aztables.Entity{
        PartitionKey: "001234",
        RowKey: "RedMarker",
    },
    Properties: map[string]interface{}{
        "Stock": 15,
        "Price": 9.99,
        "Comments": "great product",
        "OnSale": true,
        "ReducedPrice": 7.99,
        "PurchaseDate": aztables.EDMDateTime(time.Date(2021, time.August, 21, 1, 1, 0, 0, time.UTC)),
        "BinaryRepresentation": aztables.EDMBinary([]byte{"Bytesliceinfo"})
    }
}
marshalled, err := json.Marshal(myEntity)
handle(err)

resp, err := client.AddEntity(context.TODO(), marshalled, nil)
handle(err)
Listing entities

List entities in the table:

cred, err := aztables.NewSharedKeyCredential("myAccountName", "myAccountKey")
handle(err)
client, err := aztables.NewClient("https://myAccountName.table.core.windows.net/myTable", cred, nil)
handle(err)

filter := "PartitionKey eq 'markers' or RowKey eq 'Markers'"
options := &ListEntitiesOptions{
    Filter: &filter,
    Select: to.StringPtr("RowKey,Value,Product,Available"),
    Top: to.Int32Ptr(15),
}

pager := client.List(options) // pass in "nil" if you want to list all entities
for pager.NextPage(context.TODO()) {
    resp := pager.PageResponse()
    fmt.Printf("Received: %v entities\n", len(resp.Entities))

    for _, entity := range resp.Entities {
        var myEntity aztables.EDMEntity
        err = json.Unmarshal(entity, &myEntity)
        handle(err)

        fmt.Printf("Received: %v, %v, %v, %v\n", myEntity.RowKey, myEntity.Properties["Value"], myEntity.Properties["Product"], myEntity.Properties["Available"])
    }
}

err := pager.Err()
handle(err)

The pager exposes continuation tokens that can be used by a new pager instance to begin listing entities from a specific point. For example:

pager := client.List(&ListEntitiesOptions{Top: to.Int32Ptr(10)})
count := 0
for pager.NextPage(context.TODO()) {
    count += len(pager.PageResponse().Entities)

    if count > 20 {
        break
    }
}
handle(pager.Err())

newPager := client.List(&ListEntitiesOptions{
    Top:          to.Int32Ptr(10),
    PartitionKey: pager.NextPagePartitionKey(),
    RowKey:       pager.NextPageRowKey(),
})

for newPager.NextPage(context.TODO()) {
    // begin paging where 'pager' left off
}

handle(newPager.Err())

Troubleshooting

Error Handling

All I/O operations will return an error that can be investigated to discover more information about the error. In addition, you can investigate the raw response of any response object:

resp, err := client.CreateTable(context.TODO(), nil)
if err != nil {
    err = errors.As(err, azcore.HTTPResponse)
    // handle err ...
}
Logging

This module uses the classification based logging implementation in azcore. To turn on logging set AZURE_SDK_GO_LOGGING to all. If you only want to include logs for aztables, you must create your own logger and set the log classification as LogCredential.

To obtain more detailed logging, including request/response bodies and header values, make sure to leave the logger as default or enable the LogRequest and/or LogResponse classificatons. A logger that only includes credential logs can be like the following:

import azlog "github.com/Azure/azure-sdk-for-go/sdk/azcore/log"
// Set log to output to the console
log.SetListener(func(cls log.Classification, msg string) {
		fmt.Println(msg) // printing log out to the console
})

// Includes only requests and responses in credential logs
log.SetClassifications(log.Request, log.Response)

CAUTION: logs from credentials contain sensitive information. These logs must be protected to avoid compromising account security.

Next steps

Provide Feedback

If you encounter bugs or have suggestions, please open an issue and assign the Azure.Tables 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.

Additional documentation

For more extensive documentation on Azure Tables, see the Azure Tables documentation on docs.microsoft.com.

Known Issues

A list of currently known issues relating to Cosmos DB table endpoints can be found here.

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 aztables can access an Azure Storage or CosmosDB account.

The aztables package is capable of:

  • Creating, deleting, and listing tables in an account
  • Creating, deleting, updating, and querying entities in a table account
  • Creating Shared Access Signatures for authentication

Creating the Client

The Azure Data Tables library allows you to interact with two types of resources: * the tables in your account * the entities within those tables. Interaction with these resources starts with an instance of a client. To create a client object, you will need the account's table service endpoint URL and a credential that allows you to access the account.

cred, err := aztables.NewSharedKeyCredential("myAccountName", "myAccountKey")
handle(err)
serviceClient, err := aztables.NewServiceClient("https://<my_account_name>.table.core.windows.net/", cred, nil)
handle(err)

Types of Credentials

The clients support different forms of authentication. The aztables library supports any of the `azcore.TokenCredential` interfaces, authorization via a Connection String, or authorization with a Shared Access Signature token.

Using a Shared Key

To use an account shared key (aka account key or access key), provide the key as a string. This can be found in your storage account in the Azure Portal under the "Access Keys" section.

Use the key as the credential parameter to authenticate the client:

cred, err := aztables.NewSharedKeyCredential("myAccountName", "myAccountKey")
handle(err)
serviceClient, err := aztables.NewServiceClient("https://<my_account_name>.table.core.windows.net/", cred, nil)
handle(err)

Using a Connection String Depending on your use case and authorization method, you may prefer to initialize a client instance with a connection string instead of providing the account URL and credential separately. To do this, pass the connection string to the client's `from_connection_string` class method. The connection string can be found in your storage account in the [Azure Portal][azure_portal_account_url] under the "Access Keys" section or with the following Azure CLI command:

connStr := "DefaultEndpointsProtocol=https;AccountName=<my_account_name>;AccountKey=<my_account_key>;EndpointSuffix=core.windows.net"
serviceClient, err := aztables.NewServiceClientFromConnectionString(connStr, nil)

Using a Shared Access Signature To use a shared access signature (SAS) token, provide the token at the end of your service URL. You can generate a SAS token from the Azure Portal under Shared Access Signature or use the ServiceClient.GetAccountSASToken or Client.GetTableSASToken() functions.

cred, err := aztables.NewSharedKeyCredential("myAccountName", "myAccountKey")
handle(err)
service, err := aztables.NewServiceClient("https://<my_account_name>.table.core.windows.net", cred, nil)
handle(err)

resources := aztables.AccountSASResourceTypes{Service: true}
permission := aztables.AccountSASPermissions{Read: true}
start := time.Date(2021, time.August, 21, 1, 1, 0, 0, time.UTC)
expiry := time.Date(2022, time.August, 21, 1, 1, 0, 0, time.UTC)
sasUrl, err := service.GetAccountSASToken(resources, permission, start, expiry)
handle(err)

sasService, err := aztables.NewServiceClient(sasUrl, azcore.AnonymousCredential(), nil)
handle(err)

Key Concepts

Common uses of the Table service included: * Storing TBs of structured data capable of serving web scale applications * Storing datasets that do not require complex joins, foreign keys, or stored procedures and can be de-normalized for fast access * Quickly querying data using a clustered index * Accessing data using the OData protocol and LINQ filter expressions

The following components make up the Azure Data Tables Service: * The account * A table within the account, which contains a set of entities * An entity within a table, as a dictionary

The Azure Data Tables client library for Go allows you to interact with each of these components through the use of a dedicated client object.

Two different clients are provided to interact with the various components of the Table Service: 1. **`ServiceClient`** -

  • Get and set account setting
  • Query, create, and delete tables within the account.
  • Get a `Client` to access a specific table using the `NewClient` method.

2. **`Client`** -

  • Interacts with a specific table (which need not exist yet).
  • Create, delete, query, and upsert entities within the specified table.
  • Create or delete the specified table itself.

Entities are similar to rows. An entity has a PartitionKey, a RowKey, and a set of properties. A property is a name value pair, similar to a column. Every entity in a table does not need to have the same properties. Entities are returned as JSON, allowing developers to use JSON marshalling and unmarshalling techniques. Additionally, you can use the aztables.EDMEntity to ensure proper round-trip serialization of all properties.

aztables.EDMEntity{
	Entity: aztables.Entity{
		PartitionKey: "pencils",
		RowKey: "id-003",
	},
	Properties: map[string]interface{}{
		"Product": "Ticonderoga Pencils",
		"Price": 5.00,
		"Count": aztables.EDMInt64(12345678901234),
		"ProductGUID": aztables.EDMGUID("some-guid-value"),
		"DateReceived": aztables.EDMDateTime(time.Date{....}),
		"ProductCode": aztables.EDMBinary([]byte{"somebinaryvalue"})
	}
}

More Examples

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

* Creating a table * Creating entities * Querying entities

Creating a Table

Create a table in your account and get a `Client` to perform operations on the newly created table:

cred, err := aztables.NewSharedKeyCredential("myAccountName", "myAccountKey")
handle(err)
service, err := aztables.NewServiceClient("https://<my_account_name>.table.core.windows.net", cred, nil)
handle(err)
resp, err := service.CreateTable("myTable")

Creating Entities

cred, err := aztables.NewSharedKeyCredential("myAccountName", "myAccountKey")
handle(err)
service, err := aztables.NewServiceClient("https://<my_account_name>.table.core.windows.net", cred, nil)
handle(err)

myEntity := aztables.EDMEntity{
	Entity: aztables.Entity{
		PartitionKey: "001234",
		RowKey: "RedMarker",
	},
	Properties: map[string]interface{}{
		"Stock": 15,
		"Price": 9.99,
		"Comments": "great product",
		"OnSale": true,
		"ReducedPrice": 7.99,
		"PurchaseDate": aztables.EDMDateTime(time.Date(2021, time.August, 21, 1, 1, 0, 0, time.UTC)),
		"BinaryRepresentation": aztables.EDMBinary([]byte{"Bytesliceinfo"})
	}
}
marshalled, err := json.Marshal(myEntity)
handle(err)

client, err := service.NewClient("myTable")
handle(err)

resp, err := client.AddEntity(context.Background(), marshalled, nil)
handle(err)

Querying entities

cred, err := aztables.NewSharedKeyCredential("myAccountName", "myAccountKey")
handle(err)
client, err := aztables.NewClient("https://myAccountName.table.core.windows.net/myTableName", cred, nil)
handle(err)

filter := "PartitionKey eq 'markers' or RowKey eq 'id-001'"
options := &ListEntitiesOptions{
	Filter: &filter,
	Select: to.StringPtr("RowKey,Value,Product,Available"),
	Top: to.Int32Ptr(15),
}

pager := client.List(options)
for pager.NextPage(context.Background()) {
	resp := pager.PageResponse()
	fmt.Printf("Received: %v entities\n", len(resp.Entities))

	for _, entity := range resp.Entities {
		var myEntity aztables.EDMEntity
		err = json.Unmarshal(entity, &myEntity)
		handle(err)

		fmt.Printf("Received: %v, %v, %v, %v\n", myEntity.Properties["RowKey"], myEntity.Properties["Value"], myEntity.Properties["Product"], myEntity.Properties["Available"])
	}
}

if pager.Err() != nil {
	// handle error...
}

Index

Examples

Constants

This section is empty.

Variables

View Source
var SASVersion = "2019-02-02"

Functions

func FormatTimesForSASSigning

func FormatTimesForSASSigning(startTime, expiryTime time.Time) (string, string)

FormatTimesForSASSigning converts a time.Time to a snapshotTimeFormat string suitable for a SASField's StartTime or ExpiryTime fields. Returns "" if value.IsZero().

Types

type AccessPolicy

type AccessPolicy struct {
	// REQUIRED; The datetime that the policy expires.
	Expiry *time.Time `xml:"Expiry"`

	// REQUIRED; The permissions for the acl policy.
	Permission *string `xml:"Permission"`

	// REQUIRED; The datetime from which the policy is active.
	Start *time.Time `xml:"Start"`
}

AccessPolicy - An Access policy.

type AccountSASPermissions

type AccountSASPermissions struct {
	Read    bool
	Write   bool
	Delete  bool
	List    bool
	Add     bool
	Create  bool
	Update  bool
	Process bool
}

The AccountSASPermissions type simplifies creating the permissions string for an Azure Storage Account SAS. Initialize an instance of this type and then call its String method to set AccountSASSignatureValues's Permissions field.

func (*AccountSASPermissions) Parse

func (p *AccountSASPermissions) Parse(s string) error

Parse initializes the AccountSASPermissions's fields from a string.

func (AccountSASPermissions) String

func (p AccountSASPermissions) String() string

String produces the SAS permissions string for an Azure Storage account. Call this method to set AccountSASSignatureValues's Permissions field.

type AccountSASResourceTypes

type AccountSASResourceTypes struct {
	Service   bool
	Container bool
	Object    bool
}

The AccountSASResourceTypes type simplifies creating the resource types string for an Azure Storage Account SAS. Initialize an instance of this type and then call its String method to set AccountSASSignatureValues's ResourceTypes field.

func (*AccountSASResourceTypes) Parse

func (rt *AccountSASResourceTypes) Parse(s string) error

Parse initializes the AccountSASResourceType's fields from a string.

func (AccountSASResourceTypes) String

func (rt AccountSASResourceTypes) String() string

String produces the SAS resource types string for an Azure Storage account. Call this method to set AccountSASSignatureValues's ResourceTypes field.

type AccountSASSignatureValues

type AccountSASSignatureValues struct {
	Version       string      `param:"sv"`  // If not specified, this defaults to SASVersion
	Protocol      SASProtocol `param:"spr"` // See the SASProtocol* constants
	StartTime     time.Time   `param:"st"`  // Not specified if IsZero
	ExpiryTime    time.Time   `param:"se"`  // Not specified if IsZero
	Permissions   string      `param:"sp"`  // Create by initializing a AccountSASPermissions and then call String()
	IPRange       IPRange     `param:"sip"`
	Services      string      `param:"ss"`  // Create by initializing AccountSASServices and then call String()
	ResourceTypes string      `param:"srt"` // Create by initializing AccountSASResourceTypes and then call String()
}

AccountSASSignatureValues is used to generate a Shared Access Signature (SAS) for an Azure Storage account. For more information, see https://docs.microsoft.com/rest/api/storageservices/constructing-an-account-sas

func (AccountSASSignatureValues) Sign

Sign uses an account's SharedKeyCredential to sign this signature values to produce the proper SAS query parameters.

type AddEntityOptions

type AddEntityOptions struct {
	// Specifies whether the response should include the inserted entity in the payload. Possible values are return-no-content and return-content.
	ResponsePreference *ResponseFormat
}

Options for the Client.AddEntity operation

type AddEntityResponse

type AddEntityResponse struct {
	RawResponse *http.Response
	ETag        azcore.ETag
}

type Client

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

A Client represents a client to the tables service affinitized to a specific table.

func NewClient

func NewClient(serviceURL string, cred azcore.TokenCredential, options *ClientOptions) (*Client, error)

NewClient creates a Client struct in the context of the table specified in the serviceURL, authorizing requests with an Azure AD access token. The serviceURL param is expected to have the name of the table in a format similar to: "https://myAccountName.core.windows.net/<myTableName>".

Example
package main

import (
	"fmt"
	"os"

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

func main() {
	accountName, ok := os.LookupEnv("TABLES_STORAGE_ACCOUNT_NAME")
	if !ok {
		panic("TABLES_STORAGE_ACCOUNT_NAME could not be found")
	}
	serviceURL := fmt.Sprintf("https://%s.table.core.windows.net/%s", accountName, "myTableName")

	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		panic(err)
	}
	client, err := aztables.NewClient(serviceURL, cred, nil)
	if err != nil {
		panic(err)
	}
	fmt.Println(client)
}
Output:

func NewClientWithNoCredential added in v0.3.0

func NewClientWithNoCredential(serviceURL string, options *ClientOptions) (*Client, error)

NewClientWithNoCredential creates a Client struct in the context of the table specified in the serviceURL. The serviceURL param is expected to have the name of the table in a format similar to: "https://myAccountName.core.windows.net/<myTableName>?<SAS token>".

func NewClientWithSharedKey added in v0.3.0

func NewClientWithSharedKey(serviceURL string, cred *SharedKeyCredential, options *ClientOptions) (*Client, error)

NewClientWithSharedKey creates a Client struct in the context of the table specified in the serviceURL, authorizing requests with a shared key. The serviceURL param is expected to have the name of the table in a format similar to: "https://myAccountName.core.windows.net/<myTableName>".

Example
package main

import (
	"fmt"
	"os"

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

func main() {
	accountName, ok := os.LookupEnv("TABLES_STORAGE_ACCOUNT_NAME")
	if !ok {
		panic("TABLES_STORAGE_ACCOUNT_NAME could not be found")
	}
	accountKey, ok := os.LookupEnv("TABLES_PRIMARY_STORAGE_ACCOUNT_KEY")
	if !ok {
		panic("TABLES_PRIMARY_STORAGE_ACCOUNT_KEY could not be found")
	}
	serviceURL := fmt.Sprintf("https://%s.table.core.windows.net/%s", accountName, "myTableName")

	cred, err := aztables.NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		panic(err)
	}
	client, err := aztables.NewClientWithSharedKey(serviceURL, cred, nil)
	if err != nil {
		panic(err)
	}
	fmt.Println(client)
}
Output:

func (*Client) AddEntity

func (t *Client) AddEntity(ctx context.Context, entity []byte, options *AddEntityOptions) (AddEntityResponse, error)

AddEntity adds an entity (described by a byte slice) to the table. This method returns an error if an entity with the same PartitionKey and RowKey already exists in the table. If the supplied entity does not contain both a PartitionKey and a RowKey an error will be returned.

func (*Client) Create

func (t *Client) Create(ctx context.Context, options *CreateTableOptions) (CreateTableResponse, error)

Create creates the table with the tableName specified when NewClient was called.

Example
package main

import (
	"context"
	"fmt"
	"os"

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

func main() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		panic(err)
	}
	accountName, ok := os.LookupEnv("TABLES_STORAGE_ACCOUNT_NAME")
	if !ok {
		panic("TABLES_STORAGE_ACCOUNT_NAME could not be found")
	}
	serviceURL := fmt.Sprintf("https://%s.table.core.windows.net/%s", accountName, "fromTableClient")
	client, err := aztables.NewClient(serviceURL, cred, nil)
	if err != nil {
		panic(err)
	}

	// Create a table
	_, err = client.Create(context.TODO(), nil)
	if err != nil {
		panic(err)
	}
}
Output:

func (*Client) Delete

func (t *Client) Delete(ctx context.Context, options *DeleteTableOptions) (DeleteTableResponse, error)

Delete deletes the table with the tableName specified when NewClient was called.

Example
package main

import (
	"context"
	"fmt"
	"os"

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

func main() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		panic(err)
	}
	accountName, ok := os.LookupEnv("TABLES_STORAGE_ACCOUNT_NAME")
	if !ok {
		panic("TABLES_STORAGE_ACCOUNT_NAME could not be found")
	}
	serviceURL := fmt.Sprintf("https://%s.table.core.windows.net/%s", accountName, "fromTableClient")
	client, err := aztables.NewClient(serviceURL, cred, nil)
	if err != nil {
		panic(err)
	}

	// Delete a table
	_, err = client.Delete(context.TODO(), nil)
	if err != nil {
		panic(err)
	}
}
Output:

func (*Client) DeleteEntity

func (t *Client) DeleteEntity(ctx context.Context, partitionKey string, rowKey string, options *DeleteEntityOptions) (DeleteEntityResponse, error)

DeleteEntity deletes the entity with the specified partitionKey and rowKey from the table.

Example
package main

import (
	"context"
	"fmt"
	"os"

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

func main() {
	accountName, ok := os.LookupEnv("TABLES_STORAGE_ACCOUNT_NAME")
	if !ok {
		panic("TABLES_STORAGE_ACCOUNT_NAME could not be found")
	}
	accountKey, ok := os.LookupEnv("TABLES_PRIMARY_STORAGE_ACCOUNT_KEY")
	if !ok {
		panic("TABLES_PRIMARY_STORAGE_ACCOUNT_KEY could not be found")
	}
	serviceURL := fmt.Sprintf("https://%s.table.core.windows.net/%s", accountName, "myTable")

	cred, err := aztables.NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		panic(err)
	}
	client, err := aztables.NewClientWithSharedKey(serviceURL, cred, nil)
	if err != nil {
		panic(err)
	}

	anyETag := azcore.ETagAny
	_, err = client.DeleteEntity(context.TODO(), "pk001", "rk001", &aztables.DeleteEntityOptions{IfMatch: &anyETag})
	if err != nil {
		panic(err)
	}
}
Output:

func (*Client) GetAccessPolicy

func (t *Client) GetAccessPolicy(ctx context.Context, options *GetAccessPolicyOptions) (GetAccessPolicyResponse, error)

GetAccessPolicy retrieves details about any stored access policies specified on the table that may be used with the Shared Access Signature

func (*Client) GetEntity

func (t *Client) GetEntity(ctx context.Context, partitionKey string, rowKey string, options *GetEntityOptions) (GetEntityResponse, error)

GetEntity retrieves a specific entity from the service using the specified partitionKey and rowKey values. If no entity is available it returns an error

func (Client) GetTableSASToken

func (t Client) GetTableSASToken(permissions SASPermissions, start time.Time, expiry time.Time) (string, error)

GetTableSASToken is a convenience method for generating a SAS token for a specific table. It can only be used by clients created by NewClientWithSharedKey().

func (*Client) InsertEntity

func (t *Client) InsertEntity(ctx context.Context, entity []byte, options *InsertEntityOptions) (InsertEntityResponse, error)

InsertEntity inserts an entity if it does not already exist in the table. If the entity does exist, the entity is replaced or merged as specified the updateMode parameter. If the entity exists and updateMode is Merge, the property values present in the specified entity will be merged with the existing entity rather than replaced. The response type will be TableEntityMergeResponse if updateMode is Merge and TableEntityUpdateResponse if updateMode is Replace.

Example
package main

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

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

type InventoryEntity struct {
	aztables.Entity
	Price       float32
	Inventory   int32
	ProductName string
	OnSale      bool
}

func main() {
	accountName, ok := os.LookupEnv("TABLES_STORAGE_ACCOUNT_NAME")
	if !ok {
		panic("TABLES_STORAGE_ACCOUNT_NAME could not be found")
	}
	accountKey, ok := os.LookupEnv("TABLES_PRIMARY_STORAGE_ACCOUNT_KEY")
	if !ok {
		panic("TABLES_PRIMARY_STORAGE_ACCOUNT_KEY could not be found")
	}
	serviceURL := fmt.Sprintf("https://%s.table.core.windows.net/%s", accountName, "myTable")

	cred, err := aztables.NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		panic(err)
	}
	client, err := aztables.NewClientWithSharedKey(serviceURL, cred, nil)
	if err != nil {
		panic(err)
	}

	myEntity := InventoryEntity{
		Entity: aztables.Entity{
			PartitionKey: "pk001",
			RowKey:       "rk001",
		},
		Price:       3.99,
		Inventory:   20,
		ProductName: "Markers",
		OnSale:      false,
	}
	marshalled, err := json.Marshal(myEntity)
	if err != nil {
		panic(err)
	}

	_, err = client.AddEntity(context.TODO(), marshalled, nil)
	if err != nil {
		panic(err)
	}

	// Inserting an entity with int64s, binary, datetime, or guid types
	myAdvancedEntity := aztables.EDMEntity{
		Entity: aztables.Entity{
			PartitionKey: "pk001",
			RowKey:       "rk002",
		},
		Properties: map[string]interface{}{
			"Bool":     false,
			"Int32":    int32(1234),
			"Int64":    aztables.EDMInt64(123456789012),
			"Double":   1234.1234,
			"String":   "test",
			"Guid":     aztables.EDMGUID("4185404a-5818-48c3-b9be-f217df0dba6f"),
			"DateTime": aztables.EDMDateTime(time.Date(2013, time.August, 02, 17, 37, 43, 9004348, time.UTC)),
			"Binary":   aztables.EDMBinary("SomeBinary"),
		},
	}

	marshalled, err = json.Marshal(myAdvancedEntity)
	if err != nil {
		panic(err)
	}
	_, err = client.AddEntity(context.TODO(), marshalled, nil)
	if err != nil {
		panic(err)
	}
}
Output:

func (*Client) List

func (t *Client) List(listOptions *ListEntitiesOptions) ListEntitiesPager

List queries the entities using the specified ListEntitiesOptions. listOptions can specify the following properties to affect the query results returned:

Filter: An OData filter expression that limits results to those entities that satisfy the filter expression. For example, the following expression would return only entities with a PartitionKey of 'foo': "PartitionKey eq 'foo'"

Select: A comma delimited list of entity property names that selects which set of entity properties to return in the result set. For example, the following value would return results containing only the PartitionKey and RowKey properties: "PartitionKey, RowKey"

Top: The maximum number of entities that will be returned per page of results. Note: This value does not limit the total number of results if NextPage is called on the returned Pager until it returns false.

List returns a Pager, which allows iteration through each page of results.

Example
package main

import (
	"context"
	"fmt"
	"os"

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

func main() {
	accountName, ok := os.LookupEnv("TABLES_STORAGE_ACCOUNT_NAME")
	if !ok {
		panic("TABLES_STORAGE_ACCOUNT_NAME could not be found")
	}
	accountKey, ok := os.LookupEnv("TABLES_PRIMARY_STORAGE_ACCOUNT_KEY")
	if !ok {
		panic("TABLES_PRIMARY_STORAGE_ACCOUNT_KEY could not be found")
	}
	serviceURL := fmt.Sprintf("https://%s.table.core.windows.net/%s", accountName, "myTable")

	cred, err := aztables.NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		panic(err)
	}
	client, err := aztables.NewClientWithSharedKey(serviceURL, cred, nil)
	if err != nil {
		panic(err)
	}

	filter := fmt.Sprintf("PartitionKey eq '%v' or PartitionKey eq '%v'", "pk001", "pk002")
	pager := client.List(&aztables.ListEntitiesOptions{Filter: &filter})

	pageCount := 1
	for pager.NextPage(context.TODO()) {
		response := pager.PageResponse()
		fmt.Printf("There are %d entities in page #%d\n", len(response.Entities), pageCount)
		pageCount += 1
	}
	if err := pager.Err(); err != nil {
		panic(err)
	}

	// To list all entities in a table, provide nil to Query()
	listPager := client.List(nil)
	pageCount = 1
	for listPager.NextPage(context.TODO()) {
		response := listPager.PageResponse()
		fmt.Printf("There are %d entities in page #%d\n", len(response.Entities), pageCount)
		pageCount += 1
	}
	if err := pager.Err(); err != nil {
		panic(err)
	}
}
Output:

func (*Client) SetAccessPolicy

func (t *Client) SetAccessPolicy(ctx context.Context, options *SetAccessPolicyOptions) (SetAccessPolicyResponse, error)

SetAccessPolicy sets stored access policies for the table that may be used with SharedAccessSignature

func (*Client) SubmitTransaction

func (t *Client) SubmitTransaction(ctx context.Context, transactionActions []TransactionAction, tableSubmitTransactionOptions *SubmitTransactionOptions) (TransactionResponse, error)

SubmitTransaction submits the table transactional batch according to the slice of TransactionActions provided. All transactionActions must be for entities with the same PartitionKey. There can only be one transaction action for a row key, a duplicated row key will return an error. The TransactionResponse object contains the response for each sub-request in the same order that they are made in the transactionActions parameter.

Example
package main

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

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

type MyEntity struct {
	aztables.Entity
	Price       float32
	Inventory   int32
	ProductName string
	OnSale      bool
}

func main() {
	accountName, ok := os.LookupEnv("TABLES_STORAGE_ACCOUNT_NAME")
	if !ok {
		panic("TABLES_STORAGE_ACCOUNT_NAME could not be found")
	}
	accountKey, ok := os.LookupEnv("TABLES_PRIMARY_STORAGE_ACCOUNT_KEY")
	if !ok {
		panic("TABLES_PRIMARY_STORAGE_ACCOUNT_KEY could not be found")
	}
	serviceURL := fmt.Sprintf("https://%s.table.core.windows.net/%s", accountName, "tableName")

	cred, err := aztables.NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		panic(err)
	}
	client, err := aztables.NewClientWithSharedKey(serviceURL, cred, nil)
	if err != nil {
		panic(err)
	}

	batch := []aztables.TransactionAction{}

	entity1 := MyEntity{
		Entity: aztables.Entity{
			PartitionKey: "pk001",
			RowKey:       "rk001",
		},
		Price:       3.99,
		Inventory:   10,
		ProductName: "Pens",
		OnSale:      false,
	}
	marshalled, err := json.Marshal(entity1)
	if err != nil {
		panic(err)
	}
	batch = append(batch, aztables.TransactionAction{
		ActionType: aztables.Add,
		Entity:     marshalled,
	})

	entity2 := MyEntity{
		Entity: aztables.Entity{
			PartitionKey: "pk001",
			RowKey:       "rk002",
		},
		Price:       19.99,
		Inventory:   15,
		ProductName: "Calculators",
		OnSale:      false,
	}
	marshalled, err = json.Marshal(entity2)
	if err != nil {
		panic(err)
	}
	batch = append(batch, aztables.TransactionAction{
		ActionType: aztables.UpdateMerge,
		Entity:     marshalled,
	})

	entity3 := MyEntity{
		Entity: aztables.Entity{
			PartitionKey: "pk001",
			RowKey:       "rk003",
		},
		Price:       0.99,
		Inventory:   150,
		ProductName: "Pens",
		OnSale:      true,
	}
	marshalled, err = json.Marshal(entity3)
	if err != nil {
		panic(err)
	}
	batch = append(batch, aztables.TransactionAction{
		ActionType: aztables.InsertReplace,
		Entity:     marshalled,
	})

	entity4 := MyEntity{
		Entity: aztables.Entity{
			PartitionKey: "pk001",
			RowKey:       "rk004",
		},
		Price:       3.99,
		Inventory:   150,
		ProductName: "100ct Paper Clips",
		OnSale:      false,
	}
	marshalled, err = json.Marshal(entity4)
	if err != nil {
		panic(err)
	}
	batch = append(batch, aztables.TransactionAction{
		ActionType: aztables.Delete,
		Entity:     marshalled,
	})

	resp, err := client.SubmitTransaction(context.TODO(), batch, nil)
	if err != nil {
		panic(err)
	}

	for _, subResp := range *resp.TransactionResponses {
		if subResp.StatusCode != http.StatusAccepted {
			fmt.Println(subResp.Body)
		}
	}
}
Output:

func (*Client) UpdateEntity

func (t *Client) UpdateEntity(ctx context.Context, entity []byte, options *UpdateEntityOptions) (UpdateEntityResponse, error)

UpdateEntity updates the specified table entity if it exists. If updateMode is Replace, the entity will be replaced. This is the only way to remove properties from an existing entity. If updateMode is Merge, the property values present in the specified entity will be merged with the existing entity. Properties not specified in the merge will be unaffected. The specified etag value will be used for optimistic concurrency. If the etag does not match the value of the entity in the table, the operation will fail. The response type will be TableEntityMergeResponse if updateMode is Merge and TableEntityUpdateResponse if updateMode is Replace.

type ClientOptions

type ClientOptions struct {
	azcore.ClientOptions
}

type CorsRule

type CorsRule struct {
	// REQUIRED; The request headers that the origin domain may specify on the CORS request.
	AllowedHeaders *string `xml:"AllowedHeaders"`

	// REQUIRED; The methods (HTTP request verbs) that the origin domain may use for a CORS request. (comma separated)
	AllowedMethods *string `xml:"AllowedMethods"`

	// REQUIRED; The origin domains that are permitted to make a request against the service via CORS. The origin domain is the domain from which the request
	// originates. Note that the origin must be an exact
	// case-sensitive match with the origin that the user age sends to the service. You can also use the wildcard character '*' to allow all origin domains
	// to make requests via CORS.
	AllowedOrigins *string `xml:"AllowedOrigins"`

	// REQUIRED; The response headers that may be sent in the response to the CORS request and exposed by the browser to the request issuer.
	ExposedHeaders *string `xml:"ExposedHeaders"`

	// REQUIRED; The maximum amount time that a browser should cache the preflight OPTIONS request.
	MaxAgeInSeconds *int32 `xml:"MaxAgeInSeconds"`
}

CorsRule - CORS is an HTTP feature that enables a web application running under one domain to access resources in another domain. Web browsers implement a security restriction known as same-origin policy that prevents a web page from calling APIs in a different domain; CORS provides a secure way to allow one domain (the origin domain) to call APIs in another domain.

type CreateTableOptions

type CreateTableOptions struct {
}

Options for Client.Create and ServiceClient.CreateTable method

type CreateTableResponse

type CreateTableResponse struct {
	RawResponse *http.Response
}

type DeleteEntityOptions

type DeleteEntityOptions struct {
	IfMatch *azcore.ETag
}

type DeleteEntityResponse

type DeleteEntityResponse struct {
	RawResponse *http.Response
}

type DeleteTableOptions

type DeleteTableOptions struct {
}

Options for Client.Delete and ServiceClient.DeleteTable methods

type DeleteTableResponse

type DeleteTableResponse struct {
	RawResponse *http.Response
}

Response object from a ServiceClient.DeleteTable or Client.Delete operation

type EDMBinary

type EDMBinary []byte

EDMBinary represents an Entity Property that is a byte slice. A byte slice wrapped in EDMBinary will also receive the correct odata annotation for round-trip accuracy.

func (EDMBinary) MarshalText

func (e EDMBinary) MarshalText() ([]byte, error)

func (*EDMBinary) UnmarshalText

func (e *EDMBinary) UnmarshalText(data []byte) error

type EDMDateTime

type EDMDateTime time.Time

EDMDateTime represents an entity property that is a time.Time object. Using EDMDateTime guarantees proper odata type annotations.

func (EDMDateTime) MarshalText

func (e EDMDateTime) MarshalText() ([]byte, error)

func (*EDMDateTime) UnmarshalText

func (e *EDMDateTime) UnmarshalText(data []byte) error

type EDMEntity

type EDMEntity struct {
	Metadata string `json:"odata.metadata"`
	Id       string `json:"odata.id"`
	EditLink string `json:"odata.editLink"`
	Type     string `json:"odata.type"`
	Etag     string `json:"odata.etag"`
	Entity
	Properties map[string]interface{} // Type assert the value to one of these: bool, int32, float64, string, EDMDateTime, EDMBinary, EDMGUID, EDMInt64
}

EDMEntity is an entity that embeds the azcore.Entity type and has a Properties map for an unlimited

func (EDMEntity) MarshalJSON

func (e EDMEntity) MarshalJSON() ([]byte, error)

func (*EDMEntity) UnmarshalJSON

func (e *EDMEntity) UnmarshalJSON(data []byte) (err error)

type EDMGUID

type EDMGUID string

EDMGUID represents an entity property that is a GUID wrapped in a string. Using EDMGUID guarantees proper odata type annotations.

func (EDMGUID) MarshalText

func (e EDMGUID) MarshalText() ([]byte, error)

func (*EDMGUID) UnmarshalText

func (e *EDMGUID) UnmarshalText(data []byte) error

type EDMInt64

type EDMInt64 int64

EDMInt64 represents an entity property that is a 64-bit integer. Using EDMInt64 guarantees proper odata type annotations.

func (EDMInt64) MarshalText

func (e EDMInt64) MarshalText() ([]byte, error)

func (*EDMInt64) UnmarshalText

func (e *EDMInt64) UnmarshalText(data []byte) error

type EndpointType

type EndpointType string

type Entity

type Entity struct {
	PartitionKey string
	RowKey       string
	Timestamp    EDMDateTime
}

The Entity type is the bare minimum properties for a valid Entity. These should be embedded in a custom struct.

type EntityUpdateMode

type EntityUpdateMode string

EntityUpdateMode specifies what type of update to do on InsertEntity or UpdateEntity. ReplaceEntity will replace an existing entity, MergeEntity will merge properties of the entities.

const (
	ReplaceEntity EntityUpdateMode = "replace"
	MergeEntity   EntityUpdateMode = "merge"
)

type GeoReplication

type GeoReplication struct {
	// REQUIRED; A GMT date/time value, to the second. All primary writes preceding this value are guaranteed to be available for read operations at the secondary.
	// Primary writes after this point in time may or may
	// not be available for reads.
	LastSyncTime *time.Time `xml:"LastSyncTime"`

	// REQUIRED; The status of the secondary location.
	Status *GeoReplicationStatusType `xml:"Status"`
}

type GeoReplicationStatusType

type GeoReplicationStatusType string

GeoReplicationStatusType - The status of the secondary location.

const (
	GeoReplicationStatusTypeBootstrap   GeoReplicationStatusType = "bootstrap"
	GeoReplicationStatusTypeLive        GeoReplicationStatusType = "live"
	GeoReplicationStatusTypeUnavailable GeoReplicationStatusType = "unavailable"
)

func PossibleGeoReplicationStatusTypeValues

func PossibleGeoReplicationStatusTypeValues() []GeoReplicationStatusType

PossibleGeoReplicationStatusTypeValues returns the possible values for the GeoReplicationStatusType const type.

func (GeoReplicationStatusType) ToPtr

ToPtr returns a *GeoReplicationStatusType pointing to the current value.

type GetAccessPolicyOptions

type GetAccessPolicyOptions struct {
}

type GetAccessPolicyResponse

type GetAccessPolicyResponse struct {
	RawResponse       *http.Response
	SignedIdentifiers []*SignedIdentifier
}

type GetEntityOptions

type GetEntityOptions struct {
}

Options for Client.GetEntity method

type GetEntityResponse

type GetEntityResponse struct {
	// ETag contains the information returned from the ETag header response.
	ETag azcore.ETag

	// RawResponse contains the underlying HTTP response.
	RawResponse *http.Response

	// The properties of the table entity.
	Value []byte
}

GetEntityResponse is the return type for a GetEntity operation. The individual entities are stored in the Value property

type GetPropertiesOptions

type GetPropertiesOptions struct {
}

type GetPropertiesResponse

type GetPropertiesResponse struct {
	RawResponse *http.Response
	// The set of CORS rules.
	Cors []*CorsRule `xml:"Cors>CorsRule"`

	// A summary of request statistics grouped by API in hourly aggregates for tables.
	HourMetrics *Metrics `xml:"HourMetrics"`

	// Azure Analytics Logging settings.
	Logging *Logging `xml:"Logging"`

	// A summary of request statistics grouped by API in minute aggregates for tables.
	MinuteMetrics *Metrics `xml:"MinuteMetrics"`
}

type GetStatisticsOptions

type GetStatisticsOptions struct {
}

GetStatisticsOptions are the options for a ServiceClient.GetStatistics call

type GetStatisticsResponse

type GetStatisticsResponse struct {
	RawResponse    *http.Response
	GeoReplication *GeoReplication `xml:"GeoReplication"`
}

type IPRange

type IPRange struct {
	Start net.IP // Not specified if length = 0
	End   net.IP // Not specified if length = 0
}

IPRange represents a SAS IP range's start IP and (optionally) end IP.

func (*IPRange) String

func (ipr *IPRange) String() string

String returns a string representation of an IPRange.

type InsertEntityOptions

type InsertEntityOptions struct {
	ETag       azcore.ETag
	UpdateMode EntityUpdateMode
}

type InsertEntityResponse

type InsertEntityResponse struct {
	RawResponse *http.Response
	ETag        azcore.ETag
}

type ListEntitiesOptions

type ListEntitiesOptions struct {
	// OData filter expression.
	Filter *string
	// Select expression using OData notation. Limits the columns on each record to just those requested, e.g. "$select=PolicyAssignmentId, ResourceId".
	Select *string
	// Maximum number of records to return.
	Top *int32
	// The PartitionKey to start paging from
	PartitionKey *string
	// The RowKey to start paging from
	RowKey *string
}

ListEntitiesOptions contains a group of parameters for the Table.Query method.

type ListEntitiesPage

type ListEntitiesPage struct {
	// RawResponse contains the underlying HTTP response.
	RawResponse *http.Response

	// ContinuationNextPartitionKey contains the information returned from the x-ms-continuation-NextPartitionKey header response.
	ContinuationNextPartitionKey *string

	// ContinuationNextRowKey contains the information returned from the x-ms-continuation-NextRowKey header response.
	ContinuationNextRowKey *string

	// The metadata response of the table.
	ODataMetadata *string

	// List of table entities.
	Entities [][]byte
}

ListEntitiesPage is the response envelope for operations that return a list of entities.

type ListEntitiesPager

type ListEntitiesPager interface {
	// PageResponse returns the current TableQueryResponseResponse.
	PageResponse() ListEntitiesPage
	// NextPage returns true if there is another page of data available, false if not
	NextPage(context.Context) bool
	// Err returns an error if there was an error on the last request
	Err() error
	// NextPagePartitionKey returns the PartitionKey for the current page
	NextPagePartitionKey() *string
	// NextPageRowKey returns the RowKey for the current page
	NextPageRowKey() *string
}

ListEntitiesPager is a Pager for Table entity query results.

NextPage should be called first. It fetches the next available page of results from the service. If the fetched page contains results, the return value is true, else false. Results fetched from the service can be evaluated by calling PageResponse on this Pager. If the result is false, the value of Err() will indicate if an error occurred.

PageResponse returns the results from the page most recently fetched from the service.

type ListEntitiesResponse

type ListEntitiesResponse struct {
	// The metadata response of the table.
	ODataMetadata *string

	// List of table entities stored as byte slices.
	Entities [][]byte
}

ListEntitiesResponse - The properties for the table entity query response.

type ListTablesOptions

type ListTablesOptions struct {
	// OData filter expression.
	Filter *string
	// Select expression using OData notation. Limits the columns on each record to just those requested, e.g. "$select=PolicyAssignmentId, ResourceId".
	Select *string
	// Maximum number of records to return.
	Top *int32
}

ListEntitiesOptions contains a group of parameters for the ServiceClient.QueryTables method.

type ListTablesPage

type ListTablesPage struct {
	// RawResponse contains the underlying HTTP response.
	RawResponse *http.Response

	// ContinuationNextTableName contains the information returned from the x-ms-continuation-NextTableName header response.
	ContinuationNextTableName *string

	// The metadata response of the table.
	ODataMetadata *string `json:"odata.metadata,omitempty"`

	// List of tables.
	Tables []*ResponseProperties `json:"value,omitempty"`
}

ListTablesPage contains the properties of a single page response from a ListTables operation

type ListTablesPager

type ListTablesPager interface {
	// PageResponse returns the current TableQueryResponseResponse.
	PageResponse() ListTablesPage
	// NextPage returns true if there is another page of data available, false if not
	NextPage(context.Context) bool
	// Err returns an error if there was an error on the last request
	Err() error
}

ListTablesPager is a Pager for Table List operations

NextPage should be called first. It fetches the next available page of results from the service. If the fetched page contains results, the return value is true, else false. Results fetched from the service can be evaluated by calling PageResponse on this Pager. If the result is false, the value of Err() will indicate if an error occurred.

PageResponse returns the results from the page most recently fetched from the service.

type Logging

type Logging struct {
	// REQUIRED; Indicates whether all delete requests should be logged.
	Delete *bool `xml:"Delete"`

	// REQUIRED; Indicates whether all read requests should be logged.
	Read *bool `xml:"Read"`

	// REQUIRED; The retention policy.
	RetentionPolicy *RetentionPolicy `xml:"RetentionPolicy"`

	// REQUIRED; The version of Analytics to configure.
	Version *string `xml:"Version"`

	// REQUIRED; Indicates whether all write requests should be logged.
	Write *bool `xml:"Write"`
}

Logging - Azure Analytics Logging settings.

type Metrics

type Metrics struct {
	// REQUIRED; Indicates whether metrics are enabled for the Table service.
	Enabled *bool `xml:"Enabled"`

	// Indicates whether metrics should generate summary statistics for called API operations.
	IncludeAPIs *bool `xml:"IncludeAPIs"`

	// The retention policy.
	RetentionPolicy *RetentionPolicy `xml:"RetentionPolicy"`

	// The version of Analytics to configure.
	Version *string `xml:"Version"`
}

type ResponseFormat

type ResponseFormat string

ResponseFormat determines what is returned from a service request

const (
	ResponseFormatReturnContent   ResponseFormat = "return-content"
	ResponseFormatReturnNoContent ResponseFormat = "return-no-content"
)

func PossibleResponseFormatValues

func PossibleResponseFormatValues() []ResponseFormat

PossibleResponseFormatValues returns the possible values for the ResponseFormat const type.

func (ResponseFormat) ToPtr

func (c ResponseFormat) ToPtr() *ResponseFormat

ToPtr returns a *ResponseFormat pointing to the current value.

type ResponseProperties

type ResponseProperties struct {
	// The edit link of the table.
	ODataEditLink *string `json:"odata.editLink,omitempty"`

	// The id of the table.
	ODataID *string `json:"odata.id,omitempty"`

	// The odata type of the table.
	ODataType *string `json:"odata.type,omitempty"`

	// The name of the table.
	TableName *string `json:"TableName,omitempty"`
}

ResponseProperties contains the properties for a single Table

type RetentionPolicy

type RetentionPolicy struct {
	// REQUIRED; Indicates whether a retention policy is enabled for the service.
	Enabled *bool `xml:"Enabled"`

	// Indicates the number of days that metrics or logging or soft-deleted data should be retained. All data older than this value will be deleted.
	Days *int32 `xml:"Days"`
}

RetentionPolicy - The retention policy.

type SASPermissions

type SASPermissions struct {
	Read              bool
	Add               bool
	Update            bool
	Delete            bool
	StartPartitionKey string
	StartRowKey       string
	EndPartitionKey   string
	EndRowKey         string
}

The SASPermissions type simplifies creating the permissions string for an Azure Table. Initialize an instance of this type and then call its String method to set TableSASSignatureValues's Permissions field.

func (*SASPermissions) Parse

func (p *SASPermissions) Parse(s string) error

Parse initializes the TableSASPermissions's fields from a string.

func (SASPermissions) String

func (p SASPermissions) String() string

String produces the SAS permissions string for an Azure Storage blob. Call this method to set TableSASSignatureValues's Permissions field.

type SASProtocol

type SASProtocol string

SASVersion indicates the SAS version.

const (
	// SASProtocolHTTPS can be specified for a SAS protocol
	SASProtocolHTTPS SASProtocol = "https"

	// SASProtocolHTTPSandHTTP can be specified for a SAS protocol
	SASProtocolHTTPSandHTTP SASProtocol = "https,http"
)

type SASQueryParameters

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

A SASQueryParameters object represents the components that make up an Azure Storage SAS' query parameters. You parse a map of query parameters into its fields by calling NewSASQueryParameters(). You add the components to a query parameter map by calling AddToValues(). NOTE: Changing any field requires computing a new SAS signature using a XxxSASSignatureValues type.

func (*SASQueryParameters) Encode

func (p *SASQueryParameters) Encode() string

Encode encodes the SAS query parameters into URL encoded form sorted by key.

func (*SASQueryParameters) EndPartitionKey

func (p *SASQueryParameters) EndPartitionKey() string

func (*SASQueryParameters) EndRowKey

func (p *SASQueryParameters) EndRowKey() string

func (*SASQueryParameters) ExpiryTime

func (p *SASQueryParameters) ExpiryTime() time.Time

func (*SASQueryParameters) IPRange

func (p *SASQueryParameters) IPRange() IPRange

func (*SASQueryParameters) Identifier

func (p *SASQueryParameters) Identifier() string

func (*SASQueryParameters) Permissions

func (p *SASQueryParameters) Permissions() string

func (*SASQueryParameters) Protocol

func (p *SASQueryParameters) Protocol() SASProtocol

func (*SASQueryParameters) Resource

func (p *SASQueryParameters) Resource() string

func (*SASQueryParameters) ResourceTypes

func (p *SASQueryParameters) ResourceTypes() string

func (*SASQueryParameters) Services

func (p *SASQueryParameters) Services() string

func (*SASQueryParameters) Signature

func (p *SASQueryParameters) Signature() string

func (*SASQueryParameters) SignedVersion

func (p *SASQueryParameters) SignedVersion() string

func (*SASQueryParameters) StartPartitionKey

func (p *SASQueryParameters) StartPartitionKey() string

func (*SASQueryParameters) StartRowKey

func (p *SASQueryParameters) StartRowKey() string

func (*SASQueryParameters) StartTime

func (p *SASQueryParameters) StartTime() time.Time

func (*SASQueryParameters) Version

func (p *SASQueryParameters) Version() string

type SASSignatureValues

type SASSignatureValues struct {
	Version           string      // If not specified, this defaults to SASVersion
	Protocol          SASProtocol // See the SASProtocol* constants
	StartTime         time.Time   // Not specified if IsZero
	ExpiryTime        time.Time   // Not specified if IsZero
	Permissions       string      // Create by initializing a ContainerSASPermissions or TableSASPermissions and then call String()
	IPRange           IPRange
	Identifier        string
	TableName         string
	StartPartitionKey string
	StartRowKey       string
	EndPartitionKey   string
	EndRowKey         string
}

SASSignatureValues is used to generate a Shared Access Signature (SAS) for an Azure Table instance. For more information, see https://docs.microsoft.com/rest/api/storageservices/constructing-a-service-sas

func (SASSignatureValues) NewSASQueryParameters

func (v SASSignatureValues) NewSASQueryParameters(credential *SharedKeyCredential) (SASQueryParameters, error)

NewSASQueryParameters uses an account's SharedKeyCredential to sign this signature values to produce the proper SAS query parameters.

type ServiceClient

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

A ServiceClient represents a client to the table service. It can be used to query the available tables, create/delete tables, and various other service level operations.

func NewServiceClient

func NewServiceClient(serviceURL string, cred azcore.TokenCredential, options *ClientOptions) (*ServiceClient, error)

NewServiceClient creates a ServiceClient struct using the specified serviceURL, credential, and options.

Example
package main

import (
	"fmt"
	"os"

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

func main() {
	accountName, ok := os.LookupEnv("TABLES_STORAGE_ACCOUNT_NAME")
	if !ok {
		panic("TABLES_STORAGE_ACCOUNT_NAME could not be found")
	}
	serviceURL := accountName + ".table.core.windows.net"

	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		panic(err)
	}
	client, err := aztables.NewServiceClient(serviceURL, cred, nil)
	if err != nil {
		panic(err)
	}
	fmt.Println(client)
}
Output:

func NewServiceClientFromConnectionString

func NewServiceClientFromConnectionString(connectionString string, options *ClientOptions) (*ServiceClient, error)

NewServiceClientFromConnectionString creates a new ServiceClient struct from a connection string. The connection string must contain either an account name and account key or an account name and a shared access signature.

func NewServiceClientWithNoCredential added in v0.3.0

func NewServiceClientWithNoCredential(serviceURL string, options *ClientOptions) (*ServiceClient, error)

NewServiceClientWithNoCredential creates a ServiceClient struct using the specified serviceURL and options. Call this method when serviceURL contains a SAS token.

Example
package main

import (
	"fmt"
	"os"

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

func main() {
	accountName, ok := os.LookupEnv("TABLES_STORAGE_ACCOUNT_NAME")
	if !ok {
		panic("TABLES_STORAGE_ACCOUNT_NAME could not be found")
	}
	sharedAccessSignature, ok := os.LookupEnv("TABLES_SHARED_ACCESS_SIGNATURE")
	if !ok {
		panic("TABLES_SHARED_ACCESS_SIGNATURE could not be found")
	}
	serviceURL := fmt.Sprintf("%s.table.core.windows.net/?%s", accountName, sharedAccessSignature)

	client, err := aztables.NewServiceClientWithNoCredential(serviceURL, nil)
	if err != nil {
		panic(err)
	}
	fmt.Println(client)
}
Output:

func NewServiceClientWithSharedKey added in v0.3.0

func NewServiceClientWithSharedKey(serviceURL string, cred *SharedKeyCredential, options *ClientOptions) (*ServiceClient, error)

NewServiceClientWithSharedKey creates a ServiceClient struct using the specified serviceURL, credential, and options.

Example
package main

import (
	"fmt"
	"os"

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

func main() {
	accountName, ok := os.LookupEnv("TABLES_STORAGE_ACCOUNT_NAME")
	if !ok {
		panic("TABLES_STORAGE_ACCOUNT_NAME could not be found")
	}
	accountKey, ok := os.LookupEnv("TABLES_PRIMARY_STORAGE_ACCOUNT_KEY")
	if !ok {
		panic("TABLES_PRIMARY_STORAGE_ACCOUNT_KEY could not be found")
	}
	serviceURL := accountName + ".table.core.windows.net"

	cred, err := aztables.NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		panic(err)
	}
	client, err := aztables.NewServiceClientWithSharedKey(serviceURL, cred, nil)
	if err != nil {
		panic(err)
	}
	fmt.Println(client)
}
Output:

func (*ServiceClient) CreateTable

func (t *ServiceClient) CreateTable(ctx context.Context, name string, options *CreateTableOptions) (*Client, error)

Create creates a table with the specified name.

Example
package main

import (
	"context"
	"fmt"
	"os"

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

func main() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		panic(err)
	}
	accountName, ok := os.LookupEnv("TABLES_STORAGE_ACCOUNT_NAME")
	if !ok {
		panic("TABLES_STORAGE_ACCOUNT_NAME could not be found")
	}
	serviceURL := fmt.Sprintf("https://%s.table.core.windows.net", accountName)

	service, err := aztables.NewServiceClient(serviceURL, cred, nil)
	if err != nil {
		panic(err)
	}

	// Create a table
	_, err = service.CreateTable(context.TODO(), "fromServiceClient", nil)
	if err != nil {
		panic(err)
	}
}
Output:

func (*ServiceClient) DeleteTable

func (t *ServiceClient) DeleteTable(ctx context.Context, name string, options *DeleteTableOptions) (DeleteTableResponse, error)

Delete deletes a table by name.

Example
package main

import (
	"context"
	"fmt"
	"os"

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

func main() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		panic(err)
	}
	accountName, ok := os.LookupEnv("TABLES_STORAGE_ACCOUNT_NAME")
	if !ok {
		panic("TABLES_STORAGE_ACCOUNT_NAME could not be found")
	}
	serviceURL := fmt.Sprintf("https://%s.table.core.windows.net", accountName)

	service, err := aztables.NewServiceClient(serviceURL, cred, nil)
	if err != nil {
		panic(err)
	}

	// Delete a table
	_, err = service.DeleteTable(context.TODO(), "fromServiceClient", nil)
	if err != nil {
		panic(err)
	}
}
Output:

func (ServiceClient) GetAccountSASToken

func (t ServiceClient) GetAccountSASToken(resources AccountSASResourceTypes, permissions AccountSASPermissions, start time.Time, expiry time.Time) (string, error)

GetAccountSASToken is a convenience method for generating a SAS token for the currently pointed at account. This methods returns the full service URL and an error if there was an error during creation. This method can only be used by clients created by NewServiceClientWithSharedKey().

func (*ServiceClient) GetProperties

func (t *ServiceClient) GetProperties(ctx context.Context, options *GetPropertiesOptions) (GetPropertiesResponse, error)

GetProperties retrieves the properties for an account including the metrics, logging, and cors rules established.

func (*ServiceClient) GetStatistics

func (t *ServiceClient) GetStatistics(ctx context.Context, options *GetStatisticsOptions) (GetStatisticsResponse, error)

GetStatistics retrieves all the statistics for an account with Geo-redundancy established.

func (*ServiceClient) ListTables

func (t *ServiceClient) ListTables(listOptions *ListTablesOptions) ListTablesPager

List queries the existing tables using the specified ListTablesOptions. listOptions can specify the following properties to affect the query results returned:

Filter: An OData filter expression that limits results to those tables that satisfy the filter expression. For example, the following expression would return only tables with a TableName of 'foo': "TableName eq 'foo'"

Top: The maximum number of tables that will be returned per page of results. Note: This value does not limit the total number of results if NextPage is called on the returned Pager until it returns false.

List returns a Pager, which allows iteration through each page of results.

Example
package main

import (
	"context"
	"fmt"
	"os"

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

func main() {
	accountName, ok := os.LookupEnv("TABLES_STORAGE_ACCOUNT_NAME")
	if !ok {
		panic("TABLES_STORAGE_ACCOUNT_NAME could not be found")
	}
	accountKey, ok := os.LookupEnv("TABLES_PRIMARY_STORAGE_ACCOUNT_KEY")
	if !ok {
		panic("TABLES_PRIMARY_STORAGE_ACCOUNT_KEY could not be found")
	}
	serviceURL := accountName + ".table.core.windows.net"

	cred, err := aztables.NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		panic(err)
	}
	service, err := aztables.NewServiceClientWithSharedKey(serviceURL, cred, nil)
	if err != nil {
		panic(err)
	}

	myTable := "myTableName"
	filter := fmt.Sprintf("TableName ge '%v'", myTable)
	pager := service.ListTables(&aztables.ListTablesOptions{Filter: &filter})

	pageCount := 1
	for pager.NextPage(context.TODO()) {
		response := pager.PageResponse()
		fmt.Printf("There are %d tables in page #%d\n", len(response.Tables), pageCount)
		for _, table := range response.Tables {
			fmt.Printf("\tTableName: %s\n", *table.TableName)
		}
		pageCount += 1
	}
	if err := pager.Err(); err != nil {
		panic(err)
	}
}
Output:

func (*ServiceClient) NewClient

func (t *ServiceClient) NewClient(tableName string) *Client

NewClient returns a pointer to a Client affinitized to the specified table name and initialized with the same serviceURL and credentials as this ServiceClient

func (*ServiceClient) SetProperties

func (t *ServiceClient) SetProperties(ctx context.Context, properties ServiceProperties, options *SetPropertiesOptions) (SetPropertiesResponse, error)

SetProperties allows the user to set cors , metrics, and logging rules for the account.

Cors: A slice of CorsRules.

HoursMetrics: A summary of request statistics grouped in hourly aggregatess for tables

HoursMetrics: A summary of request statistics grouped in minute aggregates for tables

Logging: Azure Analytics logging settings

type ServiceProperties

type ServiceProperties struct {
	// The set of CORS rules.
	Cors []*CorsRule `xml:"Cors>CorsRule"`

	// A summary of request statistics grouped by API in hourly aggregates for tables.
	HourMetrics *Metrics `xml:"HourMetrics"`

	// Azure Analytics Logging settings.
	Logging *Logging `xml:"Logging"`

	// A summary of request statistics grouped by API in minute aggregates for tables.
	MinuteMetrics *Metrics `xml:"MinuteMetrics"`
}

ServiceProperties - Service Properties for a given table

type SetAccessPolicyOptions

type SetAccessPolicyOptions struct {
	TableACL []*SignedIdentifier
}

type SetAccessPolicyResponse

type SetAccessPolicyResponse struct {
	RawResponse *http.Response
}

type SetPropertiesOptions

type SetPropertiesOptions struct{}

type SetPropertiesResponse

type SetPropertiesResponse struct {
	RawResponse *http.Response
}

type SharedKeyCredential

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

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

func NewSharedKeyCredential

func NewSharedKeyCredential(accountName string, accountKey string) (*SharedKeyCredential, error)

NewSharedKeyCredential creates an immutable SharedKeyCredential containing the storage account's name and either its primary or secondary key.

Example
package main

import (
	"fmt"
	"os"

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

func main() {
	accountName, ok := os.LookupEnv("TABLES_STORAGE_ACCOUNT_NAME")
	if !ok {
		panic("TABLES_STORAGE_ACCOUNT_NAME could not be found")
	}
	accountKey, ok := os.LookupEnv("TABLES_PRIMARY_STORAGE_ACCOUNT_KEY")
	if !ok {
		panic("TABLES_PRIMARY_STORAGE_ACCOUNT_KEY could not be found")
	}
	serviceURL := accountName + ".table.core.windows.net"

	cred, err := aztables.NewSharedKeyCredential(accountName, accountKey)
	if err != nil {
		panic(err)
	}
	client, err := aztables.NewServiceClientWithSharedKey(serviceURL, cred, nil)
	if err != nil {
		panic(err)
	}
	fmt.Println(client)
}
Output:

func (*SharedKeyCredential) AccountName

func (c *SharedKeyCredential) AccountName() string

AccountName returns the Storage account's name.

func (*SharedKeyCredential) ComputeHMACSHA256

func (c *SharedKeyCredential) ComputeHMACSHA256(message string) (string, error)

computeHMACSHA256 generates a hash signature for an HTTP request or for a SAS.

func (*SharedKeyCredential) SetAccountKey

func (c *SharedKeyCredential) SetAccountKey(accountKey string) error

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

type SignedIdentifier

type SignedIdentifier struct {
	// REQUIRED; The access policy.
	AccessPolicy *AccessPolicy `xml:"AccessPolicy"`

	// REQUIRED; A unique id.
	ID *string `xml:"Id"`
}

SignedIdentifier - A signed identifier.

type SubmitTransactionOptions

type SubmitTransactionOptions struct {
	RequestID *string
}

type TransactionAction

type TransactionAction struct {
	ActionType TransactionType
	Entity     []byte
	IfMatch    *azcore.ETag
}

type TransactionResponse

type TransactionResponse struct {
	// RawResponse contains the underlying HTTP response.
	RawResponse *http.Response
	// The response for a single table.
	TransactionResponses *[]http.Response
	// ContentType contains the information returned from the Content-Type header response.
	ContentType string
}

type TransactionType

type TransactionType string

TransactionType is the type for a specific transaction operation.

const (
	Add           TransactionType = "add"
	UpdateMerge   TransactionType = "updatemerge"
	UpdateReplace TransactionType = "updatereplace"
	Delete        TransactionType = "delete"
	InsertMerge   TransactionType = "insertmerge"
	InsertReplace TransactionType = "insertreplace"
)

type UpdateEntityOptions

type UpdateEntityOptions struct {
	IfMatch    *azcore.ETag
	UpdateMode EntityUpdateMode
}

type UpdateEntityResponse

type UpdateEntityResponse struct {
	RawResponse *http.Response
	ETag        azcore.ETag
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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