gocosmos

package module
v0.1.10 Latest Latest
Warning

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

Go to latest
Published: Jun 15, 2022 License: MIT Imports: 26 Imported by: 0

README

gocosmos

Go Report Card PkgGoDev Actions Status codecov Release Mentioned in Awesome Go

Go driver for Azure Cosmos DB SQL API which can be used with the standard database/sql package. A REST client for Azure Cosmos DB SQL API is also included.

Example usage: REST client

import (
	"os"
	"database/sql"
	"github.com/btnguyen2k/gocosmos"
)

func main() {
	cosmosDbConnStr := "AccountEndpoint=https://localhost:8081/;AccountKey=<cosmosdb-account-key>"
	client, err := gocosmos.NewRestClient(nil, cosmosDbConnStr)
	if err != nil {
		panic(err)
	}

	dbSpec := gocosmos.DatabaseSpec{Id:"mydb", Ru: 400}
	result := client.CreateDatabase(dbSpec)
	if result.Error() != nil {
		panic(result.Error)
	}

	// database "mydb" has been created successfuly
}

Connection string syntax for Cosmos DB

AccountEndpoint=<cosmosdb-endpoint>;AccountKey=<cosmosdb-account-key>;TimeoutMs=<timeout-in-ms>;Version=<cosmosdb-api-version>;AutoId=<true/false>;InsecureSkipVerify=<true/false>

  • AccountEndpoint: (required) endpoint to access Cosmos DB. For example, the endpoint for Azure Cosmos DB Emulator running on local is https://localhost:8081/.
  • AccountKey: (required) account key to authenticate.
  • TimeoutMs: (optional) operation timeout in milliseconds. Default value is 10 seconds if not specified.
  • Version: (optional) version of Cosmos DB to use. Default value is 2018-12-31 if not specified. See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/#supported-rest-api-versions.
  • AutoId: (optional, available since v0.1.2) see auto id session.
  • InsecureSkipVerify: (optional, available since v0.1.4) if true, disable CA verification for https endpoint (useful to run against test/dev env with local/docker Cosmos DB emulator).

Example usage: database/sql driver

import (
	"database/sql"
	_ "github.com/btnguyen2k/gocosmos"
)

func main() {
	driver := "gocosmos"
	dsn := "AccountEndpoint=https://localhost:8081/;AccountKey=<cosmosdb-account-key>"
	db, err := sql.Open(driver, dsn)
	if err != nil {
		panic(err)
	}
	defer db.Close()

	_, err := db.Exec("CREATE DATABASE mydb WITH maxru=10000")
	if err != nil {
		panic(err)
	}
  
	// database "mydb" has been created successfuly
}

Data Source Name (DSN) syntax for Cosmos DB

AccountEndpoint=<cosmosdb-endpoint>;AccountKey=<cosmosdb-account-key>;TimeoutMs=<timeout-in-ms>;Version=<cosmosdb-api-version>;DefaultDb=<db-name>;AutoId=<true/false>;InsecureSkipVerify=<true/false>

  • AccountEndpoint: (required) endpoint to access Cosmos DB. For example, the endpoint for Azure Cosmos DB Emulator running on local is https://localhost:8081/.
  • AccountKey: (required) account key to authenticate.
  • TimeoutMs: (optional) operation timeout in milliseconds. Default value is 10 seconds if not specified.
  • Version: (optional) version of Cosmos DB to use. Default value is 2018-12-31 if not specified. See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/#supported-rest-api-versions.
  • DefaultDb: (optional, available since v0.1.1) specify the default database used in Cosmos DB operations. Alias Db can also be used instead of DefaultDb.
  • AutoId: (optional, available since v0.1.2) see auto id session.
  • InsecureSkipVerify: (optional, available since v0.1.4) if true, disable CA verification for https endpoint (useful to run against test/dev env with local/docker Cosmos DB emulator).
Auto-id

Azure Cosmos DB requires each document has a unique ID that identifies the document. When creating new document, if value for the unique ID field is not supplied gocosmos is able to generate one automatically. This feature is enabled by specifying setting AutoId=true in the connection string (for REST client) or Data Source Name (for database/sql driver). If not specified, default value is AutoId=true.

This settings is available since v0.1.2.

Features

The REST client supports:

  • Database: Create, Get, Delete, List and change throughput.
  • Collection: Create, Replace, Get, Delete, List and change throughput.
  • Document: Create, Replace, Get, Delete, Query and List.

The database/sql driver supports:

  • Database:
    • CREATE DATABASE
    • ALTER DATABASE
    • DROP DATABASE
    • LIST DATABASES
  • Table/Collection:
    • CREATE TABLE/COLLECTION
    • ALTER TABLE/COLLECTION
    • DROP TABLE/COLLECTION
    • LIST TABLES/COLLECTIONS
  • Item/Document:
    • INSERT
    • UPSERT
    • SELECT
    • UPDATE
    • DELETE

Summary of supported SQL statements:

Statement Syntax
Create a new database CREATE DATABASE [IF NOT EXISTS] <db-name>
Change database's throughput ALTER DATABASE <db-name> WITH RU/MAXRU=<ru>
Delete an existing database DROP DATABASE [IF EXISTS] <db-name>
List all existing databases LIST DATABASES
Create a new collection CREATE COLLECTION [IF NOT EXISTS] [<db-name>.]<collection-name> <WITH [LARGE]PK=partitionKey>
Change collection's throughput ALTER COLLECTION [<db-name>.]<collection-name> WITH RU/MAXRU=<ru>
Delete an existing collection DROP COLLECTION [IF EXISTS] [<db-name>.]<collection-name>
List all existing collections in a database LIST COLLECTIONS [FROM <db-name>]
Insert a new document into collection INSERT INTO [<db-name>.]<collection-name> ...
Insert or replace a document UPSERT INTO [<db-name>.]<collection-name> ...
Delete an existing document DELETE FROM [<db-name>.]<collection-name> WHERE id=<id-value>
Update an existing document UPDATE [<db-name>.]<collection-name> SET ... WHERE id=<id-value>
Query documents in a collection SELECT [CROSS PARTITION] ... FROM <collection-name> ... [WITH database=<db-name>]

