cosmosapi

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: May 7, 2021 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	IndexingDirectiveInclude = IndexingDirective("include")
	IndexingDirectiveExclude = IndexingDirective("exclude")

	ConsistencyLevelStrong   = ConsistencyLevel("Strong")
	ConsistencyLevelBounded  = ConsistencyLevel("Bounded")
	ConsistencyLevelSession  = ConsistencyLevel("Session")
	ConsistencyLevelEventual = ConsistencyLevel("Eventual")
)
View Source
const (
	StringType     = DataType("String")
	NumberType     = DataType("Number")
	PointType      = DataType("Point")
	PolygonType    = DataType("Polygon")
	LineStringType = DataType("LineString")
)
View Source
const (
	Hash    = IndexKind("Hash")
	Range   = IndexKind("Range")
	Spatial = IndexKind("Spatial")
)
View Source
const (
	// Request headers
	HEADER_XDATE                  = "X-Ms-Date"
	HEADER_AUTH                   = "Authorization"
	HEADER_VER                    = "X-Ms-Version"
	HEADER_CONTYPE                = "Content-Type"
	HEADER_CONLEN                 = "Content-Length"
	HEADER_IS_QUERY               = "x-ms-documentdb-isquery"
	HEADER_UPSERT                 = "x-Ms-Documentdb-Is-Upsert"
	HEADER_IF_MATCH               = "If-Match"
	HEADER_IF_NONE_MATCH          = "If-None-Match"
	HEADER_CHARGE                 = "X-Ms-Request-Charge"
	HEADER_CONSISTENCY_LEVEL      = "x-ms-consistency-level"
	HEADER_OFFER_THROUGHPUT       = "x-ms-offer-throughput"
	HEADER_OFFER_TYPE             = "x-ms-offer-type"
	HEADER_MAX_ITEM_COUNT         = "x-ms-max-item-count"
	HEADER_A_IM                   = "A-IM"
	HEADER_PARTITION_KEY_RANGE_ID = "x-ms-documentdb-partitionkeyrangeid"
	HEADER_CROSSPARTITION         = "x-ms-documentdb-query-enablecrosspartition"
	HEADER_PARTITIONKEY           = "x-ms-documentdb-partitionkey"
	HEADER_INDEXINGDIRECTIVE      = "x-ms-indexing-directive"
	HEADER_TRIGGER_PRE_INCLUDE    = "x-ms-documentdb-pre-trigger-include"
	HEADER_TRIGGER_PRE_EXCLUDE    = "x-ms-documentdb-pre-trigger-exclude"
	HEADER_TRIGGER_POST_INCLUDE   = "x-ms-documentdb-post-trigger-include"
	HEADER_TRIGGER_POST_EXCLUDE   = "x-ms-documentdb-post-trigger-exclude"

	// Both request and response
	HEADER_SESSION_TOKEN = "x-ms-session-token"
	HEADER_CONTINUATION  = "x-ms-continuation"

	// Response headers
	HEADER_REQUEST_CHARGE = "x-ms-request-charge"
	HEADER_ETAG           = "etag"
)
View Source
const MaxPrecision = -1
View Source
const QUERY_CONTENT_TYPE = "application/query+json"
View Source
const (
	StatusRetryWith = 449
)

StatusRetryWith defines the 449 http error. Not present in go std lib

Variables

