arango

package module
v0.0.0-...-c648f5a Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2015 License: GPL-2.0 Imports: 8 Imported by: 2

README

arango

Intent

I'm not a go developer and wanted to use arango for a project on my own. I decided to write my own driver for using Arango via its REST API. I did take a look at https://github.com/diegogub/aranGO but I decided that I wanted to write my own to do more go programming.

Installing

Run go get github.com/starJammer/arango

Features

  • Connect to the database arango server and get info about the current database
  • Switch databases
  • Create, drop edge and document collections
  • Save, Update, Replace, Delete documents
  • Save, Update, Replace, Delete edges
  • Retrieve document via id only, NO searching by example or AQL queries yet.
  • Retrieve documents via simple by example queries

Upcoming Features

Usage

I'll add more usage notes about different ways to do things.

//THE BELOW CODE IS JUST AN EXAMPLE AND WON'T WORK IF YOU
//TRY AND COMPILE IT

import ar "github.com/starJammer/arango"
import "fmt"

func main() {
    
    //will connect to the _system database by default
    db, err := ar.Conn( "http://localhost:8529" )

    if err != nil {
        //Any errors returned are of the type ArangoError
        aerr, ok := err.(ar.ArangoError)
        if !ok {
            fmt.Println( "Should not get here since if there is an error, its type should be ar.ArangoError" )
        }
        //See errors.go for more info on the ArangoError type
        fmt.Printf(
            "Something went wrong bro....check arango and make sure it's up.\n" + 
            "HTTP CODE : %d\n" + 
            "Arango Err Number : %d\n" + 
            "IsError : %v\n" + 
            "ErrorMessage : %s\n",
            aerr.Code,
            aerr.ErrorNum,
            aerr.IsError,
            aerr.ErrorMessage,
        )
        return
    }

    //You can also use the following two versions
    db, err := ar.ConnDb( "http://localhost:8529", "database_name" )

    //Use this in case you enabled users/passwords
    db, err := ar.ConnDbUserPassword( "http://localhost:8529", "database_name", "username", "password" )

    //You can also include the user/password in the host address like this
    db, err := ar.Conn( "http://username:password@localhost:8529" )

    //You can also use HTTPS
    ar.AllowBadSslCerts = true //set this to true if your development certs are not "official looking"
    db, err := ar.Conn( "https://username:password@localhost:8529" )


    //switch to a databes you want to use if you didn't specify the database name when connecting
    db.UseDatabase( "another_database" )

    c, err := db.CreateDocumentCollection( "things" )

    //OR you can do the following for an edge collection
    c, err := db.CreateEdgeCollection( "things" )

    if err != nil {
        fmt.Println( "Things broke again bro, you're failing. I swear it's not my code!")
    }

    type TestDocument struct {
        ar.DocumentImplementation //embed this if you want to get easy access to the Id, Key, and Rev of the documents you save

        MyField string  //Will be save in the database as "MyField" : "value"
        MyField2 bool `json:"my_field"` //Will be saved as "my_field" : "value"
    }

    var testDoc TestDocument
    var testDoc2 = new(TestDocument)

    testDoc.MyField = "some string"
    testDoc.MyField2 = true //just cuz

    //Must pass in a pointer to the document
    err = c.Save( &testDoc )
    err = c.Save( testDoc2 )

    if err != nil {
        //it should be fine though
    }

    //Info about the document from arango
    fmt.Println( testDoc.Id() )
    fmt.Println( testDoc.Key() )
    fmt.Println( testDoc.Rev() )

    testDoc.MyField = "Updating to some other value"

    //notice we pass in the id first and then a pointer to the document
    c.Update( testDoc.Id(), &testDoc )
    
    //the revision will change since we updated it
    fmt.Println( testDoc.Rev() )

    //Searching by example will return a cursor
    cur, err := db.ByExampleQuery( &ByExampleQuery{
        Collection : d.Name(),
        BatchSize : 5, //if it is 0 then it is ignored and the arango server calculates this automatically
        Limit : 5, //if 0 then it is ignored.
        Skip : 5, //if 0 then it is ignored
        Example : &struct{ MyField string }{ MyField : "some string"},
    })

    //OR you can simply call ByExample on the collection
    cur, err := d.ByExample( &struct{ MyField string }{ MyField : "some string"} )

    //OR call ByExampleQuery on the collection for more control like in the above call to the Database type
    cur, err := d.ByExampleQuery(&ByExampleQuery{
        BatchSize : 5,
        Limite : 5,
        Skip : 5,
        Example : &struct{ MyField string }{ MyField : "some string"},
        //Collection : "name" //No need for this. The collection will do it automatically
    })

    //Using a nil query will fetch everything in the collection
    cur, err := d.ByExampleQuery( nil )

    var fetchDoc = new(TestDocument)

    //Iterate over the results
    for cur.HasNext() {
        err = cur.Next( fetchDoc )
        if err != nil {
            fmt.Println( "Another unexpected error.")
        }
        //fetchDoc is now populated with one of the resulting documents from arango.
        //do what you want with it here.
    }
}