See supported SQL statements for details.

Azure Cosmos DB SQL API currently supports only SELECT statement. gocosmos implements other statements by translating the SQL statement to REST API call to Azure Cosmos DB REST API.

License

MIT - see LICENSE.md.

Documentation

Overview

Package gocosmos provides database/sql driver and a REST API client for Azure Cosmos DB SQL API.

Index

Constants

View Source
const (
	// Version of package gocosmos.
	Version = "0.1.6"
)

Variables

View Source
var (
	// ErrForbidden is returned when the operation is not allowed on the target resource.
	ErrForbidden = errors.New("StatusCode=403 Forbidden")

	// ErrNotFound is returned when target resource can not be found.
	ErrNotFound = errors.New("StatusCode=404 Not Found")

	// ErrConflict is returned when the executing operation cause conflict (e.g. duplicated id).
	ErrConflict = errors.New("StatusCode=409 Conflict")
)

Functions

This section is empty.

Types

type CollInfo

type CollInfo struct {
	Id                       string                 `json:"id"`                       // user-generated unique name for the collection
	Rid                      string                 `json:"_rid"`                     // (system generated property) _rid attribute of the collection
	Ts                       int64                  `json:"_ts"`                      // (system-generated property) _ts attribute of the collection
	Self                     string                 `json:"_self"`                    // (system-generated property) _self attribute of the collection
	Etag                     string                 `json:"_etag"`                    // (system-generated property) _etag attribute of the collection
	Docs                     string                 `json:"_docs"`                    // (system-generated property) _docs attribute of the collection
	Sprocs                   string                 `json:"_sprocs"`                  // (system-generated property) _sprocs attribute of the collection
	Triggers                 string                 `json:"_triggers"`                // (system-generated property) _triggers attribute of the collection
	Udfs                     string                 `json:"_udfs"`                    // (system-generated property) _udfs attribute of the collection
	Conflicts                string                 `json:"_conflicts"`               // (system-generated property) _conflicts attribute of the collection
	IndexingPolicy           map[string]interface{} `json:"indexingPolicy"`           // indexing policy settings for collection
	PartitionKey             map[string]interface{} `json:"partitionKey"`             // partitioning configuration settings for collection
	ConflictResolutionPolicy map[string]interface{} `json:"conflictResolutionPolicy"` // conflict resolution policy settings for collection
	GeospatialConfig         map[string]interface{} `json:"geospatialConfig"`         // Geo-spatial configuration settings for collection
}

CollInfo captures info of a CosmosDB collection.

type CollectionSpec

type CollectionSpec struct {
	DbName, CollName string
	Ru, MaxRu        int
	// PartitionKeyInfo specifies the collection's partition key.
	// At the minimum, the partition key info is a map: {paths:[/path],"kind":"Hash"}
	// If partition key is larger than 100 bytes, specify {"Version":2}
	PartitionKeyInfo map[string]interface{}
	IndexingPolicy   map[string]interface{}
	UniqueKeyPolicy  map[string]interface{}
}

CollectionSpec specifies a CosmosDB collection specifications for creation.

type Conn

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

Conn is Azure CosmosDB connection handle.

func (*Conn) Begin

func (c *Conn) Begin() (driver.Tx, error)

Begin implements driver.Conn.Begin.

func (*Conn) CheckNamedValue

func (c *Conn) CheckNamedValue(value *driver.NamedValue) error

CheckNamedValue implements driver.NamedValueChecker.CheckNamedValue.

func (*Conn) Close

func (c *Conn) Close() error

Close implements driver.Conn.Close.

func (*Conn) Prepare

func (c *Conn) Prepare(query string) (driver.Stmt, error)

Prepare implements driver.Conn.Prepare.

type DatabaseSpec

type DatabaseSpec struct {
	Id        string
	Ru, MaxRu int
}

DatabaseSpec specifies a CosmosDB database specifications for creation.

type DbInfo

type DbInfo struct {
	Id    string `json:"id"`     // user-generated unique name for the database
	Rid   string `json:"_rid"`   // (system generated property) _rid attribute of the database
	Ts    int64  `json:"_ts"`    // (system-generated property) _ts attribute of the database
	Self  string `json:"_self"`  // (system-generated property) _self attribute of the database
	Etag  string `json:"_etag"`  // (system-generated property) _etag attribute of the database
	Colls string `json:"_colls"` // (system-generated property) _colls attribute of the database
	Users string `json:"_users"` // (system-generated property) _users attribute of the database
}

DbInfo captures info of a CosmosDB database.

type DocInfo

type DocInfo map[string]interface{}

DocInfo captures info of a CosmosDB document.

func (DocInfo) Attachments

func (d DocInfo) Attachments() string

Attachments returns the value of document's "_attachments" attribute.

func (DocInfo) Etag

func (d DocInfo) Etag() string

Etag returns the value of document's "_etag" attribute.

func (DocInfo) GetAttrAsType

func (d DocInfo) GetAttrAsType(attrName string, typ reflect.Type) (interface{}, error)

GetAttrAsType returns a document attribute converting to a specific type.

Note: if typ is nil, the attribute value is returned as-is (i.e. without converting).

func (DocInfo) GetAttrAsTypeUnsafe

func (d DocInfo) GetAttrAsTypeUnsafe(attrName string, typ reflect.Type) interface{}

GetAttrAsTypeUnsafe is similar to GetAttrAsType except that it does not check for error.

func (DocInfo) Id

func (d DocInfo) Id() string

Id returns the value of document's "id" attribute.

func (DocInfo) RemoveSystemAttrs

func (d DocInfo) RemoveSystemAttrs() DocInfo

RemoveSystemAttrs returns a clone of the document with all system attributes removed.

func (DocInfo) Rid

func (d DocInfo) Rid() string

Rid returns the value of document's "_rid" attribute.

func (DocInfo) Self

func (d DocInfo) Self() string

Self returns the value of document's "_self" attribute.

func (DocInfo) Ts

func (d DocInfo) Ts() int64

Ts returns the value of document's "_ts" attribute.

func (DocInfo) TsAsTime

func (d DocInfo) TsAsTime() time.Time

TsAsTime returns the value of document's "_ts" attribute as a time.Time.

type DocReq

type DocReq struct {
	DbName, CollName, DocId string
	PartitionKeyValues      []interface{}
	MatchEtag               string // if not empty, add "If-Match" header to request
	NotMatchEtag            string // if not empty, add "If-None-Match" header to request
	ConsistencyLevel        string // accepted values: "", "Strong", "Bounded", "Session" or "Eventual"
	SessionToken            string // string token used with session level consistency
}

DocReq specifies a document request.

type DocumentSpec

type DocumentSpec struct {
	DbName, CollName   string
	IsUpsert           bool
	IndexingDirective  string // accepted value "", "Include" or "Exclude"
	PartitionKeyValues []interface{}
	DocumentData       map[string]interface{}
}

DocumentSpec specifies a CosmosDB document specifications for creation.

type Driver

type Driver struct {
}

Driver is Azure CosmosDB driver for database/sql.

func (*Driver) Open

func (d *Driver) Open(connStr string) (driver.Conn, error)

Open implements driver.Driver.Open.

connStr is expected in the following format:

AccountEndpoint=<cosmosdb-restapi-endpoint>;AccountKey=<account-key>[;TimeoutMs=<timeout-in-ms>][;Version=<cosmosdb-api-version>][;DefaultDb=<db-name>][;AutoId=<true/false>]

If not supplied, default value for TimeoutMs is 10 seconds, Version is "2018-12-31" and AutoId is true.

DefaultDb is added since v0.1.1

AutoId is added since v0.1.2

type ListDocsReq

type ListDocsReq struct {
	DbName, CollName    string
	MaxItemCount        int
	ContinuationToken   string
	ConsistencyLevel    string // accepted values: "", "Strong", "Bounded", "Session" or "Eventual"
	SessionToken        string // string token used with session level consistency
	NotMatchEtag        string
	PartitionKeyRangeId string
}

ListDocsReq specifies a list documents request.

type OfferInfo

type OfferInfo struct {
	OfferVersion    string                 `json:"offerVersion"`    // V2 is the current version for request unit-based throughput.
	OfferType       string                 `json:"offerType"`       // This value indicates the performance level for V1 offer version, allowed values for V1 offer are S1, S2, or S3. This property is set to Invalid for V2 offer version.
	Content         map[string]interface{} `json:"content"`         // Contains information about the offer – for V2 offers, this contains the throughput of the collection.
	Resource        string                 `json:"resource"`        // When creating a new collection, this property is set to the self-link of the collection.
	OfferResourceId string                 `json:"offerResourceId"` // During creation of a collection, this property is automatically associated to the resource ID, that is, _rid of the collection.
	Id              string                 `json:"id"`              // It is a system-generated property. The ID for the offer resource is automatically generated when it is created. It has the same value as the _rid for the offer.
	Rid             string                 `json:"_rid"`            // It is a system-generated property. The resource ID (_rid) is a unique identifier that is also hierarchical per the resource stack on the resource model. It is used internally for placement and navigation of the offer.
	Ts              int64                  `json:"_ts"`             // It is a system-generated property. It specifies the last updated timestamp of the resource. The value is a timestamp.
	Self            string                 `json:"_self"`           // It is a system-generated property. It is the unique addressable URI for the resource.
	Etag            string                 `json:"_etag"`           // It is a system-generated property that specifies the resource etag required for optimistic concurrency control.
	// contains filtered or unexported fields
}

OfferInfo captures info of a CosmosDB offer.

See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/offers.

func (OfferInfo) IsAutopilot

func (o OfferInfo) IsAutopilot() bool

IsAutopilot returns true if auto pilot is enabled, false otherwise.

func (OfferInfo) MaxThroughputEverProvisioned

func (o OfferInfo) MaxThroughputEverProvisioned() int

MaxThroughputEverProvisioned returns value of field 'maxThroughputEverProvisioned'

func (OfferInfo) OfferThroughput

func (o OfferInfo) OfferThroughput() int

OfferThroughput returns value of field 'offerThroughput'

type PkrangeInfo

type PkrangeInfo struct {
	Id           string `json:"id"`           // the stable and unique ID for the partition key range within each collection
	MaxExclusive string `json:"maxExclusive"` // (internal use) the maximum partition key hash value for the partition key range
	MinInclusive string `json:"minInclusive"` // (minimum use) the maximum partition key hash value for the partition key range
	Rid          string `json:"_rid"`         // (system generated property) _rid attribute of the pkrange
	Ts           int64  `json:"_ts"`          // (system-generated property) _ts attribute of the pkrange
	Self         string `json:"_self"`        // (system-generated property) _self attribute of the pkrange
	Etag         string `json:"_etag"`        // (system-generated property) _etag attribute of the pkrange
}