View Source
var (
	// TODO: useful?
	IgnoreContext bool
	// TODO: check thread safety
	ResponseHook func(ctx context.Context, method string, headers map[string][]string)
)
View Source
var (
	ErrorNotImplemented        = errors.New("not implemented")
	ErrWrongQueryContentType   = errors.New("Wrong content type. Must be " + QUERY_CONTENT_TYPE)
	ErrMaxRetriesExceeded      = errors.New("Max retries exceeded")
	ErrInvalidPartitionKeyType = errors.New("Partition key type must be a simple type (nil, string, int, float, etc.)")

	// Map http codes to cosmos errors messages
	// Description taken directly from https://docs.microsoft.com/en-us/rest/api/cosmos-db/http-status-codes-for-cosmosdb
	ErrInvalidRequest     = errors.New("The JSON, SQL, or JavaScript in the request body is invalid")
	ErrUnautorized        = errors.New("The Authorization header is invalid for the requested resource")
	ErrForbidden          = errors.New("The authorization token expired, resource quota has been reached or high resource usage")
	ErrNotFound           = errors.New("Resource that no longer exists")
	ErrTimeout            = errors.New("The operation did not complete within the allotted amount of time")
	ErrConflict           = errors.New("The ID provided has been taken by an existing resource")
	ErrPreconditionFailed = errors.New("The operation specified an eTag that is different from the version available at the server")
	ErrTooLarge           = errors.New("The document size in the request exceeded the allowable document size for a request")
	ErrTooManyRequests    = errors.New("The collection has exceeded the provisioned throughput limit")
	ErrRetryWith          = errors.New("The operation encountered a transient error. It is safe to retry the operation")
	ErrInternalError      = errors.New("The operation failed due to an unexpected service error")
	ErrUnavailable        = errors.New("The operation could not be completed because the service was unavailable")
	// Undocumented code. A known scenario where it is used is when doing a ListDocuments request with ReadFeed
	// properties on a partition that was split by a repartition.
	ErrGone = errors.New("Resource is gone")

	CosmosHTTPErrors = map[int]error{
		http.StatusOK:                    nil,
		http.StatusCreated:               nil,
		http.StatusNoContent:             nil,
		http.StatusNotModified:           nil,
		http.StatusBadRequest:            ErrInvalidRequest,
		http.StatusUnauthorized:          ErrUnautorized,
		http.StatusForbidden:             ErrForbidden,
		http.StatusNotFound:              ErrNotFound,
		http.StatusRequestTimeout:        ErrTimeout,
		http.StatusConflict:              ErrConflict,
		http.StatusGone:                  ErrGone,
		http.StatusPreconditionFailed:    ErrPreconditionFailed,
		http.StatusRequestEntityTooLarge: ErrTooLarge,
		http.StatusTooManyRequests:       ErrTooManyRequests,
		StatusRetryWith:                  ErrRetryWith,
		http.StatusInternalServerError:   ErrInternalError,
		http.StatusServiceUnavailable:    ErrUnavailable,
	}
)
View Source
var (
	ReqOpAllowCrossPartition = RequestOption("x-ms-documentdb-query-enablecrosspartition")
	ReqOpPartitionKey        = RequestOption(HEADER_PARTITIONKEY)
)
View Source
var (
	ErrThroughputRequiresPartitionKey = errors.New("Must specify PartitionKey when OfferThroughput is >= 10000")
)

Functions

func CreateCollLink(dbName, collName string) string
func CreateTriggerLink(dbName, collName, triggerName string) string

func EscapeJavaScript

func EscapeJavaScript(source []byte) string

func MarshalPartitionKeyHeader

func MarshalPartitionKeyHeader(partitionKeyValue interface{}) (string, error)

Types

type AuthorizationPayload

type AuthorizationPayload struct {
	Verb         string
	ResourceType string
	ResourceLink string
	Date         string
}

type Client

type Client struct {
	Url    string
	Config Config
	Client *http.Client
	Log    logging.ExtendedLogger
}

func New

func New(url string, cfg Config, cl *http.Client, log logging.StdLogger) *Client

New makes a new client to communicate to a cosmosdb instance. If no http.Client is provided it defaults to the http.DefaultClient The log argument can either be an StdLogger (log.Logger), an ExtendedLogger (like logrus.Logger) or nil (logging disabled)

func (*Client) CreateDocument

func (c *Client) CreateDocument(ctx context.Context, dbName, colName string,
	doc interface{}, ops CreateDocumentOptions) (*Resource, DocumentResponse, error)

func (*Client) CreateStoredProcedure

func (c *Client) CreateStoredProcedure(
	ctx context.Context, dbName, colName, sprocName, body string,
) (*StoredProcedure, error)

func (*Client) DeleteCollection

func (c *Client) DeleteCollection(ctx context.Context, dbName, colName string) error

func (*Client) DeleteDatabase

func (c *Client) DeleteDatabase(ctx context.Context, dbName string, ops *RequestOptions) error

func (*Client) DeleteDocument

func (c *Client) DeleteDocument(ctx context.Context, dbName, colName, id string, ops DeleteDocumentOptions) (DocumentResponse, error)

