ravendb

package module
Version: v0.0.0-...-8c32f0a Latest Latest
Warning

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

Go to latest
Published: Mar 29, 2022 License: MIT Imports: 34 Imported by: 3

README

Linux build Status Windows build status

This is information on how to use the library. For docs on working on the library itself see readme-dev.md.

This library requires go 1.11 or later.

API reference: https://godoc.org/github.com/ravendb/ravendb-go-client

This library is in beta state. All the basic functionality works and passes extensive test suite, but the API for more esoteric features might change.

If you encounter bugs, have suggestions or feature requests, please open an issue.

Documentation

To learn basics of RavenDB, read RavenDB Documentation or Dive into RavenDB.

Getting started

Full source code of those examples is in examples directory.

To run a a specific example, e.g. crudStore, you can run:

  • .\scripts\run_example.ps1 crudStore : works on mac / linux if you have powershell installed
  • go run examples\log.go examples\main.go crudStore : on mac / linux change paths to examples/log.go etc.
  1. Import the package
import (
	ravendb "github.com/ravendb/ravendb-go-client"
)
  1. Initialize document store (you should have one DocumentStore instance per application)
func getDocumentStore(databaseName string) (*ravendb.DocumentStore, error) {
	serverNodes := []string{"http://live-test.ravendb.net"}
	store := ravendb.NewDocumentStore(serverNodes, databaseName)
	if err := store.Initialize(); err != nil {
		return nil, err
	}
	return store, nil
}

To setup an document store with security, you'll need to provide the client certificate for authentication. Here is how to setup a document store with a certificate:

func getDocumentStore(databaseName string) (*ravendb.DocumentStore, error) {
	cerPath := "/path/to/certificate.crt"
	keyPath := "/path/to/certificate.key"
	serverNodes := []string{"https://a.tasty.ravendb.run", 
		"https://b.tasty.ravendb.run", "https://c.tasty.ravendb.run"}

	cer, err := tls.LoadX509KeyPair(cerPath, keyPath)
	if err != nil {
		return nil, err
	}
	store := ravendb.NewDocumentStore(serverNodes, databaseName)
	store.Certificate = &cer
	x509cert, err :=  x509.ParseCertificate(cer.Certificate[0])
	if err != nil {
		return nil, err
	}
	store.TrustStore = x509cert
	if err := store.Initialize(); err != nil {
		return nil, err
	}
	return store, nil
}

If you are using an encrypted certificate, see the sample code on how to translate that to tls.Certificate here: https://play.golang.org/p/8OYTuZtZIQ

  1. Open a session and close it when done
session, err = store.OpenSession()
if err != nil {
	log.Fatalf("store.OpenSession() failed with %s", err)
}
// ... use session
session.Close()
  1. Call SaveChanges() to persist changes in a session:
var e *northwind.Employee
err = session.Load(&e, "employees/7-A")
if err != nil {
    log.Fatalf("session.Load() failed with %s\n", err)
}

origName := e.FirstName
e.FirstName = e.FirstName + "Changed"
err = session.Store(e)
if err != nil {
    log.Fatalf("session.Store() failed with %s\n", err)
}

err = session.SaveChanges()
if err != nil {
    log.Fatalf("session.SaveChanges() failed with %s\n", err)
}

var e2 *northwind.Employee
err = session.Load(&e2, "employees/7-A")
if err != nil {
    log.Fatalf("session.Load() failed with %s\n", err)
}
fmt.Printf("Updated Employee.FirstName from '%s' to '%s'\n", origName, e2.FirstName)

See loadUpdateSave() in examples/main.go for full example.

CRUD example

Storing documents

product := &northwind.Product{
    Name:         "iPhone X",
    PricePerUnit: 999.99,
    Category:     "electronis",
    ReorderLevel: 15,
}
err = session.Store(product)
if err != nil {
    log.Fatalf("session.Store() failed with %s\n", err)
}

See crudStore() in examples/main.go for full example.

Loading documents

var e *northwind.Employee
err = session.Load(&e, "employees/7-A")
if err != nil {
    log.Fatalf("session.Load() failed with %s\n", err)
}
fmt.Printf("employee: %#v\n", e)

See crudLoad() in examples/main.go for full example.

Loading documents with includes

Some entities point to other entities via id. For example Employee has ReportsTo field which is an id of Employee that it reports to.

To improve performance by minimizing number of server requests, we can use includes functionality to load such linked entities.

// load employee with id "employees/7-A" and entity whose id is ReportsTo
var e *northwind.Employee
err = session.Include("ReportsTo").Load(&e, "employees/5-A")
if err != nil {
    log.Fatalf("session.Load() failed with %s\n", err)
}
if e.ReportsTo == "" {
    fmt.Printf("Employee with id employees/5-A doesn't report to anyone\n")
    return
}

numRequests := session.GetNumberOfRequests()
var reportsTo *northwind.Employee
err = session.Load(&reportsTo, e.ReportsTo)
if err != nil {
    log.Fatalf("session.Load() failed with %s\n", err)
}
if numRequests != session.GetNumberOfRequests() {
    fmt.Printf("Something's wrong, this shouldn't send a request to the server\n")
} else {
    fmt.Printf("Loading e.ReportsTo employee didn't require a new request to the server because we've loaded it in original requests thanks to using Include functionality\n")
}

See crudLoadWithInclude() in examples/main.go for full example.

Updating documents

// load entity from the server
var p *northwind.Product
err = session.Load(&p, productID)
if err != nil {
    log.Fatalf("session.Load() failed with %s\n", err)
}

// update price
origPrice = p.PricePerUnit
newPrice = origPrice + 10
p.PricePerUnit = newPrice
err = session.Store(p)
if err != nil {
    log.Fatalf("session.Store() failed with %s\n", err)
}

// persist changes on the server
err = session.SaveChanges()
if err != nil {
    log.Fatalf("session.SaveChanges() failed with %s\n", err)
}

See crudUpdate() in examples/main.go for full example.

Deleting documents

Delete using entity:

// ... store a product and remember its id in productID

var p *northwind.Product
err = session.Load(&p, productID)
if err != nil {
    log.Fatalf("session.Load() failed with %s\n", err)
}

err = session.Delete(p)
if err != nil {
    log.Fatalf("session.Delete() failed with %s\n", err)
}

err = session.SaveChanges()
if err != nil {
    log.Fatalf("session.SaveChanges() failed with %s\n", err)
}

See crudDeleteUsingEntity() in examples/main.go for full example.

Entity must be a value that we either stored in the database in the current session via Store() or loaded from database using Load(), LoadMulti(), query etc.

Delete using id:

// ... store a product and remember its id in productID

err = session.DeleteByID(productID, "")
if err != nil {
    log.Fatalf("session.Delete() failed with %s\n", err)
}

err = session.SaveChanges()
if err != nil {
    log.Fatalf("session.SaveChanges() failed with %s\n", err)
}

Second argument to DeleteByID is optional changeVector, for fine-grain concurrency control.

See crudDeleteUsingID() in examples/main.go for full example.

Querying documents

Selecting what to query

First you need to decide what to query.

RavenDB stores documents in collections. By default each type (struct) is stored in its own collection e.g. all Employee structs are stored in employees collection.

You can query by collection name:

q := session.QueryCollection("employees")

See queryCollectionByName() in examples/main.go for full example.

To get a collection name for a given type use ravendb.GetCollectionNameDefault(&MyStruct{}).

You can query a collection for a given type:

tp := reflect.TypeOf(&northwind.Employee{})
q := session.QueryCollectionForType(tp)

See queryCollectionByType() in examples/main.go for full example.

You can query an index:

q := session.QueryIndex("Orders/ByCompany")

See queryIndex() in examples/main.go for full example.

Limit what is returned

tp := reflect.TypeOf(&northwind.Product{})
q := session.QueryCollectionForType(tp)

q = q.WaitForNonStaleResults(0)
q = q.WhereEquals("Name", "iPhone X")
q = q.OrderBy("PricePerUnit")
q = q.Take(2) // limit to 2 results

See queryComplex() in examples/main.go for full example.

Obtain the results

You can get all matching results:

var products []*northwind.Product
err = q.GetResults(&products)

See queryComplex() in examples/main.go for full example.

You can get just first one:

var first *northwind.Employee
err = q.First(&first)

See queryFirst() in examples/main.go for full example.

Overview of DocumentQuery methods

SelectFields() - projections using a single field

// RQL equivalent: from employees select FirstName
q = q.SelectFields(reflect.TypeOf(""), "FirstName")

var names []string
err = q.GetResults(&names)

See querySelectSingleField() in examples/main.go for full example.

SelectFields() - projections using multiple fields

type employeeNameTitle struct {
	FirstName string
	Title     string
}

// RQL equivalent: from employees select FirstName, Title
tp := reflect.TypeOf(&northwind.Employee{})
q := session.QueryCollectionForType(tp)
q = q.SelectFields(reflect.TypeOf(&employeeNameTitle{}), "FirstName", "Title")

See querySelectFields() in examples/main.go for full example.

Distinct()

// RQL equivalent: from employees select distinct Title
tp := reflect.TypeOf(&northwind.Employee{})
q := session.QueryCollectionForType(tp)
q = q.SelectFields(reflect.TypeOf(""), "Title")
q = q.Distinct()

See queryDistinct() in examples/main.go for full example.

WhereEquals() / WhereNotEquals()

// RQL equivalent: from employees where Title = 'Sales Representative'
tp := reflect.TypeOf(&northwind.Employee{})
q := session.QueryCollectionForType(tp)
q = q.WhereEquals("Title", "Sales Representative")

See queryEquals() in examples/main.go for full example.

WhereIn

// RQL equivalent: from employees where Title in ['Sales Representative', 'Sales Manager']
tp := reflect.TypeOf(&northwind.Employee{})
q := session.QueryCollectionForType(tp)
q = q.WhereIn("Title", []interface{}{"Sales Representative", "Sales Manager"})

See queryIn() in examples/main.go for full example.

WhereStartsWith() / WhereEndsWith()

// RQL equivalent:
// from employees where startsWith('Ro')
tp := reflect.TypeOf(&northwind.Employee{})
q := session.QueryCollectionForType(tp)
q = q.WhereStartsWith("FirstName", "Ro")

See queryStartsWith() and queryEndsWith in examples/main.go for full example.

WhereBetween()

// RQL equivalent:
// from orders where Freight between 11 and 13
tp := reflect.TypeOf(&northwind.Order{})
q := session.QueryCollectionForType(tp)
q = q.WhereBetween("Freight", 11, 13)

See queryBetween() in examples/main.go for full example.

WhereGreaterThan() / WhereGreaterThanOrEqual() / WhereLessThan() / WhereLessThanOrEqual()

// RQL equivalent:
// from orders where Freight Freight > 11
tp := reflect.TypeOf(&northwind.Order{})
q := session.QueryCollectionForType(tp)
// can also be WhereGreaterThanOrEqual(), WhereLessThan(), WhereLessThanOrEqual()
q = q.WhereGreaterThan("Freight", 11)