PkrangeInfo captures info of a collection's partition key range.

See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/get-partition-key-ranges.

Available since v0.1.3.

type QueryReq

type QueryReq struct {
	DbName, CollName      string
	Query                 string
	Params                []interface{}
	MaxItemCount          int
	ContinuationToken     string
	CrossPartitionEnabled bool
	ConsistencyLevel      string // accepted values: "", "Strong", "Bounded", "Session" or "Eventual"
	SessionToken          string // string token used with session level consistency
}

QueryReq specifies a query request to query for documents.

type RespCreateColl

type RespCreateColl struct {
	RestReponse
	CollInfo
}

RespCreateColl captures the response from CreateCollection call.

type RespCreateDb

type RespCreateDb struct {
	RestReponse
	DbInfo
}

RespCreateDb captures the response from CreateDatabase call.

type RespCreateDoc

type RespCreateDoc struct {
	RestReponse
	DocInfo
}

RespCreateDoc captures the response from CreateDocument call.

type RespDeleteColl

type RespDeleteColl struct {
	RestReponse
}

RespDeleteColl captures the response from DeleteCollection call.

type RespDeleteDb

type RespDeleteDb struct {
	RestReponse
}

RespDeleteDb captures the response from DeleteDatabase call.

type RespDeleteDoc

type RespDeleteDoc struct {
	RestReponse
}

RespDeleteDoc captures the response from DeleteDocument call.

type RespGetColl

type RespGetColl struct {
	RestReponse
	CollInfo
}

RespGetColl captures the response from GetCollection call.

type RespGetDb

type RespGetDb struct {
	RestReponse
	DbInfo
}

RespGetDb captures the response from GetDatabase call.

type RespGetDoc

type RespGetDoc struct {
	RestReponse
	DocInfo
}

RespGetDoc captures the response from GetDocument call.

type RespGetOffer

type RespGetOffer struct {
	RestReponse
	OfferInfo
}

RespGetOffer captures the response from GetOffer call.

type RespGetPkranges

type RespGetPkranges struct {
	RestReponse `json:"-"`
	Pkranges    []PkrangeInfo `json:"PartitionKeyRanges"`
	Count       int64         `json:"_count"` // number of records returned from the operation
}

RespGetPkranges captures the response from GetPkranges call.

Available since v0.1.3.

type RespListColl

type RespListColl struct {
	RestReponse `json:"-"`
	Count       int64      `json:"_count"` // number of collections returned from the list operation
	Collections []CollInfo `json:"DocumentCollections"`
}

RespListColl captures the response from ListCollections call.

type RespListDb

type RespListDb struct {
	RestReponse `json:"-"`
	Count       int64    `json:"_count"` // number of databases returned from the list operation
	Databases   []DbInfo `json:"Databases"`
}

RespListDb captures the response from ListDatabases call.

type RespListDocs

type RespListDocs struct {
	RestReponse       `json:"-"`
	Count             int64     `json:"_count"` // number of documents returned from the operation
	Documents         []DocInfo `json:"Documents"`
	ContinuationToken string    `json:"-"`
	Etag              string    `json:"-"` // logical sequence number (LSN) of last document returned in the response
}

RespListDocs captures the response from ListDocuments call.

type RespQueryDocs

type RespQueryDocs struct {
	RestReponse       `json:"-"`
	Count             int64     `json:"_count"` // number of documents returned from the operation
	Documents         []DocInfo `json:"Documents"`
	ContinuationToken string    `json:"-"`
}

RespQueryDocs captures the response from QueryDocuments call.

type RespQueryOffers

type RespQueryOffers struct {
	RestReponse       `json:"-"`
	Count             int64       `json:"_count"` // number of records returned from the operation
	Offers            []OfferInfo `json:"Offers"`
	ContinuationToken string      `json:"-"`
}

RespQueryOffers captures the response from QueryOffers call.

type RespReplaceColl

type RespReplaceColl struct {
	RestReponse
	CollInfo
}

RespReplaceColl captures the response from ReplaceCollection call.

type RespReplaceDoc

type RespReplaceDoc struct {
	RestReponse
	DocInfo
}

RespReplaceDoc captures the response from ReplaceDocument call.

type RespReplaceOffer

type RespReplaceOffer struct {
	RestReponse
	OfferInfo
}

RespReplaceOffer captures the response from ReplaceOffer call.

type RestClient

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

RestClient is REST-based client for Azure CosmosDB

func NewRestClient

func NewRestClient(httpClient *http.Client, connStr string) (*RestClient, error)

NewRestClient constructs a new RestClient instance from the supplied connection string.

httpClient is reused if supplied. Otherwise, a new http.Client instance is created. connStr is expected to be in the following format:

AccountEndpoint=<cosmosdb-restapi-endpoint>;AccountKey=<account-key>[;TimeoutMs=<timeout-in-ms>][;Version=<cosmosdb-api-version>][;AutoId=<true/false>][;InsecureSkipVerify=<true/false>]

If not supplied, default value for TimeoutMs is 10 seconds, Version is "2018-12-31", AutoId is true, and InsecureSkipVerify is false

- AutoId is added since v0.1.2 - InsecureSkipVerify is added since v0.1.4

func (*RestClient) CreateCollection

func (c *RestClient) CreateCollection(spec CollectionSpec) *RespCreateColl

CreateCollection invokes CosmosDB API to create a new collection.

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

Note: ru and maxru must not be supplied together!

func (*RestClient) CreateDatabase

func (c *RestClient) CreateDatabase(spec DatabaseSpec) *RespCreateDb

CreateDatabase invokes CosmosDB API to create a new database.

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

Note: ru and maxru must not be supplied together!

func (*RestClient) CreateDocument

func (c *RestClient) CreateDocument(spec DocumentSpec) *RespCreateDoc

CreateDocument invokes CosmosDB API to create a new document.

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

func (*RestClient) DeleteCollection

func (c *RestClient) DeleteCollection(dbName, collName string) *RespDeleteColl

DeleteCollection invokes CosmosDB API to delete an existing collection.

See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/delete-a-collection.

func (*RestClient) DeleteDatabase

func (c *RestClient) DeleteDatabase(dbName string) *RespDeleteDb

DeleteDatabase invokes CosmosDB API to delete an existing database.

See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/delete-a-database.

func (*RestClient) DeleteDocument

func (c *RestClient) DeleteDocument(r DocReq) *RespDeleteDoc

DeleteDocument invokes CosmosDB API to delete an existing document.

See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/delete-a-document.

func (*RestClient) GetCollection

func (c *RestClient) GetCollection(dbName, collName string) *RespGetColl

GetCollection invokes CosmosDB API to get an existing collection.

See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/get-a-collection

func (*RestClient) GetDatabase

func (c *RestClient) GetDatabase(dbName string) *RespGetDb

GetDatabase invokes CosmosDB API to get an existing database.

See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/get-a-database.

func (*RestClient) GetDocument

func (c *RestClient) GetDocument(r DocReq) *RespGetDoc

GetDocument invokes CosmosDB API to get an existing document.

See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/get-a-document.

func (*RestClient) GetOfferForResource

func (c *RestClient) GetOfferForResource(rid string) *RespGetOffer

GetOfferForResource invokes CosmosDB API to get offer info of a resource.

Available since v0.1.1

func (*RestClient) GetPkranges

func (c *RestClient) GetPkranges(dbName, collName string) *RespGetPkranges

GetPkranges invokes CosmosDB API to retrieves the list of partition key ranges for a collection.

See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/get-partition-key-ranges.

Available since v0.1.3

func (*RestClient) ListCollections

func (c *RestClient) ListCollections(dbName string) *RespListColl

ListCollections invokes CosmosDB API to list all available collections.

See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/list-collections.

func (*RestClient) ListDatabases

func (c *RestClient) ListDatabases() *RespListDb

ListDatabases invokes CosmosDB API to list all available databases.

See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/list-databases.

func (*RestClient) ListDocuments

func (c *RestClient) ListDocuments(r ListDocsReq) *RespListDocs

ListDocuments invokes CosmosDB API to query read-feed for documents.

See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/list-documents.

func (*RestClient) QueryDocuments

func (c *RestClient) QueryDocuments(query QueryReq) *RespQueryDocs

QueryDocuments invokes CosmosDB API to query a collection for documents.

See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/query-documents.

func (*RestClient) QueryOffers

func (c *RestClient) QueryOffers(query string) *RespQueryOffers

QueryOffers invokes CosmosDB API to query existing offers.

See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/querying-offers.

Available since v0.1.1

func (*RestClient) ReplaceCollection

func (c *RestClient) ReplaceCollection(spec CollectionSpec) *RespReplaceColl

ReplaceCollection invokes CosmosDB API to replace an existing collection.

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

Note: ru and maxru must not be supplied together!

func (*RestClient) ReplaceDocument

func (c *RestClient) ReplaceDocument(matchEtag string, spec DocumentSpec) *RespReplaceDoc

ReplaceDocument invokes CosmosDB API to replace an existing document.

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

func (*RestClient) ReplaceOfferForResource

func (c *RestClient) ReplaceOfferForResource(rid string, ru, maxru int) *RespReplaceOffer

ReplaceOfferForResource invokes CosmosDB API to replace/update offer info of a resource.

  • If ru > 0 and maxru <= 0: switch to manual throughput and set provisioning value to ru.
  • If ru <= 0 and maxru > 0: switch to autopilot throughput and set max provisioning value to maxru.
  • If ru <= 0 and maxru <= 0: switch to autopilot throughput with default provisioning value.

Available since v0.1.1

type RestReponse

type RestReponse struct {
	// CallErr holds any error occurred during the REST call.
	CallErr error
	// ApiErr holds any error occurred during the API call (only available when StatusCode >= 400).
	ApiErr error
	// StatusCode captures the HTTP status code from the REST call.
	StatusCode int
	// RespBody captures the body response from the REST call.
	RespBody []byte
	// RespHeader captures the header response from the REST call.
	RespHeader map[string]string
	// RequestCharge is number of request units consumed by the operation
	RequestCharge float64
	// SessionToken is used with session level consistency. Clients must save this value and set it for subsequent read requests for session consistency.
	SessionToken string
}

RestReponse captures the response from REST API call.

func (RestReponse) Error

func (r RestReponse) Error() error

Error returns CallErr if not nil, ApiErr otherwise.

type ResultAlterCollection

type ResultAlterCollection struct {
	// Successful flags if the operation was successful or not.
	Successful bool
}

ResultAlterCollection captures the result from ALTER COLLECTION operation.

Available since v0.1.1

func (*ResultAlterCollection) LastInsertId

func (r *ResultAlterCollection) LastInsertId() (int64, error)

LastInsertId implements driver.Result.LastInsertId.

func (*ResultAlterCollection) RowsAffected

func (r *ResultAlterCollection) RowsAffected() (int64, error)

RowsAffected implements driver.Result.RowsAffected.

type ResultAlterDatabase

type ResultAlterDatabase struct {
	// Successful flags if the operation was successful or not.
	Successful bool
}

ResultAlterDatabase captures the result from ALTER DATABASE operation.