func (*Client) DeleteStoredProcedure

func (c *Client) DeleteStoredProcedure(ctx context.Context, dbName, colName, sprocName string) error

func (*Client) DeleteTrigger

func (c *Client) DeleteTrigger(ctx context.Context, dbName, colName string) error

func (*Client) ExecuteStoredProcedure

func (c *Client) ExecuteStoredProcedure(
	ctx context.Context, dbName, colName, sprocName string,
	ops ExecuteStoredProcedureOptions,
	ret interface{}, args ...interface{},
) error

func (*Client) GetCollection

func (c *Client) GetCollection(ctx context.Context, dbName, colName string) (*Collection, error)

func (*Client) GetDatabase

func (c *Client) GetDatabase(ctx context.Context, dbName string, ops *RequestOptions) (*Database, error)

func (*Client) GetDocument

func (c *Client) GetDocument(ctx context.Context, dbName, colName, id string,
	ops GetDocumentOptions, out interface{}) (DocumentResponse, error)

func (*Client) GetPartitionKeyRanges

func (c *Client) GetPartitionKeyRanges(
	ctx context.Context,
	databaseName, collectionName string,
	options *GetPartitionKeyRangesOptions,
) (response GetPartitionKeyRangesResponse, err error)

func (*Client) GetStoredProcedure

func (c *Client) GetStoredProcedure(ctx context.Context, dbName, colName, sprocName string) (*StoredProcedure, error)

func (*Client) ListDatabases

func (c *Client) ListDatabases(ctx context.Context, ops *RequestOptions) ([]Database, error)

func (*Client) ListDocuments

func (c *Client) ListDocuments(
	ctx context.Context,
	databaseName, collectionName string,
	options *ListDocumentsOptions,
	documentList interface{},
) (response ListDocumentsResponse, err error)

ListDocument reads either all documents or the incremental feed, aka. change feed.

func (*Client) ListStoredProcedures

func (c *Client) ListStoredProcedures(ctx context.Context, dbName, colName string) (*StoredProcedures, error)

func (*Client) NewPartitionKeyRangesPaginator

func (c *Client) NewPartitionKeyRangesPaginator(databaseName, collectionName string, options *GetPartitionKeyRangesOptions) *PartitionKeyRangesPaginator

NewPartitionKeyRangesPaginator returns a paginator for ListObjectsV2. Use the Next method to get the next page, and CurrentPage to get the current response page from the paginator. Next will return false if there are no more pages, or an error was encountered.

Note: This operation can generate multiple requests to a service.

// Example iterating over pages.
p := client.NewPartitionKeyRangesPaginator(input)

for p.Next() {
    err, page := p.CurrentPage(context.TODO())
    if err != nil {
      return err
    }
}

func (*Client) QueryDocuments

func (c *Client) QueryDocuments(ctx context.Context, dbName, collName string, qry Query, docs interface{}, ops QueryDocumentsOptions) (QueryDocumentsResponse, error)

QueryDocuments queries a collection in cosmosdb with the provided query. To correctly parse the returned results you currently have to pass in a slice for the returned documents, not a single document.

func (*Client) ReplaceDocument

func (c *Client) ReplaceDocument(ctx context.Context, dbName, colName, id string,
	doc interface{}, ops ReplaceDocumentOptions) (*Resource, DocumentResponse, error)

ReplaceDocument replaces a whole document.

func (*Client) ReplaceStoredProcedure

func (c *Client) ReplaceStoredProcedure(
	ctx context.Context, dbName, colName, sprocName, body string) (*StoredProcedure, error)

func (*Client) UpsertDocument

func (c *Client) UpsertDocument(ctx context.Context, link string,
	doc interface{}, ops *RequestOptions) error

type Collection

type Collection struct {
	Resource
	IndexingPolicy *IndexingPolicy `json:"indexingPolicy,omitempty"`
	Docs           string          `json:"_docs,omitempty"`
	Udf            string          `json:"_udfs,omitempty"`
	Sprocs         string          `json:"_sprocs,omitempty"`
	Triggers       string          `json:"_triggers,omitempty"`
	Conflicts      string          `json:"_conflicts,omitempty"`
	PartitionKey   *PartitionKey   `json:"partitionKey,omitempty"`
}