See queryGreater() in examples/main.go for full example.

WhereExists()

Checks if the field exists.

// RQL equivalent:
// from employees where exists ("ReportsTo")
tp := reflect.TypeOf(&northwind.Employee{})
q := session.QueryCollectionForType(tp)
q = q.WhereExists("ReportsTo")

See queryExists() in examples/main.go for full example.

ContainsAny() / ContainsAll()

// RQL equivalent:
// from employees where FirstName in ("Anne", "Nancy")
tp := reflect.TypeOf(&northwind.Employee{})
q := session.QueryCollectionForType(tp)
q = q.ContainsAny("FirstName", []interface{}{"Anne", "Nancy"})

See queryContainsAny() in examples/main.go for full example.

Performs full-text search:

// RQL equivalent:
// from employees where search(FirstName, 'Anne Nancy')
tp := reflect.TypeOf(&northwind.Employee{})
q := session.QueryCollectionForType(tp)
q = q.Search("FirstName", "Anne Nancy")

See querySearch() in examples/main.go for full example.

OpenSubclause() / CloseSubclause()

// RQL equivalent:
// from employees where (FirstName = 'Steven') or (Title = 'Sales Representative' and LastName = 'Davolio')
tp := reflect.TypeOf(&northwind.Employee{})
q := session.QueryCollectionForType(tp)
q = q.WhereEquals("FirstName", "Steven")
q = q.OrElse()
q = q.OpenSubclause()
q = q.WhereEquals("Title", "Sales Representative")
q = q.WhereEquals("LastName", "Davolio")
q = q.CloseSubclause()

See querySubclause() in examples/main.go for full example.

Not()

// RQL equivalent:
// from employees where not FirstName = 'Steven'
tp := reflect.TypeOf(&northwind.Employee{})
q := session.QueryCollectionForType(tp)
q = q.Not()
q = q.WhereEquals("FirstName", "Steven")

See queryNot() in examples/main.go for full example.

AndAlso() / OrElse()

// RQL equivalent:
// from employees where FirstName = 'Steven' or FirstName  = 'Nancy'
tp := reflect.TypeOf(&northwind.Employee{})
q := session.QueryCollectionForType(tp)
q = q.WhereEquals("FirstName", "Steven")
// can also be AndElse()
q = q.OrElse()
q = q.WhereEquals("FirstName", "Nancy")

See queryOrElse() in examples/main.go for full example.

UsingDefaultOperator()

Sets default operator (which will be used if no AndAlso() / OrElse() was called. Just after query instantiation, OR is used as default operator. Default operator can be changed only adding any conditions.

OrderBy() / RandomOrdering()

// RQL equivalent:
// from employees order by FirstName
tp := reflect.TypeOf(&northwind.Employee{})
q := session.QueryCollectionForType(tp)
// can also be RandomOrdering()
q = q.OrderBy("FirstName")

See queryOrderBy() in examples/main.go for full example.

Take()

// RQL equivalent:
// from employees order by FirstName desc
tp := reflect.TypeOf(&northwind.Employee{})
q := session.QueryCollectionForType(tp)
q = q.OrderByDescending("FirstName")
q = q.Take(2)

See queryTake() in examples/main.go for full example.

Skip()

// RQL equivalent:
// from employees order by FirstName desc
tp := reflect.TypeOf(&northwind.Employee{})
q := session.QueryCollectionForType(tp)
q = q.OrderByDescending("FirstName")
q = q.Take(2)
q = q.Skip(1)

See querySkip() in examples/main.go for full example.

Getting query statistics

To obtain query statistics use Statistics() method.

var stats *ravendb.QueryStatistics
tp := reflect.TypeOf(&northwind.Employee{})
q := session.QueryCollectionForType(tp)
q = q.WhereGreaterThan("FirstName", "Bernard")
q = q.OrderByDescending("FirstName")
q.Statistics(&stats)

Statistics:

Statistics:
{IsStale:           false,
 DurationInMs:      0,
 TotalResults:      7,
 SkippedResults:    0,
 Timestamp:         2019-02-13 02:57:31.5226409 +0000 UTC,
 IndexName:         "Auto/employees/ByLastNameAndReportsToAndSearch(FirstName)AndTitle",
 IndexTimestamp:    2019-02-13 02:57:31.5226409 +0000 UTC,
 LastQueryTime:     2019-02-13 03:50:25.7602429 +0000 UTC,
 TimingsInMs:       {},
 ResultEtag:        7591488513381790088,
 ResultSize:        0,
 ScoreExplanations: {}}

See queryStatistics() in examples/main.go for full example.

GetResults() / First() / Single() / Count()

GetResults() - returns all results

First() - first result

Single() - first result, returns error if there's more entries

Count() - returns the number of the results (not affected by take())

See queryFirst(), querySingle() and queryCount() in examples/main.go for full example.

Attachments

Store attachments

fileStream, err := os.Open(path)
if err != nil {
    log.Fatalf("os.Open() failed with '%s'\n", err)
}
defer fileStream.Close()

fmt.Printf("new employee id: %s\n", e.ID)
err = session.Advanced().Attachments().Store(e, "photo.png", fileStream, "image/png")

// could also be done using document id
// err = session.Advanced().Attachments().Store(e.ID, "photo.png", fileStream, "image/png")

if err != nil {
    log.Fatalf("session.Advanced().Attachments().Store() failed with '%s'\n", err)
}

err = session.SaveChanges()

See storeAttachments() in examples/main.go for full example.

Get attachments

attachment, err := session.Advanced().Attachments().Get(docID, "photo.png")
if err != nil {
    log.Fatalf("session.Advanced().Attachments().Get() failed with '%s'\n", err)
}
defer attachment.Close()
fmt.Print("Attachment details:\n")
pretty.Print(attachment.Details)
// read attachment data
// attachment.Data is io.Reader
var attachmentData bytes.Buffer
n, err := io.Copy(&attachmentData, attachment.Data)
if err != nil {
    log.Fatalf("io.Copy() failed with '%s'\n", err)
}
fmt.Printf("Attachment size: %d bytes\n", n)

Attachment details:

{AttachmentName: {Name:        "photo.png",
                  Hash:        "MvUEcrFHSVDts5ZQv2bQ3r9RwtynqnyJzIbNYzu1ZXk=",
                  ContentType: "image/png",
                  Size:        4579},
 ChangeVector:   "A:4905-dMAeI9ANZ06DOxCRLnSmNw",
 DocumentID:     "employees/44-A"}
Attachment size: 4579 bytes

See getAttachments() in examples/main.go for full example.

Check if attachment exists

name := "photo.png"
exists, err := session.Advanced().Attachments().Exists(docID, name)
if err != nil {
    log.Fatalf("session.Advanced().Attachments().Exists() failed with '%s'\n", err)
}

See checkAttachmentExists() in examples/main.go for full example.

Get attachment names

names, err := session.Advanced().Attachments().GetNames(doc)
if err != nil {
    log.Fatalf("session.Advanced().Attachments().GetNames() failed with '%s'\n", err)
}

Attachment names:

[{Name:        "photo.png",
  Hash:        "MvUEcrFHSVDts5ZQv2bQ3r9RwtynqnyJzIbNYzu1ZXk=",
  ContentType: "image/png",
  Size:        4579}]

See getAttachmentNames() in examples/main.go for full example.

Bulk insert

When storing multiple documents, use bulk insertion.

bulkInsert := store.BulkInsert("")

names := []string{"Anna", "Maria", "Miguel", "Emanuel", "Dayanara", "Aleida"}
for _, name := range names {
    e := &northwind.Employee{
        FirstName: name,
    }
    id, err := bulkInsert.Store(e, nil)
    if err != nil {
        log.Fatalf("bulkInsert.Store() failed with '%s'\n", err)
    }
}
// flush data and finish
err = bulkInsert.Close()

See bulkInsert() in examples/main.go for full example.

Observing changes in the database

Listen for database changes e.g. document changes.

changes := store.Changes("")

err = changes.EnsureConnectedNow()
if err != nil {
    log.Fatalf("changes.EnsureConnectedNow() failed with '%s'\n", err)
}

cb := func(change *ravendb.DocumentChange) {
    fmt.Print("change:\n")
    pretty.Print(change)
}
docChangesCancel, err := changes.ForAllDocuments(cb)
if err != nil {
    log.Fatalf("changes.ForAllDocuments() failed with '%s'\n", err)
}

defer docChangesCancel()

e := &northwind.Employee{
    FirstName: "Jon",
    LastName:  "Snow",
}
err = session.Store(e)
if err != nil {
    log.Fatalf("session.Store() failed with '%s'\n", err)
}

err = session.SaveChanges()
if err != nil {
    log.Fatalf("session.SaveChanges() failed with '%s'\n", err)
}
// cb should now be called notifying there's a new document

Example change:

{Type:           "Put",
 ID:             "Raven/Hilo/employees",
 CollectionName: "@hilo",
 ChangeVector:   "A:4892-bJERJNLunE+4xQ/yDEuk1Q"}

See changes() in examples/main.go for full example.

Streaming

Streaming allows interating over documents matching certain criteria.

It's useful when there's a large number of results as it limits memory use by reading documents in batches (as opposed to all at once).

Stream documents with ID prefix

Here we iterate over all documents in products collection:

args := &ravendb.StartsWithArgs{
    StartsWith: "products/",
}
iterator, err := session.Advanced().Stream(args)
if err != nil {
    log.Fatalf("session.Advanced().Stream() failed with '%s'\n", err)
}
for {
    var p *northwind.Product
    streamResult, err := iterator.Next(&p)
    if err != nil {
        // io.EOF means there are no more results
        if err == io.EOF {
            err = nil
        } else {
            log.Fatalf("iterator.Next() failed with '%s'\n", err)
        }
        break
    }
    // handle p
}

See streamWithIDPrefix() in examples/main.go for full example.

This returns:

streamResult:
{ID:           "products/1-A",
 ChangeVector: "A:96-bJERJNLunE+4xQ/yDEuk1Q",
 Metadata:     {},
 Document:     ... same as product but as map[string]interface{} ...

product:
{ID:              "products/1-A",
 Name:            "Chai",
 Supplier:        "suppliers/1-A",
 Category:        "categories/1-A",
 QuantityPerUnit: "10 boxes x 20 bags",
 PricePerUnit:    18,
 UnitsInStock:    1,
 UnistsOnOrder:   0,
 Discontinued:    false,
 ReorderLevel:    10}

Stream query results

tp := reflect.TypeOf(&northwind.Product{})
q := session.QueryCollectionForType(tp)
q = q.WhereGreaterThan("PricePerUnit", 15)
q = q.OrderByDescending("PricePerUnit")

iterator, err := session.Advanced().StreamQuery(q, nil)
if err != nil {
    log.Fatalf("session.Advanced().StreamQuery() failed with '%s'\n", err)
}
// rest of processing as above

See streamQueryResults() in examples/main.go for full example.

Revisions

Note: make sure to enable revisions in a given store using NewConfigureRevisionsOperation operation.

e := &northwind.Employee{
    FirstName: "Jon",
    LastName:  "Snow",
}
err = session.Store(e)
if err != nil {
    log.Fatalf("session.Store() failed with '%s'\n", err)
}
err = session.SaveChanges()
if err != nil {
    log.Fatalf("session.SaveChanges() failed with '%s'\n", err)
}

// modify document to create a new revision
e.FirstName = "Jhonny"
err = session.SaveChanges()
if err != nil {
    log.Fatalf("session.SaveChanges() failed with '%s'\n", err)
}

var revisions []*northwind.Employee
err = session.Advanced().Revisions().GetFor(&revisions, e.ID)

See revisions() in examples/main.go for full example.

Returns:

[{ID:          "employees/43-A",
  LastName:    "Snow",
  FirstName:   "Jhonny",
  Title:       "",
  Address:     nil,
  HiredAt:     {},
  Birthday:    {},
  HomePhone:   "",
  Extension:   "",
  ReportsTo:   "",
  Notes:       [],
  Territories: []},
 {ID:          "employees/43-A",
  LastName:    "Snow",
  FirstName:   "Jon",
  Title:       "",
  Address:     nil,
  HiredAt:     {},
  Birthday:    {},
  HomePhone:   "",
  Extension:   "",
  ReportsTo:   "",
  Notes:       [],
  Territories: []}]

Suggestions

Suggestions provides similarity queries. Here we're asking for FirstName values similar to Micael and the database suggests Michael.

index := ravendb.NewIndexCreationTask("EmployeeIndex")
index.Map = "from doc in docs.Employees select new { doc.FirstName }"
index.Suggestion("FirstName")

err = store.ExecuteIndex(index, "")
if err != nil {
    log.Fatalf("store.ExecuteIndex() failed with '%s'\n", err)
}

tp := reflect.TypeOf(&northwind.Employee{})
q := session.QueryCollectionForType(tp)
su := ravendb.NewSuggestionWithTerm("FirstName")
su.Term = "Micael"
suggestionQuery := q.SuggestUsing(su)
results, err := suggestionQuery.Execute()

See suggestions() in examples/main.go for full example.

Returns:

{FirstName: {Name:        "FirstName",
             Suggestions: ["michael"]}}

Advanced patching

To update documents more efficiently than sending the whole document, you can patch just a given field or atomically add/substract values of numeric fields.

err = session.Advanced().IncrementByID(product.ID, "PricePerUnit", 15)
if err != nil {
    log.Fatalf("session.Advanced().IncrementByID() failed with %s\n", err)
}

err = session.Advanced().Patch(product, "Category", "expensive products")
if err != nil {
    log.Fatalf("session.Advanced().PatchEntity() failed with %s\n", err)
}

err = session.SaveChanges()
if err != nil {
    log.Fatalf("session.SaveChanges() failed with %s\n", err)
}

See advancedPatching() in examples/main.go for full example.

Subscriptions

opts := ravendb.SubscriptionCreationOptions{
    Query: "from Products where PricePerUnit > 17 and PricePerUnit < 19",
}
subscriptionName, err := store.Subscriptions().Create(&opts, "")
if err != nil {
    log.Fatalf("store.Subscriptions().Create() failed with %s\n", err)
}
wopts := ravendb.NewSubscriptionWorkerOptions(subscriptionName)
worker, err := store.Subscriptions().GetSubscriptionWorker(tp, wopts, "")
if err != nil {
    log.Fatalf("store.Subscriptions().GetSubscriptionWorker() failed with %s\n", err)
}

results := make(chan *ravendb.SubscriptionBatch, 16)
cb := func(batch *ravendb.SubscriptionBatch) error {
    results <- batch
    return nil
}
err = worker.Run(cb)
if err != nil {
    log.Fatalf("worker.Run() failed with %s\n", err)
}

// wait for first batch result
select {
case batch := <-results:
    fmt.Print("Batch of subscription results:\n")
    pretty.Print(batch)
case <-time.After(time.Second * 5):
    fmt.Printf("Timed out waiting for first subscription batch\n")

}

_ = worker.Close()

See subscriptions() in examples/main.go for full example.

Documentation

Overview

Package ravendb implements a driver for RavenDB NOSQL document database.

For more documentation see https://github.com/ravendb/ravendb-go-client/blob/master/readme.md

Index

Constants

View Source
const (
	AttachmentDocument = "Document"
	AttachmentRevision = "Revision"
)
View Source
const (
	//CommandNone                = "NONE"
	CommandPut                 = "PUT"
	CommandPatch               = "PATCH"
	CommandDelete              = "DELETE"
	CommandAttachmentPut       = "ATTACHMENT_PUT"
	CommandAttachmentDelete    = "ATTACHMENT_DELETE"
	CommandClientAnyCommand    = "CLIENT_ANY_COMMAND"
	CommandClientNotAttachment = "CLIENT_NOT_ATTACHMENT"
)

Note: this is enum in Java but those are serialized to json as strings so making them strings is better in Go

View Source
const (
	ConnectionStringTypeNone  = "None"
	ConnectionStringTypeRaven = "Raven"
	ConnectionStringTypeSQL   = "Sql"
)
View Source
const (
	// Name of struct field that represents identity property
	IdentityProperty = "ID"

	MetadataCollection             = "@collection"
	MetadataProjection             = "@projection"
	MetadataKey                    = "@metadata"
	MetadataID                     = "@id"
	MetadataConflict               = "@conflict"
	MetadataIDProperty             = "Id"
	MetadataFlags                  = "@flags"
	MetadataAttachments            = "@attachments"
	MetadataInddexScore            = "@index-score"
	MetadataLastModified           = "@last-modified"
	MetadataRavenGoType            = "Raven-Go-Type"
	MetadataChangeVector           = "@change-vector"
	MetadataExpires                = "@expires"
	MetadataAllDocumentsCollection = "@all_docs"

	IndexingSideBySideIndexNamePrefix = "ReplacementOf/"
	IndexingFieldNameDocumentID       = "id()"
	IndexingFieldNameReduceKeyHash    = "hash(key())"
	IndexingFieldNameReduceKeyValue   = "key()"
	IndexingFieldAllFields            = "__all_fields"
	IndexingFieldsNameSpatialShare    = "spatial(shape)"
	//TBD CUSTOM_SORT_FIELD_NAME = "__customSort";
	IndexingSpatialDefaultDistnaceErrorPct = 0.025
)
View Source
const (
	DatabasePromotionStatusWaitingForFirstPromotion = "WaitingForFirstPromotion"
	DatabasePromotionStatusNotResponding            = "NotResponding"
	DatabasePromotionStatusIndexNotUpToDate         = "IndexNotUpToDate"
	DatabasePromotionStatusChangeVectorNotMerged    = "ChangeVectorNotMerged"
	DatabasePromotionStatusWaitingForResponse       = "WaitingForResponse"
	DatabasePromotionStatusOk                       = "Ok"
)
View Source
const (
	DocumentChangeNone     = "None"
	DocumentChangePut      = "Put"
	DocumentChangeDelete   = "Delete"
	DocumentChangeConflict = "Conflict"
	DocumentChangeCommon   = "Common"
)
View Source
const (
	FacetAggregationNone    = "None"
	FacetAggregationMax     = "Max"
	FacetAggregationMin     = "Min"
	FacetAggregationAverage = "Average"
	FacetAggregationSum     = "Sum"
)
View Source
const (
	FacetTermSortModeValueAsc  = "ValueAsc"
	FacetTermSortModeValueDesc = "ValueDesc"
	FacetTermSortModeCountAsc  = "CountAsc"
	FacetTermSortModeCountDesc = "CountDesc"
)
View Source
const (
	FieldIndexingNo      = "No"
	FieldIndexingSearch  = "Search"
	FieldIndexingExact   = "Exact"
	FieldIndexingDefault = "Default"
)
View Source
const (
	FieldStorageYes = "Yes"
	FieldStorageNo  = "No"
)
View Source
const (
	FieldTermVectorNo                      = "No"
	FieldTermVectorYes                     = "Yes"
	FieldTermVectorWithPositions           = "WithPositions"
	FieldTermVectorWithOffsets             = "WithOffsets"
	FieldTermVectorWithPositionsAndOffsets = "WithPositionsAndOffsets"
)
View Source
const (
	GroupByMethodNone  = "None"
	GroupByMethodArray = "Array"
)
View Source
const (
	IndexChangeNone                   = "None"
	IndexChangeBatchCompleted         = "BatchCompleted"
	IndexChangeIndexAdded             = "IndexAdded"
	IndexChangeIndexRemoved           = "IndexRemoved"
	IndexChangeIndexDemotedToIdle     = "IndexDemotedToIdle"
	IndexChangeIndexPromotedFromIdle  = "IndexPromotedFromIdle"
	IndexChangeIndexDemotedToDisabled = "IndexDemotedToDisabled"
	IndexChangeIndexMarkedAsErrored   = "IndexMarkedAsErrored"
	IndexChangeSideBySideReplace      = "SideBySideReplace"
	IndexChangeRenamed                = "Renamed"
	IndexChangeIndexPaused            = "IndexPaused"
	IndexChangeLockModeChanged        = "LockModeChanged"
	IndexChangePriorityChanged        = "PriorityChanged"
)
View Source
const (
	IndexLockModeUnlock       = "Unlock"
	IndexLockModeLockedIgnore = "LockedIgnore"
	IndexLockModeLockedError  = "LockedError"
)
View Source
const (
	IndexPriorityLow    = "Low"
	IndexPriorityNormal = "Normal"
	IndexPriorityHigh   = "High"
)
View Source
const (
	IndexRunningStatusRunning  = "Running"
	IndexRunningStatusPaused   = "Paused"
	IndexRunningStatusDisabled = "Disabled"
)
View Source
const (
	IndexStateNormal   = "Normal"
	IndexStateDisabled = "Disabled"
	IndexStateIdle     = "Idle"
	IndexStateError    = "Error"
)
View Source
const (
	IndexTypeNone          = "None"
	IndexTypeAutoMap       = "AutoMap"
	IndexTypeAutoMapReduce = "AutoMapReduce"
	IndexTypeMap           = "Map"
	IndexTypeMapReduce     = "MapReduce"
	IndexTypeFaulty        = "Faulty"
)
View Source
const (
	MoreLikeThisOptionsDefaultMaximumNumberOfTokensParsed = 5000
	MoreLikeThisOptionsDefaultMinimumTermFrequency        = 2
	MoreLikeThisOptionsDefaultMinimumDocumentFrequency    = 5
	MoreLikeThisOptionsDefaultMaximumDocumentFrequence    = math.MaxInt32
	MoreLikeThisOptionsDefaultBoost                       = false
	MoreLikeThisOptionsDefaultBoostFactor                 = 1
	MoreLikeThisOptionsDefaultMinimumWordLength           = 0
	MoreLikeThisOptionsDefaultMaximumWordLength           = 0
	MoreLikeThisOptionsDefaultMaximumQueryTerms           = 25
)
View Source
const (
	OrderingTypeString       = "STRING"
	OrderingTypeLong         = "LONG"
	OrderingTypeDouble       = "DOUBLE"
	OrderingTypeAlphaNumeric = "ALPHA_NUMERIC"
)
View Source
const (
	PatchStatusDocumentDoesNotExist = "DocumentDoesNotExist"
	PatchStatusCreated              = "Created"
	PatchStatusPatched              = "Patched"
	PatchStatusSkipped              = "Skipped"
	PatchStatusNotModified          = "NotModified"
)
View Source
const (
	QueryOperatorAnd = "And"
	QueryOperatorOr  = "Or"
)
View Source
const (
	RavenCommandResponseTypeEmpty  = "EMPTY"
	RavenCommandResponseTypeObject = "OBJECT"
	RavenCommandResponseTypeRaw    = "RAW"
)
View Source
const (
	ReadBalanceBehaviorNone        = "None"
	ReadBalanceBehaviorRoundRobin  = "RoundRobin"
	ReadBalanceBehaviorFastestNode = "FastestNode"
)
View Source
const (
	ServerNodeRoleNone       = "None"
	ServerNodeRolePromotable = "Promotable"
	ServerNodeRoleMember     = "Member"
	ServerNodeRoleRehab      = "Rehab"
)
View Source
const (
	SpatialFieldGeography = "Geography"
	SpatialFieldCartesian = "Cartesian"
)
View Source
const (
	//about 4.78 meters at equator, should be good enough (see: http://unterbahn.com/2009/11/metric-dimensions-of-geohash-partitions-at-the-equator/)
	SpatialOptionsDefaultGeohashLevel = 9
	//about 4.78 meters at equator, should be good enough
	SpatialOptionsDefaultQuadTreeLevel = 23
)
View Source
const (
	SpatialRelationWithin     = "Within"
	SpatialRelationContains   = "Contains"
	SpatialRelationDisjoin    = "Disjoint"
	SpatialRelationIntersects = "Intersects"
)
View Source
const (
	SpatialSearchStrategyGeohashPrefixTree = "GeohashPrefixTree"
	SpatialSearchStrategyQuadPrefixTree    = "QuadPrefixTree"
	SpatialSearchStrategyBoundingBox       = "BoundingBox"
)
View Source
const (
	SpatialUnitsKilometers = "Kilometers"
	SpatialUnitsMiles      = "Miles"
)
View Source
const (
	StringDistanceNone        = "None"
	StringDistanceDefault     = "Default"
	StringDistanceLevenshtein = "Levenshtein"
	StringDistanceJaroWinkler = "JaroWinkler"
	StringDistanceNGram       = "NGram"
)
View Source
const (
	SubscriptionClientMessageNone                 = "None"
	SubscriptionClientMessageAcknowledge          = "Acknowledge"
	SubscriptionClientMessageDisposedNotification = "DisposedNotification"
)
View Source
const (
	// SubscriptionOpeningStrategyOpenIfFree:
	// The client will successfully open a subscription only if there isn't any other currently connected client.
	// Otherwise it will end up with SubscriptionInUseError
	SubscriptionOpeningStrategyOpenIfFree = "OpenIfFree"
	// SubscriptionOpeningStrategyTakeOver:
	// The connecting client will successfully open a subscription even if there is another active subscription's consumer.
	// If the new client takes over an existing client then the existing one will get a SubscriptionInUseException.
	//
	// The subscription will always be held by the last connected client.
	SubscriptionOpeningStrategyTakeOver = "TakeOver"
	// SubscriptionOpeningStrategyWaitForFree:
	// If the client currently cannot open the subscription because it is used by another client but it will wait for that client
	// to complete and keep attempting to gain the subscription
	SubscriptionOpeningStrategyWaitForFree = "WaitForFree"
)
View Source
const (
	SuggestionSortModeNone       = "None"
	SuggestionSortModePopularity = "Popularity"
)
View Source
const (
	MethodsTypeCmpXChg = "CmpXChg"
)

Variables

View Source
var (

	// HTTPClientPostProcessor allows to tweak http client after it has been created
	// this allows replacing Transport with a custom transport that does logging,
	// proxying or tweaks each http request
	HTTPClientPostProcessor func(*http.Client)

	// if true, adds lots of logging to track bugs in request executor
	DebugLogRequestExecutor bool = false
	DebugTopology           bool = false
)
View Source
var (
	SuggestionOptionsDefaultOptions  = NewSuggestionOptions()
	SuggestionOptionsDefaultAccuracy = float32(0.5)
	SuggestionOptionsDefaultPageSize = 15
	SuggestionOptionsDefaultDistance = StringDistanceLevenshtein
	SuggestionOptionsDefaultSortMode = SuggestionSortModePopularity
)
View Source
var (
	// DefaultFacetOptions are default facet options
	DefaultFacetOptions = &FacetOptions{}
)
View Source
var (
	// LogSubscriptions allows to monitor read/writes made by SubscriptionWorker to a tcp connection. For debugging.
	LogSubscriptionWorker func(op string, d []byte) = func(op string, d []byte) {

	}
)
View Source
var (
	// if true, does verbose logging.
	LogVerbose = false
)

Functions

func FieldsFor

func FieldsFor(s interface{}) []string

FieldsFor returns names of all fields for the value of a struct type. They can be used in e.g. DocumentQuery.SelectFields: fields := ravendb.FieldsFor(&MyType{}) q = q.SelectFields(fields...)

func GetCollectionNameDefault

func GetCollectionNameDefault(entityOrType interface{}) string

GetCollectionNameDefault is a default way of

func GetWrappedError

func GetWrappedError(err error) error

GetWrappedError returns an error wrapped by this error If no error is wrapped, returns nil

func IsPlural

func IsPlural(word string) bool

IsPlural retruns true if word is plural

func IsSingular

func IsSingular(word string) bool

IsSingular returns true if a word is singular

func NewHttpPost

func NewHttpPost(uri string, data []byte) (*http.Request, error)

func ParseTime

func ParseTime(s string) (time.Time, error)

ParseTime parses string time value returned by RavenDB server The value can't be parsed with a single string format

func Pluralize

func Pluralize(word string, count int, inclusive bool) string

Pluralize or singularize a word based on the passed in count.

func RoundToServerTime

func RoundToServerTime(t time.Time) time.Time

RoundToServerTime rounds t to the same precision as round-tripping to the server and back. Useful for comparing time.Time values for equality with values returned by the server

func ToPlural

func ToPlural(word string) string

ToPlural makes a pluralized version of a word

func ToSingular

func ToSingular(word string) string

ToSingular singularizes a word.

Types

type AdvancedSessionExtensionBase

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

AdvancedSessionExtensionBase implements common advanced session operations

func (*AdvancedSessionExtensionBase) Defer

func (e *AdvancedSessionExtensionBase) Defer(commands ...ICommandData)

Defer defers multiple commands to be executed on SaveChnages

type AdvancedSessionOperations

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

AdvancedSessionOperations exposes advanced session operations

func (*AdvancedSessionOperations) AddAfterSaveChangesListener

func (o *AdvancedSessionOperations) AddAfterSaveChangesListener(handler func(*AfterSaveChangesEventArgs)) int

func (*AdvancedSessionOperations) AddBeforeDeleteListener

func (o *AdvancedSessionOperations) AddBeforeDeleteListener(handler func(*BeforeDeleteEventArgs)) int

func (*AdvancedSessionOperations) AddBeforeQueryListener

func (o *AdvancedSessionOperations) AddBeforeQueryListener(handler func(*BeforeQueryEventArgs)) int

func (*AdvancedSessionOperations) AddBeforeStoreListener

func (o *AdvancedSessionOperations) AddBeforeStoreListener(handler func(*BeforeStoreEventArgs)) int

func (*AdvancedSessionOperations) Attachments

func (*AdvancedSessionOperations) Clear

func (o *AdvancedSessionOperations) Clear()

func (*AdvancedSessionOperations) Defer

func (o *AdvancedSessionOperations) Defer(commands ...ICommandData)

func (*AdvancedSessionOperations) Eagerly

func (*AdvancedSessionOperations) Evict

func (o *AdvancedSessionOperations) Evict(entity interface{}) error

func (*AdvancedSessionOperations) Exists

func (o *AdvancedSessionOperations) Exists(id string) (bool, error)

func (*AdvancedSessionOperations) GetChangeVectorFor

func (o *AdvancedSessionOperations) GetChangeVectorFor(instance interface{}) (*string, error)

func (*AdvancedSessionOperations) GetCurrentSessionNode

func (o *AdvancedSessionOperations) GetCurrentSessionNode() (*ServerNode, error)

func (*AdvancedSessionOperations) GetDocumentID

func (o *AdvancedSessionOperations) GetDocumentID(instance interface{}) string

func (*AdvancedSessionOperations) GetDocumentStore

func (o *AdvancedSessionOperations) GetDocumentStore() *DocumentStore

func (*AdvancedSessionOperations) GetLastModifiedFor

func (o *AdvancedSessionOperations) GetLastModifiedFor(instance interface{}) (*time.Time, error)

func (*AdvancedSessionOperations) GetMaxNumberOfRequestsPerSession

func (o *AdvancedSessionOperations) GetMaxNumberOfRequestsPerSession() int

func (*AdvancedSessionOperations) GetMetadataFor

func (o *AdvancedSessionOperations) GetMetadataFor(instance interface{}) (*MetadataAsDictionary, error)

func (*AdvancedSessionOperations) GetNumberOfRequests

func (o *AdvancedSessionOperations) GetNumberOfRequests() int

GetNumberOfRequests returns number of requests sent to the server

func (*AdvancedSessionOperations) GetRequestExecutor

func (o *AdvancedSessionOperations) GetRequestExecutor() *RequestExecutor

func (*AdvancedSessionOperations) HasChanged

func (o *AdvancedSessionOperations) HasChanged(entity interface{}) (bool, error)

func (*AdvancedSessionOperations) HasChanges

func (o *AdvancedSessionOperations) HasChanges() bool

func (*AdvancedSessionOperations) IgnoreChangesFor

func (o *AdvancedSessionOperations) IgnoreChangesFor(entity interface{}) error

func (*AdvancedSessionOperations) Increment

func (o *AdvancedSessionOperations) Increment(entity interface{}, path string, valueToAdd interface{}) error

func (*AdvancedSessionOperations) IncrementByID

func (o *AdvancedSessionOperations) IncrementByID(id string, path string, valueToAdd interface{}) error

func (*AdvancedSessionOperations) IsLoaded

func (o *AdvancedSessionOperations) IsLoaded(id string) bool

func (*AdvancedSessionOperations) Lazily

func (*AdvancedSessionOperations) LoadIntoStream

func (o *AdvancedSessionOperations) LoadIntoStream(ids []string, output io.Writer) error

func (*AdvancedSessionOperations) LoadStartingWith

func (o *AdvancedSessionOperations) LoadStartingWith(results interface{}, args *StartsWithArgs) error

func (*AdvancedSessionOperations) LoadStartingWithIntoStream

func (o *AdvancedSessionOperations) LoadStartingWithIntoStream(output io.Writer, args *StartsWithArgs) error

func (*AdvancedSessionOperations) Patch

func (o *AdvancedSessionOperations) Patch(entity interface{}, path string, value interface{}) error

func (*AdvancedSessionOperations) PatchArray

func (o *AdvancedSessionOperations) PatchArray(entity interface{}, pathToArray string, arrayAdder func(*JavaScriptArray)) error

func (*AdvancedSessionOperations) PatchArrayByID

func (o *AdvancedSessionOperations) PatchArrayByID(id string, pathToArray string, arrayAdder func(*JavaScriptArray)) error

func (*AdvancedSessionOperations) PatchByID

func (o *AdvancedSessionOperations) PatchByID(id string, path string, value interface{}) error

func (*AdvancedSessionOperations) Query

func (*AdvancedSessionOperations) QueryCollection

func (o *AdvancedSessionOperations) QueryCollection(collectionName string) *DocumentQuery

func (*AdvancedSessionOperations) QueryCollectionForType

func (o *AdvancedSessionOperations) QueryCollectionForType(typ reflect.Type) *DocumentQuery

func (*AdvancedSessionOperations) QueryIndex

func (o *AdvancedSessionOperations) QueryIndex(indexName string) *DocumentQuery

func (*AdvancedSessionOperations) RawQuery

func (o *AdvancedSessionOperations) RawQuery(rawQuery string) *RawDocumentQuery

func (*AdvancedSessionOperations) Refresh

func (o *AdvancedSessionOperations) Refresh(entity interface{}) error

func (*AdvancedSessionOperations) RemoveAfterSaveChangesListener

func (o *AdvancedSessionOperations) RemoveAfterSaveChangesListener(handlerID int)

func (*AdvancedSessionOperations) RemoveBeforeDeleteListener

func (o *AdvancedSessionOperations) RemoveBeforeDeleteListener(handlerID int)

func (*AdvancedSessionOperations) RemoveBeforeQueryListener

func (o *AdvancedSessionOperations) RemoveBeforeQueryListener(handlerID int)

func (*AdvancedSessionOperations) RemoveBeforeStoreListener

func (o *AdvancedSessionOperations) RemoveBeforeStoreListener(handlerID int)

func (*AdvancedSessionOperations) Revisions

func (*AdvancedSessionOperations) SetMaxNumberOfRequestsPerSession

func (o *AdvancedSessionOperations) SetMaxNumberOfRequestsPerSession(n int)

func (*AdvancedSessionOperations) Stream

func (*AdvancedSessionOperations) StreamQuery

func (o *AdvancedSessionOperations) StreamQuery(query *DocumentQuery, streamQueryStats *StreamQueryStatistics) (*StreamIterator, error)

func (*AdvancedSessionOperations) StreamQueryInto

func (o *AdvancedSessionOperations) StreamQueryInto(query *DocumentQuery, output io.Writer) error

func (*AdvancedSessionOperations) StreamRawQuery

func (o *AdvancedSessionOperations) StreamRawQuery(query *RawDocumentQuery, streamQueryStats *StreamQueryStatistics) (*StreamIterator, error)

func (*AdvancedSessionOperations) StreamRawQueryInto

func (o *AdvancedSessionOperations) StreamRawQueryInto(query *RawDocumentQuery, output io.Writer) error

func (*AdvancedSessionOperations) WaitForIndexesAfterSaveChanges

func (o *AdvancedSessionOperations) WaitForIndexesAfterSaveChanges(options func(*IndexesWaitOptsBuilder))

func (*AdvancedSessionOperations) WaitForReplicationAfterSaveChanges

func (o *AdvancedSessionOperations) WaitForReplicationAfterSaveChanges(options func(*ReplicationWaitOptsBuilder))

func (*AdvancedSessionOperations) WhatChanged

func (o *AdvancedSessionOperations) WhatChanged() (map[string][]*DocumentsChanges, error)

type AfterSaveChangesEventArgs

type AfterSaveChangesEventArgs struct {
	Session    *InMemoryDocumentSessionOperations
	DocumentID string
	Entity     interface{}
	// contains filtered or unexported fields
}

AfterSaveChangesEventArgs describes arguments for "after save changes" listener

func (*AfterSaveChangesEventArgs) GetDocumentMetadata

func (a *AfterSaveChangesEventArgs) GetDocumentMetadata() *MetadataAsDictionary

GetDocumentMetadata returns metadata for the entity represented by this event

type AggregationDocumentQuery

type AggregationDocumentQuery = aggregationQueryBase

Note: AggregationDocumentQuery is fused into AggregationQueryBase because in Java AggregationQueryBase calls functions implemented in AggregationDocumentQuery and that doesn't translate to Go's embedding

func (*AggregationDocumentQuery) AndAggregateByFacet

func (q *AggregationDocumentQuery) AndAggregateByFacet(facet FacetBase) *AggregationDocumentQuery

from AggregationDocumentQuery

func (*AggregationDocumentQuery) GetIndexQuery

func (q *AggregationDocumentQuery) GetIndexQuery() (*IndexQuery, error)

type AggressiveCacheOptions

type AggressiveCacheOptions struct {
	Duration time.Duration
}

TODO: should this be exported?

type AllTopologyNodesDownError

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

AllTopologyNodesDownError represents "all topology nodes are down" error

func (*AllTopologyNodesDownError) Error

func (e *AllTopologyNodesDownError) Error() string

Error makes it conform to error interface

func (*AllTopologyNodesDownError) WrappedError

func (e *AllTopologyNodesDownError) WrappedError() error

hackish way to get a wrapped error

type AttachmentDetails

type AttachmentDetails struct {
	AttachmentName
	ChangeVector *string `json:"ChangeVector"`
	DocumentID   string  `json:"DocumentId"`
}

AttachmentDetails represents details of an attachment

type AttachmentName

type AttachmentName struct {
	Name        string `json:"Name"`
	Hash        string `json:"Hash"`
	ContentType string `json:"ContentType"`
	Size        int64  `json:"Size"`
}

AttachmentName represents infor about an attachment

type AttachmentResult

type AttachmentResult struct {
	Data    io.Reader
	Details *AttachmentDetails
	// contains filtered or unexported fields
}

AttachmentResult represents an attachment

func (*AttachmentResult) Close

func (r *AttachmentResult) Close() error

Close closes the attachment

type AttachmentType

type AttachmentType = string

type AttachmentsSessionOperations

type AttachmentsSessionOperations = DocumentSessionAttachments

TODO: make a unique wrapper type

type AuthorizationError

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

AuthorizationError represents authorization error

func (*AuthorizationError) Error

func (e *AuthorizationError) Error() string

Error makes it conform to error interface

func (*AuthorizationError) WrappedError

func (e *AuthorizationError) WrappedError() error

hackish way to get a wrapped error

type BadRequestError

type BadRequestError struct {
	RavenError
}

BadRequestError maps to server's 400 Bad Request response This is additional information sent by the server

func (*BadRequestError) Error

func (e *BadRequestError) Error() string

Error makes it conform to error interface

func (*BadRequestError) WrappedError

func (e *BadRequestError) WrappedError() error

hackish way to get a wrapped error

type BadResponseError

type BadResponseError struct {
	RavenError
}

BadResponseError represents "bad response" error

func (*BadResponseError) Error

func (e *BadResponseError) Error() string

Error makes it conform to error interface

func (*BadResponseError) WrappedError

func (e *BadResponseError) WrappedError() error

hackish way to get a wrapped error

type BatchCommand

type BatchCommand struct {
	RavenCommandBase

	Result *JSONArrayResult
	// contains filtered or unexported fields
}

BatchCommand represents batch command

func (*BatchCommand) Close

func (c *BatchCommand) Close() error

func (*BatchCommand) CreateRequest

func (c *BatchCommand) CreateRequest(node *ServerNode) (*http.Request, error)

func (*BatchCommand) SetResponse

func (c *BatchCommand) SetResponse(response []byte, fromCache bool) error

type BatchOperation

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

BatchOperation represents a batch operation

type BatchOptions

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

BatchOptions describes options for batch operations

func NewBatchOptions

func NewBatchOptions() *BatchOptions

NewBatchOptions returns new BatchOptions

type BeforeDeleteEventArgs

type BeforeDeleteEventArgs struct {
	Session    *InMemoryDocumentSessionOperations
	DocumentID string
	Entity     interface{}
	// contains filtered or unexported fields
}

BeforeDeleteEventArgs describes arguments for "before delete" listener

func (*BeforeDeleteEventArgs) GetDocumentMetadata

func (a *BeforeDeleteEventArgs) GetDocumentMetadata() *MetadataAsDictionary

GetDocumentMetadata returns metadata for the entity being deleted

type BeforeQueryEventArgs

type BeforeQueryEventArgs struct {
	Session            *InMemoryDocumentSessionOperations
	QueryCustomization *DocumentQueryCustomization
}

BeforeQueryEventArgs describes arguments for "before query" event

type BeforeStoreEventArgs

type BeforeStoreEventArgs struct {
	Session    *InMemoryDocumentSessionOperations
	DocumentID string
	Entity     interface{}
	// contains filtered or unexported fields
}

BeforeStoreEventArgs describe arguments for "before store" listener

func (*BeforeStoreEventArgs) GetDocumentMetadata

func (a *BeforeStoreEventArgs) GetDocumentMetadata() *MetadataAsDictionary

GetDocumentMetadata returns metadata for entity represented by this event

type BulkInsertAbortedError

type BulkInsertAbortedError struct {
	RavenError
}

BulkInsertAbortedError represents "bulk insert aborted" error

func (*BulkInsertAbortedError) Error

func (e *BulkInsertAbortedError) Error() string

Error makes it conform to error interface

func (*BulkInsertAbortedError) WrappedError

func (e *BulkInsertAbortedError) WrappedError() error

hackish way to get a wrapped error

type BulkInsertCommand

type BulkInsertCommand struct {
	RavenCommandBase

	Result *http.Response
	// contains filtered or unexported fields
}

BulkInsertCommand describes build insert command

func NewBulkInsertCommand

func NewBulkInsertCommand(id int64, stream io.Reader, useCompression bool) *BulkInsertCommand

NewBulkInsertCommand returns new BulkInsertCommand

func (*BulkInsertCommand) CreateRequest

func (c *BulkInsertCommand) CreateRequest(node *ServerNode) (*http.Request, error)

func (*BulkInsertCommand) Send

func (c *BulkInsertCommand) Send(client *http.Client, req *http.Request) (*http.Response, error)

func (*BulkInsertCommand) SetResponse

func (c *BulkInsertCommand) SetResponse(response []byte, fromCache bool) error

type BulkInsertOperation

type BulkInsertOperation struct {
	Command *BulkInsertCommand
	// contains filtered or unexported fields
}

BulkInsertOperation represents bulk insert operation

func NewBulkInsertOperation

func NewBulkInsertOperation(database string, store *DocumentStore) *BulkInsertOperation

NewBulkInsertOperation returns new BulkInsertOperation

func (*BulkInsertOperation) Abort

func (o *BulkInsertOperation) Abort() error

Abort aborts insert operation

func (*BulkInsertOperation) Close

func (o *BulkInsertOperation) Close() error

Close closes operation

func (*BulkInsertOperation) GetID

func (o *BulkInsertOperation) GetID(entity interface{}) (string, error)

GetID returns id for an entity

func (*BulkInsertOperation) Store

func (o *BulkInsertOperation) Store(entity interface{}, metadata *MetadataAsDictionary) (string, error)

Store schedules entity for storing and returns its id. metadata can be nil

func (*BulkInsertOperation) StoreWithID

func (o *BulkInsertOperation) StoreWithID(entity interface{}, id string, metadata *MetadataAsDictionary) error

StoreWithID stores an entity with a given id

func (*BulkInsertOperation) WaitForID

func (o *BulkInsertOperation) WaitForID() error

WaitForID waits for operation id to finish

type BulkInsertProtocolViolationError

type BulkInsertProtocolViolationError struct {
	RavenError
}

func (*BulkInsertProtocolViolationError) Error

func (e *BulkInsertProtocolViolationError) Error() string

Error makes it conform to error interface

func (*BulkInsertProtocolViolationError) WrappedError

func (e *BulkInsertProtocolViolationError) WrappedError() error

hackish way to get a wrapped error

type CancelFunc

type CancelFunc func()

type CancellationError

type CancellationError struct {
}

func (*CancellationError) Error

func (e *CancellationError) Error() string

type CertificateNameMismatchError

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

CertificateNameMismatchError is returned when subscription is in use

func (*CertificateNameMismatchError) Error

func (e *CertificateNameMismatchError) Error() string

Error makes it conform to error interface

func (*CertificateNameMismatchError) WrappedError

func (e *CertificateNameMismatchError) WrappedError() error

hackish way to get a wrapped error

type ChangeProcessingError

type ChangeProcessingError struct {
	RavenError
}

func (*ChangeProcessingError) Error

func (e *ChangeProcessingError) Error() string

Error makes it conform to error interface

func (*ChangeProcessingError) WrappedError

func (e *ChangeProcessingError) WrappedError() error

hackish way to get a wrapped error

type ChangeType

type ChangeType int

ChangeType describes a type of a change in a document

const (
	// TODO: make those into a string?
	DocumentChangeDocumentDeleted ChangeType = iota
	DocumentChangeDocumentAdded
	DocumentChangeFieldChanged
	DocumentChangeNewField
	DocumentChangeRemovedField
	DocumentChangeArrayValueChanged
	DocumentChangeArrayValueAdded
	DocumentChangeArrayValueRemoved
	DocumentChangeFieldTypeChanged
	DocumentChangeEntityTypeChanged
)

type CircleCriteria

type CircleCriteria struct {
	SpatialCriteriaCommon
	// contains filtered or unexported fields
}

CircleCriteria describes circle criteria

func NewCircleCriteria

func NewCircleCriteria(radius float64, latitude float64, longitude float64, radiusUnits SpatialUnits, relation SpatialRelation, distErrorPercent float64) *CircleCriteria

NewCircleCriteria returns new CircleCriteria

func (*CircleCriteria) GetShapeToken

func (c *CircleCriteria) GetShapeToken(addQueryParameter func(interface{}) string) *shapeToken

GetShapeToken returns shapeToken

func (*CircleCriteria) ToQueryToken

func (c *CircleCriteria) ToQueryToken(fieldName string, addQueryParameter func(interface{}) string) queryToken

ToQueryToken creates a token

type ClientConfiguration

type ClientConfiguration struct {
	Etag       int64 `json:"Etag"`
	IsDisabled bool  `json:"Disabled"`
	// TODO: should this be *int ?
	MaxNumberOfRequestsPerSession int                 `json:"MaxNumberOfRequestsPerSession"`
	ReadBalanceBehavior           ReadBalanceBehavior `json:"ReadBalanceBehavior"`
}

ClientConfiguration represents client configuration

type ClientVersionMismatchError

type ClientVersionMismatchError struct {
	RavenError
}

ClientVersionMismatchError is returned when subscription is in use

func (*ClientVersionMismatchError) Error

func (e *ClientVersionMismatchError) Error() string

Error makes it conform to error interface

func (*ClientVersionMismatchError) WrappedError

func (e *ClientVersionMismatchError) WrappedError() error

hackish way to get a wrapped error

type ClusterRequestExecutor

type ClusterRequestExecutor = RequestExecutor

Note: for simplicity ClusterRequestExecutor logic is implemented in RequestExecutor because Go doesn't support inheritance

type ClusterTopology

type ClusterTopology struct {
	TopologyID string            `json:"TopologyId"`
	AllNodes   map[string]string `json:"AllNodes"`
	// Those map name like A to server url like http://localhost:9999
	Members     map[string]string `json:"Members"`
	Promotables map[string]string `json:"Promotables"`
	Watchers    map[string]string `json:"Watchers"`
	LastNodeId  string            `json:"LastNodeId"`
	Etag        int               `json:"Etag"`
}

ClusterTopology is a part of ClusterTopologyResponse

type CmpXchg

type CmpXchg struct {
	MethodCallData
}

CmpXchg represents data for cmp xchg method

func CmpXchgValue

func CmpXchgValue(key string) *CmpXchg

CmpXchgValue returns CmpXchg for a given key

type CollectionStatistics

type CollectionStatistics struct {
	CountOfDocuments int            `json:"CountOfDocuments"`
	CountOfConflicts int            `json:"CountOfConflicts"`
	Collections      map[string]int `json:"Collections"`
}

CollectionStatistics describes collection statistics

type CollectionStats

type CollectionStats struct {
	LastProcessedDocumentEtag  int64 `json:"LastProcessedDocumentEtag"`
	LastProcessedTombstoneEtag int64 `json:"LastProcessedTombstoneEtag"`
	DocumentLag                int64 `json:"DocumentLag"`
	TombstoneLag               int64 `json:"TombstoneLag"`
}

func NewCollectionStats

func NewCollectionStats() *CollectionStats

type CommandData

type CommandData struct {
	ID           string
	Name         string
	ChangeVector *string
	Type         CommandType
}

CommandData describes common data for commands

type CommandExecutionError

type CommandExecutionError struct {
	RavenError
}

func (*CommandExecutionError) Error

func (e *CommandExecutionError) Error() string

Error makes it conform to error interface

func (*CommandExecutionError) WrappedError

func (e *CommandExecutionError) WrappedError() error

hackish way to get a wrapped error

type CommandType

type CommandType = string

using type alias for easy json serialization

type CompactDatabaseCommand

type CompactDatabaseCommand struct {
	RavenCommandBase

	Result *OperationIDResult
	// contains filtered or unexported fields
}

CompactDatabaseCommand describes "compact database" command

func NewCompactDatabaseCommand

func NewCompactDatabaseCommand(conventions *DocumentConventions, compactSettings *CompactSettings) (*CompactDatabaseCommand, error)

NewCompactDatabaseCommand returns new CompactDatabaseCommand

func (*CompactDatabaseCommand) CreateRequest

func (c *CompactDatabaseCommand) CreateRequest(node *ServerNode) (*http.Request, error)

func (*CompactDatabaseCommand) SetResponse

func (c *CompactDatabaseCommand) SetResponse(response []byte, fromCache bool) error

type CompactDatabaseOperation

type CompactDatabaseOperation struct {
	Command *CompactDatabaseCommand
	// contains filtered or unexported fields
}

CompactDatabaseOperation describes "compact database" operation

func NewCompactDatabaseOperation

func NewCompactDatabaseOperation(compactSettings *CompactSettings) *CompactDatabaseOperation

NewCompactDatabaseOperation returns new CompactDatabaseOperation

func (*CompactDatabaseOperation) GetCommand

func (o *CompactDatabaseOperation) GetCommand(conventions *DocumentConventions) (RavenCommand, error)

GetCommand returns a command

type CompactSettings

type CompactSettings struct {
	DatabaseName string   `json:"DatabaseName"`
	Documents    bool     `json:"Documents"`
	Indexes      []string `json:"Indexes,omitempty"`
}

CompactSettings is an argument to CompactDatabaseOperation

type CompareExchangeResult

type CompareExchangeResult struct {
	Value        interface{}
	Index        int64
	IsSuccessful bool
}

CompareExchangeResult describes result of compare exchange

type CompareExchangeValue

type CompareExchangeValue struct {
	Key   string
	Index int64
	Value interface{}
}

CompareExchangeValue represents value for compare exchange

func NewCompareExchangeValue

func NewCompareExchangeValue(key string, index int64, value interface{}) *CompareExchangeValue

NewCompareExchangeValue returns new CompareExchangeValue

type CompilationError

type CompilationError struct {
	RavenError
}

func (*CompilationError) Error

func (e *CompilationError) Error() string

Error makes it conform to error interface

func (*CompilationError) WrappedError

func (e *CompilationError) WrappedError() error

hackish way to get a wrapped error

type ConcurrencyCheckMode

type ConcurrencyCheckMode int

ConcurrencyCheckMode describes concurrency check

const (
	// ConcurrencyCheckAuto is automatic optimistic concurrency check depending on UseOptimisticConcurrency setting or provided Change Vector
	ConcurrencyCheckAuto ConcurrencyCheckMode = iota
	// ConcurrencyCheckForced forces optimistic concurrency check even if UseOptimisticConcurrency is not set
	ConcurrencyCheckForced
	// ConcurrencyCheckDisabled disables optimistic concurrency check even if UseOptimisticConcurrency is set
	ConcurrencyCheckDisabled
)

type ConcurrencyError

type ConcurrencyError struct {
	RavenError

	ExpectedETag         int64
	ActualETag           int64
	ExpectedChangeVector string
	ActualChangeVector   string
}

ConcurrencyError represents concurrency error

func (*ConcurrencyError) Error

func (e *ConcurrencyError) Error() string

Error makes it conform to error interface

func (*ConcurrencyError) WrappedError

func (e *ConcurrencyError) WrappedError() error

hackish way to get a wrapped error

type ConfigureRevisionsCommand

type ConfigureRevisionsCommand struct {
	RavenCommandBase

	Result *ConfigureRevisionsOperationResult
	// contains filtered or unexported fields
}

ConfigureRevisionsCommand represents configure revisions command

func NewConfigureRevisionsCommand

func NewConfigureRevisionsCommand(configuration *RevisionsConfiguration) *ConfigureRevisionsCommand

NewConfigureRevisionsCommand returns new ConfigureRevisionsCommand

func (*ConfigureRevisionsCommand) CreateRequest

func (c *ConfigureRevisionsCommand) CreateRequest(node *ServerNode) (*http.Request, error)

func (*ConfigureRevisionsCommand) SetResponse

func (c *ConfigureRevisionsCommand) SetResponse(response []byte, fromCache bool) error

type ConfigureRevisionsOperation

type ConfigureRevisionsOperation struct {
	Command *ConfigureRevisionsCommand
	// contains filtered or unexported fields
}

ConfigureRevisionsOperation represents configure revisions operation

func NewConfigureRevisionsOperation

func NewConfigureRevisionsOperation(configuration *RevisionsConfiguration) *ConfigureRevisionsOperation

NewConfigureRevisionsOperation returns new ConfigureRevisionsOperation

func (*ConfigureRevisionsOperation) GetCommand

func (o *ConfigureRevisionsOperation) GetCommand(conventions *DocumentConventions) (RavenCommand, error)

GetCommand returns new RavenCommand for this operation

type ConfigureRevisionsOperationResult

type ConfigureRevisionsOperationResult struct {
	RaftCommandIndex int64 `json:"RaftCommandIndex"`
}

ConfigureRevisionsOperationResult represents result of configure revisions operation

type Conflict

type Conflict struct {
	LastModified Time                   `json:"LastModified"`
	ChangeVector string                 `json:"ChangeVector"`
	Doc          map[string]interface{} `json:"Doc"`
}

Conflict represents conflict

type ConflictError

type ConflictError struct {
	RavenError
}

ConflictError maps to server's 409 Conflict response

func (*ConflictError) Error

func (e *ConflictError) Error() string

Error makes it conform to error interface

func (*ConflictError) WrappedError

func (e *ConflictError) WrappedError() error

hackish way to get a wrapped error

type ConflictSolver

type ConflictSolver struct {
	ResolveByCollection map[string]*ScriptResolver `json:"ResolveByCollection"`
	ResolveToLatest     bool                       `json:"ResolveToLatest"`
}

ConflictSolver describes how to resolve conflicts

type ConnectionString

type ConnectionString struct {
	Name string `json:"Name"`
	// Note: Java has this as a virtual function getType()
	Type ConnectionStringType `json:"Type"`
}

ConnectionString represents connection string used as argument to PutConnectionStringCommand

type ConnectionStringType

type ConnectionStringType = string

TODO: only used in ConnectionString which is unused

type CreateDatabaseCommand

type CreateDatabaseCommand struct {
	RavenCommandBase

	Result *DatabasePutResult
	// contains filtered or unexported fields
}

CreateDatabaseCommand represents "create database" command

func NewCreateDatabaseCommand

func NewCreateDatabaseCommand(conventions *DocumentConventions, databaseRecord *DatabaseRecord, replicationFactor int) (*CreateDatabaseCommand, error)

NewCreateDatabaseCommand returns new CreateDatabaseCommand

func (*CreateDatabaseCommand) CreateRequest

func (c *CreateDatabaseCommand) CreateRequest(node *ServerNode) (*http.Request, error)

func (*CreateDatabaseCommand) SetResponse

func (c *CreateDatabaseCommand) SetResponse(response []byte, fromCache bool) error

type CreateDatabaseOperation

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

CreateDatabaseOperation represents "create database" operation

func NewCreateDatabaseOperation

func NewCreateDatabaseOperation(databaseRecord *DatabaseRecord, replicationFactor int) *CreateDatabaseOperation

NewCreateDatabaseOperation returns CreateDatabaseOperation

func (*CreateDatabaseOperation) GetCommand

func (o *CreateDatabaseOperation) GetCommand(conventions *DocumentConventions) (RavenCommand, error)

GetCommand returns command for this operation

type CreateSampleDataCommand

type CreateSampleDataCommand struct {
	RavenCommandBase
}

CreateSampleDataCommand represents command for creating sample data

func NewCreateSampleDataCommand

func NewCreateSampleDataCommand(conventions *DocumentConventions) *CreateSampleDataCommand

NewCreateSampleDataCommand returns new CreateSampleDataCommand

func (*CreateSampleDataCommand) CreateRequest

func (c *CreateSampleDataCommand) CreateRequest(node *ServerNode) (*http.Request, error)

type CreateSampleDataOperation

type CreateSampleDataOperation struct {
	Command *CreateSampleDataCommand
}

CreateSampleDataOperation represents operation to create sample data

func NewCreateSampleDataOperation

func NewCreateSampleDataOperation() *CreateSampleDataOperation

NewCreateSampleDataOperation

func (*CreateSampleDataOperation) GetCommand

func (o *CreateSampleDataOperation) GetCommand(conventions *DocumentConventions) (RavenCommand, error)

GetCommand returns a comman

type CreateSubscriptionCommand

type CreateSubscriptionCommand struct {
	RavenCommandBase

	Result *CreateSubscriptionResult
	// contains filtered or unexported fields
}

CreateSubscriptionCommand represents "create subscription" command

func (*CreateSubscriptionCommand) CreateRequest

func (c *CreateSubscriptionCommand) CreateRequest(node *ServerNode) (*http.Request, error)

func (*CreateSubscriptionCommand) SetResponse

func (c *CreateSubscriptionCommand) SetResponse(response []byte, fromCache bool) error

type CreateSubscriptionResult

type CreateSubscriptionResult struct {
	Name string `json:"Name"`
}

CreateSubscriptionResult represents result for "create subscription" command

type CurrentIndexAndNode

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

func NewCurrentIndexAndNode

func NewCurrentIndexAndNode(currentIndex int, currentNode *ServerNode) *CurrentIndexAndNode

type DatabaseChanges

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

DatabaseChanges notifies about changes to a database

func (*DatabaseChanges) AddConnectionStatusChanged

func (c *DatabaseChanges) AddConnectionStatusChanged(handler func()) int

func (*DatabaseChanges) AddOnError

func (c *DatabaseChanges) AddOnError(handler func(error)) int

func (*DatabaseChanges) Close

func (c *DatabaseChanges) Close()

Close closes DatabaseChanges and release its resources

func (*DatabaseChanges) EnsureConnectedNow

func (c *DatabaseChanges) EnsureConnectedNow() error

func (*DatabaseChanges) ForAllDocuments

func (c *DatabaseChanges) ForAllDocuments(cb func(*DocumentChange)) (CancelFunc, error)

ForAllDocuments registers a callback that will be called for changes on all documents. It returns a function to call to unregister the callback.

func (*DatabaseChanges) ForAllIndexes

func (c *DatabaseChanges) ForAllIndexes(cb func(*IndexChange)) (CancelFunc, error)

ForAllIndexes registers a callback that will be called when a change on any index happens. It returns a function to call to unregister the callback.

func (*DatabaseChanges) ForAllOperations

func (c *DatabaseChanges) ForAllOperations(cb func(change *OperationStatusChange)) (CancelFunc, error)

ForAllOperations registers a callback that will be called when any operation changes status. It returns a function to call to unregister the callback.

func (*DatabaseChanges) ForDocument

func (c *DatabaseChanges) ForDocument(docID string, cb func(*DocumentChange)) (CancelFunc, error)

ForDocument registers a callback that will be called for changes on a ocument with a given id It returns a function to call to unregister the callback.

func (*DatabaseChanges) ForDocumentsInCollection

func (c *DatabaseChanges) ForDocumentsInCollection(collectionName string, cb func(*DocumentChange)) (CancelFunc, error)

ForDocumentsInCollection registers a callback that will be called on changes for documents in a given collection. It returns a function to call to unregister the callback.

func (*DatabaseChanges) ForDocumentsInCollectionOfType

func (c *DatabaseChanges) ForDocumentsInCollectionOfType(clazz reflect.Type, cb func(*DocumentChange)) (CancelFunc, error)

ForDocumentsInCollectionOfType registers a callback that will be called on changes for documents of a given type. It returns a function to call to unregister the callback.

func (*DatabaseChanges) ForDocumentsStartingWith

func (c *DatabaseChanges) ForDocumentsStartingWith(docIDPrefix string, cb func(*DocumentChange)) (CancelFunc, error)

ForDocumentsStartingWith registers a callback that will be called for changes on documents whose id starts with a given prefix. It returns a function to call to unregister the callback.

func (*DatabaseChanges) ForIndex

func (c *DatabaseChanges) ForIndex(indexName string, cb func(*IndexChange)) (CancelFunc, error)

ForIndex registers a callback that will be called for changes in an index with a given name. It returns a function to call to unregister the callback.

func (*DatabaseChanges) ForOperationID

func (c *DatabaseChanges) ForOperationID(operationID int64, cb func(*OperationStatusChange)) (CancelFunc, error)

ForOperationID registers a callback that will be called when a change happens to operation with a given id. It returns a function to call to unregister the callback.

func (*DatabaseChanges) RemoveConnectionStatusChanged

func (c *DatabaseChanges) RemoveConnectionStatusChanged(handlerID int)

func (*DatabaseChanges) RemoveOnError

func (c *DatabaseChanges) RemoveOnError(handlerID int)

type DatabaseConcurrentLoadTimeoutError

type DatabaseConcurrentLoadTimeoutError struct {
	RavenError
}

func (*DatabaseConcurrentLoadTimeoutError) Error

func (e *DatabaseConcurrentLoadTimeoutError) Error() string

Error makes it conform to error interface

func (*DatabaseConcurrentLoadTimeoutError) WrappedError

func (e *DatabaseConcurrentLoadTimeoutError) WrappedError() error

hackish way to get a wrapped error

type DatabaseDisabledError

type DatabaseDisabledError struct {
	RavenError
}

func (*DatabaseDisabledError) Error

func (e *DatabaseDisabledError) Error() string

Error makes it conform to error interface

func (*DatabaseDisabledError) WrappedError

func (e *DatabaseDisabledError) WrappedError() error

hackish way to get a wrapped error

type DatabaseDoesNotExistError

type DatabaseDoesNotExistError struct {
	RavenError
}

DatabaseDoesNotExistError represents "database not not exist" error

func (*DatabaseDoesNotExistError) Error

func (e *DatabaseDoesNotExistError) Error() string

Error makes it conform to error interface

func (*DatabaseDoesNotExistError) WrappedError

func (e *DatabaseDoesNotExistError) WrappedError() error

hackish way to get a wrapped error

type DatabaseLoadFailureError

type DatabaseLoadFailureError struct {
	RavenError
}

func (*DatabaseLoadFailureError) Error

func (e *DatabaseLoadFailureError) Error() string

Error makes it conform to error interface

func (*DatabaseLoadFailureError) WrappedError

func (e *DatabaseLoadFailureError) WrappedError() error

hackish way to get a wrapped error

type DatabaseLoadTimeoutError

type DatabaseLoadTimeoutError struct {
	RavenError
}

func (*DatabaseLoadTimeoutError) Error

func (e *DatabaseLoadTimeoutError) Error() string

Error makes it conform to error interface

func (*DatabaseLoadTimeoutError) WrappedError

func (e *DatabaseLoadTimeoutError) WrappedError() error

hackish way to get a wrapped error

type DatabaseNotRelevantError

type DatabaseNotRelevantError struct {
	RavenError
}

func (*DatabaseNotRelevantError) Error

func (e *DatabaseNotRelevantError) Error() string

Error makes it conform to error interface

func (*DatabaseNotRelevantError) WrappedError

func (e *DatabaseNotRelevantError) WrappedError() error

hackish way to get a wrapped error

type DatabasePromotionStatus

type DatabasePromotionStatus = string

type DatabasePutResult

type DatabasePutResult struct {
	RaftCommandIndex int64    `json:"RaftCommandIndex"`
	Name             string   `json:"Name"`
	DatabaseTopology Topology `json:"Topology"`
	NodesAddedTo     []string `json:"NodesAddedTo"`
}

DatabasePutResult describes server response for e.g. CreateDatabaseCommand

type DatabaseRecord

type DatabaseRecord struct {
	DatabaseName         string            `json:"DatabaseName"`
	Disabled             bool              `json:"Disabled"`
	DataDirectory        string            `json:"DataDirectory,omitempty"`
	Settings             map[string]string `json:"Settings"`
	ConflictSolverConfig *ConflictSolver   `json:"ConflictSolverConfig"`
	Encrypted            bool              `json:"Encrypted"`
	DatabaseTopology     *DatabaseTopology `json:"DatabaseTopology"`
}

DatabaseRecord represents database record

func NewDatabaseRecord

func NewDatabaseRecord() *DatabaseRecord

NewDatabaseRecord returns new database record

type DatabaseRecordWithEtag

type DatabaseRecordWithEtag struct {
	DatabaseRecord
	Etag int64 `json:"Etag"`
}

DatabaseRecordWithEtag represents database record with etag

type DatabaseStatistics

type DatabaseStatistics struct {
	LastDocEtag               int64 `json:"LastDocEtag"`
	CountOfIndexes            int   `json:"CountOfIndexes"`
	CountOfDocuments          int64 `json:"CountOfDocuments"`
	CountOfRevisionDocuments  int64 `json:"CountOfRevisionDocuments"` // TODO: present in Java, not seen in JSON
	CountOfDocumentsConflicts int64 `json:"CountOfDocumentsConflicts"`
	CountOfTombstones         int64 `json:"CountOfTombstones"`
	CountOfConflicts          int64 `json:"CountOfConflicts"`
	CountOfAttachments        int64 `json:"CountOfAttachments"`
	CountOfUniqueAttachments  int64 `json:"CountOfUniqueAttachments"`

	Indexes []*IndexInformation `json:"Indexes"`

	DatabaseChangeVector                     string `json:"DatabaseChangeVector"`
	DatabaseID                               string `json:"DatabaseId"`
	Is64Bit                                  bool   `json:"Is64Bit"`
	Pager                                    string `json:"Pager"`
	LastIndexingTime                         *Time  `json:"LastIndexingTime"`
	SizeOnDisk                               *Size  `json:"SizeOnDisk"`
	TempBuffersSizeOnDisk                    *Size  `json:"TempBuffersSizeOnDisk"`
	NumberOfTransactionMergerQueueOperations int    `json:"NumberOfTransactionMergerQueueOperations"`
}

DatabaseStatistics describes a result of GetStatisticsCommand

func (*DatabaseStatistics) GetLastIndexingTime

func (s *DatabaseStatistics) GetLastIndexingTime() *time.Time

GetLastIndexingTime returns last indexing time

type DatabaseTopology

type DatabaseTopology struct {
	Members                  []string          `json:"Members"`
	Promotables              []string          `json:"Promotables"`
	Rehabs                   []string          `json:"Rehabs"`
	PredefinedMentors        map[string]string `json:"PredefinedMentors"`
	DemotionReasons          map[string]string `json:"DemotionReasons"`
	PromotablesStatus        map[string]string `json:"PromotablesStatus"`
	ReplicationFactor        int               `json:"ReplicationFactor"`
	DynamicNodesDistribution bool              `json:"DynamicNodesDistribution"`
	Stamp                    LeaderStamp       `json:"Stamp"`
}

DatabaseTopology describes a topology of the database

type DeleteAttachmentCommand

type DeleteAttachmentCommand struct {
	RavenCommandBase
	// contains filtered or unexported fields
}

func NewDeleteAttachmentCommand

func NewDeleteAttachmentCommand(documentID string, name string, changeVector *string) (*DeleteAttachmentCommand, error)

func (*DeleteAttachmentCommand) CreateRequest

func (c *DeleteAttachmentCommand) CreateRequest(node *ServerNode) (*http.Request, error)

type DeleteAttachmentCommandData

type DeleteAttachmentCommandData struct {
	*CommandData
}

func NewDeleteAttachmentCommandData

func NewDeleteAttachmentCommandData(documentID string, name string, changeVector *string) (*DeleteAttachmentCommandData, error)

NewDeleteAttachmentCommandData creates CommandData for Delete Attachment command

type DeleteAttachmentOperation

type DeleteAttachmentOperation struct {
	Command *DeleteAttachmentCommand
	// contains filtered or unexported fields
}

func NewDeleteAttachmentOperation

func NewDeleteAttachmentOperation(documentID string, name string, changeVector *string) *DeleteAttachmentOperation

func (*DeleteAttachmentOperation) GetCommand

func (o *DeleteAttachmentOperation) GetCommand(store *DocumentStore, conventions *DocumentConventions, cache *httpCache) (RavenCommand, error)

type DeleteByIndexCommand

type DeleteByIndexCommand struct {
	RavenCommandBase

	Result *OperationIDResult
	// contains filtered or unexported fields
}

func NewDeleteByIndexCommand

func NewDeleteByIndexCommand(conventions *DocumentConventions, queryToDelete *IndexQuery, options *QueryOperationOptions) (*DeleteByIndexCommand, error)

func (*DeleteByIndexCommand) CreateRequest

func (c *DeleteByIndexCommand) CreateRequest(node *ServerNode) (*http.Request, error)

func (*DeleteByIndexCommand) SetResponse

func (c *DeleteByIndexCommand) SetResponse(response []byte, fromCache bool) error

type DeleteByQueryOperation

type DeleteByQueryOperation struct {
	Command *DeleteByIndexCommand
	// contains filtered or unexported fields
}

func NewDeleteByQueryOperation

func NewDeleteByQueryOperation(queryToDelete *IndexQuery, options *QueryOperationOptions) (*DeleteByQueryOperation, error)

func (*DeleteByQueryOperation) GetCommand

func (o *DeleteByQueryOperation) GetCommand(store *DocumentStore, conventions *DocumentConventions, cache *httpCache) (RavenCommand, error)

type DeleteCommandData

type DeleteCommandData struct {
	CommandData
}

DeleteCommandData represents data for delete command

type DeleteCompareExchangeValueOperation

type DeleteCompareExchangeValueOperation struct {
	Command *RemoveCompareExchangeValueCommand
	// contains filtered or unexported fields
}

func NewDeleteCompareExchangeValueOperation

func NewDeleteCompareExchangeValueOperation(clazz reflect.Type, key string, index int64) (*DeleteCompareExchangeValueOperation, error)

func (*DeleteCompareExchangeValueOperation) GetCommand

func (o *DeleteCompareExchangeValueOperation) GetCommand(store *DocumentStore, conventions *DocumentConventions, cache *httpCache) (RavenCommand, error)

type DeleteDatabaseCommand

type DeleteDatabaseCommand struct {
	RavenCommandBase

	Result *DeleteDatabaseResult
	// contains filtered or unexported fields
}

func NewDeleteDatabaseCommand

func NewDeleteDatabaseCommand(conventions *DocumentConventions, parameters *DeleteDatabaseParameters) (*DeleteDatabaseCommand, error)

func (*DeleteDatabaseCommand) CreateRequest

func (c *DeleteDatabaseCommand) CreateRequest(node *ServerNode) (*http.Request, error)

func (*DeleteDatabaseCommand) SetResponse

func (c *DeleteDatabaseCommand) SetResponse(response []byte, fromCache bool) error

type DeleteDatabaseParameters

type DeleteDatabaseParameters struct {
	DatabaseNames             []string       `json:"DatabaseNames"`
	HardDelete                bool           `json:"HardDelete"`
	FromNodes                 []string       `json:"FromNodes"`
	TimeToWaitForConfirmation *time.Duration `json:"TimeToWaitForConfirmation"`
}

type DeleteDatabaseResult

type DeleteDatabaseResult struct {
	RaftCommandIndex int64    `json:"RaftCommandIndex"`
	PendingDeletes   []string `json:"PendingDeletes"`
}

DeleteDatabaseResult represents result of Delete Database command

type DeleteDatabasesOperation

type DeleteDatabasesOperation struct {
	Command *DeleteDatabaseCommand
	// contains filtered or unexported fields
}

func NewDeleteDatabasesOperation

func NewDeleteDatabasesOperation(databaseName string, hardDelete bool) *DeleteDatabasesOperation

func NewDeleteDatabasesOperation2

func NewDeleteDatabasesOperation2(databaseName string, hardDelete bool, fromNode string, timeToWaitForConfirmation time.Duration) *DeleteDatabasesOperation

func NewDeleteDatabasesOperationWithParameters

func NewDeleteDatabasesOperationWithParameters(parameters *DeleteDatabaseParameters) *DeleteDatabasesOperation

func (*DeleteDatabasesOperation) GetCommand

func (o *DeleteDatabasesOperation) GetCommand(conventions *DocumentConventions) (RavenCommand, error)

type DeleteDocumentCommand

type DeleteDocumentCommand struct {
	RavenCommandBase
	// contains filtered or unexported fields
}

func NewDeleteDocumentCommand

func NewDeleteDocumentCommand(id string, changeVector *string) *DeleteDocumentCommand

func (*DeleteDocumentCommand) CreateRequest

func (c *DeleteDocumentCommand) CreateRequest(node *ServerNode) (*http.Request, error)

type DeleteIndexCommand

type DeleteIndexCommand struct {
	RavenCommandBase
	// contains filtered or unexported fields
}

func NewDeleteIndexCommand

func NewDeleteIndexCommand(indexName string) (*DeleteIndexCommand, error)

func (*DeleteIndexCommand) CreateRequest

func (c *DeleteIndexCommand) CreateRequest(node *ServerNode) (*http.Request, error)

type DeleteIndexOperation

type DeleteIndexOperation struct {
	Command *DeleteIndexCommand
	// contains filtered or unexported fields
}

func NewDeleteIndexOperation

func NewDeleteIndexOperation(indexName string) *DeleteIndexOperation

func (*DeleteIndexOperation) GetCommand

func (o *DeleteIndexOperation) GetCommand(conventions *DocumentConventions) (RavenCommand, error)

type DeleteSubscriptionCommand

type DeleteSubscriptionCommand struct {
	RavenCommandBase
	// contains filtered or unexported fields
}

DeleteSubscriptionCommand describes "delete subscription" command