Documentation ¶
Overview ¶
Package interstellar is a client for using the SQL CosmoDB API over REST/HTTP. It provides a generic way of interacting with arbitrary resources in Cosmos DB via the Client And also convenience functions for interacting with resources types like Databases, Collections, Documents, and Offers.
Index ¶
- Constants
- func ParseArrayFromResponse(r io.Reader, key string) ([]json.RawMessage, error)
- func ParseArrayResponse(r io.Reader) ([]json.RawMessage, error)
- func ParseObjectResponse(r io.Reader) (map[string]json.RawMessage, error)
- type Authorizer
- type Client
- func (c *Client) CreateDatabase(ctx context.Context, id string, opts RequestOptions) (*DatabaseResource, *ResponseMetadata, error)
- func (c *Client) CreateDatabaseRaw(ctx context.Context, id string, opts RequestOptions) ([]byte, *ResponseMetadata, error)
- func (c *Client) CreateOrReplaceResource(ctx context.Context, request ClientRequest) ([]byte, *ResponseMetadata, error)
- func (c *Client) DeleteResource(ctx context.Context, request ClientRequest) (bool, *ResponseMetadata, error)
- func (c *Client) GetResource(ctx context.Context, request ClientRequest) ([]byte, *ResponseMetadata, error)
- func (c *Client) ListDatabases(ctx context.Context, opts RequestOptions, fn PaginateDatabaseResource) error
- func (c *Client) ListDatabasesRaw(ctx context.Context, opts RequestOptions, fn PaginateRawResources) error
- func (c *Client) ListOffers(ctx context.Context, opts RequestOptions, fn PaginateOfferResource) error
- func (c *Client) ListOffersRaw(ctx context.Context, opts RequestOptions, fn PaginateRawResources) error
- func (c *Client) ListResources(ctx context.Context, key string, request ClientRequest, ...) error
- func (c *Client) NewHTTPRequest(ctx context.Context, req ClientRequest) (*http.Request, error)
- func (c *Client) QueryOffersRaw(ctx context.Context, query *Query, fn PaginateRawResources) error
- func (c *Client) ReplaceOffer(ctx context.Context, req ReplaceOfferRequest) (*OfferResource, *ResponseMetadata, error)
- func (c *Client) WithDatabase(id string) *DatabaseClient
- func (c *Client) WithOffer(id string) *OfferClient
- type ClientRequest
- type CollectionClient
- func (c *CollectionClient) CreateDocument(ctx context.Context, req CreateDocumentRequest) ([]byte, *ResponseMetadata, error)
- func (c *CollectionClient) CreateStoredProcedure(ctx context.Context, req CreateStoredProcedureRequest) (*StoredProcedureResource, *ResponseMetadata, error)
- func (c *CollectionClient) CreateUserDefinedFunction(ctx context.Context, req CreateUserDefinedFunctionRequest) (*UserDefinedFunctionResource, *ResponseMetadata, error)
- func (c *CollectionClient) CreateUserDefinedFunctionRaw(ctx context.Context, req CreateUserDefinedFunctionRequest) ([]byte, *ResponseMetadata, error)
- func (c *CollectionClient) Delete(ctx context.Context, opts RequestOptions) (bool, *ResponseMetadata, error)
- func (c *CollectionClient) Get(ctx context.Context, opts RequestOptions) (*CollectionResource, *ResponseMetadata, error)
- func (c *CollectionClient) GetRaw(ctx context.Context, opts RequestOptions) ([]byte, *ResponseMetadata, error)
- func (c *CollectionClient) ListDocumentsRaw(ctx context.Context, opts RequestOptions, fn PaginateRawResources) error
- func (c *CollectionClient) ListStoredProcedures(ctx context.Context, opts RequestOptions, fn PaginateSProcResource) error
- func (c *CollectionClient) ListUserDefinedFunctions(ctx context.Context, opts RequestOptions, fn PaginateUDFResource) error
- func (c *CollectionClient) ListUserDefinedFunctionsRaw(ctx context.Context, opts RequestOptions, fn PaginateRawResources) error
- func (c *CollectionClient) QueryDocumentsRaw(ctx context.Context, query *Query, fn PaginateRawResources) error
- func (c *CollectionClient) ResourceLink() string
- func (c *CollectionClient) WithDocument(id string, partitionKey []string) *DocumentClient
- func (c *CollectionClient) WithStoredProcedure(id string) *SProcClient
- func (c *CollectionClient) WithUDF(id string) *UDFClient
- type CollectionExcludedPath
- type CollectionIncludedPath
- type CollectionIndex
- type CollectionIndexingPolicy
- type CollectionPartitionKey
- type CollectionResource
- type CommonRequestOptions
- type ConnectionString
- type ConsistencyLevel
- type CreateCollectionRequest
- type CreateDocumentRequest
- type CreateStoredProcedureRequest
- type CreateUserDefinedFunctionRequest
- type DataType
- type DatabaseClient
- func (c *DatabaseClient) CreateCollection(ctx context.Context, req CreateCollectionRequest) (*CollectionResource, *ResponseMetadata, error)
- func (c *DatabaseClient) CreateCollectionRaw(ctx context.Context, req CreateCollectionRequest) ([]byte, *ResponseMetadata, error)
- func (c *DatabaseClient) Delete(ctx context.Context, opts RequestOptions) (bool, *ResponseMetadata, error)
- func (c *DatabaseClient) Get(ctx context.Context, opts RequestOptions) (*DatabaseResource, *ResponseMetadata, error)
- func (c *DatabaseClient) GetRaw(ctx context.Context, opts RequestOptions) ([]byte, *ResponseMetadata, error)
- func (c *DatabaseClient) ListCollections(ctx context.Context, opts RequestOptions, fn PaginateCollectionResource) error
- func (c *DatabaseClient) ListCollectionsRaw(ctx context.Context, opts RequestOptions, fn PaginateRawResources) error
- func (c *DatabaseClient) ResourceLink() string
- func (c *DatabaseClient) WithCollection(id string) *CollectionClient
- type DatabaseResource
- type DocumentClient
- func (c *DocumentClient) Delete(ctx context.Context, opts RequestOptions) (bool, *ResponseMetadata, error)
- func (c *DocumentClient) Get(ctx context.Context, opts RequestOptions, v interface{}) (*ResponseMetadata, error)
- func (c *DocumentClient) GetRaw(ctx context.Context, opts RequestOptions) ([]byte, *ResponseMetadata, error)
- func (c *DocumentClient) ReplaceDocument(ctx context.Context, req ReplaceDocumentRequest) ([]byte, *ResponseMetadata, error)
- func (c *DocumentClient) ResourceLink() string
- type DocumentIndexingDirective
- type DocumentProperties
- type Error
- type IndexingMode
- type MasterKey
- type OfferClient
- type OfferContent
- type OfferContentV2
- type OfferResource
- type OfferType
- type OfferVersion
- type PaginateCollectionResource
- type PaginateDatabaseResource
- type PaginateOfferResource
- type PaginateRawResources
- type PaginateSProcResource
- type PaginateUDFResource
- type PartitionKind
- type Query
- type QueryParameter
- type ReplaceDocumentRequest
- type ReplaceOfferRequest
- type RequestOptions
- type RequestOptionsFunc
- type RequestOptionsList
- type Requester
- type ResourceType
- type ResponseMetadata
- type SProcClient
- func (c *SProcClient) Delete(ctx context.Context, opts RequestOptions) (bool, *ResponseMetadata, error)
- func (c *SProcClient) Execute(ctx context.Context, opts RequestOptions, args ...interface{}) ([]byte, *ResponseMetadata, error)
- func (c *SProcClient) Func(opts RequestOptions) func(context.Context, ...interface{}) ([]byte, *ResponseMetadata, error)
- func (c *SProcClient) Replace(ctx context.Context, body string, opts RequestOptions) (*StoredProcedureResource, *ResponseMetadata, error)
- func (c *SProcClient) ResourceLink() string
- type StoredProcedureResource
- type UDFClient
- func (c *UDFClient) Delete(ctx context.Context, opts RequestOptions) (bool, *ResponseMetadata, error)
- func (c *UDFClient) Replace(ctx context.Context, body string, opts RequestOptions) (*UserDefinedFunctionResource, *ResponseMetadata, error)
- func (c *UDFClient) ReplaceRaw(ctx context.Context, body string, opts RequestOptions) ([]byte, *ResponseMetadata, error)
- func (c *UDFClient) ResourceLink() string
- type UserDefinedFunctionResource
Examples ¶
Constants ¶
const ( // TokenVersion is the version of the token that is implemented // See https://docs.microsoft.com/en-us/rest/api/documentdb/access-control-on-documentdb-resources // for more information TokenVersion = "1.0" // MasterTokenAuthType specifies that the type of authentication used is 'master' when computing the hash signature for an authenticated REST API call. // See https://docs.microsoft.com/en-us/rest/api/cosmos-db/access-control-on-cosmosdb-resources#constructkeytoken for the specification. MasterTokenAuthType = "master" )
const ( // ErrPreconditionFailed is returned when an optimistic concurrency check fails ErrPreconditionFailed = Error("interstellar: request precondition failed") // ErrResourceNotFound is returned when a resource is not found ErrResourceNotFound = Error("interstellar: resource not found") )
const ( // ContentTypeJSON is the MIME-Type for generic JSON content ContentTypeJSON = "application/json" // ContentTypeQueryJSON is the MIME-Type for CosmosDB Queries (json) ContentTypeQueryJSON = "application/query+json" )
const ( // HeaderUserAgent used to differentiate different client applications. // Recommended format is {user agent name}/{version} // For example: MyApplication/1.0.0 // See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/common-cosmosdb-rest-request-headers HeaderUserAgent = "User-Agent" // HeaderContentType is used mostly for POST query operations // where the Content-Type header must be application/query+json // See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/common-cosmosdb-rest-request-headers HeaderContentType = "Content-Type" // HeaderIfMatch used for optimistic concurrency based off ETag // See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/common-cosmosdb-rest-request-headers HeaderIfMatch = "If-Match" // HeaderIfNoneMatch used for optimistic concurrency based off ETag // See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/common-cosmosdb-rest-request-headers HeaderIfNoneMatch = "If-None-Match" // HeaderIfModifiedSince used for optimistic concurrency based off Modified Date (RFC1123 Date/Time Format) // See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/common-cosmosdb-rest-request-headers HeaderIfModifiedSince = "If-Modified-Since" // HeaderActivityID "x-ms-activity-id" // See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/common-cosmosdb-rest-request-headers HeaderActivityID = "x-ms-activity-id" // HeaderConsistencyLevel Strong, Bounded, Session, or Eventual (in order of strongest to weakest) // See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/common-cosmosdb-rest-request-headers HeaderConsistencyLevel = "x-ms-consistency-level" // HeaderMaxItemCount is supplied in list/query operations to limit the number of results per page. // See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/common-cosmosdb-rest-request-headers HeaderMaxItemCount = "x-ms-max-item-count" // HeaderDocDBPartitionKey the partition key value for the requested document or attachment. // The format of this header is a JSON array of values // See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/common-cosmosdb-rest-request-headers HeaderDocDBPartitionKey = "x-ms-documentdb-partitionkey" // HeaderDocDBQueryEnableCrossPartition is set to true for queries which should span multiple partitions, and a partition key is not supplied. // See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/common-cosmosdb-rest-request-headers HeaderDocDBQueryEnableCrossPartition = "x-ms-documentdb-query-enablecrosspartition" // HeaderMSAPIVersion is used to specify which version of the REST API is being used by the request // See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/common-cosmosdb-rest-request-headers HeaderMSAPIVersion = "x-ms-version" // HeaderAIM is sued to indicate the Change Feed request. It must be set to "incremental feed" or otherwise omitted. // See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/common-cosmosdb-rest-request-headers HeaderAIM = "A-IM" // HeaderDocDBPartitionKeyRangeID Used in change feed requests. This is a number which is the Parittion Key Range ID used for reading data. HeaderDocDBPartitionKeyRangeID = "x-ms-documentdb-partitionkeyrangeid" )
Common Request Headers https://docs.microsoft.com/en-us/rest/api/cosmos-db/common-cosmosdb-rest-request-headers
const ( // HeaderDate is the date time of the response. This date time format conforms to the RFC 1123 date time format expressed in Coordinated Universal Time. // See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/common-cosmosdb-rest-response-headers HeaderDate = "Date" // HeaderETag indicates the etage of the resource. the same as the `_etag` property on the resource body. // See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/common-cosmosdb-rest-response-headers HeaderETag = "ETag" // HeaderAltContentPath is the alternate content path of the resource. // See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/common-cosmosdb-rest-response-headers HeaderAltContentPath = "x-ms-alt-content-path" // HeaderContinuation represents the intermediate state of query (or read-feed) execution, and is returned when there are additional results aside from what was returned in the response. Clients can resubmitted the request with a request header containing the value of x-ms-continuation. // See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/common-cosmosdb-rest-response-headers HeaderContinuation = "x-ms-continuation" // HeaderItemCount is the number of items returned for a query or read-feed request. // See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/common-cosmosdb-rest-response-headers HeaderItemCount = "x-ms-item-count" // HeaderRequestCharge is the number of normalized requests a.k.a. request units (RU) for the operation. For more information, see Request units in Azure Cosmos DB. // See: https://docs.microsoft.com/en-us/azure/cosmos-db/request-units/ // See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/common-cosmosdb-rest-response-headers HeaderRequestCharge = "x-ms-request-charge" // HeaderResourceQuota is the allotted quota for a resource in an account. // See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/common-cosmosdb-rest-response-headers HeaderResourceQuota = "x-ms-resource-quota" // HeaderResourceUsage is the current usage count of a resource in an account. When deleting a resource, this shows the number of resources after the deletion. // See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/common-cosmosdb-rest-response-headers HeaderResourceUsage = "x-ms-resource-usage" // HeaderRetryAfterMS is the number of milliseconds to wait to retry the operation after an initial operation received HTTP status code 429 and was throttled. // See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/common-cosmosdb-rest-response-headers HeaderRetryAfterMS = "x-ms-retry-after-ms" // HeaderSchemaVersion Shows the resource schema version number. // See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/common-cosmosdb-rest-response-headers HeaderSchemaVersion = "x-ms-schemaversion" // HeaderServiceVersion is the service version number. // See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/common-cosmosdb-rest-response-headers HeaderServiceVersion = "x-ms-serviceversion" // HeaderSessionToken is the session token of the request. // For session consistency, clients must echo this request via the x-ms-session-token request header for subsequent operations made to the corresponding collection. // See: https://docs.microsoft.com/azure/cosmos-db/consistency-levels // See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/common-cosmosdb-rest-response-headers HeaderSessionToken = "x-ms-session-token" )
Common Response Headers https://docs.microsoft.com/en-us/rest/api/cosmos-db/common-cosmosdb-rest-response-headers
const ( // ConsistencyStrong denotes the operation should be strongly consistent. (Limited Linearizability guarantee) ConsistencyStrong = ConsistencyLevel("Strong") // ConsistencyBounded denotes a slightly weaker consistency than strong. Reads may lag behind writes by a constant number or time frame. ConsistencyBounded = ConsistencyLevel("Bounded") // ConsistencySession is consistency scoped to a single client/session. Read your writes, monotonic reads, monotonic writes. ConsistencySession = ConsistencyLevel("Session") // ConsistencyEventual is the weakest consistency level. ConsistencyEventual = ConsistencyLevel("Eventual") )
const ( // HeaderOfferType is used to set the Offer type on the Collection at creation time. This is one of the pre-defined levels: S1,S2,S3. HeaderOfferType = "x-ms-offer-type" // HeaderOfferThroughput is used to set the provisioned RU Throughput on the collection at creation time. HeaderOfferThroughput = "x-ms-offer-throughput" )
const ( // IndexingModeNone means no indexing is performed at all IndexingModeNone = IndexingMode("None") // IndexingModeConsistent means the index is updated synchronously on each insertion, replacement, or deletion action taken on a document in the collection (MSFT) IndexingModeConsistent = IndexingMode("Consistent") // IndexingModeLazy means the index is updated asynchronously and may be out of date, eliminating the ability to consistently "read your writes". IndexingModeLazy = IndexingMode("Lazy") )
const ( // DataTypeString denotes a string type DataTypeString = DataType("String") // DataTypeNumber denotes a number type (int or float) DataTypeNumber = DataType("Number") // DataTypePoint denotes a GeoJSON Point. (RFC7946 § 3.1.2) DataTypePoint = DataType("Point") // DataTypePolygon denotes a GeoJSON Polygon. (RFC7946 § 3.1.6) DataTypePolygon = DataType("Polygon") // DataTypeLineString a GeoJSON LineString. (RFC7946 § 3.1.4) DataTypeLineString = DataType("LineString") )
const ( // PartititionKindHash is used to enable equality comparisons PartititionKindHash = PartitionKind("Hash") // PartititionKindRange is used to enable sorting and range comparisons PartititionKindRange = PartitionKind("Range") // PartititionKindSpatial is used to enable spacial queries (such as geographic coordinates) PartititionKindSpatial = PartitionKind("Spatial") )
const ( // DocumentIndexingInclude specifies that the document should be included in the collection index. DocumentIndexingInclude = DocumentIndexingDirective("Include") // DocumentIndexingExclude specifies that the document should be excluded from the collection index. DocumentIndexingExclude = DocumentIndexingDirective("Exclude") )
const ( // OfferTypeInvalid indicates the performance level is user-defined OfferTypeInvalid = OfferType("Invalid") // OfferTypeS1 maps to the S1 performance level OfferTypeS1 = OfferType("S1") // OfferTypeS2 maps to the S3 performance level OfferTypeS2 = OfferType("S2") // OfferTypeS3 maps to the S3 performance level OfferTypeS3 = OfferType("S3") )
const APIVersion = "2017-02-22"
APIVersion is the version of the CosmosDB REST API supported See https://docs.microsoft.com/en-us/rest/api/cosmos-db/#supported-rest-api-versions for available versions and changelog
const DefaultUserAgent = "Go-Interstellar/0.1"
DefaultUserAgent which is set on outgoing http requests if none is set on the client
const ( // ErrKeyNotFound is returned when the required key was missing from the response object ErrKeyNotFound = Error("interstellar: key was not found in the response object") )
const ErrOfferInvalidVersion = Error("insterstellar: invalid offer version")
ErrOfferInvalidVersion is returned when an invalid offer version is read
const HeaderAuthorization = "Authorization"
HeaderAuthorization is the header used to pass the Authorization token to the API
const HeaderDocDBIsQuery = "x-ms-documentdb-isquery"
HeaderDocDBIsQuery is used to indicate the POST request is a query, not a Create. Must be set to "true".
const HeaderDocDBIsUpsert = "x-ms-documentdb-is-upsert"
HeaderDocDBIsUpsert is set to true if the document should be created if it does not exist, or updated in-place if it does.
const HeaderIndexingDirective = "x-ms-indexing-directive"
HeaderIndexingDirective is used to enable or disable indexing on the resource.
const HeaderMSDate = "x-ms-date"
HeaderMSDate is the date/time of the request. This date time format conforms to the RFC 1123 date time format expressed in Coordinated Universal Time. This is passed in the request and much match the date in the hash for the Authorization header See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/access-control-on-cosmosdb-resources#constructkeytoken
Variables ¶
This section is empty.
Functions ¶
func ParseArrayFromResponse ¶
ParseArrayFromResponse parses a list of results from the response object mapped by given key. An error will be returend if the read bytes do not parse to a JSON object containing the desired key => list pair
Example Input JSON:
{ "key": [1,2,"3",true] }
If the key is not found in the object, ErrKeyNotFound is returned
func ParseArrayResponse ¶
func ParseArrayResponse(r io.Reader) ([]json.RawMessage, error)
ParseArrayResponse parses the response into a JSON array
Example Input JSON:
[1,2,"3",true]
func ParseObjectResponse ¶
ParseObjectResponse parses the response into a json object An error will be returend if the read bytes do not parse to an object with string keys
Example Input JSON:
{ "key1": [1,2,"3",true], "key2": "foo", "key3": { "bar": "baz" } }
Types ¶
type Authorizer ¶
type Authorizer interface {
Authorize(r *http.Request, resourceType ResourceType, resourceLink string) (*http.Request, error)
}
Authorizer is an interface used to authorize Cosmos DB Requests
type Client ¶
type Client struct { UserAgent string Endpoint string Authorizer Requester }
Client for making API calls against CosmosDB
Example (Custom) ¶
key, _ := interstellar.ParseMasterKey("C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==") _ = &interstellar.Client{ UserAgent: interstellar.DefaultUserAgent, Endpoint: "https://localhost:8081", Authorizer: key, Requester: http.DefaultClient, }
Output:
func NewClient ¶
func NewClient(cs ConnectionString, req Requester) (*Client, error)
NewClient creates client to the given CoasmosDB account in the ConnectionString And will use the Requester to send HTTP requests and read responses
Example ¶
cstring := "AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==" cs, _ := interstellar.ParseConnectionString(cstring) _, _ = interstellar.NewClient(cs, nil)
Output:
func (*Client) CreateDatabase ¶
func (c *Client) CreateDatabase(ctx context.Context, id string, opts RequestOptions) (*DatabaseResource, *ResponseMetadata, error)
CreateDatabase creates a new database with the given ID
func (*Client) CreateDatabaseRaw ¶
func (c *Client) CreateDatabaseRaw(ctx context.Context, id string, opts RequestOptions) ([]byte, *ResponseMetadata, error)
CreateDatabaseRaw creates a new database with the given ID and returns the raw response
func (*Client) CreateOrReplaceResource ¶
func (c *Client) CreateOrReplaceResource(ctx context.Context, request ClientRequest) ([]byte, *ResponseMetadata, error)
CreateOrReplaceResource creates new or replaces existing resources inside a given collection.
If the ClientRequest.Method is not set, it will default to POST. If it is given, it must be PUT or POST; otherwise an error will be returned.
For example, this can be used to create a new collection inside a database, a new document inside a collection, or update a document with new data.
func (*Client) DeleteResource ¶
func (c *Client) DeleteResource(ctx context.Context, request ClientRequest) (bool, *ResponseMetadata, error)
DeleteResource issues a delete command against a resource designate by the request
func (*Client) GetResource ¶
func (c *Client) GetResource(ctx context.Context, request ClientRequest) ([]byte, *ResponseMetadata, error)
GetResource retrieves the body of a resource given by the request For example, this can be used to get the full body of a Collection resource, or a Document resource by it ID
func (*Client) ListDatabases ¶
func (c *Client) ListDatabases(ctx context.Context, opts RequestOptions, fn PaginateDatabaseResource) error
ListDatabases lists each database in the CosmosDB Account given to the pagination function
func (*Client) ListDatabasesRaw ¶
func (c *Client) ListDatabasesRaw(ctx context.Context, opts RequestOptions, fn PaginateRawResources) error
ListDatabasesRaw lists each database in the CosmosDB Account as raw JSON objects given to the pagination function
func (*Client) ListOffers ¶
func (c *Client) ListOffers(ctx context.Context, opts RequestOptions, fn PaginateOfferResource) error
ListOffers lists each collection in the CosmosDB account
func (*Client) ListOffersRaw ¶
func (c *Client) ListOffersRaw(ctx context.Context, opts RequestOptions, fn PaginateRawResources) error
ListOffersRaw lists each offer in the CosmosDB account as raw JSON objects
func (*Client) ListResources ¶
func (c *Client) ListResources(ctx context.Context, key string, request ClientRequest, fn PaginateRawResources) error
ListResources executes requests on a collection results to paginate through all the sub-resources. For example, this can be used to paginate through all documents within a collection.
After each successful result list is returned, the array of objects are extracted from the given Key and passed to the supplied PaginateRawResources function. If PaginateRawResources function returns (true, nil), the next page will be requested If PaginateRawResources function returns (false, nil), then pagination will stop, and ListResults will return without error. If PaginateRawResources function returns a non-nil error, then pagination will stop, and ListResults will return that error. Pagination will also stop after the last page is returned from the API
func (*Client) NewHTTPRequest ¶
NewHTTPRequest creates a new authorized http request that can be run against a Requester such as *http.Client or anything implementing the Requester interface
func (*Client) QueryOffersRaw ¶
QueryOffersRaw executes the given OfferQuery and paginates through the offers
func (*Client) ReplaceOffer ¶
func (c *Client) ReplaceOffer(ctx context.Context, req ReplaceOfferRequest) (*OfferResource, *ResponseMetadata, error)
ReplaceOffer replaces an existing offer with new parameters
func (*Client) WithDatabase ¶
func (c *Client) WithDatabase(id string) *DatabaseClient
WithDatabase creates a DatabaseClient for the given Database ID
func (*Client) WithOffer ¶
func (c *Client) WithOffer(id string) *OfferClient
WithOffer creates a OfferClient for the given Offer within this account
type ClientRequest ¶
type ClientRequest struct { // Method is the HTTP Method/Verb used for the request Method string // Path is the URL path portion of the request Path string // ResourceType is the type of resource being requested, such as "dbs" or "colls" ResourceType ResourceType // ResourceLink is the identity property of the resource that the request is directed at. // See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/access-control-on-cosmosdb-resources // For example, the format for a collection is: "dbs/{db.id}/colls/{coll.id}" like "dbs/MyDatabase/colls/MyCollection". // The resource links is CASE SENSITIVE. // Note: It is NOT the same as the '_self' property of a resource (in most cases). ResourceLink string // Options allow for applying additional headers and other request options to the HTTP request Options RequestOptions // Body is a reader which should be sent as the body of the request Body io.Reader // GetBody is used to set the body of the request for retrys and resubmissions GetBody func() (io.ReadCloser, error) }
ClientRequest encapsulates the CosmosDB API request parameters
type CollectionClient ¶
CollectionClient is a client scoped to a single collection Used to perform API calls within the scope of the Collection resource
func (*CollectionClient) CreateDocument ¶
func (c *CollectionClient) CreateDocument(ctx context.Context, req CreateDocumentRequest) ([]byte, *ResponseMetadata, error)
CreateDocument creates or updates a document in the collection
func (*CollectionClient) CreateStoredProcedure ¶ added in v0.0.2
func (c *CollectionClient) CreateStoredProcedure(ctx context.Context, req CreateStoredProcedureRequest) (*StoredProcedureResource, *ResponseMetadata, error)
CreateStoredProcedure creates a Stored Procedure
func (*CollectionClient) CreateUserDefinedFunction ¶
func (c *CollectionClient) CreateUserDefinedFunction(ctx context.Context, req CreateUserDefinedFunctionRequest) (*UserDefinedFunctionResource, *ResponseMetadata, error)
CreateUserDefinedFunction creates a UDF
func (*CollectionClient) CreateUserDefinedFunctionRaw ¶
func (c *CollectionClient) CreateUserDefinedFunctionRaw(ctx context.Context, req CreateUserDefinedFunctionRequest) ([]byte, *ResponseMetadata, error)
CreateUserDefinedFunctionRaw creates a UDF
func (*CollectionClient) Delete ¶
func (c *CollectionClient) Delete(ctx context.Context, opts RequestOptions) (bool, *ResponseMetadata, error)
Delete will delete the collection See Client.DeleteResource for more information
func (*CollectionClient) Get ¶
func (c *CollectionClient) Get(ctx context.Context, opts RequestOptions) (*CollectionResource, *ResponseMetadata, error)
Get retrieves the CollectionResource
func (*CollectionClient) GetRaw ¶
func (c *CollectionClient) GetRaw(ctx context.Context, opts RequestOptions) ([]byte, *ResponseMetadata, error)
GetRaw retrieves the raw collection
func (*CollectionClient) ListDocumentsRaw ¶
func (c *CollectionClient) ListDocumentsRaw(ctx context.Context, opts RequestOptions, fn PaginateRawResources) error
ListDocumentsRaw lists each document in the collection as raw JSON objects
func (*CollectionClient) ListStoredProcedures ¶ added in v0.0.2
func (c *CollectionClient) ListStoredProcedures(ctx context.Context, opts RequestOptions, fn PaginateSProcResource) error
ListStoredProcedures lists each stored procedure in the collection
func (*CollectionClient) ListUserDefinedFunctions ¶
func (c *CollectionClient) ListUserDefinedFunctions(ctx context.Context, opts RequestOptions, fn PaginateUDFResource) error
ListUserDefinedFunctions lists each User-defined Function in the collection
func (*CollectionClient) ListUserDefinedFunctionsRaw ¶
func (c *CollectionClient) ListUserDefinedFunctionsRaw(ctx context.Context, opts RequestOptions, fn PaginateRawResources) error
ListUserDefinedFunctionsRaw lists all user-defined functions
func (*CollectionClient) QueryDocumentsRaw ¶
func (c *CollectionClient) QueryDocumentsRaw(ctx context.Context, query *Query, fn PaginateRawResources) error
QueryDocumentsRaw posts the query to the collection and paginates through the results using the supplied paginate function
Example ¶
// error handling omitted for brevity // Document inside the collection for Unmarshaling type Document struct { ID string `json:"id"` Name string `json:"name"` Address string `json:"address"` } // Get a client cs, _ := interstellar.ParseConnectionString("AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==") client, _ := interstellar.NewClient(cs, nil) // Construct a query which returns documents which have a name prefixed with `ab`, 10 per page. query := &interstellar.Query{ Query: "SELECT * FROM Documents d WHERE STARTSWITH(d.name,@prefix)", Parameters: []interstellar.QueryParameter{ interstellar.QueryParameter{Name: "@prefix", Value: "ab"}, }, MaxItemCount: 10, } // Results var docs []Document // Get the CollectionClient scoped to `dbs/db1/colls/col1` cc := client.WithDatabase("db1").WithCollection("col1") // Perform the query, and paginate through all the results cc.QueryDocumentsRaw(context.Background(), query, func(resList []json.RawMessage, meta interstellar.ResponseMetadata) (bool, error) { for _, raw := range resList { var doc Document if err := json.Unmarshal(raw, &doc); err != nil { return false, err } docs = append(docs, doc) } // true = get next page return true, nil })
Output:
func (*CollectionClient) ResourceLink ¶
func (c *CollectionClient) ResourceLink() string
ResourceLink gets the resource link for the collection
func (*CollectionClient) WithDocument ¶
func (c *CollectionClient) WithDocument(id string, partitionKey []string) *DocumentClient
WithDocument creates a DocumentClient for the given Document ID and PartitionKey within this Collection
func (*CollectionClient) WithStoredProcedure ¶ added in v0.0.2
func (c *CollectionClient) WithStoredProcedure(id string) *SProcClient
WithStoredProcedure creates a SProcClient for the given Stored Procedure within this Collection
func (*CollectionClient) WithUDF ¶
func (c *CollectionClient) WithUDF(id string) *UDFClient
WithUDF creates a UDFClient for the given UDF within this Collection
type CollectionExcludedPath ¶
type CollectionExcludedPath struct {
Path string `json:"path"`
}
CollectionExcludedPath represents a JSON Path to exclude from indexing inside a CollectionIndexingPolicy
type CollectionIncludedPath ¶
type CollectionIncludedPath struct { Path string `json:"path"` Indexes []*CollectionIndex `json:"indexes"` }
CollectionIncludedPath represents a JSON Path and the type of data to include when indexing. This is part of a CollectionIndexingPolicy
type CollectionIndex ¶
type CollectionIndex struct { DataType DataType `json:"dataType"` Precision int `json:"precision,omitempty"` Kind PartitionKind `json:"kind"` }
CollectionIndex describes the type of data and precision that an included indexing path should used when being indexed. From [Microsoft Documentation](https://docs.microsoft.com/en-us/rest/api/cosmos-db/collections#indexing-policy) > The type or scheme used for index entries has a direct impact on index storage and performance. > For a scheme using higher precision, queries are typically faster. However, there is also a higher storage overhead for the index. > Choosing a lower precision means that more documents might have to be processed during query execution, but the storage overhead will be lower.
type CollectionIndexingPolicy ¶
type CollectionIndexingPolicy struct { // Automatic indicates whether automatic indexing is on or off. // The default value is True, thus all documents are indexed. // Setting the value to False would allow manual configuration of indexing paths. Automatic *bool `json:"automatic,omitempty"` // IndexingMode indicates the consistency of indexing with respect to document modifications. // By default, the indexing mode is Consistent. This means that indexing occurs synchronously during insertion, replacment or deletion of documents. // To have indexing occur asynchronously, set the indexing mode to lazy. IndexingMode *IndexingMode `json:"indexingMode,omitempty"` // IncludedPaths specifies which paths must be included in indexing IncludedPaths []*CollectionIncludedPath `json:"includedPaths,omitempty"` // ExcludedPaths specifies Which paths must be excluded from indexing ExcludedPaths []*CollectionExcludedPath `json:"excludedPaths,omitempty"` }
CollectionIndexingPolicy represents the indexing policy configuration for a Collection
type CollectionPartitionKey ¶
type CollectionPartitionKey struct { // Paths lists the document attributes to include in the parition scheme Paths []string `json:"paths"` // Kind is the algorithm used for partitioning. // Note: Only PartititionKindHash is supported. Kind PartitionKind `json:"kind"` }
CollectionPartitionKey specifies the partition key indexing config
type CollectionResource ¶
type CollectionResource struct { // ID is the unique user generated name for the collection. ID string `json:"id"` // ResourceID is a unique identifier that is also hierarchical per the resource stack on the resource model. It is used internally for placement of and navigation to the collection resource. ResourceID string `json:"_rid,omitempty"` // Timestamp is a system generated property. It denotes the last updated timestamp of the resource. Timestamp int64 `json:"_ts,omitempty"` // Self is the unique addressable URI for the resource. Self string `json:"_self,omitempty"` // ETag value required for optimistic concurrency control. ETag string `json:"_etag,omitempty"` // Docs specifies the addressable path of the documents resource. Docs string `json:"_docs,omitempty"` // Sprocs specifies the addressable path of the stored procedures (sprocs) resource. Sprocs string `json:"_sprocs,omitempty"` // Triggers specifies the addressable path of the triggers resource. Triggers string `json:"_triggers,omitempty"` // UDFs specifies the addressable path of the user-defined functions (udfs) resource. UDFs string `json:"_udfs,omitempty"` // Conflicts specifies the addressable path of the conflicts resource. // During an operation on a resource within a collection, if a conflict occurs, users can inspect the conflicting resources by performing a GET on the conflicts URI path. // Conflicts string `json:"_conflicts,omitempty"` // IndexingPolicy settings for collection. IndexingPolicy *CollectionIndexingPolicy `json:"indexingPolicy,omitempty"` // PartitionKey is the partitioning configuration settings for collection. PartitionKey *CollectionPartitionKey `json:"partitionKey,omitempty"` }
CollectionResource represents a Collection container in Cosmos DB Documentation adapted from adapted from docs.microsoft.com See https://docs.microsoft.com/en-us/rest/api/cosmos-db/collections for the latest documentation
type CommonRequestOptions ¶
type CommonRequestOptions struct { ActivityID string ContentType string IfMatch string IfNoneMatch string IfModifiedSince time.Time SessionToken string ConsistencytLevel ConsistencyLevel DocumentDBPartitionKey string DocumentDBPartitionKeyRangeID string DocumentDBQueryEnableCrossPartition bool ChangeFeed bool MaxItemCount int Continuation string }
CommonRequestOptions is a helper which adds additional options to their appropriate headers in the CosmosDB HTTP request The specific options which are permitted varies depending on the request See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/common-cosmosdb-rest-request-headers
func (*CommonRequestOptions) ApplyOptions ¶
func (o *CommonRequestOptions) ApplyOptions(req *http.Request)
ApplyOptions sets the common headers defined in the CommonRequestOptions struct on the given http request object
type ConnectionString ¶
ConnectionString is the connection string for accessing a storage account
func ParseConnectionString ¶
func ParseConnectionString(connectionString string) (ConnectionString, error)
ParseConnectionString parses a connection string to the storage account The format of the connection string is as follows:
AccountEndpoint=https://accountname.documents.azure.com:443/;AccountKey=BASE64KEY;
type ConsistencyLevel ¶
type ConsistencyLevel string
ConsistencyLevel specifies the consistency level of the operation See https://docs.microsoft.com/azure/cosmos-db/consistency-levels for more information
type CreateCollectionRequest ¶
type CreateCollectionRequest struct { OfferThroughput int `json:"-"` OfferType OfferType `json:"-"` Options RequestOptions `json:"-"` ID string `json:"id"` IndexingPolicy *CollectionIndexingPolicy `json:"indexingPolicy,omitempty"` PartitionKey *CollectionPartitionKey `json:"partitionKey,omitempty"` }
CreateCollectionRequest captures the request options for creating a new Collection
func (CreateCollectionRequest) ApplyOptions ¶
func (c CreateCollectionRequest) ApplyOptions(req *http.Request)
ApplyOptions applies additional headers necessary to complete a CreateCollection request
type CreateDocumentRequest ¶
type CreateDocumentRequest struct { // Partition Key for partitioned collections PartitionKey []string // Upsert indicates if the request should replace the existing document Upsert bool // IndexingDirective determines if the document will be indexed IndexingDirective *DocumentIndexingDirective // Document is the replacement document. This will be marshalled into JSON // Either this or Document must be non-nil. Document interface{} // Body is the document body as JSON bytes. Either this or Document must be non-nil. Body []byte // Options are any additional request options to add to the request Options RequestOptions // Unmarshaler is an optional Unmarshaler that will be called with the response body Unmarshaler json.Unmarshaler }
CreateDocumentRequest are parameters for CreateDocument
func (CreateDocumentRequest) ApplyOptions ¶
func (r CreateDocumentRequest) ApplyOptions(req *http.Request)
ApplyOptions applies the request options to the api request
type CreateStoredProcedureRequest ¶ added in v0.0.2
type CreateStoredProcedureRequest struct { ID string `json:"id"` Body string `json:"body"` Options RequestOptions `json:"-"` }
CreateStoredProcedureRequest are parameters for CreateStoredProcedure
func (CreateStoredProcedureRequest) ApplyOptions ¶ added in v0.0.2
func (r CreateStoredProcedureRequest) ApplyOptions(req *http.Request)
ApplyOptions applies the request options to the api request
type CreateUserDefinedFunctionRequest ¶
type CreateUserDefinedFunctionRequest struct { ID string `json:"id"` Body string `json:"body"` Options RequestOptions `json:"-"` }
CreateUserDefinedFunctionRequest are parameters for CreateUserDefinedFunction
func (CreateUserDefinedFunctionRequest) ApplyOptions ¶
func (r CreateUserDefinedFunctionRequest) ApplyOptions(req *http.Request)
ApplyOptions applies the request options to the api request
type DatabaseClient ¶
DatabaseClient is a client scoped to a single database Used to perform API calls within the scope of the Database resource
func (*DatabaseClient) CreateCollection ¶
func (c *DatabaseClient) CreateCollection(ctx context.Context, req CreateCollectionRequest) (*CollectionResource, *ResponseMetadata, error)
CreateCollection creates a new collection
func (*DatabaseClient) CreateCollectionRaw ¶
func (c *DatabaseClient) CreateCollectionRaw(ctx context.Context, req CreateCollectionRequest) ([]byte, *ResponseMetadata, error)
CreateCollectionRaw creates a new collection and returns the raw response
func (*DatabaseClient) Delete ¶
func (c *DatabaseClient) Delete(ctx context.Context, opts RequestOptions) (bool, *ResponseMetadata, error)
Delete will delete the database See Client.DeleteResource for more information
func (*DatabaseClient) Get ¶
func (c *DatabaseClient) Get(ctx context.Context, opts RequestOptions) (*DatabaseResource, *ResponseMetadata, error)
Get retrieves the DatabaseResource
func (*DatabaseClient) GetRaw ¶
func (c *DatabaseClient) GetRaw(ctx context.Context, opts RequestOptions) ([]byte, *ResponseMetadata, error)
GetRaw retrieves the raw database resource
func (*DatabaseClient) ListCollections ¶
func (c *DatabaseClient) ListCollections(ctx context.Context, opts RequestOptions, fn PaginateCollectionResource) error
ListCollections lists each collection in the database
func (*DatabaseClient) ListCollectionsRaw ¶
func (c *DatabaseClient) ListCollectionsRaw(ctx context.Context, opts RequestOptions, fn PaginateRawResources) error
ListCollectionsRaw lists each collection in the database as raw JSON objects
func (*DatabaseClient) ResourceLink ¶
func (c *DatabaseClient) ResourceLink() string
ResourceLink gets the resource link for the database
func (*DatabaseClient) WithCollection ¶
func (c *DatabaseClient) WithCollection(id string) *CollectionClient
WithCollection creates a CollectionClient for the given Collection within this Database
type DatabaseResource ¶
type DatabaseResource struct { // ID is the unique user generated name for the database. ID string `json:"id"` // ResourceID is a unique identifier that is also hierarchical per the resource stack on the resource model. It is used internally for placement of and navigation to the database resource. ResourceID string `json:"_rid,omitempty"` // Timestamp is a system generated property. It denotes the last updated timestamp of the resource. Timestamp int64 `json:"_ts,omitempty"` // Self is the unique addressable URI for the resource. Self string `json:"_self,omitempty"` // ETag value required for optimistic concurrency control. ETag string `json:"_etag,omitempty"` // Colls specifies the addressable path of the collections resource. Colls string `json:"_colls,omitempty"` // Users specifies the addressable path of the users resource. Users string `json:"_users,omitempty"` }
DatabaseResource represents a Database in Cosmos DB Documentation adapted from adapted from docs.microsoft.com See https://docs.microsoft.com/en-us/rest/api/cosmos-db/databases for the latest documentation
type DocumentClient ¶
type DocumentClient struct { Client *Client DatabaseID string CollectionID string DocumentID string PartitionKey []string }
DocumentClient is a client scoped to a single document Used to perform API calls within the scope of a single Document resource
func (*DocumentClient) Delete ¶
func (c *DocumentClient) Delete(ctx context.Context, opts RequestOptions) (bool, *ResponseMetadata, error)
Delete removes the document from the collection
func (*DocumentClient) Get ¶
func (c *DocumentClient) Get(ctx context.Context, opts RequestOptions, v interface{}) (*ResponseMetadata, error)
Get retrieves the raw document and unmarshalls the content into the given value
func (*DocumentClient) GetRaw ¶
func (c *DocumentClient) GetRaw(ctx context.Context, opts RequestOptions) ([]byte, *ResponseMetadata, error)
GetRaw retrieves the raw document
func (*DocumentClient) ReplaceDocument ¶
func (c *DocumentClient) ReplaceDocument(ctx context.Context, req ReplaceDocumentRequest) ([]byte, *ResponseMetadata, error)
ReplaceDocument replaces this document
func (*DocumentClient) ResourceLink ¶
func (c *DocumentClient) ResourceLink() string
ResourceLink gets the resource link for the document
type DocumentIndexingDirective ¶
type DocumentIndexingDirective string
DocumentIndexingDirective determines if a document create/update should be indexed
type DocumentProperties ¶
type DocumentProperties struct { ID string `json:"id"` ETag string `json:"_etag"` ResourceID string `json:"_rid"` Timestamp int64 `json:"_ts"` Self string `json:"_self"` Attachments string `json:"_attachments"` }
DocumentProperties are the well-known properties that may exist on a Document resources
type Error ¶
type Error string
Error is an interstellar generated error This type is an alias for 'string' and is used to ensure the interstellar sential errors can be made constant
type IndexingMode ¶
type IndexingMode string
IndexingMode specifies how indexing will be performed on each insertion, replacement, or deletion action. You can choose between synchronous (Consistent), asynchronous (Lazy) index updates, and no indexing (None).
type MasterKey ¶
type MasterKey []byte
MasterKey is the shared key for the storage account
func ParseMasterKey ¶
ParseMasterKey parses a base-64 encoded shared access key
func (MasterKey) Authorize ¶
func (k MasterKey) Authorize(r *http.Request, resourceType ResourceType, resourceLink string) (*http.Request, error)
Authorize implements the authorization header for Microsoft Azure Storage services See https://docs.microsoft.com/en-us/rest/api/cosmos-db/access-control-on-cosmosdb-resources#constructkeytoken for implementation details. This implementation assumes the latest version of the API is 2017-04-17
type OfferClient ¶
OfferClient is a client scoped to a single offer Used to perform API calls within the scope of the Offer resource
func (*OfferClient) Get ¶
func (c *OfferClient) Get(ctx context.Context, opts RequestOptions) (*OfferResource, *ResponseMetadata, error)
Get retrieves the OfferResource
func (*OfferClient) GetRaw ¶
func (c *OfferClient) GetRaw(ctx context.Context, opts RequestOptions) ([]byte, *ResponseMetadata, error)
GetRaw retrieves the raw offer JSON
type OfferContent ¶
type OfferContent struct { // V2 is the OfferContentV2 version of the schema for user-defined performance parameters V2 *OfferContentV2 }
OfferContent encapsulates the different offer schemas depending on OfferVersion
type OfferContentV2 ¶
type OfferContentV2 struct { OfferThroughput int `json:"offerThroughput"` // RUPMEnabled is Request Units(RU)/Minute throughput is enabled/disabled for collection in the Azure Cosmos DB service. RUPMEnabled *bool `json:"offerIsRUPerMinuteThroughputEnabled,omitempty"` }
OfferContentV2 is the content of the OfferVersion "V2" for user-defined throughput
type OfferResource ¶
type OfferResource struct { ID string ResourceID string Timestamp time.Time Self string ETag string OfferVersion OfferVersion OfferType OfferType Content *OfferContent Resource string OfferResourceID string }
OfferResource represents a performance-level offering on a resource
func (*OfferResource) MarshalJSON ¶
func (oc *OfferResource) MarshalJSON() ([]byte, error)
MarshalJSON implementes json.Marshaler for OfferResource
func (*OfferResource) UnmarshalJSON ¶
func (oc *OfferResource) UnmarshalJSON(data []byte) error
UnmarshalJSON implementes json.Unmarshaler for OfferResource
type OfferType ¶
type OfferType string
OfferType is used to specify the pre-defined performance levels for the CosmosDB container
type OfferVersion ¶
type OfferVersion string
OfferVersion differentiates different offer schemas
const ( // OfferV1 uses a set list of OfferTypes OfferV1 OfferVersion = "V1" // OfferV2 allows tunable request unit throughput OfferV2 OfferVersion = "V2" )
type PaginateCollectionResource ¶
type PaginateCollectionResource func(resList []CollectionResource, meta ResponseMetadata) (bool, error)
PaginateCollectionResource pagination function for a list of CollectionResource
type PaginateDatabaseResource ¶
type PaginateDatabaseResource func(resList []DatabaseResource, meta ResponseMetadata) (bool, error)
PaginateDatabaseResource pagination function for a list of DatabaseResources
type PaginateOfferResource ¶
type PaginateOfferResource func(resList []OfferResource, meta ResponseMetadata) (bool, error)
PaginateOfferResource pagination function for a list of OfferResource
type PaginateRawResources ¶
type PaginateRawResources func(resList []json.RawMessage, meta ResponseMetadata) (bool, error)
PaginateRawResources is run by the List* operations with each page of results from the API. Returning `false` from the function will stop pagination and return a nil error. Returning a non-nil `error` from this function will stop pagination and return the error
type PaginateSProcResource ¶ added in v0.0.2
type PaginateSProcResource func(resList []StoredProcedureResource, meta ResponseMetadata) (bool, error)
PaginateSProcResource pagination function for a list of StoredProcedureResource
type PaginateUDFResource ¶
type PaginateUDFResource func(resList []UserDefinedFunctionResource, meta ResponseMetadata) (bool, error)
PaginateUDFResource pagination function for a list of UserDefiendFunctions
type PartitionKind ¶
type PartitionKind string
PartitionKind is the kind of index used for equality or range comparison
type Query ¶
type Query struct { // Query is the SQL-like query text. // See https://docs.microsoft.com/en-us/azure/cosmos-db/how-to-sql-query for the Grammar reference Query string `json:"query"` // Parameters are the collection of named query parameters and their values that may be referenced by the Query string. Parameters []QueryParameter `json:"parameters,omitempty"` // MaxItemCount sets the desired maximum number of items returned in a single page of results MaxItemCount int `json:"-"` // Continuation is used to get the next page of results from a query. // Setting this value, will set the corresponding x-ms-continuation header on the query request. // This value is opaque, and is returned when there are additional results aside from what was returned in the response. Continuation string `json:"-"` // EnableCrossPartition enables the query to span across multiple partitions. EnableCrossPartition bool `json:"-"` // ConsistencytLevel sets the consistency level override. // This must be the same or weaker than the account's configured consistency level. ConsistencytLevel ConsistencyLevel `json:"-"` // SessionToken must be set when using a consistency level of "Session". // The "SessionToken" recevied from a response must be echo'd back in the next request. SessionToken string `json:"-"` // RequestOptions applies additional request options to the query RequestOptions RequestOptions `json:"-"` }
Query encapsulates a SQL-like query on the Collection Parameters can be added by using the AddParameter method Additional query options can be addy by supplying a QueryOptions
func (*Query) AddParameter ¶
AddParameter adds a new named parameter to the query
func (*Query) AddParameterSensitive ¶
AddParameterSensitive adds a new named parameter to the query and sets the Sensitive flag
func (*Query) ApplyOptions ¶
ApplyOptions applies the additional query options to the API request
type QueryParameter ¶
type QueryParameter struct { // Name is the name of the query parameter. // All names should begin with an '@'; such as '@id' or '@name' Name string `json:"name"` // Value is the corresponding value of the named parameter. // The value should be JSON-marshalable, such as a primitive type or a type that implements the json.Marshaler behavior Value interface{} `json:"value"` // Sensitive is a flag that, if set to true, prevents the Value from being printed as part of the String() method // This value is not used by the Query API, and is only useful in debugging Sensitive bool `json:"-"` }
QueryParameter encapsulates a named query parameter for a query along with its value
func (QueryParameter) Format ¶
func (p QueryParameter) Format(f fmt.State, c rune)
Format implements fmt.Formatter for QueryParameter
func (QueryParameter) String ¶
func (p QueryParameter) String() string
String returns the query parameter as a string key=value
type ReplaceDocumentRequest ¶
type ReplaceDocumentRequest struct { // ETag is used for optimistic concurrency. If set, the ETag value of the existing document must match this in order for the operation to complete. ETag string // IndexingDirective determines if the document will be indexed IndexingDirective *DocumentIndexingDirective // Document is the replacement document. This will be marshalled into JSON // Either this or Document must be non-nil. Document interface{} // Body is the document body as JSON bytes. Either this or Document must be non-nil. Body []byte // Options are any additional request options to add to the request Options RequestOptions // Unmarshaler is an optional Unmarshaler that will be called with the response body Unmarshaler json.Unmarshaler }
ReplaceDocumentRequest are parameters for CreateDocument
func (ReplaceDocumentRequest) ApplyOptions ¶
func (r ReplaceDocumentRequest) ApplyOptions(req *http.Request)
ApplyOptions applies the request options to the api request
type ReplaceOfferRequest ¶
type ReplaceOfferRequest struct { Offer *OfferResource Options RequestOptions }
ReplaceOfferRequest encapsulates the offer to replace
func (ReplaceOfferRequest) ApplyOptions ¶
func (r ReplaceOfferRequest) ApplyOptions(req *http.Request)
ApplyOptions applies the request options to the api request
type RequestOptions ¶
RequestOptions augments the request, such as adding headers, or query parameter to an existing http.Request
type RequestOptionsFunc ¶
RequestOptionsFunc implements RequestOptions for a pure function Can be used to apply options with an anonymous function such as RequestOptionsFunc(func(req *http.Request) { ... })
func (RequestOptionsFunc) ApplyOptions ¶
func (fn RequestOptionsFunc) ApplyOptions(req *http.Request)
ApplyOptions implementation for RequestOptions interface
type RequestOptionsList ¶
type RequestOptionsList []RequestOptions
RequestOptionsList implements RequestOptions for a list/slice of RequestOptionsListRequestOptionsList
func (RequestOptionsList) ApplyOptions ¶
func (l RequestOptionsList) ApplyOptions(req *http.Request)
ApplyOptions implementation for RequestOptions interface
type Requester ¶
Requester is an interface for sending HTTP requests and receiving responses *http.Client implicitly implements this interface already But more complicated logic such as logging are possible here as well
type ResourceType ¶
type ResourceType string
ResourceType indicates the type of resource being requested. Used mostly in Authentication.
const ( // ResourceDatabases is the resource type of a Database ResourceDatabases ResourceType = "dbs" // ResourceCollections is the resource type of a Collection ResourceCollections ResourceType = "colls" // ResourceDocuments is the resource type of a Document ResourceDocuments ResourceType = "docs" // ResourceAttachments is the resource type of an Attachment ResourceAttachments ResourceType = "attachments" // ResourceStoredProcedures is the resource type of a Stored Procedure (sproc) ResourceStoredProcedures ResourceType = "sprocs" // ResourceUserDefinedFunctions is the resource type of a User-Defined Function (udf) ResourceUserDefinedFunctions ResourceType = "udfs" // ResourceTriggers is the resource type of a Trigger ResourceTriggers ResourceType = "triggers" // ResourceUsers is the resource type of a User ResourceUsers ResourceType = "users" // ResourcePermissions is the resource type of a Permission ResourcePermissions ResourceType = "permissions" // ResourceOffers is the resource type of an Offer ResourceOffers ResourceType = "offers" )
func (ResourceType) String ¶
func (rt ResourceType) String() string
type ResponseMetadata ¶
type ResponseMetadata struct { Date time.Time ETag string ActivityID string AltContentPath string Continuation string RequestCharge string ResourceQuota string RetryAfterMS time.Duration ItemCount int64 ResourceUsage string SchemaVersion string ServiceVersion string SessionToken string }
ResponseMetadata is the parsed header values from the response See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/common-cosmosdb-rest-response-headers
func GetResponseMetadata ¶
func GetResponseMetadata(resp *http.Response) (m ResponseMetadata)
GetResponseMetadata extracts response metadata from the http headers And parses them into native types where applicable (such as time or numbers)
type SProcClient ¶ added in v0.0.2
SProcClient is a client scoped to a single stored procedure Used to perform API calls within the scope of the Stored Procedure resource
func (*SProcClient) Delete ¶ added in v0.0.2
func (c *SProcClient) Delete(ctx context.Context, opts RequestOptions) (bool, *ResponseMetadata, error)
Delete deletes the stored procedure
func (*SProcClient) Execute ¶ added in v0.0.2
func (c *SProcClient) Execute(ctx context.Context, opts RequestOptions, args ...interface{}) ([]byte, *ResponseMetadata, error)
Execute the stored procedure and return the raw result body
func (*SProcClient) Func ¶ added in v0.0.2
func (c *SProcClient) Func(opts RequestOptions) func(context.Context, ...interface{}) ([]byte, *ResponseMetadata, error)
Func returns a function that can be called with with the stored procedures expected arguments, and returns the raw body The returned function takes a context object as its first parameter for cancellation/deadline The rest of the parameters are passed directly to the stored procedure (after being marshalled to JSON)
func (*SProcClient) Replace ¶ added in v0.0.2
func (c *SProcClient) Replace(ctx context.Context, body string, opts RequestOptions) (*StoredProcedureResource, *ResponseMetadata, error)
Replace replaces a Stored Procedure Body with the new one
func (*SProcClient) ResourceLink ¶ added in v0.0.2
func (c *SProcClient) ResourceLink() string
ResourceLink gets the resource link for the stored procedure
type StoredProcedureResource ¶ added in v0.0.2
type StoredProcedureResource struct { // ID is the unique user generated name for the Stored Procedure. The id must not exceed 255 characters. ID string `json:"id"` // ResourceID is a unique identifier that is also hierarchical per the resource stack on the resource model. It is used internally for placement of and navigation to the collection resource. ResourceID string `json:"_rid,omitempty"` // Timestamp is a system generated property. It denotes the last updated timestamp of the resource. Timestamp int64 `json:"_ts,omitempty"` // Self is the unique addressable URI for the resource. Self string `json:"_self,omitempty"` // ETag value required for optimistic concurrency control. ETag string `json:"_etag,omitempty"` // Body is the body of the Stored Procedure (javascript) Body string `json:"body"` }
StoredProcedureResource represents a Stored Procedure in Cosmos DB Documentation adapted from adapted from docs.microsoft.com See https://docs.microsoft.com/en-us/rest/api/cosmos-db/collections for the latest documentation
type UDFClient ¶
UDFClient is a client scoped to a single user-defined function Used to perform API calls within the scope of the UDF resource
func (*UDFClient) Delete ¶
func (c *UDFClient) Delete(ctx context.Context, opts RequestOptions) (bool, *ResponseMetadata, error)
Delete deletes the user-defined function
func (*UDFClient) Replace ¶
func (c *UDFClient) Replace(ctx context.Context, body string, opts RequestOptions) (*UserDefinedFunctionResource, *ResponseMetadata, error)
Replace replaces a UDF Body with the new one
func (*UDFClient) ReplaceRaw ¶
func (c *UDFClient) ReplaceRaw(ctx context.Context, body string, opts RequestOptions) ([]byte, *ResponseMetadata, error)
ReplaceRaw replaces a UDF Body with the new one
func (*UDFClient) ResourceLink ¶
ResourceLink gets the resource link for the user-defined function
type UserDefinedFunctionResource ¶
type UserDefinedFunctionResource struct { // ID is the unique user generated name for the UDF. The id must not exceed 255 characters. ID string `json:"id"` // ResourceID is a unique identifier that is also hierarchical per the resource stack on the resource model. It is used internally for placement of and navigation to the collection resource. ResourceID string `json:"_rid,omitempty"` // Timestamp is a system generated property. It denotes the last updated timestamp of the resource. Timestamp int64 `json:"_ts,omitempty"` // Self is the unique addressable URI for the resource. Self string `json:"_self,omitempty"` // ETag value required for optimistic concurrency control. ETag string `json:"_etag,omitempty"` // Body is the body of the User Defined Function (javascript) Body string `json:"body"` }
UserDefinedFunctionResource represents a User Defined Function in Cosmos DB Documentation adapted from adapted from docs.microsoft.com See https://docs.microsoft.com/en-us/rest/api/cosmos-db/collections for the latest documentation