type CollectionReplaceOptions

type CollectionReplaceOptions struct {
	Resource
	Id                string          `json:"id"`
	IndexingPolicy    *IndexingPolicy `json:"indexingPolicy,omitempty"`
	PartitionKey      *PartitionKey   `json:"partitionKey,omitempty"`
	DefaultTimeToLive int             `json:"defaultTtl,omitempty"`
}

type CollectionTriggers

type CollectionTriggers struct {
	Rid      string    `json:"_rid,omitempty"`
	Count    int32     `json:"_count,omitempty"`
	Triggers []Trigger `json:"Triggers"`
}

type CompositeIndex

type CompositeIndex []struct {
	Path  string     `json:"path"`
	Order IndexOrder `json:"order,omitempty"`
}

type Config

type Config struct {
	MasterKey  string
	MaxRetries int
}

Config is required as input parameter for the constructor creating a new cosmosdb client.

type ConsistencyLevel

type ConsistencyLevel string

type CreateCollectionOptions

type CreateCollectionOptions struct {
	Id             string          `json:"id"`
	IndexingPolicy *IndexingPolicy `json:"indexingPolicy,omitempty"`
	PartitionKey   *PartitionKey   `json:"partitionKey,omitempty"`

	// RTUs [400 - 250000]. Do not use in combination with OfferType
	OfferThroughput OfferThroughput `json:"offerThroughput,omitempty"`
	// S1,S2,S3. Do not use in combination with OfferThroughput
	OfferType         OfferType `json:"offerType,omitempty"`
	DefaultTimeToLive int       `json:"defaultTtl,omitempty"`
}

type CreateCollectionResponse

type CreateCollectionResponse struct {
	ResponseBase
	Collection Collection
}

type CreateDatabaseOptions

type CreateDatabaseOptions struct {
	ID string `json:"id"`
}

type CreateDocumentOptions

type CreateDocumentOptions struct {
	PartitionKeyValue   interface{}
	IsUpsert            bool
	IndexingDirective   IndexingDirective
	PreTriggersInclude  []string
	PostTriggersInclude []string
}

func (CreateDocumentOptions) AsHeaders

func (ops CreateDocumentOptions) AsHeaders() (map[string]string, error)

type DataType

type DataType string

type Database

type Database struct {
	Resource
	Colls string `json:"_colls,omitempty"`
	Users string `json:"_users,omitempty"`
}

Database

type DeleteDocumentOptions

type DeleteDocumentOptions struct {
	PartitionKeyValue   interface{}
	PreTriggersInclude  []string
	PostTriggersInclude []string
}

DeleteDocumentOptions contains all options that can be used for deleting documents.

func (DeleteDocumentOptions) AsHeaders

func (ops DeleteDocumentOptions) AsHeaders() (map[string]string, error)

type Document

type Document struct {
	Resource
	Attachments string `json:"attachments,omitempty"`
}

Document

type DocumentCollection

type DocumentCollection struct {
	Rid                 string       `json:"_rid,omitempty"`
	Count               int32        `json:"_count,omitempty"`
	DocumentCollections []Collection `json:"DocumentCollections"`
}

type DocumentResponse

type DocumentResponse struct {
	RUs          float64
	SessionToken string
	StatusCode   int //HTTP status code of response, saves searching error messages for 404s, etc.
}

type ExcludedPath

type ExcludedPath struct {
	Path string `json:"path"`
}

type ExecuteStoredProcedureOptions

type ExecuteStoredProcedureOptions struct {
	PartitionKeyValue interface{}
}

func (ExecuteStoredProcedureOptions) AsHeaders

func (ops ExecuteStoredProcedureOptions) AsHeaders() (map[string]string, error)

type GetDocumentOptions

type GetDocumentOptions struct {
	IfNoneMatch       string
	PartitionKeyValue interface{}
	ConsistencyLevel  ConsistencyLevel
	SessionToken      string
}

func (GetDocumentOptions) AsHeaders

func (ops GetDocumentOptions) AsHeaders() (map[string]string, error)

type GetPartitionKeyRangesOptions

type GetPartitionKeyRangesOptions struct {
	MaxItemCount int
	Continuation string
}

