• Start

Languages

/

Go

/

Concepts

Live queries

The Go SDK supports real-time live queries that stream change notifications from the database through Go channels.

Live queries allow your application to receive real-time notifications whenever records in a table are created, updated, or deleted. The Go SDK delivers notifications through Go channels, making it easy to integrate with goroutines and concurrent patterns.

Live queries require a WebSocket connection (ws:// or wss://). They are available on *DB and *Session but not on *Transaction.

Function

Description

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

Starts a live query on a table and returns its UUID

surrealdb.Kill(ctx, s, id)

Stops a live query and closes its notification channel

db.LiveNotifications(id)

Returns the notification channel for a live query

db.CloseLiveNotifications(id)

Closes the notification channel without killing the server-side query

Use the Live function to subscribe to changes on a table. It returns a UUID that identifies the live query.

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

The diff parameter controls notification format. When false, notifications contain the full record. When true, they contain JSON Patch diffs instead.

After starting a live query, call .LiveNotifications() on the *DB or *Session to get a channel that receives Notification values.

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

for notification := range ch {
	fmt.Printf("Action: %s, Result: %v\n", notification.Action, notification.Result)
}

Each notification includes:

FieldTypeDescription
ID*models.UUIDThe live query UUID
ActionActionOne of CREATE, UPDATE, or DELETE
Resultinterface{}The record data or JSON Patch diff

A common pattern is to process live query notifications in a separate goroutine while the main goroutine continues other work.

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

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

go func() {
	for n := range ch {
		switch n.Action {
		case "CREATE":
			fmt.Println("New record:", n.Result)
		case "UPDATE":
			fmt.Println("Updated record:", n.Result)
		case "DELETE":
			fmt.Println("Deleted record:", n.Result)
		}
	}
}()

Use the Kill function to terminate a live query on the server and close its notification channel.

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

Kill both sends the kill RPC to the server and closes the local notification channel. If you only want to close the channel without killing the server-side query, use .CloseLiveNotifications() instead.

Was this page helpful?