gocosmos

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 13, 2024 License: MIT Imports: 29 Imported by: 8

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 is also included.

database/sql driver

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 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 calls.

Example usage:
package main

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

Note: line-break is for readability only!

AccountEndpoint=<cosmosdb-endpoint>
;AccountKey=<cosmosdb-account-key>
[;TimeoutMs=<timeout-in-ms>]
[;Version=<cosmosdb-api-version>]
[;DefaultDb|Db=<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 2020-07-15 if not specified. See: https://learn.microsoft.com/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 Data Source Name (for database/sql driver) or the connection string (for REST client). If not specified, default value is AutoId=true.

This setting is available since v0.1.2.

Known issues

GROUP BY combined with ORDER BY is not supported

Azure Cosmos DB does not support GROUP BY combined with ORDER BY yet. You will receive the following error message:

'ORDER BY' is not supported in presence of GROUP BY.

Cross-partition paging

Cross-partition paging can be done with the OFFSET...LIMIT clause. However, the query is not stable without ORDER BY. The returned results may not be consistent from query to query.

Queries that may consume a large amount of memory

These queries may consume a large amount of memory if executed against a large table:

  • OFFSET...LIMIT clause with big offset or limit values.
  • SELECT DISTINCT and SELECT DISTINCT VALUE queries.
  • Queries with GROUP BY clause.

REST client

See the REST.md file for details.

License

This project is licensed under the MIT License - see the LICENSE.md file for details.

Support and Contribution

Disclaimer: I am also a core maintainer of microsoft/gocosmos. Features and bug fixes are synchronized between the two projects.

This project uses GitHub Issues to track bugs and feature requests. Please search the existing issues before filing new issues to avoid duplicates. For new issues, file your bug or feature request as a new Issue.

Please create pull requests in the microsoft/gocosmos repository.

If you find this project useful, please start it.

Documentation

Overview

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

Index

Constants

View Source
const (

	// DefaultApiVersion holds the default REST API version if not specified in the connection string.
	//
	// See: https://learn.microsoft.com/en-us/rest/api/cosmos-db/#supported-rest-api-versions
	//
	// @Available since v0.3.0
	DefaultApiVersion = "2020-07-15"
)
View Source
const (
	// Version holds the semantic version number of package gocosmos.
	Version = "1.1.0"
)

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")

	// ErrPreconditionFailure is returned when operation specified an eTag that is different from the version available
	// at the server, that is, an optimistic concurrency error.
	//
	// @Available since v0.2.1
	ErrPreconditionFailure = errors.New("StatusCode=412 Precondition failure")

	// ErrOperationNotSupported is returned to indicate that the operation is not supported.
	//
	// @Available since v0.2.1
	ErrOperationNotSupported = errors.New("this operation is not supported")

	// ErrExecNotSupported is returned to indicate that the Exec/ExecContext operation is not supported.
	//
	// @Available since v0.2.1
	ErrExecNotSupported = errors.New("this operation is not supported, please use Query")

	// ErrQueryNotSupported is returned to indicate that the Query/QueryContext operation is not supported.
	//
	// @Available since v0.2.1
	ErrQueryNotSupported = errors.New("this operation is not supported, please use Exec")
)

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             PkInfo                 `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 Cosmos DB 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 Cosmos DB collection specifications for creation.

type Conn

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

Conn is Azure Cosmos DB implementation of driver.Conn.

func (*Conn) Begin

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

Begin implements driver.Conn/Begin.

func (*Conn) BeginTx added in v1.0.0

func (c *Conn) BeginTx(_ context.Context, _ driver.TxOptions) (driver.Tx, error)

BeginTx implements driver.ConnBeginTx/BeginTx.

@Available since v0.2.1

func (*Conn) CheckNamedValue

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

CheckNamedValue implements driver.NamedValueChecker/CheckNamedValue.

func (*Conn) Close

func (c *Conn) Close() error

Close implements driver.Conn/Close.

func (*Conn) Ping added in v1.1.0

func (c *Conn) Ping(_ context.Context) error

Ping implements driver.Pinger/Ping.

@Available since v1.1.0

func (*Conn) Prepare

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

Prepare implements driver.Conn/Prepare.

func (*Conn) PrepareContext added in v1.0.0

func (c *Conn) PrepareContext(_ context.Context, query string) (driver.Stmt, error)

PrepareContext implements driver.ConnPrepareContext/PrepareContext.

@Available since v0.2.1

func (*Conn) String added in v1.1.0

func (c *Conn) String() string

String implements fmt.Stringer/String.

@Available since v1.1.0

type Connector added in v1.1.0

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

Connector is Azure Cosmos DB implementation of driver.Connector.

@Available since v1.1.0

func (*Connector) Connect added in v1.1.0

func (c *Connector) Connect(_ context.Context) (driver.Conn, error)

Connect implements driver.Connector/Connect.

func (*Connector) Driver added in v1.1.0

func (c *Connector) Driver() driver.Driver

Driver implements driver.Connector/Driver.

func (*Connector) String added in v1.1.0

func (c *Connector) String() string

String implements fmt.Stringer/String.

type DatabaseSpec

type DatabaseSpec struct {
	Id        string
	Ru, MaxRu int
}

DatabaseSpec specifies a Cosmos DB 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 Cosmos DB database.

type DocInfo

type DocInfo map[string]interface{}

DocInfo is a Cosmos DB document.

func (DocInfo) AsMap added in v1.0.0

func (d DocInfo) AsMap() map[string]interface{}

AsMap return the document as [string]interface{}

Available since v0.1.9

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       DocInfo
}

DocumentSpec specifies a Cosmos DB document specifications for creation.

type Driver

type Driver struct {
}

Driver is Azure Cosmos DB implementation of driver.Driver.

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>][;InsecureSkipVerify=<true/false>]

If not supplied, default value for TimeoutMs is 10 seconds, Version is DefaultApiVersion (which is "2020-07-15"), AutoId is true, and InsecureSkipVerify is false

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

func (*Driver) OpenConnector added in v1.1.0

func (d *Driver) OpenConnector(connStr string) (driver.Connector, error)

OpenConnector implements driver.DriverContext/OpenConnector.

@Available since v1.1.0

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
	PkRangeId         string
	IsIncrementalFeed bool // (available since v0.1.9) if "true", the request is used to fetch the incremental changes to documents within the collection
}

ListDocsReq specifies a list documents request.

type OfferInfo added in v0.1.1

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 Cosmos DB offer.

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

func (OfferInfo) IsAutopilot added in v0.1.1

func (o OfferInfo) IsAutopilot() bool

IsAutopilot returns true if autopilot is enabled, false otherwise.

func (OfferInfo) MaxThroughputEverProvisioned added in v0.1.1

func (o OfferInfo) MaxThroughputEverProvisioned() int

MaxThroughputEverProvisioned returns value of field 'maxThroughputEverProvisioned'

func (OfferInfo) OfferThroughput added in v0.1.1

func (o OfferInfo) OfferThroughput() int

OfferThroughput returns value of field 'offerThroughput'

type PkInfo added in v1.0.0

type PkInfo map[string]interface{}

PkInfo holds partitioning configuration settings for a collection.

@Available since v0.3.0

func (PkInfo) Kind added in v1.0.0

func (pk PkInfo) Kind() string

func (PkInfo) Paths added in v1.0.0

func (pk PkInfo) Paths() []string

func (PkInfo) Version added in v1.0.0

func (pk PkInfo) Version() int

type PkrangeInfo added in v0.1.3

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 QueriedDocs added in v1.0.0

type QueriedDocs []interface{}

QueriedDocs is list of returned documents from a query such as result from RestClient.QueryDocuments call. A query can return a list of documents or a list of scalar values.

Available since v0.1.9

func (QueriedDocs) AsDocInfoAt added in v1.0.0

func (docs QueriedDocs) AsDocInfoAt(i int) DocInfo

AsDocInfoAt returns the i-th queried document as a DocInfo.

func (QueriedDocs) AsDocInfoSlice added in v1.0.0

func (docs QueriedDocs) AsDocInfoSlice() []DocInfo

AsDocInfoSlice returns the queried documents as []DocInfo.

func (QueriedDocs) Flatten added in v1.0.0

func (docs QueriedDocs) Flatten(queryPlan *RespQueryPlan) QueriedDocs

Flatten transforms result from execution of a rewritten query to the non-rewritten form.

Available since v0.2.0

func (QueriedDocs) Merge added in v1.0.0

func (docs QueriedDocs) Merge(queryPlan *RespQueryPlan, otherDocs QueriedDocs) QueriedDocs

Merge merges this document list with another using the rule determined by supplied query plan and returns the merged list.

Available since v0.2.0

func (QueriedDocs) ReduceDistinct added in v1.0.0

func (docs QueriedDocs) ReduceDistinct(queryPlan *RespQueryPlan) QueriedDocs

ReduceDistinct removes duplicated rows from a SELECT DISTINCT query.

Available since v0.2.0

func (QueriedDocs) ReduceGroupBy added in v1.0.0

func (docs QueriedDocs) ReduceGroupBy(queryPlan *RespQueryPlan) QueriedDocs

ReduceGroupBy merge rows returned from a SELECT...GROUP BY "rewritten" query.

Available since v0.2.0

type QueryReq

type QueryReq struct {
	DbName, CollName      string
	Query                 string
	Params                []interface{}
	MaxItemCount          int    // if max-item-count = 0: use server side default value, (since v0.1.8) if max-item-count < 0: client will fetch all returned documents from server
	PkRangeId             string // (since v0.1.8) if non-empty, query will perform only on this PkRangeId (if PkRangeId and PkValue are specified, PkRangeId takes priority)
	PkValue               string // (since v0.1.8) if non-empty, query will perform only on the partition that PkValue maps to (if PkRangeId and PkValue are specified, PkRangeId takes priority)
	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 {
	RestResponse
	CollInfo
}

RespCreateColl captures the response from RestClient.CreateCollection call.

type RespCreateDb

type RespCreateDb struct {
	RestResponse
	DbInfo
}

RespCreateDb captures the response from RestClient.CreateDatabase call.

type RespCreateDoc

type RespCreateDoc struct {
	RestResponse
	DocInfo
}

RespCreateDoc captures the response from RestClient.CreateDocument call.

type RespDeleteColl

type RespDeleteColl struct {
	RestResponse
}

RespDeleteColl captures the response from RestClient.DeleteCollection call.

type RespDeleteDb

type RespDeleteDb struct {
	RestResponse
}

RespDeleteDb captures the response from RestClient.DeleteDatabase call.

type RespDeleteDoc

type RespDeleteDoc struct {
	RestResponse
}

RespDeleteDoc captures the response from RestClient.DeleteDocument call.

type RespGetColl

type RespGetColl struct {
	RestResponse
	CollInfo
}

RespGetColl captures the response from RestClient.GetCollection call.

type RespGetDb

type RespGetDb struct {
	RestResponse
	DbInfo
}

RespGetDb captures the response from RestClient.GetDatabase call.

type RespGetDoc

type RespGetDoc struct {
	RestResponse
	DocInfo
}

RespGetDoc captures the response from RestClient.GetDocument call.

type RespGetOffer added in v0.1.1

type RespGetOffer struct {
	RestResponse
	OfferInfo
}

RespGetOffer captures the response from RestClient.GetOffer call.

type RespGetPkranges added in v0.1.3

type RespGetPkranges struct {
	RestResponse `json:"-"`
	Pkranges     []PkrangeInfo `json:"PartitionKeyRanges"`
	Count        int           `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 {
	RestResponse `json:"-"`
	Count        int        `json:"_count"` // number of collections returned from the list operation
	Collections  []CollInfo `json:"DocumentCollections"`
}

RespListColl captures the response from RestClient.ListCollections call.

type RespListDb

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

RespListDb captures the response from RestClient.ListDatabases call.

type RespListDocs

type RespListDocs struct {
	RestResponse      `json:"-"`
	Count             int       `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 RestClient.ListDocuments call.

type RespQueryDocs

type RespQueryDocs struct {
	RestResponse       `json:"-"`
	Count              int            `json:"_count"` // number of documents returned from the operation
	Documents          QueriedDocs    `json:"Documents"`
	ContinuationToken  string         `json:"-"`
	QueryPlan          *RespQueryPlan `json:"-"` // (available since v0.2.0) the query plan used to execute the query
	RewrittenDocuments QueriedDocs    `json:"-"` // (available since v0.2.0) the original returned documents from the execution of RespQueryPlan.QueryInfo.RewrittenQuery
}

RespQueryDocs captures the response from RestClient.QueryDocuments call.

type RespQueryOffers added in v0.1.1

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

RespQueryOffers captures the response from RestClient.QueryOffers call.

type RespQueryPlan added in v0.1.8

type RespQueryPlan struct {
	RestResponse              `json:"-"`
	QueryExecutionInfoVersion int `json:"partitionedQueryExecutionInfoVersion"`
	QueryInfo                 struct {
		DistinctType                string            `json:"distinctType"` // possible values: None, Ordered, Unordered
		Top                         int               `json:"top"`
		Offset                      int               `json:"offset"`
		Limit                       int               `json:"limit"`
		OrderBy                     []string          `json:"orderBy"` // possible values: Ascending, Descending
		OrderByExpressions          []string          `json:"orderByExpressions"`
		GroupByExpressions          []string          `json:"groupByExpressions"`
		GroupByAliases              []string          `json:"groupByAliases"`
		Aggregates                  []string          `json:"aggregates"` // possible values: Average, Count, Max, Min, Sum
		GroupByAliasToAggregateType map[string]string `json:"groupByAliasToAggregateType"`
		RewrittenQuery              string            `json:"rewrittenQuery"`
		HasSelectValue              bool              `json:"hasSelectValue"`
		DCountInfo                  typDCountInfo     `json:"dCountInfo"`
	} `json:"queryInfo"`
}

RespQueryPlan captures the response from QueryPlan call.

Available since v0.1.8

func (*RespQueryPlan) IsDistinctQuery added in v1.0.0

func (qp *RespQueryPlan) IsDistinctQuery() bool

IsDistinctQuery tests if duplicates are eliminated in the query's projection.

Available v0.1.9

func (*RespQueryPlan) IsGroupByQuery added in v1.0.0

func (qp *RespQueryPlan) IsGroupByQuery() bool

IsGroupByQuery tests if "group-by" aggregation is in the query's projection.

Available v0.1.9

func (*RespQueryPlan) IsOrderByQuery added in v1.0.0

func (qp *RespQueryPlan) IsOrderByQuery() bool

IsOrderByQuery tests if "order-by" clause is in the query's projection.

Available v0.1.9

type RespReplaceColl

type RespReplaceColl struct {
	RestResponse
	CollInfo
}

RespReplaceColl captures the response from RestClient.ReplaceCollection call.

type RespReplaceDoc

type RespReplaceDoc struct {
	RestResponse
	DocInfo
}

RespReplaceDoc captures the response from RestClient.ReplaceDocument call.

type RespReplaceOffer added in v0.1.1

type RespReplaceOffer struct {
	RestResponse
	OfferInfo
}

RespReplaceOffer captures the response from RestClient.ReplaceOffer call.

type RestClient

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

RestClient is REST-based client for Azure Cosmos DB

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 DefaultApiVersion (which is "2020-07-15"), 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 Cosmos DB 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 Cosmos DB 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 Cosmos DB 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 Cosmos DB 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 Cosmos DB 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 Cosmos DB API to delete an existing document.

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

func (*RestClient) GetApiVersion added in v1.0.0

func (c *RestClient) GetApiVersion() string

GetApiVersion returns the Azure Cosmos DB APi version string, either from connection string or default value.

@Available since v1.0.0

func (*RestClient) GetAutoId added in v1.0.0

func (c *RestClient) GetAutoId() bool

GetAutoId returns the auto-id flag.

@Available since v1.0.0

func (*RestClient) GetCollection

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

GetCollection invokes Cosmos DB 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 Cosmos DB 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 Cosmos DB API to get an existing document.

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

func (*RestClient) GetOfferForResource added in v0.1.1

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

GetOfferForResource invokes Cosmos DB API to get offer info of a resource.

Available since v0.1.1

func (*RestClient) GetPkranges added in v0.1.3

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

GetPkranges invokes Cosmos DB 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 Cosmos DB 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 Cosmos DB 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 Cosmos DB API to query read-feed for documents.

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

Note: if fetching incremental feed (ListDocsReq.IsIncrementalFeed = true), it is the caller responsibility to resubmit the request with proper value of etag (ListDocsReq.NotMatchEtag)

func (*RestClient) QueryDocuments

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

QueryDocuments invokes Cosmos DB API to query a collection for documents.

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

Known issues:

  • (*) `GROUP BY` with `ORDER BY` queries are currently not supported by Cosmos DB! Resolution/Workaround: NONE!
  • Paging a cross-partition `OFFSET...LIMIT` query using QueryReq.MaxItemCount: it would not work. Moreover, the result returned from QueryDocumentsCrossPartition might be different from or the one returned from call to QueryDocuments without pagination. Resolution/Workaround: NONE!
  • Paging a cross-partition `ORDER BY` query using QueryReq.MaxItemCount would not work: returned rows might not be in the expected order. Resolution/Workaround: use QueryDocumentsCrossPartition or QueryDocuments without paging (caution: intermediate results are kept in memory, be alerted for out-of-memory error).
  • Paging a cross-partition `SELECT DISTINCT/VALUE` query using QueryReq.MaxItemCount would not work: returned rows might be duplicated. Resolution/Workaround: use QueryDocumentsCrossPartition or QueryDocuments without paging (caution: intermediate results are kept in memory, be alerted for out-of-memory error).
  • Cross-partition queries that combine `GROUP BY` with QueryReq.MaxItemCount would not work: the aggregate function might not work properly. Resolution/Workaround: use QueryDocumentsCrossPartition or QueryDocuments without QueryReq.MaxItemCount (caution: intermediate results are kept in memory, be alerted for out-of-memory error).

func (*RestClient) QueryDocumentsCrossPartition added in v1.0.0

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

QueryDocumentsCrossPartition can be used as a workaround for known issues with QueryDocuments.

Caution: intermediate results are kept in memory, and all matched rows are returned. Be alerted for out-of-memory error!

Available since v0.2.0

func (*RestClient) QueryOffers added in v0.1.1

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

QueryOffers invokes Cosmos DB 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) QueryPlan added in v0.1.8

func (c *RestClient) QueryPlan(query QueryReq) *RespQueryPlan

QueryPlan invokes Cosmos DB API to generate query plan.

Available since v0.1.8

func (*RestClient) ReplaceCollection

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

ReplaceCollection invokes Cosmos DB 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 Cosmos DB API to replace an existing document.

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

func (*RestClient) ReplaceOfferForResource added in v0.1.1

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

ReplaceOfferForResource invokes Cosmos DB 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

func (*RestClient) SetAutoId added in v1.0.0

func (c *RestClient) SetAutoId(value bool) *RestClient

SetAutoId sets value for the auto-id flag.

@Available since v1.0.0

type RestResponse added in v1.0.0

type RestResponse 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
}

RestResponse captures the response from REST API call.

func (RestResponse) Error added in v1.0.0

func (r RestResponse) Error() error

Error returns CallErr if not nil, ApiErr otherwise.

type ResultNoResultSet added in v1.0.0

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

ResultNoResultSet captures the result from statements that do not expect a ResultSet to be returned.

@Available since v0.2.1

func (*ResultNoResultSet) LastInsertId added in v1.0.0

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

LastInsertId implements driver.Result/LastInsertId.

func (*ResultNoResultSet) RowsAffected added in v1.0.0

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

RowsAffected implements driver.Result/RowsAffected.

type ResultResultSet added in v1.0.0

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

ResultResultSet captures the result from statements that expect a ResultSet to be returned.

@Available since v0.2.1

func (*ResultResultSet) Close added in v1.0.0

func (r *ResultResultSet) Close() error

Close implements driver.Rows/Close.

func (*ResultResultSet) ColumnTypeDatabaseTypeName added in v1.0.0

func (r *ResultResultSet) ColumnTypeDatabaseTypeName(index int) string

ColumnTypeDatabaseTypeName implements driver.RowsColumnTypeDatabaseTypeName/ColumnTypeDatabaseTypeName

func (*ResultResultSet) ColumnTypeScanType added in v1.0.0

func (r *ResultResultSet) ColumnTypeScanType(index int) reflect.Type

ColumnTypeScanType implements driver.RowsColumnTypeScanType/ColumnTypeScanType

func (*ResultResultSet) Columns added in v1.0.0

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

Columns implements driver.Rows/Columns.

func (*ResultResultSet) Next added in v1.0.0

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

Next implements driver.Rows/Next.

type Stmt

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

Stmt is Azure Cosmos DB abstract implementation of driver.Stmt.

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.

func (*Stmt) String added in v1.1.0

func (s *Stmt) String() string

String implements interface fmt.Stringer/String.

@Available since v1.1.0

type StmtAlterCollection added in v0.1.1

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

StmtAlterCollection implements "ALTER COLLECTION" statement.

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 added in v0.1.1

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

Exec implements driver.Stmt/Exec.

func (*StmtAlterCollection) ExecContext added in v1.1.0

func (s *StmtAlterCollection) ExecContext(_ context.Context, args []driver.NamedValue) (driver.Result, error)

ExecContext implements driver.StmtExecContext/ExecContext.

@Available since v1.1.0

func (*StmtAlterCollection) Query added in v0.1.1

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

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

func (*StmtAlterCollection) String added in v1.1.0

func (s *StmtAlterCollection) String() string

String implements fmt.Stringer/String.

@Available since v1.1.0

type StmtAlterDatabase added in v0.1.1

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

StmtAlterDatabase implements "ALTER DATABASE" statement.

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 added in v0.1.1

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

Exec implements driver.Stmt/Exec.

func (*StmtAlterDatabase) ExecContext added in v1.1.0

func (s *StmtAlterDatabase) ExecContext(_ context.Context, args []driver.NamedValue) (driver.Result, error)

ExecContext implements driver.StmtExecContext/ExecContext.

@Available since v1.1.1

func (*StmtAlterDatabase) Query added in v0.1.1

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

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

func (*StmtAlterDatabase) String added in v1.1.0

func (s *StmtAlterDatabase) String() string

String implements fmt.Stringer/String.

@Available since v1.1.0

type StmtCRUD added in v1.0.0

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

StmtCRUD is abstract implementation of "INSERT|UPSERT|UPDATE|DELETE|SELECT" operations.

@Available since v0.3.0

func (*StmtCRUD) String added in v1.1.0

func (s *StmtCRUD) String() string

String implements interface fmt.Stringer/String.

@Available since v1.1.0

type StmtCreateCollection

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

StmtCreateCollection implements "CREATE COLLECTION" statement.

Syntax:

CREATE COLLECTION|TABLE [IF NOT EXISTS] [<db-name>.]<collection-name>
<WITH 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!

- partitionKey is either single (single value of /path) or hierarchical, up to 3 path levels, levels are separated by commas, for example: /path1,/path2,/path3.

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

- 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

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

Exec implements driver.Stmt/Exec.

func (*StmtCreateCollection) ExecContext added in v1.1.0

func (s *StmtCreateCollection) ExecContext(_ context.Context, args []driver.NamedValue) (driver.Result, error)

ExecContext implements driver.StmtExecContext/ExecContext.

@Available since v1.1.0

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.

func (*StmtCreateCollection) String added in v1.1.0

func (s *StmtCreateCollection) String() string

String implements fmt.Stringer/String.

@Available since v1.1.0

type StmtCreateDatabase

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

StmtCreateDatabase implements "CREATE DATABASE" statement.

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

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

Exec implements driver.Stmt/Exec.

func (*StmtCreateDatabase) ExecContext added in v1.1.0

func (s *StmtCreateDatabase) ExecContext(_ context.Context, args []driver.NamedValue) (driver.Result, error)

ExecContext implements driver.StmtExecContext/ExecContext.

@Available since v1.1.0

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.

func (*StmtCreateDatabase) String added in v1.1.0

func (s *StmtCreateDatabase) String() string

String implements fmt.Stringer/String.

@Available since v1.1.0

type StmtDelete

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

StmtDelete implements "DELETE" operation.

Syntax:

DELETE FROM <db-name>.<collection-name>
WHERE id=<id-value>
[AND pk1-path=<pk1-value> [AND pk2-path=<pk2-value> ...]]

- DELETE removes only one document specified by 'id'.
- The clause WHERE id=<id-value> is mandatory, and 'id' is a keyword, _not_ a field name.
- <id-value> and <pk-value> must be a placeholder (e.g. :1, @2 or $3), or JSON value.
- Supplying pk-paths and pk-values is highly recommended to save one round-trip to server to fetch the collection's partition key info.
- If collection's PK has more than one path (i.e. sub-partition is used), the partition paths must be specified in the same order as in the collection (.e.g. AND field1=value1 AND field2=value2...).

See StmtInsert for details on <id-value> and <pk-value>.

func (*StmtDelete) Exec

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

Exec implements driver.Stmt/Exec.

func (*StmtDelete) ExecContext added in v1.1.0

func (s *StmtDelete) ExecContext(_ context.Context, args []driver.NamedValue) (driver.Result, error)

ExecContext implements driver.StmtExecContext/ExecContext.

@Available since v1.1.0

func (*StmtDelete) Query

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

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

func (*StmtDelete) String added in v1.1.0

func (s *StmtDelete) String() string

String implements interface fmt.Stringer/String.

@Available since v1.1.0

type StmtDropCollection

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

StmtDropCollection implements "DROP COLLECTION" statement.

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

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

Exec implements driver.Stmt/Exec.

func (*StmtDropCollection) ExecContext added in v1.1.0

func (s *StmtDropCollection) ExecContext(_ context.Context, args []driver.NamedValue) (driver.Result, error)

ExecContext implements driver.StmtExecContext/ExecContext.

@Available since v1.1.0

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.

func (*StmtDropCollection) String added in v1.1.0

func (s *StmtDropCollection) String() string

String implements fmt.Stringer/String.

@Available since v1.1.0

type StmtDropDatabase

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

StmtDropDatabase implements "DROP DATABASE" statement.

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(args []driver.Value) (driver.Result, error)

Exec implements driver.Stmt/Exec.

func (*StmtDropDatabase) ExecContext added in v1.1.0

func (s *StmtDropDatabase) ExecContext(_ context.Context, args []driver.NamedValue) (driver.Result, error)

ExecContext implements driver.StmtExecContext/ExecContext.

@Available since v1.1.0

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.

func (*StmtDropDatabase) String added in v1.1.0

func (s *StmtDropDatabase) String() string

String implements fmt.Stringer/String.

@Available since v1.1.0

type StmtInsert

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

StmtInsert implements "INSERT" operation.

Syntax:

INSERT|UPSERT INTO <db-name>.<collection-name>
(<field-list>)
VALUES (<value-list>)
[WITH PK=/pk-path]

- 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\"]"

- Using WITH PK is highly recommended to save one round-trip to server to fetch the collection's partition key info.
- If collection's PK has more than one path (i.e. sub-partition is used), the partition paths are comma separated, prefixed with '/', and must be specified in the same order as in the collection (.e.g. WITH PK=/field1,/field2...).

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.

func (*StmtInsert) ExecContext added in v1.1.0

func (s *StmtInsert) ExecContext(_ context.Context, args []driver.NamedValue) (driver.Result, error)

ExecContext implements driver.StmtExecContext/ExecContext.

@Available since v1.1.0

func (*StmtInsert) Query

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

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

func (*StmtInsert) String added in v1.1.0

func (s *StmtInsert) String() string

String implements interface fmt.Stringer/String.

@Available since v1.1.0

type StmtListCollections

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

StmtListCollections implements "LIST DATABASES" statement.

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(args []driver.Value) (driver.Rows, error)

Query implements driver.Stmt/Query.

func (*StmtListCollections) QueryContext added in v1.1.0

func (s *StmtListCollections) QueryContext(_ context.Context, args []driver.NamedValue) (driver.Rows, error)

QueryContext implements driver.StmtQueryContext/QueryContext.

@Available since v1.1.0

func (*StmtListCollections) String added in v1.1.0

func (s *StmtListCollections) String() string

String implements fmt.Stringer/String.

@Available since v1.1.0

type StmtListDatabases

type StmtListDatabases struct {
	*Stmt
}

StmtListDatabases implements "LIST DATABASES" statement.

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(args []driver.Value) (driver.Rows, error)

Query implements driver.Stmt/Query.

func (*StmtListDatabases) QueryContext added in v1.1.0

func (s *StmtListDatabases) QueryContext(_ context.Context, args []driver.NamedValue) (driver.Rows, error)

QueryContext implements driver.StmtQueryContext/QueryContext.

@Available since v1.1.0

func (*StmtListDatabases) String added in v1.1.0

func (s *StmtListDatabases) String() string

String implements fmt.Stringer/String.

@Available since v1.1.0

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|CrossPartition[=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(_ []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.

func (*StmtSelect) QueryContext added in v1.1.0

func (s *StmtSelect) QueryContext(_ context.Context, args []driver.NamedValue) (driver.Rows, error)

QueryContext implements driver.StmtQueryContext/QueryContext.

@Available since v1.1.0

func (*StmtSelect) String added in v1.1.0

func (s *StmtSelect) String() string

String implements interface fmt.Stringer/String.

@Available since v1.1.0

type StmtUpdate

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

StmtUpdate implements "UPDATE" operation.

Syntax:

UPDATE <db-name>.<collection-name>
SET <field-name1>=<value1>[,<field-nameN>=<valueN>]*
WHERE id=<id-value>
[AND pk1-path=<pk1-value> [AND pk2-path=<pk2-value> ...]]

- UPDATE modifies only one document specified by 'id'.
- The clause WHERE id=<id-value> is mandatory, and 'id' is a keyword, _not_ a field name.
- <id-value> and <pk-value> must be a placeholder (e.g. :1, @2 or $3), or JSON value.
- Supplying pk-paths and pk-values is highly recommended to save one round-trip to server to fetch the collection's partition key info.
- If collection's PK has more than one path (i.e. sub-partition is used), the partition paths must be specified in the same order as in the collection (.e.g. AND field1=value1 AND field2=value2...).

See StmtInsert for details on <id-value> and <pk-value>.

func (*StmtUpdate) Exec

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

Exec implements driver.Stmt/Exec.

func (*StmtUpdate) ExecContext added in v1.1.0

func (s *StmtUpdate) ExecContext(_ context.Context, args []driver.NamedValue) (driver.Result, error)

ExecContext implements driver.StmtExecContext/ExecContext.

@Available since v1.1.0

func (*StmtUpdate) Query

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

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

func (*StmtUpdate) String added in v1.1.0

func (s *StmtUpdate) String() string

String implements interface fmt.Stringer/String.

@Available since v1.1.0

Jump to

Keyboard shortcuts

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