Skip to content

Concepts

Value types

The Go SDK sends values to SurrealDB as CBOR, and decodes the values it receives into the Go types you choose. Most SurrealDB types map onto ordinary Go types, such as string, int64 and map[string]any. The others have a type in the models package, such as models.RecordID and models.PlainDate. This page lists how each type converts, and covers the types that need care.

Type

Description

models.RecordID

A record ID, with a table name and an ID

models.Table

A table name

models.CustomDateTime

A datetime, which wraps

time.Time
models.CustomDuration

A duration, which wraps

time.Duration
models.PlainDate

,

PlainTime

,

Timestamp

,

Interval

The date, time, timestamp and interval kinds of SurrealDB 4.0

models.BigDecimal

,

Float16

,

DecimalString

Decimals and the numbers Go has no type for

models.UUID

A UUID

models.Set

A set of distinct values

models.Regex

A regular expression

models.File

A pointer to a file in a bucket

models.GeometryPoint

and the other geometry types

GeoJSON geometry values

models.Range

A range with included or excluded bounds

The first column is what you send. The last column is what a value decodes into when the target is any, as it is in a map[string]any or a []any. A struct field of a concrete type, such as Age int, takes any value that converts to it.

Go valueSurrealDB typeDecoded into any as
nil, a nil pointerNULLnil
models.NoneNONEnil
boolboolbool
int, int64intuint64 for a value of zero or more, int64 for a negative one
float64floatfloat64
stringstringstring
[]bytebytes[]byte
[]T, []anyarray[]any
map[string]any, a structobjectmap[string]any
time.Time, models.CustomDateTimedatetime, or NONE for a zero timemodels.CustomDateTime
time.Duration, models.CustomDurationdurationmodels.CustomDuration
models.DecimalStringdecimalmodels.DecimalString
models.UUIDuuidmodels.UUID
models.RecordIDrecordmodels.RecordID
models.Tabletablemodels.Table
models.Setsetmodels.Set
models.Filefilemodels.File
models.GeometryPoint and the other geometry typesgeometryThe same type
models.Rangerange
regexp.Regexp, *regexp.RegexpNot sent: encoding fails. Use models.Regex.

The kinds that SurrealDB 4.0 adds, such as sized numbers and dates, are in SurrealDB 4.0 kinds. The SDK matches struct fields by their json tags, and omitempty leaves a field out when it holds its zero value.

The SDK uses one of two versions of the CBOR protocol: cbor.2 with SurrealDB 4.0, and plain CBOR with earlier servers. It offers cbor.2 when it connects. db.CBORVersion() reports which version a connection uses. The two versions differ only for the kinds that SurrealDB 4.0 adds, which plain CBOR cannot carry. Over plain CBOR, the SDK and the server send each of these kinds as the nearest older kind. They cannot send a regex at all.

To keep plain CBOR with a SurrealDB 4.0 server, set DisableCBORv2 in the connection configuration.

A models.RecordID holds a table name and an ID. Build one with models.NewRecordID, or receive one in a result. The ID can be a string, a number, an array or an object:

import "github.com/surrealdb/surrealdb.go/v2/pkg/models"

id := models.NewRecordID("person", "tobie")
numeric := models.NewRecordID("event", 42)
compound := models.NewRecordID("temperature", []any{"London", 2026})

To read a record ID from text such as "person:tobie", use models.ParseRecordID. It always makes a string ID, so "event:42" becomes event:⟨42⟩ rather than event:42. In a struct, use *models.RecordID with omitempty for the id field, so that you can send the struct without an ID:

type Person struct {
	ID   *models.RecordID `json:"id,omitempty"`
	Name string           `json:"name"`
}

A plain string given as the target of a CRUD function is always a table name, even when it holds a :. See Targeting records and tables.

SurrealDB keeps NONE and NULL apart. NONE is a value that does not exist, and NULL is a value that exists and is empty. The SDK sends nil and a nil pointer as NULL, and models.None as NONE. Both decode into nil:

_, err := surrealdb.Create[map[string]any](ctx, db, models.NewRecordID("person", "tobie"), map[string]any{
	"nickname": models.None,
	"manager":  nil,
})

Here the server does not store nickname at all, and it stores manager as NULL. A field defined as option<string> accepts NONE, and one defined as string | null accepts NULL.

The SDK sends a zero time.Time as NONE, so a struct field of type time.Time that you never set leaves the field out. The new models types of SurrealDB 4.0 work differently. Their zero value is a real value, such as the date 1970-01-01, rather than NONE. For an optional field of one of those types, use a pointer with omitempty.

Send a time.Time as it is. The SDK sends it as a SurrealDB datetime with its nanoseconds, and a zero time.Time as NONE:

type Event struct {
	ID        *models.RecordID `json:"id,omitempty"`
	StartedAt time.Time        `json:"started_at"`
}

_, err := surrealdb.Create[Event](ctx, db, "event", Event{StartedAt: time.Now()})

A datetime decodes into a time.Time field, or into a models.CustomDateTime when the target is any. CustomDateTime embeds time.Time, so it has the same methods. To store NULL rather than NONE for a missing time, use a *time.Time that is nil.

Send a time.Duration as it is. The SDK sends it as a SurrealDB duration:

type Job struct {
	ID      *models.RecordID `json:"id,omitempty"`
	Timeout time.Duration    `json:"timeout"`
}

_, err := surrealdb.Create[Job](ctx, db, "job", Job{Timeout: 90 * time.Second})

A duration decodes into a time.Duration field, or into a models.CustomDuration when the target is any. Version 1 of the SDK stored a time.Duration as an int of nanoseconds. A value stored this way also decodes into a time.Duration field.

The SDK sends a Go int, int64 or float64 as a SurrealDB int or float. It sends a uint64 above math.MaxInt64 as a u64 over cbor.2, and as a decimal over plain CBOR. A SurrealDB decimal decodes into a models.DecimalString, which keeps its digits as text. The next section and the Numbers page cover the sized numbers and bigdecimal of SurrealDB 4.0.

SurrealDB 4.0 adds sized numbers, bigdecimal, the calendar kinds date, time, timestamp and interval, and regex. Over cbor.2, each kind keeps its type when you send it and when you receive it. It decodes into any as the Go type in the second column. Over plain CBOR, the SDK and the server send the nearest older kind:

SurrealQLGo typeOver plain CBOR
i8, u8, i16, u16, i32, u32int8, uint8, int16, uint16, int32, uint32int
u64uint64 above math.MaxInt64decimal
f16models.Float16float
f32float32float
bigdecimalmodels.BigDecimaldecimal when the value fits one, otherwise its text
datemodels.PlainDateA datetime at midnight UTC
timemodels.PlainTimeThe duration since midnight
timestampmodels.TimestampA datetime, with the wall clock read as UTC
intervalmodels.IntervalIts ISO 8601 text
regexmodels.RegexNot sent: encoding fails with constants.ErrNeedsCBOR2
results, err := surrealdb.Query[[]any](ctx, db,
	"RETURN [type::of($level), type::of($score), type::of($due)]",
	map[string]any{
		"level": int8(5),
		"score": float32(1.5),
		"due":   models.MustParsePlainDate("2024-02-29"),
	},
)
fmt.Println((*results)[0].Result)
Output with SurrealDB 4.0
[i8 f32 date]

Against a SurrealDB 3.x server, the same query prints [int float datetime]. You can also decode a value of one of these kinds into a Go type other than its own. The value then decodes in the form that plain CBOR carries. For example, a date decodes into a time.Time as midnight UTC on that date.

When you send a Go int8, the server stores it as an i8, so a later read into any gives an int8 back. Code that asserts the type of a decoded number, such as v.(uint64), has to allow for the sized types. Decoding into a struct field of a concrete type converts every numeric kind.

A SurrealDB set holds distinct values in order. To send a set, build a models.Set with models.NewSet. The server sorts it and removes duplicates:

results, err := surrealdb.Query[models.Set](ctx, db, "RETURN $tags", map[string]any{
	"tags": models.NewSet("go", "db", "go"),
})
fmt.Println((*results)[0].Result)
Output
[db go]

A set decodes into any as a models.Set, so a set that you read and write back stays a set. It also decodes into a slice of a concrete type, such as []string.

A models.Regex holds the text of a pattern, which the server compiles with the syntax of the Rust regex crate:

results, err := surrealdb.Query[bool](ctx, db, "RETURN $name = $pattern", map[string]any{
	"name":    "tobie",
	"pattern": models.Regex{Pattern: "^[a-z]+$"},
})

The SDK never compiles a pattern. It also refuses to send a Go *regexp.Regexp, because the Go syntax is not the same. A regex needs SurrealDB 4.0.

The SDK has a type for each GeoJSON geometry. models.GeometryPoint holds a longitude and a latitude, and you build the other types from points:

point := models.GeometryPoint{Longitude: -0.118, Latitude: 51.509}

line := models.GeometryLine{
	{Longitude: -0.118, Latitude: 51.509},
	{Longitude: -0.076, Latitude: 51.508},
}

A models.File points to a file in a bucket, as the SurrealQL value f"bucket:/key" does. Build one with models.NewFile("docs", "/report.pdf"). Send it as a variable.

A models.Range holds two bounds, each included or excluded. Use it as the ID of a models.RecordID to select a range of records.

Was this page helpful?

Last updated