Available since v0.1.1

func (*ResultAlterDatabase) LastInsertId

func (r *ResultAlterDatabase) LastInsertId() (int64, error)

LastInsertId implements driver.Result.LastInsertId.

func (*ResultAlterDatabase) RowsAffected

func (r *ResultAlterDatabase) RowsAffected() (int64, error)

RowsAffected implements driver.Result.RowsAffected.

type ResultCreateCollection

type ResultCreateCollection struct {
	// Successful flags if the operation was successful or not.
	Successful bool
	// InsertId holds the "_rid" if the operation was successful.
	InsertId string
}

ResultCreateCollection captures the result from CREATE COLLECTION operation.

func (*ResultCreateCollection) LastInsertId

func (r *ResultCreateCollection) LastInsertId() (int64, error)

LastInsertId implements driver.Result.LastInsertId.

func (*ResultCreateCollection) RowsAffected

func (r *ResultCreateCollection) RowsAffected() (int64, error)

RowsAffected implements driver.Result.RowsAffected.

type ResultCreateDatabase

type ResultCreateDatabase struct {
	// Successful flags if the operation was successful or not.
	Successful bool
	// InsertId holds the "_rid" if the operation was successful.
	InsertId string
}

ResultCreateDatabase captures the result from CREATE DATABASE operation.

func (*ResultCreateDatabase) LastInsertId

func (r *ResultCreateDatabase) LastInsertId() (int64, error)

LastInsertId implements driver.Result.LastInsertId.

func (*ResultCreateDatabase) RowsAffected

func (r *ResultCreateDatabase) RowsAffected() (int64, error)

RowsAffected implements driver.Result.RowsAffected.

type ResultDelete

type ResultDelete struct {
	// Successful flags if the operation was successful or not.
	Successful bool
	// StatusCode is the HTTP status code returned from CosmosDB.
	StatusCode int
}

ResultDelete captures the result from DELETE operation.

func (*ResultDelete) LastInsertId

func (r *ResultDelete) LastInsertId() (int64, error)

LastInsertId implements driver.Result.LastInsertId.

func (*ResultDelete) RowsAffected

func (r *ResultDelete) RowsAffected() (int64, error)

RowsAffected implements driver.Result.RowsAffected.

type ResultInsert

type ResultInsert struct {
	// Successful flags if the operation was successful or not.
	Successful bool
	// InsertId holds the "_rid" if the operation was successful.
	InsertId string
}

ResultInsert captures the result from INSERT operation.

func (*ResultInsert) LastInsertId

func (r *ResultInsert) LastInsertId() (int64, error)

LastInsertId implements driver.Result.LastInsertId.

func (*ResultInsert) RowsAffected

func (r *ResultInsert) RowsAffected() (int64, error)

RowsAffected implements driver.Result.RowsAffected.

type ResultSelect

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

ResultSelect captures the result from SELECT operation.

func (*ResultSelect) Close

func (r *ResultSelect) Close() error

Close implements driver.Rows.Close.

func (*ResultSelect) Columns

func (r *ResultSelect) Columns() []string

Columns implements driver.Rows.Columns.

func (*ResultSelect) Next

func (r *ResultSelect) Next(dest []driver.Value) error

Next implements driver.Rows.Next.

type ResultUpdate

type ResultUpdate struct {
	// Successful flags if the operation was successful or not.
	Successful bool
}

ResultUpdate captures the result from UPDATE operation.

func (*ResultUpdate) LastInsertId

func (r *ResultUpdate) LastInsertId() (int64, error)

LastInsertId implements driver.Result.LastInsertId.

func (*ResultUpdate) RowsAffected

func (r *ResultUpdate) RowsAffected() (int64, error)

RowsAffected implements driver.Result.RowsAffected.

type RowsListCollections

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

RowsListCollections captures the result from LIST COLLECTIONS operation.

func (*RowsListCollections) Close

func (r *RowsListCollections) Close() error

Close implements driver.Rows.Close.

func (*RowsListCollections) Columns

func (r *RowsListCollections) Columns() []string

Columns implements driver.Rows.Columns.

func (*RowsListCollections) Next

func (r *RowsListCollections) Next(dest []driver.Value) error

Next implements driver.Rows.Next.

type RowsListDatabases

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

RowsListDatabases captures the result from LIST DATABASES operation.

func (*RowsListDatabases) Close

func (r *RowsListDatabases) Close() error

Close implements driver.Rows.Close.

func (*RowsListDatabases) Columns

func (r *RowsListDatabases) Columns() []string

Columns implements driver.Rows.Columns.

func (*RowsListDatabases) Next

func (r *RowsListDatabases) Next(dest []driver.Value) error

Next implements driver.Rows.Next.

type Stmt

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

Stmt is Azure CosmosDB prepared statement handle.

func (*Stmt) Close

func (s *Stmt) Close() error

Close implements driver.Stmt.Close.

func (*Stmt) NumInput

func (s *Stmt) NumInput() int

NumInput implements driver.Stmt.NumInput.

type StmtAlterCollection

type StmtAlterCollection struct {
	*Stmt
	// contains filtered or unexported fields
}

StmtAlterCollection implements "ALTER COLLECTION" operation.

Syntax:

ALTER COLLECTION|TABLE [<db-name>.]<collection-name> WITH RU|MAXRU=<ru>

- ru: an integer specifying CosmosDB's collection throughput expressed in RU/s. Supply either RU or MAXRU, not both!

Available since v0.1.1

func (*StmtAlterCollection) Exec

Exec implements driver.Stmt.Exec. Upon successful call, this function returns (*ResultAlterCollection, nil).

func (*StmtAlterCollection) Query