func (GetPartitionKeyRangesOptions) AsHeaders

func (ops GetPartitionKeyRangesOptions) AsHeaders() (map[string]string, error)

type GetPartitionKeyRangesResponse

type GetPartitionKeyRangesResponse struct {
	Id                 string
	Rid                string
	PartitionKeyRanges []PartitionKeyRange
	RequestCharge      float64
	SessionToken       string
	Continuation       string
	Etag               string
}

type IncludedPath

type IncludedPath struct {
	Path    string  `json:"path"`
	Indexes []Index `json:"indexes,omitempty"`
}

type Index

type Index struct {
	DataType  DataType  `json:"dataType,omitempty"`
	Kind      IndexKind `json:"kind,omitempty"`
	Precision int       `json:"precision,omitempty"`
}

type IndexKind

type IndexKind string

type IndexOrder

type IndexOrder string
const (
	Ascending  IndexOrder = "ascending"
	Descending IndexOrder = "descending"
)

type IndexingDirective

type IndexingDirective string

type IndexingMode

type IndexingMode string

type IndexingPolicy

type IndexingPolicy struct {
	IndexingMode IndexingMode     `json:"indexingMode,omitempty"`
	Automatic    bool             `json:"automatic"`
	Included     []IncludedPath   `json:"includedPaths,omitempty"`
	Excluded     []ExcludedPath   `json:"excludedPaths,omitempty"`
	Composite    []CompositeIndex `json:"compositeIndexes,omitempty"`
}

type ListCollectionsOptions

type ListCollectionsOptions struct {
	MaxItemCount int
	Continuation string
}

type ListCollectionsResponse

type ListCollectionsResponse struct {
	RequestCharge float64
	SessionToken  string
	Continuation  string
	Etag          string
	Collections   DocumentCollection
}

type ListDocumentsOptions

type ListDocumentsOptions struct {
	MaxItemCount        int
	AIM                 string
	Continuation        string
	IfNoneMatch         string
	PartitionKeyRangeId string
}

func (ListDocumentsOptions) AsHeaders

func (ops ListDocumentsOptions) AsHeaders() (map[string]string, error)

type ListDocumentsResponse

type ListDocumentsResponse struct {
	ResponseBase
	SessionToken string
	Continuation string
	Etag         string
}

type Offer

type Offer struct {
	Resource
	OfferVersion    string                 `json:"offerVersion"`
	OfferType       OfferType              `json:"offerType"`
	Content         OfferThroughputContent `json:"content,omitempty"`
	OfferResourceId string                 `json:"offerResourceId"`
}

type OfferReplaceOptions

type OfferReplaceOptions struct {
	OfferVersion     string                 `json:"offerVersion"`
	OfferType        OfferType              `json:"offerType"`
	Content          OfferThroughputContent `json:"content,omitempty"`
	ResourceSelfLink string                 `json:"resource"`
	OfferResourceId  string                 `json:"offerResourceId"`
	Id               string                 `json:"id"`
	Rid              string                 `json:"_rid"`
}

https://docs.microsoft.com/en-us/rest/api/cosmos-db/replace-an-offer

type OfferThroughput

type OfferThroughput int32

type OfferThroughputContent

type OfferThroughputContent struct {
	Throughput OfferThroughput `json:"offerThroughput"`
}

type OfferType

type OfferType string

type Offers

type Offers struct {
	Rid    string  `json:"_rid,omitempty"`
	Count  int32   `json:"_count,omitempty"`
	Offers []Offer `json:"Offers"`
}

type PartitionKey

type PartitionKey struct {
	Paths []string `json:"paths"`
	Kind  string   `json:"kind"`
}

type PartitionKeyRange

type PartitionKeyRange struct {
	Id           string   `json:"id"`
	MaxExclusive string   `json:"maxExclusive"`
	MinInclusive string   `json:"minInclusive"`
	Parents      []string `json:"parents"`
}

type PartitionKeyRangesPaginator

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

PartitionKeyRangesPaginator is a paginator over the "Get Partition key ranges" API endpoint. This paginator is not threadsafe.

func (*PartitionKeyRangesPaginator) CurrentPage

CurrentPage returns the current page of partition key ranges. Panics if Next() has not yet been called.

