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]any{ "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]any{ "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.Ptr("RowKey,Value,Product,Available"), Top: to.Ptr(int32(((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 ¶
- Variables
- func FormatTimesForSASSigning(startTime, expiryTime time.Time) (string, string)
- type AccessPolicy
- type AccountSASPermissions
- type AccountSASResourceTypes
- type AccountSASSignatureValues
- type AddEntityOptions
- type AddEntityResponse
- type Client
- func NewClient(serviceURL string, cred azcore.TokenCredential, options *ClientOptions) (*Client, error)
- func NewClientWithNoCredential(serviceURL string, options *ClientOptions) (*Client, error)
- func NewClientWithSharedKey(serviceURL string, cred *SharedKeyCredential, options *ClientOptions) (*Client, error)
- func (t *Client) AddEntity(ctx context.Context, entity []byte, options *AddEntityOptions) (AddEntityResponse, error)
- func (t *Client) CreateTable(ctx context.Context, options *CreateTableOptions) (CreateTableResponse, error)
- func (t *Client) Delete(ctx context.Context, options *DeleteTableOptions) (DeleteTableResponse, error)
- func (t *Client) DeleteEntity(ctx context.Context, partitionKey string, rowKey string, ...) (DeleteEntityResponse, error)
- func (t *Client) GetAccessPolicy(ctx context.Context, options *GetAccessPolicyOptions) (GetAccessPolicyResponse, error)
- func (t *Client) GetEntity(ctx context.Context, partitionKey string, rowKey string, ...) (GetEntityResponse, error)
- func (t Client) GetTableSASURL(permissions SASPermissions, start time.Time, expiry time.Time) (string, error)
- func (t *Client) NewListEntitiesPager(listOptions *ListEntitiesOptions) *runtime.Pager[ListEntitiesResponse]
- func (t *Client) SetAccessPolicy(ctx context.Context, options *SetAccessPolicyOptions) (SetAccessPolicyResponse, error)
- func (t *Client) SubmitTransaction(ctx context.Context, transactionActions []TransactionAction, ...) (TransactionResponse, error)
- func (t *Client) UpdateEntity(ctx context.Context, entity []byte, options *UpdateEntityOptions) (UpdateEntityResponse, error)
- func (t *Client) UpsertEntity(ctx context.Context, entity []byte, options *UpsertEntityOptions) (UpsertEntityResponse, error)
- type ClientOptions
- type CorsRule
- type CreateTableOptions
- type CreateTableResponse
- type DeleteEntityOptions
- type DeleteEntityResponse
- type DeleteTableOptions
- type DeleteTableResponse
- type EDMBinary
- type EDMDateTime
- type EDMEntity
- type EDMGUID
- type EDMInt64
- type Entity
- type GeoReplication
- type GeoReplicationStatus
- type GetAccessPolicyOptions
- type GetAccessPolicyResponse
- type GetEntityOptions
- type GetEntityResponse
- type GetPropertiesOptions
- type GetPropertiesResponse
- type GetStatisticsOptions
- type GetStatisticsResponse
- type IPRange
- type ListEntitiesOptions
- type ListEntitiesResponse
- type ListTablesOptions
- type ListTablesResponse
- type Logging
- type MetadataFormat
- type Metrics
- type RetentionPolicy
- type SASPermissions
- type SASProtocol
- type SASQueryParameters
- func (p *SASQueryParameters) Encode() string
- func (p *SASQueryParameters) EndPartitionKey() string
- func (p *SASQueryParameters) EndRowKey() string
- func (p *SASQueryParameters) ExpiryTime() time.Time
- func (p *SASQueryParameters) IPRange() IPRange
- func (p *SASQueryParameters) Identifier() string
- func (p *SASQueryParameters) Permissions() string
- func (p *SASQueryParameters) Protocol() SASProtocol
- func (p *SASQueryParameters) Resource() string
- func (p *SASQueryParameters) ResourceTypes() string
- func (p *SASQueryParameters) Services() string
- func (p *SASQueryParameters) Signature() string
- func (p *SASQueryParameters) SignedVersion() string
- func (p *SASQueryParameters) StartPartitionKey() string
- func (p *SASQueryParameters) StartRowKey() string
- func (p *SASQueryParameters) StartTime() time.Time
- func (p *SASQueryParameters) Version() string
- type SASSignatureValues
- type ServiceClient
- func NewServiceClient(serviceURL string, cred azcore.TokenCredential, options *ClientOptions) (*ServiceClient, error)
- func NewServiceClientFromConnectionString(connectionString string, options *ClientOptions) (*ServiceClient, error)
- func NewServiceClientWithNoCredential(serviceURL string, options *ClientOptions) (*ServiceClient, error)
- func NewServiceClientWithSharedKey(serviceURL string, cred *SharedKeyCredential, options *ClientOptions) (*ServiceClient, error)
- func (t *ServiceClient) CreateTable(ctx context.Context, name string, options *CreateTableOptions) (CreateTableResponse, error)
- func (t *ServiceClient) DeleteTable(ctx context.Context, name string, options *DeleteTableOptions) (DeleteTableResponse, error)
- func (t ServiceClient) GetAccountSASURL(resources AccountSASResourceTypes, permissions AccountSASPermissions, ...) (string, error)
- func (t *ServiceClient) GetProperties(ctx context.Context, options *GetPropertiesOptions) (GetPropertiesResponse, error)
- func (t *ServiceClient) GetStatistics(ctx context.Context, options *GetStatisticsOptions) (GetStatisticsResponse, error)
- func (t *ServiceClient) NewClient(tableName string) *Client
- func (t *ServiceClient) NewListTablesPager(listOptions *ListTablesOptions) *runtime.Pager[ListTablesResponse]
- func (t *ServiceClient) SetProperties(ctx context.Context, properties ServiceProperties, ...) (SetPropertiesResponse, error)
- type ServiceProperties
- type SetAccessPolicyOptions
- type SetAccessPolicyResponse
- type SetPropertiesOptions
- type SetPropertiesResponse
- type SharedKeyCredential
- type SignedIdentifier
- type SubmitTransactionOptions
- type TableErrorCode
- type TableProperties
- type TransactionAction
- type TransactionResponse
- type TransactionType
- type UpdateEntityOptions
- type UpdateEntityResponse
- type UpdateMode
- type UpsertEntityOptions
- type UpsertEntityResponse
Examples ¶
- Client.CreateTable
- Client.Delete
- Client.DeleteEntity
- Client.NewListEntitiesPager
- Client.SubmitTransaction
- Client.UpsertEntity
- NewClient
- NewClientWithSharedKey
- NewServiceClient
- NewServiceClientWithNoCredential
- NewServiceClientWithSharedKey
- NewSharedKeyCredential
- ServiceClient.CreateTable
- ServiceClient.DeleteTable
- ServiceClient.GetAccountSASURL
- ServiceClient.NewListTablesPager
- ServiceClient.SetProperties
Constants ¶
This section is empty.
Variables ¶
var SASVersion = "2019-02-02"
SASVersion is the default SAS Version
Functions ¶
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 }
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 ¶
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://learn.microsoft.com/rest/api/storageservices/constructing-an-account-sas
func (AccountSASSignatureValues) Sign ¶
func (v AccountSASSignatureValues) Sign(sharedKeyCredential *SharedKeyCredential) (SASQueryParameters, error)
Sign uses an account's SharedKeyCredential to sign this signature values to produce the proper SAS query parameters.
type AddEntityOptions ¶
type AddEntityOptions struct { // Format specifies the amount of metadata returned. // The default is MetadataFormatMinimal. Format *MetadataFormat }
AddEntityOptions contains optional parameters for Client.AddEntity
type AddEntityResponse ¶
type AddEntityResponse struct { // ETag contains the information returned from the ETag header response. ETag azcore.ETag // The OData properties of the table entity in JSON format. Value []byte }
AddEntityResponse contains response fields for Client.AddEntityResponse
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
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.table.core.windows.net/<myTableName>". Pass in nil for options to construct the client with the default ClientOptions.
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.table.core.windows.net/<myTableName>?<SAS token>". Pass in nil for options to construct the client with the default ClientOptions.
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.table.core.windows.net/<myTableName>". Pass in nil for options to construct the client with the default ClientOptions.
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. If the service returns a non-successful HTTP status code, the function returns an *azcore.ResponseError type. Specify nil for options if you want to use the default options.
func (*Client) CreateTable ¶ added in v0.7.0
func (t *Client) CreateTable(ctx context.Context, options *CreateTableOptions) (CreateTableResponse, error)
CreateTable creates the table with the tableName specified when NewClient was called. If the service returns a non-successful HTTP status code, the function returns an *azcore.ResponseError type. Specify nil for options if you want to use the default options. NOTE: creating a table with the same name as a table that's in the process of being deleted will return an *azcore.ResponseError with error code TableBeingDeleted and status code http.StatusConflict.
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.CreateTable(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. If the service returns a non-successful HTTP status code, the function returns an *azcore.ResponseError type. Specify nil for options if you want to use the default options. NOTE: deleting a table can take up to 40 seconds or more to complete. If a table with the same name is created while the delete is still in progress, an *azcore.ResponseError is returned with error code TableBeingDeleted and status code http.StatusConflict.
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. If the service returns a non-successful HTTP status code, the function returns an *azcore.ResponseError type. Specify nil for options if you want to use the default options.
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. If the service returns a non-successful HTTP status code, the function returns an *azcore.ResponseError type. Specify nil for options if you want to use the default options.
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. If the service returns a non-successful HTTP status code, the function returns an *azcore.ResponseError type. Specify nil for options if you want to use the default options.
func (Client) GetTableSASURL ¶ added in v0.7.0
func (t Client) GetTableSASURL(permissions SASPermissions, start time.Time, expiry time.Time) (string, error)
GetTableSASURL 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) NewListEntitiesPager ¶ added in v0.8.0
func (t *Client) NewListEntitiesPager(listOptions *ListEntitiesOptions) *runtime.Pager[ListEntitiesResponse]
NewListEntitiesPager queries the entities using the specified ListEntitiesOptions. ListEntitiesOptions 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.
NewListEntitiesPager returns a Pager, which allows iteration through each page of results. Use nil for listOptions if you want to use the default options. For more information about writing query strings, check out:
- API Documentation: https://learn.microsoft.com/rest/api/storageservices/querying-tables-and-entities
- README samples: https://github.com/Azure/azure-sdk-for-go/blob/main/sdk/data/aztables/README.md#writing-filters
Example ¶
package main import ( "context" "encoding/json" "fmt" "os" "time" "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) } // For more information about writing query strings, check out: // - API Documentation: https://learn.microsoft.com/rest/api/storageservices/querying-tables-and-entities // - README samples: https://github.com/Azure/azure-sdk-for-go/blob/main/sdk/data/aztables/README.md#writing-filters filter := fmt.Sprintf("PartitionKey eq '%s' or PartitionKey eq '%s'", "pk001", "pk002") pager := client.NewListEntitiesPager(&aztables.ListEntitiesOptions{Filter: &filter}) pageCount := 1 for pager.More() { response, err := pager.NextPage(context.TODO()) if err != nil { panic(err) } fmt.Printf("There are %d entities in page #%d\n", len(response.Entities), pageCount) for _, entity := range response.Entities { var myEntity aztables.EDMEntity err = json.Unmarshal(entity, &myEntity) if err != nil { panic(err) } sp := myEntity.Properties["String"].(string) dp := myEntity.Properties["Double"].(float64) dt := myEntity.Properties["DateTime"].(aztables.EDMDateTime) t1 := time.Time(dt) fmt.Printf("Received: %s, %s, %s, %.2f, %s", myEntity.PartitionKey, myEntity.RowKey, sp, dp, t1.String()) } pageCount += 1 } // To list all entities in a table, provide nil to Query() listPager := client.NewListEntitiesPager(nil) pageCount = 0 for listPager.More() { response, err := listPager.NextPage(context.TODO()) if err != nil { panic(err) } fmt.Printf("There are %d entities in page #%d\n", len(response.Entities), pageCount) pageCount += 1 for _, entity := range response.Entities { var myEntity aztables.EDMEntity err = json.Unmarshal(entity, &myEntity) if err != nil { panic(err) } sp := myEntity.Properties["String"].(string) dp := myEntity.Properties["Double"].(float64) dt := myEntity.Properties["DateTime"].(aztables.EDMDateTime) t1 := time.Time(dt) fmt.Printf("Received: %s, %s, %s, %.2f, %s", myEntity.PartitionKey, myEntity.RowKey, sp, dp, t1.String()) } } }
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. If the service returns a non-successful HTTP status code, the function returns an *azcore.ResponseError type. Specify nil for options if you want to use the default options.
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 RowKey, a duplicated row key will return an error. A storage account will return a 202 Accepted response when a transaction fails, the multipart data will have 4XX responses for the batch request that failed. For more information about error responses see https://learn.microsoft.com/rest/api/storageservices/performing-entity-group-transactions#sample-error-response
Example ¶
package main import ( "context" "encoding/json" "errors" "fmt" "io" "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "github.com/Azure/azure-sdk-for-go/sdk/data/aztables" ) type MyEntity struct { aztables.Entity Value int } func main() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { panic(err) } serviceURL := fmt.Sprintf("https://%s.table.core.windows.net/%s", "myAccountName", "tableName") client, err := aztables.NewClient(serviceURL, cred, nil) if err != nil { panic(err) } batch := []aztables.TransactionAction{} baseEntity := MyEntity{ Entity: aztables.Entity{ PartitionKey: "myPartitionKey", RowKey: "", }, } for i := 0; i < 10; i++ { baseEntity.RowKey = fmt.Sprintf("rk-%d", i) baseEntity.Value = i marshalled, err := json.Marshal(baseEntity) if err != nil { panic(err) } batch = append(batch, aztables.TransactionAction{ ActionType: aztables.TransactionTypeAdd, Entity: marshalled, }) } _, err = client.SubmitTransaction(context.TODO(), batch, nil) if err != nil { var httpErr *azcore.ResponseError if errors.As(err, &httpErr) { body, err := io.ReadAll(httpErr.RawResponse.Body) if err != nil { panic(err) } fmt.Println(string(body)) // Do some parsing of the body } else { panic(err) } } }
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. If the service returns a non-successful HTTP status code, the function returns an *azcore.ResponseError type. Specify nil for options if you want to use the default options.
func (*Client) UpsertEntity ¶ added in v0.7.0
func (t *Client) UpsertEntity(ctx context.Context, entity []byte, options *UpsertEntityOptions) (UpsertEntityResponse, error)
UpsertEntity 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. If the service returns a non-successful HTTP status code, the function returns an *azcore.ResponseError type. Specify nil for options if you want to use the default options.
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]any{ "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:
type ClientOptions ¶
type ClientOptions struct {
azcore.ClientOptions
}
ClientOptions contains the optional parameters for client constructors.
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 { }
CreateTableOptions contains optional parameters for Client.Create and ServiceClient.CreateTable
type CreateTableResponse ¶
type CreateTableResponse struct { // The name of the table. TableName *string `json:"TableName,omitempty"` }
CreateTableResponse contains response fields for Client.Create and ServiceClient.CreateTable
type DeleteEntityOptions ¶
DeleteEntityOptions contains optional parameters for Client.DeleteEntity
type DeleteEntityResponse ¶
type DeleteEntityResponse struct { }
DeleteEntityResponse contains response fields for Client.DeleteEntity
type DeleteTableOptions ¶
type DeleteTableOptions struct { }
DeleteTableOptions contains optional parameters for Client.Delete and ServiceClient.DeleteTable
type DeleteTableResponse ¶
type DeleteTableResponse struct { }
DeleteTableResponse contains response fields for ServiceClient.DeleteTable and Client.Delete
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 ¶
MarshalText implements the encoding.TextMarshaler interface
func (*EDMBinary) UnmarshalText ¶
UnmarshalText implements the encoding.TextMarshaler interface
type EDMDateTime ¶
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)
MarshalText implements the encoding.TextMarshaler interface
func (*EDMDateTime) UnmarshalText ¶
func (e *EDMDateTime) UnmarshalText(data []byte) error
UnmarshalText implements the encoding.TextMarshaler interface
type EDMEntity ¶
type EDMEntity struct { Entity 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"` Properties map[string]any // 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 user defined entity properties
func (EDMEntity) MarshalJSON ¶
MarshalJSON implements the json.Marshal method
func (*EDMEntity) UnmarshalJSON ¶
UnmarshalJSON implements the json.Unmarshal method
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 ¶
MarshalText implements the encoding.TextMarshaler interface
func (*EDMGUID) UnmarshalText ¶
UnmarshalText implements the encoding.TextMarshaler interface
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 ¶
MarshalText implements the encoding.TextMarshaler interface
func (*EDMInt64) UnmarshalText ¶
UnmarshalText implements the encoding.TextMarshaler interface
type Entity ¶
type Entity struct { PartitionKey string RowKey string Timestamp EDMDateTime }
Entity is the bare minimum properties for a valid Entity. These should be embedded in a custom struct.
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 *GeoReplicationStatus `xml:"Status"` }
GeoReplication represents the GeoReplication status of an account
type GeoReplicationStatus ¶ added in v0.7.0
type GeoReplicationStatus string
GeoReplicationStatus - The status of the secondary location.
const ( GeoReplicationStatusBootstrap GeoReplicationStatus = "bootstrap" GeoReplicationStatusLive GeoReplicationStatus = "live" )
func PossibleGeoReplicationStatusValues ¶ added in v0.8.0
func PossibleGeoReplicationStatusValues() []GeoReplicationStatus
PossibleGeoReplicationStatusValues returns the possible values for the GeoReplicationStatus const type.
type GetAccessPolicyOptions ¶
type GetAccessPolicyOptions struct { }
GetAccessPolicyOptions contains optional parameters for Client.GetAccessPolicy
type GetAccessPolicyResponse ¶
type GetAccessPolicyResponse struct {
SignedIdentifiers []*SignedIdentifier
}
GetAccessPolicyResponse contains response fields for Client.GetAccessPolicy
type GetEntityOptions ¶
type GetEntityOptions struct { // Format specifies the amount of metadata returned. // The default is MetadataFormatMinimal. Format *MetadataFormat }
GetEntityOptions contains optional parameters for Client.GetEntity
type GetEntityResponse ¶
type GetEntityResponse struct { // ETag contains the information returned from the ETag header response. ETag azcore.ETag // The OData properties of the table entity in JSON format. Value []byte }
GetEntityResponse contains response fields for Client.GetEntity
type GetPropertiesOptions ¶
type GetPropertiesOptions struct { }
GetPropertiesOptions contains optional parameters for Client.GetProperties
type GetPropertiesResponse ¶
type GetPropertiesResponse struct {
ServiceProperties
}
GetPropertiesResponse contains response fields for Client.GetProperties
type GetStatisticsOptions ¶
type GetStatisticsOptions struct { }
GetStatisticsOptions contains optional parameters for ServiceClient.GetStatistics
type GetStatisticsResponse ¶
type GetStatisticsResponse struct {
GeoReplication *GeoReplication `xml:"GeoReplication"`
}
GetStatisticsResponse contains response fields for Client.GetStatistics
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.
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 NextPartitionKey to start paging from NextPartitionKey *string // The NextRowKey to start paging from NextRowKey *string // Format specifies the amount of metadata returned. // The default is MetadataFormatMinimal. Format *MetadataFormat }
ListEntitiesOptions contains optional parameters for Table.Query
type ListEntitiesResponse ¶
type ListEntitiesResponse struct { // NextPartitionKey contains the information returned from the x-ms-continuation-NextPartitionKey header response. NextPartitionKey *string // NextRowKey contains the information returned from the x-ms-continuation-NextRowKey header response. NextRowKey *string // List of table entities. Entities [][]byte }
ListEntitiesResponse contains response fields for ListEntitiesPager.NextPage
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 // NextTableName is the continuation token for the next table to page from NextTableName *string // Format specifies the amount of metadata returned. // The default is MetadataFormatMinimal. Format *MetadataFormat }
ListTablesOptions contains optional parameters for ServiceClient.QueryTables
type ListTablesResponse ¶ added in v0.7.0
type ListTablesResponse struct { // NextTableName contains the information returned from the x-ms-continuation-NextTableName header response. NextTableName *string // List of tables. Tables []*TableProperties `json:"value,omitempty"` }
ListTablesResponse contains response fields for ListTablesPager.NextPage
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 MetadataFormat ¶ added in v1.2.0
type MetadataFormat = generated.ODataMetadataFormat
MetadataFormat specifies the level of OData metadata returned with an entity. https://learn.microsoft.com/rest/api/storageservices/payload-format-for-table-service-operations#json-format-applicationjson-versions-2013-08-15-and-later
const ( MetadataFormatFull MetadataFormat = generated.ODataMetadataFormatApplicationJSONODataFullmetadata MetadataFormatMinimal MetadataFormat = generated.ODataMetadataFormatApplicationJSONODataMinimalmetadata MetadataFormatNone MetadataFormat = generated.ODataMetadataFormatApplicationJSONODataNometadata )
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"` }
Metrics are the metrics for a 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 }
SASPermissions 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
SASProtocol indicates the SAS protocol
const ( // SASProtocolHTTPS can be specified for a SAS protocol SASProtocolHTTPS SASProtocol = "https" // SASProtocolHTTPSandHTTP can be specified for a SAS protocol SASProtocolHTTPSandHTTP SASProtocol = "https,http" )
func PossibleSASProtocolValues ¶ added in v0.6.0
func PossibleSASProtocolValues() []SASProtocol
PossibleSASProtocolValues returns the possible values for the SASProtocol const type.
type SASQueryParameters ¶
type SASQueryParameters struct {
// contains filtered or unexported fields
}
SASQueryParameters represents the components that make up an Azure Storage SAS' query parameters. You parse a map of query parameters into its fields by calling Sign(). 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
EndPartitionKey gets the end PartitionKey of a SASQueryParameter
func (*SASQueryParameters) EndRowKey ¶
func (p *SASQueryParameters) EndRowKey() string
EndRowKey gets the end RowKey of a SASQueryParameter
func (*SASQueryParameters) ExpiryTime ¶
func (p *SASQueryParameters) ExpiryTime() time.Time
ExpiryTime gets the expiry time of a SASQueryParameter
func (*SASQueryParameters) IPRange ¶
func (p *SASQueryParameters) IPRange() IPRange
IPRange gets the IP Range of a SASQueryParameter
func (*SASQueryParameters) Identifier ¶
func (p *SASQueryParameters) Identifier() string
Identifier gets the identifier of a SASQueryParameter
func (*SASQueryParameters) Permissions ¶
func (p *SASQueryParameters) Permissions() string
Permissions gets the permissions of a SASQueryParameter
func (*SASQueryParameters) Protocol ¶
func (p *SASQueryParameters) Protocol() SASProtocol
Protocol gets the protocol of a SASQueryParameter
func (*SASQueryParameters) Resource ¶
func (p *SASQueryParameters) Resource() string
Resource gets the resource of a SASQueryParameter
func (*SASQueryParameters) ResourceTypes ¶
func (p *SASQueryParameters) ResourceTypes() string
ResourceTypes gets the resource types of a SASQueryParameter
func (*SASQueryParameters) Services ¶
func (p *SASQueryParameters) Services() string
Services gets the services of a SASQueryParameter
func (*SASQueryParameters) Signature ¶
func (p *SASQueryParameters) Signature() string
Signature gets the signature of a SASQueryParameter
func (*SASQueryParameters) SignedVersion ¶
func (p *SASQueryParameters) SignedVersion() string
SignedVersion gets the signed version of a SASQueryParameter
func (*SASQueryParameters) StartPartitionKey ¶
func (p *SASQueryParameters) StartPartitionKey() string
StartPartitionKey gets the start PartitionKey of a SASQueryParameter
func (*SASQueryParameters) StartRowKey ¶
func (p *SASQueryParameters) StartRowKey() string
StartRowKey gets the start RowKey of a SASQueryParameter
func (*SASQueryParameters) StartTime ¶
func (p *SASQueryParameters) StartTime() time.Time
StartTime gets the start time of a SASQueryParameter
func (*SASQueryParameters) Version ¶
func (p *SASQueryParameters) Version() string
Version gets the version of a SASQueryParameter
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://learn.microsoft.com/rest/api/storageservices/constructing-a-service-sas
func (SASSignatureValues) Sign ¶ added in v0.7.0
func (v SASSignatureValues) Sign(credential *SharedKeyCredential) (string, error)
Sign uses an account's SharedKeyCredential to sign this signature values to produce the proper SAS string.
type ServiceClient ¶
type ServiceClient struct {
// contains filtered or unexported fields
}
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. Pass in nil for options to construct the client with the default ClientOptions.
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. Pass in nil for options to construct the client with the default ClientOptions.
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. Pass in nil for options to construct the client with the default ClientOptions.
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. Pass in nil for options to construct the client with the default ClientOptions.
func (*ServiceClient) CreateTable ¶
func (t *ServiceClient) CreateTable(ctx context.Context, name string, options *CreateTableOptions) (CreateTableResponse, error)
CreateTable creates a table with the specified name. If the service returns a non-successful HTTP status code, the function returns an *azcore.ResponseError type. Specify nil for options if you want to use the default options.
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)
DeleteTable deletes a table by name. If the service returns a non-successful HTTP status code, the function returns an *azcore.ResponseError type. Specify nil for options if you want to use the default options.
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) GetAccountSASURL ¶ added in v0.7.0
func (t ServiceClient) GetAccountSASURL(resources AccountSASResourceTypes, permissions AccountSASPermissions, start time.Time, expiry time.Time) (string, error)
GetAccountSASURL 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().
Example ¶
package main import ( "fmt" "time" "github.com/Azure/azure-sdk-for-go/sdk/data/aztables" ) func main() { cred, err := aztables.NewSharedKeyCredential("myAccountName", "myAccountKey") if err != nil { panic(err) } service, err := aztables.NewServiceClientWithSharedKey("https://<myAccountName>.table.core.windows.net", cred, nil) if err != nil { panic(err) } resources := aztables.AccountSASResourceTypes{Service: true} permission := aztables.AccountSASPermissions{Read: true} start := time.Now() expiry := start.AddDate(1, 0, 0) sasURL, err := service.GetAccountSASURL(resources, permission, start, expiry) if err != nil { panic(err) } serviceURL := fmt.Sprintf("https://<myAccountName>.table.core.windows.net/?%s", sasURL) sasService, err := aztables.NewServiceClientWithNoCredential(serviceURL, nil) if err != nil { panic(err) } _ = sasService }
Output:
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. If the service returns a non-successful HTTP status code, the function returns an *azcore.ResponseError type. Specify nil for options if you want to use the default options.
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. If the service returns a non-successful HTTP status code, the function returns an *azcore.ResponseError type. Specify nil for options if you want to use the default options.
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) NewListTablesPager ¶ added in v0.8.0
func (t *ServiceClient) NewListTablesPager(listOptions *ListTablesOptions) *runtime.Pager[ListTablesResponse]
NewListTablesPager 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.
NewListTablesPager returns a Pager, which allows iteration through each page of results. Specify nil for listOptions if you want to use the default options. For more information about writing query strings, check out:
- API Documentation: https://learn.microsoft.com/rest/api/storageservices/querying-tables-and-entities
- README samples: https://github.com/Azure/azure-sdk-for-go/blob/main/sdk/data/aztables/README.md#writing-filters
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.NewListTablesPager(&aztables.ListTablesOptions{Filter: &filter}) pageCount := 1 for pager.More() { response, err := pager.NextPage(context.TODO()) if err != nil { panic(err) } 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.Name) } pageCount += 1 } }
Output:
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. If the service returns a non-successful HTTP status code, the function returns an *azcore.ResponseError type. Specify nil for options if you want to use the default options.
Example ¶
package main import ( "context" "os" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "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) } service, err := aztables.NewServiceClient(serviceURL, cred, nil) if err != nil { panic(err) } getResp, err := service.GetProperties(context.TODO(), nil) if err != nil { panic(err) } getResp.HourMetrics = &aztables.Metrics{ Enabled: to.Ptr(true), } getResp.Logging = &aztables.Logging{ Delete: to.Ptr(true), Read: to.Ptr(true), Write: to.Ptr(true), } getResp.Cors = append(getResp.Cors, &aztables.CorsRule{ AllowedHeaders: to.Ptr("x-allowed-header"), AllowedMethods: to.Ptr("POST,GET"), }) _, err = service.SetProperties(context.TODO(), getResp.ServiceProperties, nil) if err != nil { panic(err) } }
Output:
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
}
SetAccessPolicyOptions contains optional parameters for Client.SetAccessPolicy
type SetAccessPolicyResponse ¶
type SetAccessPolicyResponse struct { }
SetAccessPolicyResponse contains response fields for Client.SetAccessPolicy
type SetPropertiesOptions ¶
type SetPropertiesOptions struct { }
SetPropertiesOptions contains optional parameters for Client.SetProperties
type SetPropertiesResponse ¶
type SetPropertiesResponse struct { }
SetPropertiesResponse contains response fields for Client.SetProperties
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.
func (*SharedKeyCredential) AccountName ¶
func (c *SharedKeyCredential) AccountName() string
AccountName returns the Storage account's name.
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 { }
SubmitTransactionOptions contains optional parameters for Client.SubmitTransaction
type TableErrorCode ¶ added in v0.8.0
type TableErrorCode string
TableErrorCode is the error code returned by the service on failed operations. For more information about Table service error codes: https://learn.microsoft.com/rest/api/storageservices/table-service-error-codes
const ( DuplicatePropertiesSpecified TableErrorCode = "DuplicatePropertiesSpecified" EntityAlreadyExists TableErrorCode = "EntityAlreadyExists" EntityNotFound TableErrorCode = "EntityNotFound" EntityTooLarge TableErrorCode = "EntityTooLarge" HostInformationNotPresent TableErrorCode = "HostInformationNotPresent" InvalidDuplicateRow TableErrorCode = "InvalidDuplicateRow" InvalidInput TableErrorCode = "InvalidInput" InvalidValueType TableErrorCode = "InvalidValueType" InvalidXmlDocument TableErrorCode = "InvalidXmlDocument" JSONFormatNotSupported TableErrorCode = "JsonFormatNotSupported" MethodNotAllowed TableErrorCode = "MethodNotAllowed" NotImplemented TableErrorCode = "NotImplemented" OutOfRangeInput TableErrorCode = "OutOfRangeInput" PropertiesNeedValue TableErrorCode = "PropertiesNeedValue" PropertyNameInvalid TableErrorCode = "PropertyNameInvalid" PropertyNameTooLong TableErrorCode = "PropertyNameTooLong" PropertyValueTooLarge TableErrorCode = "PropertyValueTooLarge" ResourceNotFound TableErrorCode = "ResourceNotFound" TableAlreadyExists TableErrorCode = "TableAlreadyExists" TableBeingDeleted TableErrorCode = "TableBeingDeleted" TableNotFound TableErrorCode = "TableNotFound" TooManyProperties TableErrorCode = "TooManyProperties" UpdateConditionNotSatisfied TableErrorCode = "UpdateConditionNotSatisfied" XMethodIncorrectCount TableErrorCode = "XMethodIncorrectCount" XMethodIncorrectValue TableErrorCode = "XMethodIncorrectValue" XMethodNotUsingPost TableErrorCode = "XMethodNotUsingPost" )
func PossibleTableErrorCodeValues ¶ added in v0.8.0
func PossibleTableErrorCodeValues() []TableErrorCode
PossibleTableErrorCodeValues returns a slice of all possible TableErrorCode values
type TableProperties ¶ added in v0.6.0
type TableProperties struct { // The name of the table. Name *string `json:"TableName,omitempty"` // The OData properties of the table in JSON format. Value []byte }
TableProperties contains the properties for a single Table
type TransactionAction ¶
type TransactionAction struct { ActionType TransactionType Entity []byte IfMatch *azcore.ETag }
TransactionAction represents a single action within a Transaction
type TransactionResponse ¶
type TransactionResponse struct { }
TransactionResponse contains response fields for Client.TransactionResponse
type TransactionType ¶
type TransactionType string
TransactionType is the type for a specific transaction operation.
const ( TransactionTypeAdd TransactionType = "add" TransactionTypeUpdateMerge TransactionType = "updatemerge" TransactionTypeUpdateReplace TransactionType = "updatereplace" TransactionTypeDelete TransactionType = "delete" TransactionTypeInsertMerge TransactionType = "insertmerge" TransactionTypeInsertReplace TransactionType = "insertreplace" )
func PossibleTransactionTypeValues ¶ added in v0.6.0
func PossibleTransactionTypeValues() []TransactionType
PossibleTransactionTypeValues returns the possible values for the TransactionType const type.
type UpdateEntityOptions ¶
type UpdateEntityOptions struct { IfMatch *azcore.ETag UpdateMode UpdateMode }
UpdateEntityOptions contains optional parameters for Client.UpdateEntity
type UpdateEntityResponse ¶
UpdateEntityResponse contains response fields for Client.UpdateEntity
type UpdateMode ¶ added in v0.7.0
type UpdateMode string
UpdateMode specifies what type of update to do on UpsertEntity or UpdateEntity. UpdateModeReplace will replace an existing entity, UpdateModeMerge will merge properties of the entities.
const ( UpdateModeReplace UpdateMode = "replace" UpdateModeMerge UpdateMode = "merge" )
func PossibleUpdateModeValues ¶ added in v0.7.0
func PossibleUpdateModeValues() []UpdateMode
PossibleUpdateModeValues returns the possible values for the EntityUpdateMode const type.
type UpsertEntityOptions ¶ added in v0.8.0
type UpsertEntityOptions struct { // ETag is the optional etag for the Table ETag azcore.ETag // UpdateMode is the desired mode for the Update. Use UpdateModeReplace to replace fields on // the entity, use UpdateModeMerge to merge fields of the entity. UpdateMode UpdateMode }
UpsertEntityOptions contains optional parameters for Client.InsertEntity
type UpsertEntityResponse ¶ added in v0.8.0
UpsertEntityResponse contains response fields for Client.InsertEntity