Documentation

Overview

Package arango provides a golang driver for the arangodb database. It utilizes the RESTFUL API made available by the database server.

Index

Constants

View Source
const (
	DOCUMENT_COLLECTION = 2
	EDGE_COLLECTION     = 3
)

Collection types

See arango manual or rest api docs for what these might mean

View Source
const (
	NEW_BORN_STATUS       = 1
	UNLOADED_STATUS       = 2
	LOADED_STATUS         = 3
	BEING_UNLOADED_STATUS = 4
	DELETED_STATUS        = 5
)

Collection statuses

See arango manual or rest api docs for what these might mean

Variables

View Source
var (
	//AllowBadSslCerts is to be used for development to allow self signed certs
	//This will not affect connections that have already been made, only
	//new connections that are created will be affected by this.
	AllowBadSslCerts = false
)

Functions

This section is empty.

Types

type ArangoEdge

type ArangoEdge interface {
	From() string
	SetFrom(string)

	To() string
	SetTo(string)
}

type ArangoError

type ArangoError struct {
	IsError      bool   `json:"error"`
	Code         int    `json:"code"`
	ErrorNum     int    `json:"errorNum"`
	ErrorMessage string `json:"errorMessage"`

	//Reserved for some operations that will return
	//the id, rev, or key of the document.
	//For example, /_api/document/{doc-handle} when it
	//return a 412 error
	Id  string `json:"_id,omitempty"`
	Rev string `json:"_rev,omitempty"`
	Key string `json:"_key,omitempty"`
}

ArangoError is the base set of json fields in a typical arango response. All the api functions will return an ArangoError when something bad happens. Nil will be returned when things went as planned. If an error happened BEFORE we consulted the REST API, meaning the error happened in my code or because of parameter checks before the http request, then Code and ErrorNum will be -1. Otherwise, if we succeeded in making the request to the server, they will contain whatever the server/api would normally return.

func (ArangoError) Error

func (a ArangoError) Error() string

type ByExampleQuery

type ByExampleQuery struct {
	Collection string      `json:"collection"`
	Example    interface{} `json:"example"`
	Skip       int         `json:"skip,omitempty"`
	Limit      int         `json:"limit,omitempty"`
	BatchSize  int         `json:"batchSize,omitempty"`
}

type Collection

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

Collection represents a collection from arangodb Don't instantiate this yourself. Use db.Collection to get the one you want.

func (*Collection) ByExample

func (c *Collection) ByExample(example interface{}) (*Cursor, error)

func (*Collection) ByExampleQuery

func (c *Collection) ByExampleQuery(query *ByExampleQuery) (*Cursor, error)

func (*Collection) DoCompact

func (c *Collection) DoCompact() bool

DoCompact will only have an accurate answer if you call c.Properties first

func (*Collection) Document

func (c *Collection) Document(documentHandle interface{},
	document interface{}) error

Document will fetch the document associated with the documentHandle. An error will be returned if anything goes wrong. Otherwise, document be populated with the document values from arango. json.Unmarhshal is used under the hood so make sure you understand how string literals tags work with the encoding/json package. This uses the GET /_api/document/{document-handle} endpoint. The method provides a extra bit of functionality in that it won't let you fetch an document NOT from this collection. For example, you can't request 'users/123413' when the collection name is 'places'. If you want to look up an arbitrary document then use db.Document()

func (*Collection) DocumentWithOptions

func (c *Collection) DocumentWithOptions(documentHandle interface{},
	document interface{},
	options *GetOptions) error

func (*Collection) Drop

func (c *Collection) Drop() error

Drop deletes the collection from the database DO NOT expect the collection to work after dropping it. Calling any further methods on it will result in unexpected behavior

func (*Collection) Edge

func (c *Collection) Edge(documentHandle interface{},
	edge interface{}) error

func (*Collection) EdgeWithOptions

func (c *Collection) EdgeWithOptions(documentHandle interface{},
	edge interface{},
	options *GetOptions) error

func (*Collection) FirstExample

func (c *Collection) FirstExample(example, document interface{}) error

func (*Collection) Id

func (c *Collection) Id() string

Id returns the id of the collection.

func (*Collection) IsSystem

func (c *Collection) IsSystem() bool

IsSystem returns whether the collection is a system collection or not. System collections typically start with an underscore like _system

func (*Collection) IsVolatile

func (c *Collection) IsVolatile() bool

IsVolatile will only have an accurate answer if you call c.Properties first

func (*Collection) JournalSize

func (c *Collection) JournalSize() int

JournalSize will only have an accurate answer if you call c.Properties first

func (*Collection) KeyOptions

func (c *Collection) KeyOptions() *KeyOptions

KeyOptions will only have an accurate answer if you call c.Properties first

func (*Collection) Name

func (c *Collection) Name() string

Name returns the name of the collection.

func (*Collection) NumberOfShards

func (c *Collection) NumberOfShards() int

NumberOfShards will only have an accurate answer if you call c.Properties first

func (*Collection) Properties

func (c *Collection) Properties() error

Properties fetches additional properties of the collection. It queries the /_api/collection/{collection-name}/properties endpoint and causes the collection to switch to the loaded state if it was unloaded before. Use this especially if you want to update some of the properties like the Status().

func (*Collection) Replace

func (c *Collection) Replace(documentHandle interface{},
	document interface{}) error

func (*Collection) ReplaceEdge

func (c *Collection) ReplaceEdge(documentHandle interface{},
	edge interface{}) error

func (*Collection) ReplaceEdgeWithOptions

func (c *Collection) ReplaceEdgeWithOptions(documentHandle interface{},
	edge interface{},
	options *ReplaceOptions) error

func (*Collection) ReplaceWithOptions

func (c *Collection) ReplaceWithOptions(documentHandle interface{},
	document interface{},
	options *ReplaceOptions) error

func (*Collection) Save

func (c *Collection) Save(document interface{}) error

Save creates a document in the collection. Uses the POST /_api/document endpoint If your document embeds the DocumentImplementation type or it has fields to hold the Id, Rev, and Key fields from arango, then it will be populated with the Id, Rev, Key fields during the json.Unmarshal call

func (*Collection) SaveEdge

func (c *Collection) SaveEdge(from, to, edge interface{}) error

SaveEdge creates a new edge using pointing from "from" to "to". Will probably result in an error if arango determines that this collection is not an edge collection.

func (*Collection) SaveEdgeWithOptions

func (c *Collection) SaveEdgeWithOptions(from, to, edge interface{}, options *SaveOptions) error

SaveEdgeWithOptions creates a new edge using pointing from "from" to "to" and allows you to specify more options. Will probably result in an error if arango determines that this collection is not an edge collection.

func (*Collection) SaveWithOptions

func (c *Collection) SaveWithOptions(document interface{}, options *SaveOptions) error

SaveWithOptions lets you save a document but lets you specify some options See the POST /_api/document endpoint for more info.

func (*Collection) ShardKeys

func (c *Collection) ShardKeys() []string

ShardKeys will only have an accurate answer if you call c.Properties first

func (*Collection) Status

func (c *Collection) Status() int

Status returns the status of the collection. The result is cached. Call Properties() to refresh. The status can be any of the constants defined above. const ( NEW_BORN_STATUS = 1 UNLOADED_STATUS = 2 LOADED_STATUS = 3 BEING_UNLOADED_STATUS = 4 DELETED_STATUS = 5 )

func (*Collection) Type

func (c *Collection) Type() int

Type returns the type of the collection. Either it is a document or an edge collection The type is returned as one of the two constants:

DOCUMENT_COLLECTION = 2
EDGE_COLLECTION     = 3

func (*Collection) Update

func (c *Collection) Update(documentHandle interface{},
	document interface{}) error

func (*Collection) UpdateEdge

func (c *Collection) UpdateEdge(documentHandle interface{},
	edge interface{}) error

func (*Collection) UpdateEdgeWithOptions

func (c *Collection) UpdateEdgeWithOptions(documentHandle interface{},
	edge interface{},
	options *UpdateOptions) error

func (*Collection) UpdateWithOptions

func (c *Collection) UpdateWithOptions(documentHandle interface{},
	document interface{},
	options *UpdateOptions) error

func (*Collection) WaitForSync

func (c *Collection) WaitForSync() bool

WaitForSync will only have an accurate answer if you call c.Properties first

type CollectionCreationOptions

type CollectionCreationOptions struct {
	WaitForSync    bool        `json:"waitForSync,omitempty"`
	DoCompact      bool        `json:"doCompact"`
	JournalSize    int         `json:"journalSize,omitempty"`
	IsSystem       bool        `json:"isSystem,omitempty"`
	IsVolatile     bool        `json:"isVolatile,omitempty"`
	KeyOptions     *KeyOptions `json:"keyOptions,omitempty"`
	Type           int         `json:"type,omitempty"`
	NumberOfShards int         `json:"numberOfShards,omitempty"`
	ShardKeys      []string    `json:"shardKeys,omitempty"`
	//You can set name manually but it will be overriden with
	//whatever the create methods are called with so don't bother.
	Name string `json:"name"`
}

CollectionCreationOptions represent options when creating a new collection. Look at the documentation for the POST to /_api/collection for information on the defaults, optionals, and required attributes.

func DefaultCollectionOptions

func DefaultCollectionOptions() CollectionCreationOptions

DefaultCollectionOptions creates a default set of collection options If you will always be using the defaults then just use the Create method as it uses the defaults.

type Cursor

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

Cursor represents a collection of items that you can iterate over. This library will produce a Cursor type whenever ArangoDb produces a list of objects that match a query.

func (Cursor) Close

func (c Cursor) Close() error

func (Cursor) Code

func (c Cursor) Code() int

func (Cursor) Count

func (c Cursor) Count() int

func (Cursor) Error

func (c Cursor) Error() bool

func (Cursor) HasMore

func (c Cursor) HasMore() bool

func (*Cursor) Next

func (c *Cursor) Next(next interface{}) error

Next retrieves the next item from the cursor. According to the arango docs : Note that even if hasMore returns true, the next call might still return no documents. If, however, hasMore is false, then the cursor is exhausted. Once the hasMore attribute has a value of false, the client can stop.

type Database

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

Database is an arango database connection. It is connected to one database at a time. You can switch databases with the UseDatabase Method. Do NOT instantiate this yourself. Use one of the Conn/ConnDb/ConnDbUserPassword methods instead.

func Conn

func Conn(host string) (*Database, error)

Conn returns a new database connection to an arango server. This function will connect to the _system database

The url can be in the following forms http://[username[:password]@]host:port or https://...etc

func ConnDb

func ConnDb(host, databaseName string) (*Database, error)

ConnDb returns a new database connection to an arango server. This function will connect to the given database using the default root user with a blank password.

func ConnDbUserPassword

func ConnDbUserPassword(host, databaseName, user, password string) (*Database, error)

ConnDbUserPassword returns a new database to an arango server. This function will connect to the given database using the given user name and password. This method is here for no reason really other than to separate the database host from the user name. So you can make host=http://localhost:1324 and specify the user and password separately. Otherwise, you can just use ConnDb and specify the user info in the host string

func (*Database) ByExampleQuery

func (db *Database) ByExampleQuery(query *ByExampleQuery) (*Cursor, error)

func (*Database) Collection

func (db *Database) Collection(collectionName string) (*Collection, error)

Collection gets a collection by name from the database. Similar to calling db._collection( 'name' ) in arangosh See /_api/collection/{collection-name} endpoint for more info. An error with a code 404 is returned if it doesn't exist.

Note : This method should not trigger the collection to be loaded

func (*Database) CreateCollection