func (s *StmtAlterCollection) Query(_ []driver.Value) (driver.Rows, error)

Query implements driver.Stmt.Query. This function is not implemented, use Exec instead.

type StmtAlterDatabase

type StmtAlterDatabase struct {
	*Stmt
	// contains filtered or unexported fields
}

StmtAlterDatabase implements "ALTER DATABASE" operation.

Syntax:

ALTER DATABASE <db-name> WITH RU|MAXRU=<ru>

- ru: an integer specifying CosmosDB's database throughput expressed in RU/s. Supply either RU or MAXRU, not both!

Available since v0.1.1

func (*StmtAlterDatabase) Exec

func (s *StmtAlterDatabase) Exec(_ []driver.Value) (driver.Result, error)

Exec implements driver.Stmt.Exec. Upon successful call, this function return (*ResultAlterDatabase, nil).

func (*StmtAlterDatabase) Query

func (s *StmtAlterDatabase) Query(_ []driver.Value) (driver.Rows, error)

Query implements driver.Stmt.Query. This function is not implemented, use Exec instead.

type StmtCreateCollection

type StmtCreateCollection struct {
	*Stmt
	// contains filtered or unexported fields
}

StmtCreateCollection implements "CREATE COLLECTION" operation.

Syntax:

CREATE COLLECTION|TABLE [IF NOT EXISTS] [<db-name>.]<collection-name> <WITH [LARGE]PK=partitionKey> [WITH RU|MAXRU=ru] [WITH UK=/path1:/path2,/path3;/path4]

- ru: an integer specifying CosmosDB's collection throughput expressed in RU/s. Supply either RU or MAXRU, not both!

- If "IF NOT EXISTS" is specified, Exec will silently swallow the error "409 Conflict".

- Use LARGEPK if partitionKey is larger than 100 bytes.

- Use UK to define unique keys. Each unique key consists a list of paths separated by comma (,). Unique keys are separated by colons (:) or semi-colons (;).

func (*StmtCreateCollection) Exec

Exec implements driver.Stmt.Exec. Upon successful call, this function returns (*ResultCreateCollection, nil).

func (*StmtCreateCollection) Query

func (s *StmtCreateCollection) Query(_ []driver.Value) (driver.Rows, error)

Query implements driver.Stmt.Query. This function is not implemented, use Exec instead.

type StmtCreateDatabase

type StmtCreateDatabase struct {
	*Stmt
	// contains filtered or unexported fields
}

StmtCreateDatabase implements "CREATE DATABASE" operation.

Syntax:

CREATE DATABASE [IF NOT EXISTS] <db-name> [WITH RU|MAXRU=ru]

- ru: an integer specifying CosmosDB's database throughput expressed in RU/s. Supply either RU or MAXRU, not both!

- If "IF NOT EXISTS" is specified, Exec will silently swallow the error "409 Conflict".

func (*StmtCreateDatabase) Exec

Exec implements driver.Stmt.Exec. Upon successful call, this function return (*ResultCreateDatabase, nil).

func (*StmtCreateDatabase) Query

func (s *StmtCreateDatabase) Query(_ []driver.Value) (driver.Rows, error)

Query implements driver.Stmt.Query. This function is not implemented, use Exec instead.

type StmtDelete

type StmtDelete struct {
	*Stmt
	// contains filtered or unexported fields
}

StmtDelete implements "DELETE" operation.

Syntax:

DELETE FROM <db-name>.<collection-name> WHERE id=<id-value>

- Currently DELETE only removes one document specified by id.

- <id-value> is treated as string. `WHERE id=abc` has the same effect as `WHERE id="abc"`.

func (*StmtDelete) Exec

func (s *StmtDelete) Exec(args []driver.Value) (driver.Result, error)

Exec implements driver.Stmt.Exec. This function always return nil driver.Result.

Note: this function expects the last argument is partition key value.

func (*StmtDelete) Query

func (s *StmtDelete) Query(args []driver.Value) (driver.Rows, error)

Query implements driver.Stmt.Query. This function is not implemented, use Exec instead.

type StmtDropCollection

type StmtDropCollection struct {
	*Stmt
	// contains filtered or unexported fields
}

StmtDropCollection implements "DROP COLLECTION" operation.

Syntax:

DROP COLLECTION|TABLE [IF EXISTS] [<db-name>.]<collection-name>

If "IF EXISTS" is specified, Exec will silently swallow the error "404 Not Found".

func (*StmtDropCollection) Exec

Exec implements driver.Stmt.Exec. This function always return a nil driver.Result.

func (*StmtDropCollection) Query

func (s *StmtDropCollection) Query(_ []driver.Value) (driver.Rows, error)

Query implements driver.Stmt.Query. This function is not implemented, use Exec instead.

type StmtDropDatabase

type StmtDropDatabase struct {
	*Stmt
	// contains filtered or unexported fields
}

StmtDropDatabase implements "DROP DATABASE" operation.

Syntax:

DROP DATABASE [IF EXISTS] <db-name>

- If "IF EXISTS" is specified, Exec will silently swallow the error "404 Not Found".

func (*StmtDropDatabase) Exec

func (s *StmtDropDatabase) Exec(_ []driver.Value) (driver.Result, error)

Exec implements driver.Stmt.Exec. This function always return a nil driver.Result.

func (*StmtDropDatabase) Query

func (s *StmtDropDatabase) Query(_ []driver.Value) (driver.Rows, error)

Query implements driver.Stmt.Query. This function is not implemented, use Exec instead.

type StmtInsert

type StmtInsert struct {
	*Stmt
	// contains filtered or unexported fields
}

StmtInsert implements "INSERT" operation.

Syntax:

INSERT|UPSERT INTO <db-name>.<collection-name> (<field-list>) VALUES (<value-list>)

- values are comma separated.
- a value is either:
  - a placeholder (e.g. :1, @2 or $3)
  - a null
  - a number
  - a boolean (true/false)
  - a string (inside double quotes) that must be a valid JSON, e.g.
    - a string value in JSON (include the double quotes): "\"a string\""
    - a number value in JSON (include the double quotes): "123"
    - a boolean value in JSON (include the double quotes): "true"
    - a null value in JSON (include the double quotes): "null"
    - a map value in JSON (include the double quotes): "{\"key\":\"value\"}"
    - a list value in JSON (include the double quotes): "[1,true,null,\"string\"]"

CosmosDB automatically creates a few extra fields for the insert document. See https://docs.microsoft.com/en-us/azure/cosmos-db/account-databases-containers-items#properties-of-an-item.

func (*StmtInsert) Exec

func (s *StmtInsert) Exec(args []driver.Value) (driver.Result, error)

Exec implements driver.Stmt.Exec. Upon successful call, this function returns (*ResultInsert, nil).

Note: this function expects the last argument is partition key value.

func (*StmtInsert) Query

func (s *StmtInsert) Query(args []driver.Value) (driver.Rows, error)

Query implements driver.Stmt.Query. This function is not implemented, use Exec instead.

type StmtListCollections

type StmtListCollections struct {
	*Stmt
	// contains filtered or unexported fields
}

StmtListCollections implements "LIST DATABASES" operation.

Syntax:

LIST COLLECTIONS|TABLES|COLLECTION|TABLE [FROM <db-name>]

func (*StmtListCollections) Exec

Exec implements driver.Stmt.Exec. This function is not implemented, use Query instead.

func (*StmtListCollections) Query

func (s *StmtListCollections) Query(_ []driver.Value) (driver.Rows, error)

Query implements driver.Stmt.Query.

type StmtListDatabases

type StmtListDatabases struct {
	*Stmt
}

StmtListDatabases implements "LIST DATABASES" operation.

Syntax:

LIST DATABASES|DATABASE

func (*StmtListDatabases) Exec

func (s *StmtListDatabases) Exec(_ []driver.Value) (driver.Result, error)

Exec implements driver.Stmt.Exec. This function is not implemented, use Query instead.

func (*StmtListDatabases) Query

func (s *StmtListDatabases) Query(_ []driver.Value) (driver.Rows, error)

Query implements driver.Stmt.Query.

type StmtSelect

type StmtSelect struct {
	*Stmt
	// contains filtered or unexported fields
}

StmtSelect implements "SELECT" operation. The "SELECT" query follows CosmosDB's SQL grammar (https://docs.microsoft.com/en-us/azure/cosmos-db/sql-query-select) with a few extensions:

Syntax:

SELECT [CROSS PARTITION] ... FROM <collection/table-name> ... WITH database|db=<db-name> [WITH collection|table=<collection/table-name>] [WITH cross_partition=true]

- (extension) If the collection is partitioned, specify "CROSS PARTITION" to allow execution across multiple partitions.
  This clause is not required if query is to be executed on a single partition.
  Cross-partition execution can also be enabled using WITH cross_partition=true.
- (extension) Use "WITH database=<db-name>" (or "WITH db=<db-name>") to specify the database on which the query is to be executed.
- (extension) Use "WITH collection=<coll-name>" (or "WITH table=<coll-name>") to specify the collection/table on which the query is to be executed.
  If not specified, collection/table name is extracted from the "FROM <collection/table-name>" clause.
- (extension) Use placeholder syntax @i, $i or :i (where i denotes the i-th parameter, the first parameter is 1)

func (*StmtSelect) Exec

func (s *StmtSelect) Exec(args []driver.Value) (driver.Result, error)

Exec implements driver.Stmt.Exec. This function is not implemented, use Query instead.

func (*StmtSelect) Query

func (s *StmtSelect) Query(args []driver.Value) (driver.Rows, error)

Query implements driver.Stmt.Query. Upon successful call, this function returns (*ResultSelect, nil).

type StmtUpdate

type StmtUpdate struct {
	*Stmt
	// contains filtered or unexported fields
}

StmtUpdate implements "UPDATE" operation.

Syntax:

UPDATE <db-name>.<collection-name> SET <field-name>=<value>[,<field-name>=<value>]*, WHERE id=<id-value>

- <id-value> is treated as a string. `WHERE id=abc` has the same effect as `WHERE id="abc"`.
- <value> is either:
  - a placeholder (e.g. :1, @2 or $3)
  - a null
  - a number
  - a boolean (true/false)
  - a string (inside double quotes) that must be a valid JSON, e.g.
    - a string value in JSON (include the double quotes): "\"a string\""
    - a number value in JSON (include the double quotes): "123"
    - a boolean value in JSON (include the double quotes): "true"
    - a null value in JSON (include the double quotes): "null"
    - a map value in JSON (include the double quotes): "{\"key\":\"value\"}"
    - a list value in JSON (include the double quotes): "[1,true,null,\"string\"]"

Currently UPDATE only updates one document specified by id.

func (*StmtUpdate) Exec

func (s *StmtUpdate) Exec(args []driver.Value) (driver.Result, error)

Exec implements driver.Stmt.Exec. Upon successful call, this function returns (*ResultUpdate, nil).

Note: this function expects the last argument is partition key value.

func (*StmtUpdate) Query

func (s *StmtUpdate) Query(args []driver.Value) (driver.Rows, error)

Query implements driver.Stmt.Query. This function is not implemented, use Exec instead.

Jump to

Keyboard shortcuts

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