Go Embedded
Run Traverse inside your Go program, with no server: open or create a .tvdb file, query it with openCypher or GQL, and load data with the bulk writer.
Install
go get github.com/truespar/traverse/go@v0.9.2
# the native library (Linux x64; Windows x64 traverse-ffi-0.9.2-x86_64-windows.zip,
# macOS on Apple silicon traverse-ffi-0.9.2-aarch64-macos.tar.gz)
curl -LO https://github.com/truespar/traverse/releases/download/v0.9.2/traverse-ffi-0.9.2-x86_64-linux.tar.gz
tar xzf traverse-ffi-0.9.2-x86_64-linux.tar.gz
export TRAVERSE_FFI_LIB=$PWD/traverse-ffi-0.9.2-x86_64-linux/libtraverse_ffi.soNo CGo. The package loads the native library at run time: from TRAVERSE_FFI_LIB, next to your executable, or from the system's library path (traverse_ffi.dll on Windows, libtraverse_ffi.so on Linux, libtraverse_ffi.dylib on macOS). The traverse-ffi archives on the release have it for Windows x64, Linux x64 and macOS on Apple silicon; Open returns an error when it's missing or from another version.
Open a Database
package main
import (
"fmt"
"log"
traverse "github.com/truespar/traverse/go"
)
func main() {
// open, or create, a database file
db, err := traverse.Open("mydb.tvdb")
if err != nil {
log.Fatal(err)
}
defer db.Close()
}Close rolls back transactions still open on the database, saves it, and leaves the .tvdb as a single file. Another process can't open the file while it's open.
Run Queries
Execute on the database runs a query as a transaction of its own: a read runs on a snapshot and never waits, a write commits when it succeeds and rolls back when it fails.
if _, err := db.Execute("CREATE (:Person {name: 'Alice', age: 30}), (:Person {name: 'Bob', age: 25})"); err != nil {
log.Fatal(err)
}
result, err := db.Execute("MATCH (n:Person) RETURN n.name AS name, n.age AS age ORDER BY name")
if err != nil {
log.Fatal(err)
}
for _, row := range result.Rows {
fmt.Println(row["name"], row["age"]) // Alice 30, then Bob 25
}GQL
ExecuteGql runs ISO/IEC 39075 GQL instead of openCypher (on the database or a transaction):
result, err := db.ExecuteGql("MATCH (n:Person) FILTER n.age > 26 RETURN n.name AS name")Transactions
// a write transaction
tx, err := db.Begin()
if err != nil {
log.Fatal(err)
}
if _, err := tx.Execute("CREATE (:Person {name: 'Carol', age: 41})"); err != nil {
tx.Abort()
log.Fatal(err)
}
if err := tx.Commit(); err != nil {
log.Fatal(err)
}
// a read transaction: a snapshot of the database as of now, alongside the writer and other readers
snap, err := db.BeginRead()
if err != nil {
log.Fatal(err)
}
counted, _ := snap.Execute("MATCH (p:Person) RETURN count(p) AS n")
fmt.Println(counted.Rows[0]["n"]) // 3
snap.Commit() // ends the read transactionOne write transaction is active at a time: Begin waits for the active one for up to the busy timeout (5 seconds, SetBusyTimeout changes it), then fails with ErrBusy. A statement that fails after changing data fails its transaction: later statements and Commit return ErrTransaction, and only Abort ends it. A transaction dropped without Commit or Abort is rolled back.
A commit is durable when it returns: it's written to the database's redo log first. The database also saves itself in the background (once the log has grown by 64 MiB, or when a commit has gone five minutes unsaved), so reopening after a crash replays little.
QueryResult
result, _ := db.Execute("MATCH (n:Person) RETURN n.name, n.age")
fmt.Println(result.Columns) // [n.name n.age]
fmt.Println(result.RowCount) // 3
// rows are []map[string]interface{}
for _, row := range result.Rows {
fmt.Printf("%v is %v years old\n", row["n.name"], row["n.age"])
}
// node values
result, _ = db.Execute("MATCH (n:Person {name: 'Alice'}) RETURN n")
node := result.Rows[0]["n"].(traverse.Node)
fmt.Println(node.ID, node.Labels, node.Properties)
// relationship values
db.Execute("MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'}) CREATE (a)-[:KNOWS]->(b)")
result, _ = db.Execute("MATCH ()-[r:KNOWS]->() RETURN r LIMIT 1")
edge := result.Rows[0]["r"].(traverse.Edge)
fmt.Println(edge.Type, edge.Source, edge.Target)Bulk Writer
A bulk load is a write transaction that skips the redo log: Commit saves the database with the load in it, so the data is written once and is durable when Commit returns. Readers don't see the load until then, and Abort rolls it back.
writer, err := db.BulkWriter()
if err != nil {
log.Fatal(err)
}
acme, err := writer.CreateNode([]string{"Company"}, map[string]string{"name": "Acme", "founded": "1998"})
if err != nil {
writer.Abort()
log.Fatal(err)
}
globex, err := writer.CreateNode([]string{"Company"}, map[string]string{"name": "Globex", "founded": "2004"})
if err != nil {
writer.Abort()
log.Fatal(err)
}
if _, err := writer.CreateEdge(acme, globex, "OWNS", map[string]string{"share": "0.6"}); err != nil {
writer.Abort()
log.Fatal(err)
}
if err := writer.CreateIndex("company_name", "Company", "name"); err != nil {
writer.Abort()
log.Fatal(err)
}
if err := writer.Commit(); err != nil {
log.Fatal(err)
}Note: the Go bulk writer takes property values as strings and infers their types (numbers, booleans, strings). CreateEdgeIndex(name, type, property) indexes a relationship property, or with an empty property the relationship type.
A file built this way can be uploaded to a Traverse server and put behind an alias, so queries move to the new data in one step.
Timeouts, Cancelling and Errors
db.SetBusyTimeout(10 * time.Second) // wait for another writer
db.SetStatementTimeout(30 * time.Second) // how long a statement may run (0: no limit)
// a context stops the statement when it's cancelled or its deadline passes
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
_, err = db.ExecuteContext(ctx, "MATCH (n) RETURN count(n)")
_, err = db.Execute("MATCH (p:Person) RETURN nosuchfunction(p.name)")
var tvErr *traverse.TraverseError
if errors.As(err, &tvErr) {
fmt.Println(tvErr.Code, tvErr.GqlStatus) // the error code, and 42N48 (unknown function)
}A statement that runs past the statement timeout, that another goroutine stops with Transaction.Cancel, or whose context ends, fails with ErrInterrupted. GqlStatus holds the error's GQLSTATUS code (the ISO/IEC 39075 code where the standard has one). Embedded transactions show in SHOW TRANSACTIONS, and TERMINATE TRANSACTIONS stops them.
Error codes:
traverse.ErrIO // I/O error
traverse.ErrCorrupt // the file is damaged
traverse.ErrLocked // another process has the file open
traverse.ErrSyntax // query syntax error
traverse.ErrType // type mismatch
traverse.ErrSemantic // semantic error
traverse.ErrGraph // node or relationship not found
traverse.ErrTransaction // transaction error
traverse.ErrInvalidArg // invalid argument
traverse.ErrInternal // internal error
traverse.ErrResourceExhausted // a resource limit was exceeded (memory budget, readers)
traverse.ErrBusy // the writer lock stayed taken for the whole busy timeout
traverse.ErrInterrupted // the statement was stoppedFlush and Close
if err := db.Flush(); err != nil { // save now
log.Fatal(err)
}
if err := db.Close(); err != nil { // roll back open transactions, save, release the file
log.Fatal(err)
}