func (db *Database) CreateCollection(collectionName string, options CollectionCreationOptions) (*Collection, error)

CreateCollection is the generic collection creating method. Use it for more control. It allows you finer control by using the CollectionCreationOptions An error is returned if there was an issue. Otherwise, it was a success and you can use db.Collection( collectionName ) to get the collection you just created and work with it.

func (*Database) CreateDatabase

func (db *Database) CreateDatabase(name string, options *DatabaseOptions, users []User) error

CreateDatabase creates a new database and is modeled after db._createDatabase users can be nil, or it can be a list of users you want created

func (*Database) CreateDocumentCollection

func (db *Database) CreateDocumentCollection(collectionName string) (*Collection, error)

Shortcut method for CreateCollection that will use default options to create the document collection.

func (*Database) CreateEdgeCollection

func (db *Database) CreateEdgeCollection(collectionName string) (*Collection, error)

Shortcut method for CreateCollection that will use default options to create the edge collection

func (*Database) DeleteDocumentWithOptions

func (db *Database) DeleteDocumentWithOptions(documentHandle interface{}, options *DeleteOptions) error

func (*Database) DeleteEdgeWithOptions

func (db *Database) DeleteEdgeWithOptions(documentHandle interface{}, options *DeleteOptions) error

func (*Database) Document

func (db *Database) Document(documentHandle interface{}, document interface{}) error

Document looks for a document in the database

func (*Database) DocumentWithOptions

func (db *Database) DocumentWithOptions(documentHandle interface{}, document interface{}, options *GetOptions) error

DocumentWithOptions looks for a document in the database

func (*Database) DropCollection

func (db *Database) DropCollection(collectionName string) error

DropCollection drops the collection in the database by name.

func (*Database) DropDatabase

func (db *Database) DropDatabase(name string) error

func (*Database) Edge

func (db *Database) Edge(documentHandle, edge interface{}) error

Edge retrieves an edge in the database

func (*Database) EdgeWithOptions

func (db *Database) EdgeWithOptions(documentHandle interface{}, edge interface{}, options *GetOptions) error

EdgeWithOptions retrieves an edge in the database

func (*Database) FirstExample

func (db *Database) FirstExample(query *FirstExampleQuery, document interface{}) error

FirstExample will call the PUT /_api/simple/first-example endpoint. The value pointed to by document is populated with the result from Arango.

func (*Database) Id

func (db *Database) Id() string

func (*Database) IsSystem

func (db *Database) IsSystem() bool

func (*Database) Name

func (db *Database) Name() string

func (*Database) Path

func (db *Database) Path() string

func (*Database) ReplaceDocumentWithOptions

func (db *Database) ReplaceDocumentWithOptions(documentHandle, document interface{}, options *ReplaceOptions) error

func (*Database) ReplaceEdgeWithOptions

func (db *Database) ReplaceEdgeWithOptions(documentHandle, edge interface{}, options *ReplaceOptions) error

ReplaceEdgeWithOptions

func (*Database) SaveDocumentWithOptions

func (db *Database) SaveDocumentWithOptions(document interface{}, options *SaveOptions) error

Saves a document using the POST /_api/document endpoint. Look at arango api docs for more info.

func (*Database) SaveEdgeWithOptions

func (db *Database) SaveEdgeWithOptions(from, to, edge interface{}, options *SaveOptions) error

func (*Database) UpdateDocumentWithOptions

func (db *Database) UpdateDocumentWithOptions(documentHandle, document interface{}, options *UpdateOptions) error

func (*Database) UpdateEdgeWithOptions

func (db *Database) UpdateEdgeWithOptions(documentHandle, edge interface{}, options *UpdateOptions) error

func (*Database) UseDatabase

func (db *Database) UseDatabase(databaseName string) (*Database, error)

UseDatabase will switch databases as if you called db._useDatabase in arangosh. No error if successful, otherwise an error. Under the hood it just makes another call to ConnDb Using the same credentials used for the original database and returns the results.

type DatabaseOptions

type DatabaseOptions struct{}

DatabaseOptions currently has nothing in it but is left as a placeholder for future use when arangodb makes use of it

type DeleteOptions

type DeleteOptions ReplaceOptions

func DefaultDeleteOptions

