The Go SDK has a generic function for each common operation on records: Select, Create, Insert, Update, Upsert, Merge, Patch, Delete, Relate and InsertRelation. Each one sends a SurrealQL statement and decodes the result into the Go type that you pass as its type parameter. All of them work with a *DB, a *Session or a *Transaction. This page covers how to target records and how to use each function.
API references
Function | Description |
|---|---|
surrealdb.Select[T](ctx, s, what) | Selects a record, the records of a table, or a range of records |
surrealdb.Create[T](ctx, s, what, data) | Creates a record |
surrealdb.Insert[T](ctx, s, table, data) | Inserts one or more records into a table |
surrealdb.Update[T](ctx, s, what, data) | Replaces the content of existing records |
surrealdb.Upsert[T](ctx, s, what, data) | Creates records, or replaces their content when they exist |
surrealdb.Merge[T](ctx, s, what, data) | Merges data into existing records |
surrealdb.Patch(ctx, s, what, patches) | Applies JSON Patch operations and returns the changes |
surrealdb.PatchWithResult[T](ctx, s, what, patches, output) | Applies JSON Patch operations and returns what you choose |
surrealdb.Delete[T](ctx, s, what) | Deletes records and returns them as they were |
surrealdb.Relate[T](ctx, s, rel) | Creates a relation with a generated ID |
surrealdb.InsertRelation[T](ctx, s, rel) | Inserts a relation, with an ID you can choose |
Targeting records and tables
The functions that take a what argument accept a models.RecordID, a models.Table, a string, or a slice of record IDs or tables. The value that you pass decides what the statement works on and the shape of its result:
what | Works on | Result |
|---|---|---|
models.NewRecordID("person", "tobie") | One record | The record, or nil when it does not exist |
models.Table("person") | Every record in the table | A slice of records |
"person" | Every record in the table, or one new record for Create | A slice of records, or the created record for Create |
A models.RecordID whose ID is a models.Range | The records in the range | A slice of records |
[]models.RecordID, []models.Table | Each record or table in the slice | A slice of records |
A string is always a table name. The SDK never reads a string as a record ID. "person:tobie" names a table called person:tobie, so Select returns the error The table 'person:tobie' does not exist. Use models.NewRecordID for a record. When the ID arrives as text, models.ParseRecordID parses it. But ParseRecordID always makes a string ID, so the ID does not match a record whose ID is a number.
Match the type parameter to the result. For a single record, pass the record type, such as Person. For a table, a range or a slice, pass a slice, such as []Person. If the types do not match, the SDK cannot decode the result and returns an error such as cannot decode array into main.Person. The examples on this page use this type:
type Person struct {
ID *models.RecordID `json:"id,omitempty"`
Name string `json:"name"`
Surname string `json:"surname,omitempty"`
Age int `json:"age,omitempty"`
}Use *models.RecordID with omitempty for the id field. You can then send the struct without an ID, and read it back with one.
Selecting records
Select reads one record, the records of a table, or the records in a range:
people, err := surrealdb.Select[[]Person](ctx, db, models.Table("person"))
if err != nil {
log.Fatal(err)
}
tobie, err := surrealdb.Select[Person](ctx, db, models.NewRecordID("person", "tobie"))
if err != nil {
log.Fatal(err)
}
if tobie == nil {
fmt.Println("no such person")
}When the record does not exist, Select returns nil and no error.
Selecting a range of records
To select the records whose IDs fall in a range, pass a models.RecordID whose ID is a models.Range. The example below selects reading:2 and reading:3, from 2 included to 4 excluded:
rng := models.RecordID{
Table: "reading",
ID: models.Range[int, models.BoundIncluded[int], models.BoundExcluded[int]]{
Begin: &models.BoundIncluded[int]{Value: 2},
End: &models.BoundExcluded[int]{Value: 4},
},
}
readings, err := surrealdb.Select[[]map[string]any](ctx, db, rng)A nil Begin or End leaves that side of the range open. The query builder has helpers that build the range for you, such as surrealql.RangeBeginInclusiveEndExclusive(2, 4). For an array ID such as temp:['London', 'West', 1], use models.None as the lowest value of a part, as in []any{"London", models.None, models.None}.
Creating records
Create creates a record from a struct or a map. To choose the ID, pass a models.RecordID. To let SurrealDB generate the ID, pass the table name as a string. Both forms return the created record:
tobie, err := surrealdb.Create[Person](ctx, db, models.NewRecordID("person", "tobie"), Person{
Name: "Tobie",
Surname: "Morgan Hitchcock",
Age: 35,
})
jaime, err := surrealdb.Create[Person](ctx, db, "person", Person{Name: "Jaime"})
fmt.Println(jaime.ID)person:1wxlej6yf7cvn3t27m0fWith a models.Table, Create returns a slice, so pass []Person as the type parameter. If you pass nil data, Create creates a record with no fields other than its ID.
To ignore the result, pass struct{} as the type parameter:
_, err := surrealdb.Create[struct{}](ctx, db, "person", Person{Name: "Ana"})Inserting records
Insert inserts one record or a slice of records into a table, and always returns a slice:
inserted, err := surrealdb.Insert[Person](ctx, db, models.Table("person"), []Person{
{Name: "Alice", Age: 30},
{Name: "Bob", Age: 25},
})
fmt.Println(len(*inserted))2The type parameter of Insert is the type of one record. The function returns *[]T. A record in the data can have its own id. Insert cannot create a relation: use InsertRelation for that.
Replacing records
Update replaces the whole content of existing records with the data you pass. It removes the fields that the data leaves out:
updated, err := surrealdb.Update[Person](ctx, db, models.NewRecordID("person", "tobie"), Person{
Name: "Tobie",
}) Update performs a full replacement, so it removes the surname and age of person:tobie. Use Merge to change some fields and keep the others.
Update changes only records that exist, and creates nothing. On a table, it updates every record. Use Upsert to create the record when it is missing.
Upserting records
Upsert creates a record when it does not exist, and replaces its content when it does:
ana, err := surrealdb.Upsert[Person](ctx, db, models.NewRecordID("person", "ana"), Person{
Name: "Ana",
Age: 16,
})Merging data into records
Merge merges the data you pass into existing records, and keeps the fields that the data does not mention:
merged, err := surrealdb.Merge[Person](ctx, db, models.NewRecordID("person", "tobie"), map[string]any{
"age": 36,
})A merge into a table changes every record in the table, and returns a slice:
everyone, err := surrealdb.Merge[[]Person](ctx, db, models.Table("person"), map[string]any{
"active": true,
})Applying JSON Patch operations
Patch applies JSON Patch operations to a record, and returns the operations that changed it. Each operation is a PatchData with an Op, a Path and a Value:
changes, err := surrealdb.Patch(ctx, db, models.NewRecordID("person", "tobie"), []surrealdb.PatchData{
{Op: "replace", Path: "/age", Value: 37},
{Op: "add", Path: "/verified", Value: true},
})The operations are add, remove, replace, move, copy and test. Patch returns *[]PatchData, which fits the result for one record. For a table, the result holds the changes of each record, so use PatchWithResult.
Choosing what a patch returns
PatchWithResult applies JSON Patch operations in the same way as Patch. It returns what its last argument asks for:
ReturnMode | Returns |
|---|---|
surrealdb.ReturnAfter | The records after the change |
surrealdb.ReturnBefore | The records before the change |
surrealdb.ReturnDiff | The JSON Patch operations that changed each record |
surrealdb.ReturnNone | Nothing: the result is nil |
patched, err := surrealdb.PatchWithResult[Person](ctx, db,
models.NewRecordID("person", "tobie"),
[]surrealdb.PatchData{{Op: "replace", Path: "/age", Value: 38}},
surrealdb.ReturnAfter,
)
fmt.Println(patched.Age)38For a table, use a slice as the type parameter, such as []Person for ReturnAfter, or [][]surrealdb.PatchData for ReturnDiff:
diffs, err := surrealdb.PatchWithResult[[][]surrealdb.PatchData](ctx, db,
models.Table("person"),
[]surrealdb.PatchData{{Op: "replace", Path: "/active", Value: false}},
surrealdb.ReturnDiff,
)Deleting records
Delete deletes a record, the records of a table, or a range of records. It returns the records as they were before the delete:
deleted, err := surrealdb.Delete[Person](ctx, db, models.NewRecordID("person", "ana"))
everyone, err := surrealdb.Delete[[]Person](ctx, db, models.Table("person"))Relating records
Relate creates an edge in a relation table, from one record to another, with a generated ID. Describe the edge with a Relationship:
edge, err := surrealdb.Relate[map[string]any](ctx, db, &surrealdb.Relationship{
In: models.NewRecordID("person", "tobie"),
Out: models.NewRecordID("person", "jaime"),
Relation: models.Table("knows"),
Data: map[string]any{"since": 2020},
})Relate ignores the ID field of the Relationship. This field exists so that the SDK can decode an edge into the struct.
Inserting relations
InsertRelation inserts an edge, as INSERT RELATION does. If the Relationship has an ID, InsertRelation uses that ID. Otherwise, it generates an ID. It returns a slice:
id := models.NewRecordID("knows", "tobie_jaime")
edges, err := surrealdb.InsertRelation[[]map[string]any](ctx, db, &surrealdb.Relationship{
ID: &id,
In: models.NewRecordID("person", "tobie"),
Out: models.NewRecordID("person", "jaime"),
Relation: models.Table("knows"),
})When you only need the ID of the edge, decode into []connection.ResponseID[models.RecordID].
Learn more
DB API reference for complete function signatures and parameters
Executing queries for running SurrealQL statements directly
Value types for the Go types that each SurrealDB kind uses
RecordID reference for building record IDs
SurrealQL statements for the statements these functions send