gocosmosdb

package module
v0.0.0-...-47ffcf1 Latest Latest
Warning

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

Go to latest
Published: Sep 7, 2019 License: MIT Imports: 22 Imported by: 0

README

gocosmosdb - Go client for Azure CosmosDB SQL API

GoDoc Build Status Coverage Status Go Report Card

Key Features
  • Client Connection Pooling
  • Retry With Backoff
  • TTL for documents
  • Advanced Debugging
Get Started
Installation
$ go get github.com/intwinelabs/gocosomsdb
Example
package main

import (
	"context"
	"io/ioutil"
	"time"

	"github.com/intwinelabs/gocosmosdb"
	"github.com/intwinelabs/logger"
)

func main() {
	log := logger.Init("CosmosGoApp", false, true, ioutil.Discard)
	client := gocosmosdb.New("connection-url", gocosmosdb.Config{MasterKey: "master-key"}, log)

	// create a database
	db, err := client.CreateDatabase(`{ "id": "intwineLabs" }`)
	if err != nil {
		log.Fatal(err)
	}

	// create a collection
	coll, err := client.CreateCollection(db.Self, `{"id": "users"}`)
	if err != nil {
		log.Fatal(err)
	}

	// user struct
	type User struct {
		gocosmosdb.Document
		// To set documents TTL
		gocosmosdb.Expirable
		// Your external fields
		Name  string `json:"name,omitempty"`
		Email string `json:"email,omitempty"`
	}

	// user to store
	var user User
	// Note: If the `Id` is missing(or empty) in the payload it will generate
	// random document id(i.e: uuid4)
	user.Id = "uuid"
	user.Name = "Bad MF"
	user.Email = "badmf@intwine.io"
	// This tells CosmosDB to expire the doc in 24 hours
	user.SetTTL(24 * time.Hour)

	// create the document
	_, err = client.CreateDocument(coll.Self, &user)
	if err != nil {
		log.Fatal(err)
	}

	// query to documents
	var users []User
	_, err = client.QueryDocuments(coll.Self, "SELECT * FROM ROOT r", &users)
	if err != nil {
		log.Fatal(err)
	}
	for _, user := range users {
		log.Infof("Name:%s, Email: %s", user.Name, user.Email)
	}

	// run stored procedure with context timeout
	ctx, _ := context.WithTimeout(context.Background(), 250*time.Millisecond)
	docs := []User{}
	_, err = client.ExecuteStoredProcedure(coll.Self+"sprocs/Sl8fALN4sw4CAAAAAAAAgA==", []string{"param1"}, &docs, gocosmosdb.WithContext(ctx))
	if err != nil {
		log.Fatal(err)
	}
}
Azure Cosmos DB SQL REST API Reference
Contributing
  • Reporting Issues - When reporting issues on GitHub please include your host OS (Ubuntu 16.04, Fedora 19, etc) sudo lsb_release -a, the output of uname -a, go version. Please include the steps required to reproduce the problem. This info will help us review and fix your issue faster.
  • We welcome your pull requests - We are always thrilled to receive pull requests, and do our best to process them as fast as possible.
    • Not sure if that typo is worth a pull request? Do it! We will appreciate it.
    • If your pull request is not accepted on the first try, don't be discouraged! We will do our best to give you feedback on what to improve.
    • We're trying very hard to keep gocosmosdb lean and focused. We don't want it to do everything for everybody. This means that we might decide against incorporating a new feature. However, we encourage you to fork our repo and implement it on top of gocosmosdb.
    • Any changes or improvements should be documented as a GitHub issue before we add it to the project and anybody starts working on it.
  • Please check for existing issues first - If it does add a quick "+1". This will help prioritize the most common problems and requests.
Credits

This library is derived from:

License

Copyright (c) 2018 Intwine Labs, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Documentation

Index

Constants

View Source
const (
	// HeaderActivityID - A client supplied identifier for the operation, which is echoed in the server response.
	// The recommended value is a unique identifier.
	HeaderActivityID = "X-Ms-Activity-Id"

	// HeaderAIM - Indicates a change feed request. Must be set to "Incremental feed", or omitted otherwise.
	HeaderAIM = "A-IM"

	//HeaderAllowTenativeWrites - For using multiple write locations.
	HeaderAllowTenativeWrites = "X-Ms-Cosmos-Allow-Tentative-Writes"

	// HeaderAuth - The authorization token for the request
	HeaderAuth = "Authorization"

	// HeaderConsistencyLevel - The consistency level override for read options against documents and attachments.
	// The valid values are: Strong, Bounded, Session, or Eventual
	HeaderConsistencyLevel = "X-Ms-Consistency-Level"

	// HeaderContentLength - Indicates the size of the entity-body, in bytes, sent to the recipient.
	HeaderContentLength = "Content-Length"

	// HeaderContentType - POST it must be application/query+json
	// attachments must be set to the Mime type of the attachment
	// all other tasks must be application/json
	HeaderContentType = "Content-Type"

	// HeaderContinuation - A string token returned for queries and read-feed operations if there are more
	// results to be read. Clients can retrieve the next page of results by resubmitting the request with this value.
	HeaderContinuation = "X-Ms-Continuation"

	// HeaderCrossPartition - When this header is set to true and if your query doesn't have a partition key, Azure
	// Cosmos DB fans out the query across partitions. The fan out is done by issuing individual queries to all the
	// partitions. To read the query results, the client applications should consume the results from the FeedResponse
	// and check for the ContinuationToken property. To read all the results, keep iterating on the data until the
	// ContinuationToken is null.
	HeaderCrossPartition = "X-Ms-Documentdb-Query-Enablecrosspartition"

	// HeaderEnableScan - Use an index scan to process the query if the right index path of type is not available.
	HeaderEnableScan = "X-Ms-Documentdb-Query-Enable-Scan"

	// HeaderIfMatch - Used to make operation conditional for optimistic concurrency.
	// The value should be the etag value of the resource.
	HeaderIfMatch = "If-Match"

	// HeaderIfModifiedSince - Returns etag of resource modified after specified date in RFC 1123 format.
	// Ignored when If-None-Match is specified
	HeaderIfModifiedSince = "If-Modified-Since"

	// HeaderIfNonMatch - Makes operation conditional to only execute if the resource has changed.
	// The value should be the etag of the resource.
	HeaderIfNonMatch = "If-None-Match"

	// HeaderIndexingDirective - Overide the collections default indexing policy, set to Include or Exclude.
	HeaderIndexingDirective = "x-ms-indexing-directive"

	// HeaderIsQuery - Required for queries. This property must be set to true.
	HeaderIsQuery = "X-Ms-Documentdb-Isquery"

	// HeaderIsQueryPlan -
	HeaderIsQueryPlan = "X-Ms-Cosmos-Is-Query-Plan-Request"

	// HeaderMaxItemCount - An integer indicating the maximum number of items to be returned per page.
	// An x-ms-max-item-count of -1 can be specified to let the service determine the optimal item count.
	HeaderMaxItemCount = "X-Ms-Max-Item-Count"

	// HeaderOfferThroughput - The user specified throughput for the collection expressed in units of 100
	// request units per second.
	HeaderOfferThroughput = "X-Ms-Offer-Throughput"

	// HeaderParalelizeCrossPartition - Sets the query to run in parallel across partitions.
	HeaderParalelizeCrossPartition = "X-Ms-Documentdb-Query-Parallelizecrosspartitionquery"

	// HeaderPartitionKey - The partition key value for the requested document or attachment operation.
	// Required for operations against documents and attachments when the collection definition includes
	// a partition key definition. This value is used to scope your query to documents that match the partition
	// key criteria. By design it's a single partition query. Supported in API versions 2015-12-16 and newer.
	// Currently, the SQL API supports a single partition key, so this is an array containing just one value.
	HeaderPartitionKey = "X-Ms-Documentdb-Partitionkey"

	// HeaderPartitionKeyRangeID - Used in change feed requests. The partition key range ID for reading data.
	HeaderPartitionKeyRangeID = "X-Ms-Documentdb-Partitionkeyrangeid"

	// HeaderPopulateQueryMetrics - Set to obtain detailed metrics on query execution.
	HeaderPopulateQueryMetrics = "X-Ms-Documentdb-Populatequerymetrics"

	// HeaderQueryMetrics - The query statistics for the execution. This is a delimited string containing statistics
	// of time spent in the various phases of query execution.
	HeaderQueryMetrics = "X-Ms-Documentdb-Query-Metrics"

	// HeaderQueryVersion - Set the query version.
	HeaderQueryVersion = "X-Ms-Cosmos-Query-Version"

	// HeaderRequestCharge - The number of request units consumed by the operation.
	HeaderRequestCharge = "X-Ms-Request-Charge"

	// HeaderSessionToken - A string token used with session level consistency.
	HeaderSessionToken = "X-Ms-Session-Token"

	// HeaderSupportedQueryFeatures -
	HeaderSupportedQueryFeatures = "X-Ms-Cosmos-Supported-Query-Features"

	// HeaderUpsert - If set to true, Cosmos DB creates the document with the ID (and partition key value if applicable)
	// if it doesn’t exist, or update the document if it exists.
	HeaderUpsert = "X-Ms-Documentdb-Is-Upsert"

	// HeaderUserAgent - A string that specifies the client user agent performing the request.
	// The recommended format is {user agent name}/{version}.
	HeaderUserAgent = "User-Agent"

	// HeaderVersion - The version of the Cosmos DB REST service.
	HeaderVersion = "X-Ms-Version"

	// HeaderXDate - The date of the request per RFC 1123 date format expressed in Coordinated Universal Time.
	// For example, Fri, 08 Apr 2015 03:52:31 GMT.
	HeaderXDate = "X-Ms-Date"
)
View Source
const (
	// SupportedQueryVersion - The current query version supported.
	SupportedQueryVersion = "1.4"

	// SupportedVersion - The current supported API version.
	SupportedAPIVersion            = "2018-12-31"
	SupportedAPIVersionNoPartition = "2017-02-22"

	// UserAgent - The current version of gocosmosdb.
	UserAgent = "gocosmosdb/1.0"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type CallOption

type CallOption func(r *Request) error

CallOption function

func ChangeFeed

func ChangeFeed() CallOption

ChangeFeed - indicates a change feed request

func ConsistencyLevel

func ConsistencyLevel(consistency Consistency) CallOption

ConsistencyLevel - override for read options against documents and attachments. The valid values are: Strong, Bounded, Session, or Eventual (in order of strongest to weakest). The override must be the same or weaker than the account�s configured consistency level.

func Continuation

func Continuation(continuation string) CallOption

Continuation - a string token returned for queries and read-feed operations if there are more results to be read. Clients can retrieve the next page of results by resubmitting the request with the x-ms-continuation request header set to this value.

func CrossPartition

func CrossPartition() CallOption

CrossPartition - allows query to run on all partitions

func EnableParallelizeCrossPartitionQuery

func EnableParallelizeCrossPartitionQuery() CallOption

EnableParallelizeCrossPartitionQuery - add the parallelize header

func EnablePopulateQueryMetrics

func EnablePopulateQueryMetrics() CallOption

EnablePopulateQueryMetrics - add the parallelize header

func EnableQueryScan

func EnableQueryScan() CallOption

EnableQueryScan - add the scan header

func IfMatch

func IfMatch(eTag string) CallOption

IfMatch - used to make operation conditional for optimistic concurrency. The value should be the etag value of the resource. (applicable only on PUT and DELETE)

func IfModifiedSince

func IfModifiedSince(date string) CallOption

IfModifiedSince - returns etag of resource modified after specified date in RFC 1123 format. Ignored when If-None-Match is specified Optional (applicable only on GET)

func IfNoneMatch

func IfNoneMatch(eTag string) CallOption

IfNoneMatch - makes operation conditional to only execute if the resource has changed. The value should be the etag of the resource. Optional (applicable only on GET)

func Limit

func Limit(limit int) CallOption

Limit - set max item count for response

func PartitionKey

func PartitionKey(partitionKey interface{}) CallOption

PartitionKey - specificy which partiotion will be used to satisfty the request

func PartitionKeyRangeID

func PartitionKeyRangeID(id int) CallOption

PartitionKeyRangeID - adds the partition key range header

func QueryVersion

func QueryVersion() CallOption

QueryVersion - add the query latest query version header

func SessionToken

func SessionToken(sessionToken string) CallOption

SessionToken - a string token used with session level consistency.

func ThroughputRUs

func ThroughputRUs(rus int) CallOption

ThroughputRUs - adds throughput headers for container creation

func Upsert

func Upsert() CallOption

Upsert - if set to true, Cosmos DB creates the document with the ID (and partition key value if applicable) if it doesn’t exist, or update the document if it exists.

func WithContext

func WithContext(ctx context.Context) CallOption

WithContext - adds a context to the request

type Collection

type Collection struct {
	Resource
	IndexingPolicy  IndexingPolicy  `json:"indexingPolicy,omitempty"`
	PartitionKeyDef PartitionKeyDef `json:"partitionKey,omitempty"`
	Docs            string          `json:"_docs,omitempty"`
	Udf             string          `json:"_udfs,omitempty"`
	Sporcs          string          `json:"_sporcs,omitempty"`
	Triggers        string          `json:"_triggers,omitempty"`
	Conflicts       string          `json:"_conflicts,omitempty"`
}

Collection

type Config

type Config struct {
	MasterKey               string
	Debug                   bool
	Verbose                 bool
	PartitionKeyStructField string // eg. "Id"
	PartitionKeyPath        string // slash denoted path eg. "/id"
	RetryWaitMin            time.Duration
	RetryWaitMax            time.Duration
	RetryMax                int
	Pooled                  bool
}

Config - Stores configuration for the gocosmosdb client

type Consistency

type Consistency string

Consistency type to define consistency levels

const (
	// Strong consistency level
	Strong Consistency = "strong"

	// Bounded consistency level
	Bounded Consistency = "bounded"

	// Session consistency level
	Session Consistency = "session"

	// Eventual consistency level
	Eventual Consistency = "eventual"
)

type CosmosDB

type CosmosDB struct {
	Config Config
	Logger *logger.Logger
	// contains filtered or unexported fields
}

CosmosDB - Struct that stores the client and logger

func New

func New(url string, config Config, log *logger.Logger) *CosmosDB

New - Creates CosmosDB Client and returns it

func (*CosmosDB) CreateCollection

func (c *CosmosDB) CreateCollection(db string, body interface{}, opts ...CallOption) (coll *Collection, err error)

CreateCollection - Creates a new collections in the database.

coll, err := client.CreateCollection("dbs/{db-id}/", `{"id": "coll-id"}`)

func (*CosmosDB) CreateDatabase

func (c *CosmosDB) CreateDatabase(body interface{}, opts ...CallOption) (db *Database, err error)

CreateDatabase - Creates a new database in the database account.

db, err := client.CreateDatabase(`{ "id": "db-id" }`)

func (*CosmosDB) CreateDocument

func (c *CosmosDB) CreateDocument(coll string, doc interface{}, opts ...CallOption) (*Response, error)

CreateDocument - Creates a new document in the collection.

err := client.CreateDocument("dbs/{db-id}/colls/{coll-id}", &doc)

func (*CosmosDB) CreateStoredProcedure

func (c *CosmosDB) CreateStoredProcedure(coll string, body interface{}, opts ...CallOption) (sproc *Sproc, err error)

CreateStoredProcedure - Creates a new stored procedure in the collection.

	sprocBody := gocosmosdb.Sproc{
   	Body: "function () {\r\n    var context = getContext();\r\n    var response = context.getResponse();\r\n\r\n    response.setBody(\"Hello, World\");\r\n}",
   	Id: "sproc_1"
	}
	sproc, err := client.CreateStoredProcedure("dbs/{db-id}/colls/{coll-id}/sprocs", &sprocBody)

func (*CosmosDB) CreateUserDefinedFunction

func (c *CosmosDB) CreateUserDefinedFunction(coll string, body interface{}, opts ...CallOption) (udf *UDF, err error)

CreateUserDefinedFunction - Creates a new user defined function in the collection.

	udfBody := gocosmosdb.UDF{
   	Body: "function tax(income) {\r\n    if(income == undefined) \r\n        throw 'no input';\r\n    if (income < 1000) \r\n        return income * 0.1;\r\n    else if (income < 10000) \r\n        return income * 0.2;\r\n    else\r\n        return income * 0.4;\r\n}",
   	Id: "simpleTaxUDF"
	}
	udf, err := client.CreateUserDefinedFunction("dbs/{db-id}/colls/{coll-id}/udfs", &udfBody)

func (*CosmosDB) DeleteCollection

func (c *CosmosDB) DeleteCollection(link string) (*Response, error)

DeleteCollection - Deletes a collection from a database.

err := client.DeleteCollection("dbs/{db-id}/colls/{coll-id}")

func (*CosmosDB) DeleteDatabase

func (c *CosmosDB) DeleteDatabase(link string) (*Response, error)

DeleteDatabase - Deletes a database from a database account.

err := client.DeleteDatabase("dbs/{db-id}")

func (*CosmosDB) DeleteDocument

func (c *CosmosDB) DeleteDocument(link string, opts ...CallOption) (*Response, error)

DeleteDocument - Deletes a document from a collection.

err := client.DeleteDocument("dbs/{db-id}/colls/{coll-id}/docs/{doc-id}")

func (*CosmosDB) DeleteStoredProcedure

func (c *CosmosDB) DeleteStoredProcedure(link string) (*Response, error)

DeleteStoredProcedure - Deletes a stored procedure from a collection.

err := client.DeleteStoredProcedure("dbs/{db-id}/colls/{coll-id}/sprocs/{sproc-id}")

func (*CosmosDB) DeleteUserDefinedFunction

func (c *CosmosDB) DeleteUserDefinedFunction(link string) (*Response, error)

DeleteUserDefinedFunction - Deletes a user defined function from a collection.

err := client.DeleteUserDefinedFunction("dbs/{db-id}/colls/{coll-id}/udfs/{udf-id}")

func (*CosmosDB) DisableDebug

func (c *CosmosDB) DisableDebug()

DisableDebug - disables the CosmosDB debugging

func (*CosmosDB) EnableDebug

func (c *CosmosDB) EnableDebug()

EnableDebug - enables the CosmosDB debugging

func (*CosmosDB) ExecuteStoredProcedure

func (c *CosmosDB) ExecuteStoredProcedure(link string, params, body interface{}, opts ...CallOption) (resp *Response, err error)

ExecuteStoredProcedure - Executes a stored procedure and marshals the data into the passed interface.

err := client.ExecuteStoredProcedure("dbs/{db-id}/colls/{coll-id}/sprocs/{sproc-id}", []interface{}{p1, p2}, &docs)

func (*CosmosDB) GetConfig

func (c *CosmosDB) GetConfig() Config

GetConfig - returns the CosmosDB config

func (*CosmosDB) GetURI

func (c *CosmosDB) GetURI() string

GetURI - returns the CosmosDB URI

func (*CosmosDB) NewPagableQuery

func (c *CosmosDB) NewPagableQuery(coll string, query *QueryWithParameters, limit int, docs interface{}, opts ...CallOption) *PagableQuery

NewPagableQuery - Creates a pagable query that populates the passed docs interface

func (*CosmosDB) QueryCollections

func (c *CosmosDB) QueryCollections(db, query string, opts ...CallOption) (colls []Collection, err error)

QueryCollections - Retrieves all collections that satisfy passed query.

colls, err := client.QueryCollections("SELECT * FROM ROOT r")

func (*CosmosDB) QueryDatabases

func (c *CosmosDB) QueryDatabases(query string, opts ...CallOption) (dbs []Database, err error)

QueryDatabases - Retrieves all databases that satisfy the passed query.

dbs, err := client.QueryDatabases("SELECT * FROM ROOT r")

func (*CosmosDB) QueryDocuments

func (c *CosmosDB) QueryDocuments(coll, query string, docs interface{}, opts ...CallOption) (resp *Response, err error)

QueryDocuments - Retrieves all documents in a collection that satisfy the passed query and marshals them into the passed interface.

err := client.QueryDocuments(coll, "SELECT * FROM ROOT r", &docs)

func (*CosmosDB) QueryDocumentsWithParameters

func (c *CosmosDB) QueryDocumentsWithParameters(coll string, query *QueryWithParameters, docs interface{}, opts ...CallOption) (resp *Response, err error)

QueryDocumentsWithParameters - Retrieves all documents in a collection that satisfy a passed query with parameters and marshals them into the passed interface.

err := client.QueryDocumentsWithParameters(coll, queryWithParams, &docs)

func (*CosmosDB) QueryPartitionKeyRanges

func (c *CosmosDB) QueryPartitionKeyRanges(coll string, query string, opts ...CallOption) (ranges []PartitionKeyRange, err error)

QueryPartitionKeyRanges - Retrieves all partition ranges in a collection.

pks, err := client.QueryPartitionKeyRanges(coll, "SELECT * FROM ROOT r")

func (*CosmosDB) QueryStoredProcedures

func (c *CosmosDB) QueryStoredProcedures(coll, query string, opts ...CallOption) (sprocs []Sproc, err error)

QueryStoredProcedures - Retrieves all stored procedures that satisfy the passed query.

colls, err := client.QueryStoredProcedures("SELECT * FROM ROOT r")

func (*CosmosDB) QueryUserDefinedFunctions

func (c *CosmosDB) QueryUserDefinedFunctions(coll, query string, opts ...CallOption) (udfs []UDF, err error)

QueryUserDefinedFunctions - Retrieves all user defined functions that satisfy the passed query.

colls, err := client.QueryUserDefinedFunctions("SELECT * FROM ROOT r")

func (*CosmosDB) ReadCollection

func (c *CosmosDB) ReadCollection(link string, opts ...CallOption) (coll *Collection, err error)

ReadCollection - Retrieves a collection by performing a GET on a specific collection resource.

coll, err := client.ReadCollection("dbs/{db-id}/colls/{coll-id}")

func (*CosmosDB) ReadCollections

func (c *CosmosDB) ReadCollections(db string, opts ...CallOption) (colls []Collection, err error)

ReadCollections - Retrieves all collections by performing a GET on a specific database.

colls, err := client.ReadCollections("dbs/{db-id}/colls")

func (*CosmosDB) ReadDatabase

func (c *CosmosDB) ReadDatabase(link string, opts ...CallOption) (db *Database, err error)

ReadDatabase - Retrieves a database resource by performing a GET on the database resource.

db, err := client.ReadDatabase("dbs/{db-id}")

func (*CosmosDB) ReadDatabases

func (c *CosmosDB) ReadDatabases(opts ...CallOption) (dbs []Database, err error)

ReadDatabases - Retrieves all databases by performing a GET on a specific account.

dbs, err := client.ReadDatabases("dbs")

func (*CosmosDB) ReadDocument

func (c *CosmosDB) ReadDocument(link string, doc interface{}, opts ...CallOption) (resp *Response, err error)

ReadDocument - Retrieves a document by performing a GET on a specific document resource and marshals the document into that passed docStruct

err = client.ReadDocument("dbs/{db-id}/colls/{coll-id}/docs/{doc-id}", &docStruct)

func (*CosmosDB) ReadDocuments

func (c *CosmosDB) ReadDocuments(coll string, docs interface{}, opts ...CallOption) (*Response, error)

ReadDocuments - Retrieves a stored procedure by performing a GET on a specific stored procedure resource.

err = client.ReadDocuments("dbs/{db-id}/colls/{coll-id}/docs", &docStructSlice)

func (*CosmosDB) ReadStoredProcedure

func (c *CosmosDB) ReadStoredProcedure(link string, opts ...CallOption) (sproc *Sproc, err error)

ReadStoredProcedure - Retrieves a stored procedure by performing a GET on a specific stored procedure resource. sproc, err := client.ReadStoredProcedure("dbs/{db-id}/sprocs/{sproc-id}")

func (*CosmosDB) ReadStoredProcedures

func (c *CosmosDB) ReadStoredProcedures(coll string, opts ...CallOption) (sprocs []Sproc, err error)

ReadStoredProcedures - Retrieves all stored procedures by performing a GET on a specific database.

sprocs, err := client.ReadStoredProcedures("dbs/{db-id}/sprocs")

func (*CosmosDB) ReadUserDefinedFunction

func (c *CosmosDB) ReadUserDefinedFunction(link string, opts ...CallOption) (udf *UDF, err error)

ReadUserDefinedFunction - Retrieves a user defined function by performing a GET on a specific user defined function resource. udf, err := client.ReadUserDefinedFunction("dbs/{db-id}/udfs/{udf-id}")

func (*CosmosDB) ReadUserDefinedFunctions

func (c *CosmosDB) ReadUserDefinedFunctions(coll string, opts ...CallOption) (udfs []UDF, err error)

ReadUserDefinedFunctions - Retrieves all user defined functions by performing a GET on a specific database.

udfs, err := client.ReadUserDefinedFunctions("dbs/{db-id}/udfs")

func (*CosmosDB) ReplaceDatabase

func (c *CosmosDB) ReplaceDatabase(link string, body interface{}, opts ...CallOption) (db *Database, err error)

ReplaceDatabase - Replaces a existing database in a database account.

db, err := client.ReplaceDatabase("dbs/{db-id}", "`{ "id": "new-db-id" }`)

func (*CosmosDB) ReplaceDocument

func (c *CosmosDB) ReplaceDocument(link string, doc interface{}, opts ...CallOption) (*Response, error)

ReplaceDocument - Replaces a existing document in a collection.

db, err := client.ReplaceDocument("dbs/{db-id}/colls/{coll-id}/docs/{doc-id}", &doc)

func (*CosmosDB) ReplaceDocumentAsync

func (c *CosmosDB) ReplaceDocumentAsync(link string, doc interface{}, opts ...CallOption) (*Response, error)

ReplaceDocumentAsync - Replaces a document that has a matching etag.

db, err := client.ReplaceDocumentAsync("dbs/{db-id}/colls/{coll-id}/docs/{doc-id}", &doc)

func (*CosmosDB) ReplaceStoredProcedure

func (c *CosmosDB) ReplaceStoredProcedure(link string, body interface{}, opts ...CallOption) (sproc *Sproc, err error)

ReplaceStoredProcedure - Replaces a stored procedure in a collection.

db, err := client.ReplaceDatabase("dbs/{db-id}/colls/{coll-id}/sprocs/{sproc-id}", &sprocBody)

func (*CosmosDB) ReplaceUserDefinedFunction

func (c *CosmosDB) ReplaceUserDefinedFunction(link string, body interface{}, opts ...CallOption) (udf *UDF, err error)

ReplaceUserDefinedFunction - Replaces a user defined function in a collection.

db, err := client.ReplaceDatabase("dbs/{db-id}/colls/{coll-id}/udfs/{udf-id}", &udfBody)

func (*CosmosDB) UpsertDocument

func (c *CosmosDB) UpsertDocument(coll string, doc interface{}, opts ...CallOption) (*Response, error)

UpsertDocument - Creates a new document or replaces the existing document with matching id in the collection.

err := client.UpsertDocument("dbs/{db-id}/colls/{coll-id}", &doc)

type Database

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

Database

type Document

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

Document

type Expirable

type Expirable struct {
	TTL int64 `json:"ttl"`
}

Expirable

func (*Expirable) SetTTL

func (exp *Expirable) SetTTL(dur time.Duration)

SetTTL takes a duration and sets the field value

type IndexingPolicy

type IndexingPolicy struct {
	Automatic     bool `json:"automatic,omitempty"`
	IncludedPaths []struct {
		Indexes []struct {
			DataType  string `json:"dataType,omitempty"`
			Kind      string `json:"kind,omitempty"`
			Precision int    `json:"precision,omitempty`
		} `json:"indexes,omitempty"`
		Path string `json:"path,omitempty"`
	} `json:"includedPaths,omitempty"`
	IndexingMode string `json:"indexingMode,omitempty"`
}

Indexing policy

type Metrics

type Metrics struct {
	TotalExecutionTimeInMs         float64 `json:"totalExecutionTimeInMs,omitempty"`
	QueryCompileTimeInMs           float64 `json:"queryCompileTimeInMs,omitempty"`
	QueryLogicalPlanBuildTimeInMs  float64 `json:"queryLogicalPlanBuildTimeInMs,omitempty"`
	QueryPhysicalPlanBuildTimeInMs float64 `json:"queryPhysicalPlanBuildTimeInMs,omitempty"`
	QueryOptimizationTimeInMs      float64 `json:"queryOptimizationTimeInMs,omitempty"`
	VMExecutionTimeInMs            float64 `json:"VMExecutionTimeInMs,omitempty"`
	IndexLookupTimeInMs            float64 `json:"indexLookupTimeInMs,omitempty"`
	DocumentLoadTimeInMs           float64 `json:"documentLoadTimeInMs,omitempty"`
	SystemFunctionExecuteTimeInMs  float64 `json:"systemFunctionExecuteTimeInMs,omitempty"`
	UserFunctionExecuteTimeInMs    float64 `json:"userFunctionExecuteTimeInMs,omitempty"`
	RetrievedDocumentCount         int     `json:"retrievedDocumentCount,omitempty"`
	RetrievedDocumentSize          int     `json:"retrievedDocumentSize,omitempty"`
	OutputDocumentCount            int     `json:"outputDocumentCount,omitempty"`
	WriteOutputTimeInMs            float64 `json:"writeOutputTimeInMs,omitempty"`
	IndexUtilizationRatio          float64 `json:"indexUtilizationRatio,omitempty"`
	RequestCharge                  float64 `json:"requestCharge,omitempty"`
}

Metrics

type PagableQuery

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

PagableQuery

func (*PagableQuery) Done

func (q *PagableQuery) Done() bool

Done - returns true if no more pages are available

func (*PagableQuery) Next

func (q *PagableQuery) Next() error

Next - marshals the next page of docs into the passed interface

type PartitionKeyDef

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

Partition Key

type PartitionKeyRange

type PartitionKeyRange struct {
	Resource
	MinInclusive string `json:"minInclusive,omitempty"`
	MaxInclusive string `json:"maxExclusive,omitempty"`
}

PartitionKeyRange partition key range model

type QueryParameter

type QueryParameter struct {
	Name  string      `json:"name"`
	Value interface{} `json:"value"`
}

QueryParameter

type QueryWithParameters

type QueryWithParameters struct {
	Query      string           `json:"query"`
	Parameters []QueryParameter `json:"parameters"`
}

QueryWithParameters

type Request

type Request struct {
	*http.Request
	// contains filtered or unexported fields
}

Resource Request

func ResourceRequest

func ResourceRequest(link string, req *http.Request) *Request

Return new resource request with type and id

func (*Request) DefaultHeaders

func (req *Request) DefaultHeaders(mKey string) (err error)

Add 3 default headers to *Request "x-ms-date", "x-ms-version", "authorization"

func (*Request) QueryHeaders

func (req *Request) QueryHeaders(len int)

Add headers for query request

func (*Request) QueryMetricsHeaders

func (req *Request) QueryMetricsHeaders()

Add headers for query metrics request

type RequestError

type RequestError struct {
	Code       string        `json:"code"`
	StatusCode int           `json:"statusCode"`
	Message    string        `json:"message"`
	RId        string        `json:"rId"`
	RType      string        `json:"rType`
	Request    *http.Request `json:"request"`
}

RequestError

func (RequestError) Error

func (e RequestError) Error() string

Implement Error function

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"`
	Count int    `json:"_count,omitempty"`
}

Resource

type Response

type Response struct {
	Header http.Header
}

func (*Response) Continuation

func (r *Response) Continuation() string

Continuation - returns continuation token for paged request. Pass this value to next request to get next page of documents.

func (*Response) GetQueryMetrics

func (r *Response) GetQueryMetrics() (*Metrics, error)

GetQueryMetrics - returns a responses metrics

func (*Response) GetRUs

func (r *Response) GetRUs() (float64, error)

GetRUs - returns a responses RUs

func (*Response) SessionToken

func (r *Response) SessionToken() string

SessionToken - returns session token for session consistent request. Pass this value to next request to maintain session consistency documents.

type Sproc

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

Stored Procedure

type UDF

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

User Defined Function

Jump to

Keyboard shortcuts

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