Skip to content

Concepts

Live queries

A live query sends your program a notification each time a record in a table is created, updated or deleted. The Go SDK delivers the notifications on a Go channel, so a goroutine can read them while the rest of the program continues to run. This page shows how to start a live query, read its notifications and stop it. It also explains what happens to a live query when the client reconnects.

Live queries need a WebSocket connection (ws:// or wss://). They are available on a *DB and a *Session, but not on a *Transaction. Over HTTP, Live fails with Unable to perform the realtime query.

Function

Description

surrealdb.Live(ctx, s, table, diff)

Starts a live query on a table and returns its UUID

db.LiveNotifications(id)

Returns the notification channel of a live query

surrealdb.Kill(ctx, s, id)

Stops a live query and closes its channel

db.CloseLiveNotifications(id)

Closes the channel without stopping the live query on the server

Live starts a live query on a table and returns a *models.UUID that identifies it. The table must exist, so define it first:

if _, err := surrealdb.Query[any](ctx, db, "DEFINE TABLE IF NOT EXISTS person", nil); err != nil {
	log.Fatal(err)
}

liveID, err := surrealdb.Live(ctx, db, models.Table("person"), false)
if err != nil {
	log.Fatal(err)
}

The last argument chooses what each notification holds. With false, it holds the record. With true, it holds the JSON Patch operations that changed the record.

.LiveNotifications() returns the channel that receives the live query's Notification values. Read it in a goroutine:

notifications, err := db.LiveNotifications(liveID.String())
if err != nil {
	log.Fatal(err)
}

go func() {
	for n := range notifications {
		switch n.Action {
		case connection.CreateAction:
			fmt.Println("created:", n.Result)
		case connection.UpdateAction:
			fmt.Println("updated:", n.Result)
		case connection.DeleteAction:
			fmt.Println("deleted:", n.Result)
		}
	}
	fmt.Println("live query ended")
}()

Each notification holds three fields:

FieldTypeDescription
ID*models.UUIDThe UUID of the live query
Actionconnection.ActionCREATE, UPDATE, DELETE or KILLED
ResultanyThe record, as a map[string]any, or the JSON Patch operations

The SDK decodes Result into any, so a record arrives as a map[string]any, with its id as a models.RecordID. The connection package is github.com/surrealdb/surrealdb.go/v2/pkg/connection.

When several changes happen quickly, one after another, their notifications can arrive in a different order from the changes.

Kill stops the live query on the server:

if err := surrealdb.Kill(ctx, db, liveID.String()); err != nil {
	log.Fatal(err)
}

The server then sends a notification with the action KILLED. After that, the channel closes and the for ... range loop ends.

.CloseLiveNotifications() closes the channel without stopping the live query on the server. The server can also end a live query itself, for example when its table is removed. The channel then receives a KILLED notification but stays open, so call .CloseLiveNotifications() to close it.

With diff set to true, each notification holds the JSON Patch operations that changed the record. Result is then a []any of maps with op, path and value keys:

liveID, err := surrealdb.Live(ctx, db, models.Table("person"), true)
if err != nil {
	log.Fatal(err)
}

notifications, err := db.LiveNotifications(liveID.String())
if err != nil {
	log.Fatal(err)
}

for n := range notifications {
	if ops, ok := n.Result.([]any); ok {
		for _, op := range ops {
			fmt.Println(op)
		}
	}
}

A diff is smaller than the whole record, which matters for large records that change one field at a time.

A LIVE SELECT statement sent with Query starts a live query too, and returns its UUID. It can filter the records and choose the fields that notifications hold:

result, err := surrealdb.Query[models.UUID](ctx, db,
	"LIVE SELECT * FROM product WHERE stock < 10",
	nil,
)
if err != nil {
	log.Fatal(err)
}

liveID := (*result)[0].Result.String()
notifications, err := db.LiveNotifications(liveID)

Read and stop it as you would one that Live started. When the client reconnects, it cannot restart a live query that a LIVE SELECT statement started: see Reconnecting.

A live query belongs to the session that started it. Start it on a *Session and read it with that session's .LiveNotifications():

liveID, err := surrealdb.Live(ctx, session, models.Table("person"), false)
if err != nil {
	log.Fatal(err)
}

notifications, err := session.LiveNotifications(liveID.String())

The live query runs with the permissions of the user that the session is signed in as. .Reset() and .Detach() on a session kill its live queries.

When the client reconnects, it starts each live query that Live started again on the new connection. The query keeps its UUID, so the channel from .LiveNotifications() keeps receiving notifications. The live query restarts in the namespace and database that its session had selected when you called Live. It uses these even if the session has selected others since then.

The client ends a live query instead of restarting it in two cases:

  • The session is no longer signed in as the same user as when the query started. This makes sure that a live query never runs as someone else.

  • The server refuses to start the live query again.

When the client ends a live query, its channel closes. The status event of the reconnect reports surrealdb.ErrLiveQueryEnded, and .LiveNotifications() returns that error for the query.

The client does not receive notifications for changes that happen while it is disconnected. A reconnect loses a live query that a LIVE SELECT statement started, so use Live for a live query that must survive a reconnect.

Was this page helpful?

Last updated