func DefaultDeleteOptions() *DeleteOptions

type DocumentImplementation

type DocumentImplementation struct {
	ArangoId  string `json:"_id,omitempty"`
	ArangoRev string `json:"_rev,omitempty"`
	ArangoKey string `json:"_key,omitempty"`
}

DocumentImplementation is an embeddable type that you can use that already implements the Document interfaces.

func (*DocumentImplementation) Id

func (*DocumentImplementation) Key

func (d *DocumentImplementation) Key() string

func (*DocumentImplementation) Rev

func (d *DocumentImplementation) Rev() string

func (*DocumentImplementation) SetId

func (d *DocumentImplementation) SetId(id string)

func (*DocumentImplementation) SetKey

func (d *DocumentImplementation) SetKey(key string)

func (*DocumentImplementation) SetRev

func (d *DocumentImplementation) SetRev(rev string)

type EdgeImplementation

type EdgeImplementation struct {
	DocumentImplementation
	ArangoFrom string `json:"_from,omitempty"`
	ArangoTo   string `json:"_to,omitempty"`
}

EdgeImplementation is an embeddable type that you can use that already implements the edge interfaces.

func (*EdgeImplementation) From

func (e *EdgeImplementation) From() string

func (*EdgeImplementation) SetFrom

func (e *EdgeImplementation) SetFrom(from string)

func (*EdgeImplementation) SetTo

func (e *EdgeImplementation) SetTo(to string)

func (*EdgeImplementation) To

func (e *EdgeImplementation) To() string

type FirstExampleQuery

type FirstExampleQuery struct {
	Collection string      `json:"collection"`
	Example    interface{} `json:"example"`
}

type GetOptions

type GetOptions struct {
	IfNoneMatch string
	IfMatch     string
}

GetOptions are used when fetching documents Read the GET /_api/document/{document-handle} info

type HasArangoId

type HasArangoId interface {
	Id() string
	SetId(string)
}

type HasArangoKey

type HasArangoKey interface {
	Key() string
	SetKey(string)
}

type HasArangoRev

type HasArangoRev interface {
	Rev() string
	SetRev(string)
}

type KeyOptions

type KeyOptions struct {
	Type          string `json:"type,omitempty"`
	AllowUserKeys bool   `json:"allowUserKeys"`
	Increment     int    `json:"increment"`
	Offset        int    `json:"offset"`
}

KeyOptions stores information about how a collection's key is configured. It is used during collection creation to specify how the new collection's key should be setup.

It is also used for existing collections so you know how the collection's key is configured.

If you've fetched KeyOptions by calling c.Properties then treat these as read only values. You changing them yourself won't do anything special.

type ReplaceOptions

type ReplaceOptions struct {
	WaitForSync bool
	Rev         string
	Policy      string
	IfMatch     string
}

func DefaultReplaceOptions

func DefaultReplaceOptions() *ReplaceOptions

DefaultReplaceOptions returns options with default values according to arango You don't really need this unless you plan on using the Rev/IfMatch or WaitForSync options. In that case, it helps to have this method to have the defaults that arango will use. That way you only change what you need.

type SaveOptions

type SaveOptions struct {
	//The collection to save the item to. Irrelevant when called from a Collection struct
	Collection string

	//CreateCollection specifies if the collection should be created at the same time as this document is being saved.
	//Irrelevant if called from a collection struct
	CreateCollection bool

	//Wait until document has been synced to disk.
	WaitForSync bool
}

Save options represent options available when calling the Post /_api/document/ endpoint

type UpdateOptions

type UpdateOptions struct {
	KeepNull    bool
	MergeArrays bool

	WaitForSync bool
	Rev         string
	Policy      string
	IfMatch     string
}

func DefaultUpdateOptions

func DefaultUpdateOptions() *UpdateOptions

DefaultUpdateOptions returns options with default values according to arango You don't really need this unless you plan on using the Rev/IfMatch or other options. In that case, it helps to have this method to have the defaults that arango will use. That way you only change what you need.

type User

type User struct {
	Username string      `json:"username"`
	Passwd   string      `json:"passwd"`
	Active   bool        `json:"active"`
	Extra    interface{} `json:"extra"`
}

Jump to

Keyboard shortcuts

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