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 ¶
- Variables
- func FormatTimesForSASSigning(startTime, expiryTime time.Time) (string, string)
- type AccessPolicy
- type AccountSASPermissions
- type AccountSASResourceTypes
- type AccountSASSignatureValues
- type AddEntityOptions
- type AddEntityResponse
- type Client
- func (t *Client) AddEntity(ctx context.Context, entity []byte, options *AddEntityOptions) (AddEntityResponse, error)
- func (t *Client) Create(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) GetTableSASToken(permissions SASPermissions, start time.Time, expiry time.Time) (string, error)
- func (t *Client) InsertEntity(ctx context.Context, entity []byte, options *InsertEntityOptions) (InsertEntityResponse, error)
- func (t *Client) List(listOptions *ListEntitiesOptions) ListEntitiesPager
- 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)
- 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 EndpointType
- type Entity
- type EntityUpdateMode
- type GeoReplication
- type GeoReplicationStatusType
- type GetAccessPolicyOptions
- type GetAccessPolicyResponse
- type GetEntityOptions
- type GetEntityResponse
- type GetPropertiesOptions
- type GetPropertiesResponse
- type GetStatisticsOptions
- type GetStatisticsResponse
- type IPRange
- type InsertEntityOptions
- type InsertEntityResponse
- type ListEntitiesOptions
- type ListEntitiesPage
- type ListEntitiesPager
- type ListEntitiesResponse
- type ListTablesOptions
- type ListTablesPage
- type ListTablesPager
- type Logging
- type Metrics
- type ResponseFormat
- type ResponseProperties
- 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 (t *ServiceClient) CreateTable(ctx context.Context, name string, options *CreateTableOptions) (*Client, error)
- func (t *ServiceClient) DeleteTable(ctx context.Context, name string, options *DeleteTableOptions) (DeleteTableResponse, error)
- func (t ServiceClient) GetAccountSASToken(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) ListTables(listOptions *ListTablesOptions) ListTablesPager
- func (t *ServiceClient) NewClient(tableName string) *Client
- func (t *ServiceClient) SetProperties(ctx context.Context, properties ServiceProperties, ...) (SetPropertiesResponse, error)
- type ServiceProperties
- type SetAccessPolicyOptions
- type SetAccessPolicyResponse
- type SetPropertiesOptions
- type SetPropertiesResponse
- type SharedKeyCredential
- func (c *SharedKeyCredential) AccountName() string
- func (c *SharedKeyCredential) ComputeHMACSHA256(message string) (string, error)
- func (c *SharedKeyCredential) NewAuthenticationPolicy(options runtime.AuthenticationOptions) policy.Policy
- func (c *SharedKeyCredential) SetAccountKey(accountKey string) error
- type SignedIdentifier
- type SubmitTransactionOptions
- type TransactionAction
- type TransactionResponse
- type TransactionType
- type UpdateEntityOptions
- type UpdateEntityResponse
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var SASVersion = "2019-02-02"
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 }
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 ¶
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 ¶
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 { // 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 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.Credential, options *ClientOptions) (*Client, error)
NewClient creates a Client struct in the context of the table specified in the serviceURL, credential, and options. The serviceURL param is expected to have the name of the table in a format similar to: "https://myAccountName.core.windows.net/<myTableName>". If the serviceURL contains a Shared Access Signature, use azcore.NewAnonymousCredential() as the credential.
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.NewClient(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.Background(), 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.Background(), 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.NewClient(serviceURL, cred, nil) if err != nil { panic(err) } anyETag := azcore.ETagAny _, err = client.DeleteEntity(context.Background(), "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 if the supplied azcore.Credential during creation was a SharedKeyCredential.
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.NewClient(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.Background(), 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.Background(), 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.NewClient(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.Background()) { 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.Background()) { 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.NewClient(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.Background(), 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 { // Transport sets the transport for making HTTP requests. Transport policy.Transporter // Retry configures the built-in retry policy behavior. Retry policy.RetryOptions // Telemetry configures the built-in telemetry policy behavior. Telemetry policy.TelemetryOptions // PerCallPolicies are policies that execute once per operation PerCallPolicies []policy.Policy // PerTryPolicies are policies that execute once per retry of an operation PerTryPolicies []policy.Policy }
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 DeleteEntityOptions ¶
type DeleteEntityResponse ¶
type DeleteTableOptions ¶
type DeleteTableOptions struct { }
Options for Client.Delete and ServiceClient.DeleteTable methods
type DeleteTableResponse ¶
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 (*EDMBinary) UnmarshalText ¶
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)
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 (*EDMEntity) UnmarshalJSON ¶
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 (*EDMGUID) UnmarshalText ¶
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 (*EDMInt64) UnmarshalText ¶
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" )
func PossibleGeoReplicationStatusTypeValues ¶
func PossibleGeoReplicationStatusTypeValues() []GeoReplicationStatusType
PossibleGeoReplicationStatusTypeValues returns the possible values for the GeoReplicationStatusType const type.
func (GeoReplicationStatusType) ToPtr ¶
func (c GeoReplicationStatusType) ToPtr() *GeoReplicationStatusType
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 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.
type InsertEntityOptions ¶
type InsertEntityOptions struct { ETag azcore.ETag UpdateMode EntityUpdateMode }
type InsertEntityResponse ¶
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 }
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 }
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.Credential, 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 (*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.Background(), "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.Background(), "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 if the supplied azcore.Credential during creation was a SharedKeyCredential.
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.NewServiceClient(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.Background()) { 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 SetPropertiesOptions ¶
type SetPropertiesOptions struct{}
type SetPropertiesResponse ¶
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) ComputeHMACSHA256 ¶
func (c *SharedKeyCredential) ComputeHMACSHA256(message string) (string, error)
computeHMACSHA256 generates a hash signature for an HTTP request or for a SAS.
func (*SharedKeyCredential) NewAuthenticationPolicy ¶
func (c *SharedKeyCredential) NewAuthenticationPolicy(options runtime.AuthenticationOptions) policy.Policy
NewAuthenticationPolicy implements the Credential interface on SharedKeyCredential.
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 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 }