func (*PartitionKeyRangesPaginator) Next

Next returns true if there are more pages to be read, and false if the previous CurrentPage call returned an error, or if there are no more pages to be read.

type Query

type Query struct {
	Query  string       `json:"query"`
	Params []QueryParam `json:"parameters,omitempty"`
	Token  string       `json:"-"` // continuation token
}

type QueryDocumentsOptions

type QueryDocumentsOptions struct {
	PartitionKeyValue    interface{}
	IsQuery              bool
	ContentType          string
	MaxItemCount         int
	Continuation         string
	EnableCrossPartition bool
	ConsistencyLevel     ConsistencyLevel
	SessionToken         string
}

QueryDocumentsOptions bundles all options supported by Cosmos DB when querying for documents.

func DefaultQueryDocumentOptions

func DefaultQueryDocumentOptions() QueryDocumentsOptions

DefaultQueryDocumentOptions returns QueryDocumentsOptions populated with sane defaults. For QueryDocumentsOptions Cosmos DB requires some specific options which are not obvious. This function helps to get things right.

type QueryDocumentsResponse

type QueryDocumentsResponse struct {
	ResponseBase
	Documents    interface{}
	Count        int `json:"_count"`
	Continuation string
}

TODO: add missing fields

type QueryParam

type QueryParam struct {
	Name  string      `json:"name"` // should contain a @ character
	Value interface{} `json:"value"`
}

type ReplaceDocumentOptions

type ReplaceDocumentOptions struct {
	PartitionKeyValue   interface{}
	IndexingDirective   IndexingDirective
	PreTriggersInclude  []string
	PostTriggersInclude []string
	IfMatch             string
	ConsistencyLevel    ConsistencyLevel
	SessionToken        string
}

func (ReplaceDocumentOptions) AsHeaders

func (ops ReplaceDocumentOptions) AsHeaders() (map[string]string, error)

type RequestError

type RequestError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

Request Error

func (RequestError) Error

func (e RequestError) Error() string

Implement Error function

type RequestOption

type RequestOption string

type RequestOptions

type RequestOptions map[RequestOption]string

type Resource

type Resource struct {
	Id   string `json:"id,omitempty"`
	Self string `json:"_self,omitempty"`
	Etag string `json:"_etag,omitempty"`
	Rid  string `json:"_rid,omitempty"`
	Ts   int    `json:"_ts,omitempty"`
}

type ResponseBase

type ResponseBase struct {
	RequestCharge float64
}

type Sproc

type Sproc struct {
	Resource
	Body string `json:"body,omitempty"`
}

Stored Procedure

type StoredProcedure

type StoredProcedure struct {
	Resource
	Body string `json:"body"`
}

type StoredProcedures

type StoredProcedures struct {
	Resource
	StoredProcedures []StoredProcedure `json:"StoredProcedures"`
	Count            int               `json:"_count,omitempty"`
}

type Trigger

type Trigger struct {
	Resource
	Id        string           `json:"id"`
	Body      string           `json:"body"`
	Operation TriggerOperation `json:"triggerOperation"`
	Type      TriggerType      `json:"triggerType"`
}

type TriggerCreateOptions

type TriggerCreateOptions struct {
	Id        string           `json:"id"`
	Body      string           `json:"body"`
	Operation TriggerOperation `json:"triggerOperation"`
	Type      TriggerType      `json:"triggerType"`
}

https://docs.microsoft.com/en-us/rest/api/cosmos-db/create-a-trigger

type TriggerOperation

type TriggerOperation string

type TriggerReplaceOptions

type TriggerReplaceOptions struct {
	Id        string           `json:"id"`
	Body      string           `json:"body"`
	Operation TriggerOperation `json:"triggerOperation"`
	Type      TriggerType      `json:"triggerType"`
}

https://docs.microsoft.com/en-us/rest/api/cosmos-db/replace-a-trigger

type TriggerType

type TriggerType string

type UDF

type UDF struct {
	Resource
	Body string `json:"body,omitempty"`
}

User Defined Function

type UpsertDocumentOptions

type UpsertDocumentOptions struct {
	PreTriggersInclude  []string
	PostTriggersInclude []string
}

Jump to

Keyboard shortcuts

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