Using an embedded instance

Setup

  1. Build surrealdb.c and set up CGO

  2. Run the command go get github.com/surrealdb/surrealdb.c.go

  3. Write code to connect to an embedded instance of SurrealDB.

The following code shows a simple example that opens up an embedded instance in memory, defines a table and then creates and selects a person record that matches the Person struct that the output deserializes into.

package main

import (
"context"
"fmt"
"log"

surrealdb "github.com/surrealdb/surrealdb.c.go"
)

type Person struct {
ID surrealdb.RecordID[string] `cbor:"id,omitempty"`
Name string `cbor:"name"`
Age int64 `cbor:"age"`
}

func main() {
ctx := context.Background()

db, err := surrealdb.Open(ctx, "mem://")
if err != nil {
log.Fatal(err)
}
defer db.Close()

db.Use(ctx, "test", "test")
db.Query(ctx, "DEFINE TABLE person SCHEMALESS", nil)
db.Query(ctx, "CREATE $rid CONTENT $content", map[string]any{
"rid": surrealdb.NewRecordID("person", "alice"),
"content": Person{Name: "Alice", Age: 30},
})

results, _ := surrealdb.Query[Person](ctx, db, "SELECT * FROM person", nil)
for _, p := range results[0].Values() {
fmt.Printf("%s: %s (age %d)\n", p.ID, p.Name, p.Age)
}
}

More information

For more information on the Go bindings used for an embedded SurrealDB instance, see this page for the surrealdb.c.go repo.

Pages of particular note are: