### Initialize GeometryPoint Source: https://surrealdb.com/docs/reference/golang/api/values/geometry Example of creating a new GeometryPoint instance. ```go point := models.GeometryPoint{Longitude: -0.118, Latitude: 51.509} ``` -------------------------------- ### RecordID construction examples Source: https://surrealdb.com/docs/reference/golang/api/values/record-id Examples showing the creation of RecordID instances with string, numeric, and composite identifiers. ```go id := models.NewRecordID("persons", "tobie") numericID := models.NewRecordID("events", 42) compositeID := models.NewRecordID("access", []any{"us", 2026}) ``` -------------------------------- ### Session usage example Source: https://surrealdb.com/docs/reference/golang/api/core/session Demonstrates attaching a session, authenticating, selecting a namespace/database, and executing a query. ```go session, err := db.Attach(ctx) if err != nil { log.Fatal(err) } defer session.Detach(ctx) session.SignIn(ctx, surrealdb.Auth{Username: "root", Password: "root"}) session.Use(ctx, "my_ns", "my_db") results, err := surrealdb.Query[[]Person](ctx, session, "SELECT * FROM persons", nil) ``` -------------------------------- ### session.Begin() Source: https://surrealdb.com/docs/reference/golang/api/core/session Starts a new interactive transaction within this session. ```APIDOC ## session.Begin() ### Description Starts a new interactive transaction within this session. ### Signature `tx, err := session.Begin(ctx)` ### Returns `(*Transaction, error)` ``` -------------------------------- ### Install SurrealDB Go SDK Source: https://surrealdb.com/docs/reference/golang/installation Use this command to fetch the SDK package from pkg.go.dev. ```bash go get github.com/surrealdb/surrealdb.go ``` -------------------------------- ### Start a transaction with db.Begin() or session.Begin() Source: https://surrealdb.com/docs/reference/golang/api/core/transaction Use these methods to initiate a transaction on the default database connection or a specific session. ```go tx, err := db.Begin(ctx) ``` ```go tx, err := session.Begin(ctx) ``` -------------------------------- ### db.Begin(ctx) Source: https://surrealdb.com/docs/reference/golang/api/core/transaction Starts a new interactive transaction on the default SurrealDB session. ```APIDOC ## db.Begin(ctx) ### Description Starts a transaction on the default session. Returns an error if the connection is not a WebSocket. ### Signature `tx, err := db.Begin(ctx)` ### Parameters - **ctx** (context.Context) - Required - Context for the operation. ### Returns - **(*Transaction, error)** - The transaction object or an error. ``` -------------------------------- ### Begin Transaction Source: https://surrealdb.com/docs/reference/golang/api/core/db Starts an interactive transaction on the default session. Supported only on WebSocket connections. ```go tx, err := db.Begin(ctx) ``` -------------------------------- ### SignIn syntax and examples Source: https://surrealdb.com/docs/reference/golang/api/core/db Signs in an existing user using credentials provided as an Auth struct or map. The authData determines the authentication level. ```go token, err := db.SignIn(ctx, authData) ``` ```go token, err := db.SignIn(ctx, surrealdb.Auth{ Username: "root", Password: "root", }) ``` ```go token, err := db.SignIn(ctx, map[string]any{ "NS": "my_ns", "DB": "my_db", "AC": "user_access", "user": "tobie", "pass": "s3cret", }) ``` -------------------------------- ### session.Begin(ctx) Source: https://surrealdb.com/docs/reference/golang/api/core/transaction Starts a new interactive transaction within a specific session. ```APIDOC ## session.Begin(ctx) ### Description Starts a transaction within a specific session. Returns an error if the session has been detached. ### Signature `tx, err := session.Begin(ctx)` ### Parameters - **ctx** (context.Context) - Required - Context for the operation. ### Returns - **(*Transaction, error)** - The transaction object or an error. ``` -------------------------------- ### Start a transaction from a session Source: https://surrealdb.com/docs/reference/golang/concepts/multiple-sessions Initiates a transaction that inherits the session's authentication and namespace context. ```go tx, err := session.Begin(ctx) if err != nil { log.Fatal(err) } defer tx.Cancel(ctx) surrealdb.Create[any](ctx, tx, models.Table("events"), map[string]any{"type": "login"}) if err := tx.Commit(ctx); err != nil { log.Fatal(err) } ``` -------------------------------- ### Usage of Geometry Types Source: https://surrealdb.com/docs/reference/golang/api/values/geometry Example showing how to use geometry types within a struct and initialize lines and polygons. ```go import "github.com/surrealdb/surrealdb.go/pkg/models" type Location struct { ID *models.RecordID `json:"id,omitempty"` Name string `json:"name"` Position models.GeometryPoint `json:"position"` Boundary models.GeometryPolygon `json:"boundary"` } line := models.GeometryLine{ {Longitude: -0.118, Latitude: 51.509}, {Longitude: -0.076, Latitude: 51.508}, } polygon := models.GeometryPolygon{ models.GeometryLine{ {Longitude: -0.12, Latitude: 51.50}, {Longitude: -0.08, Latitude: 51.50}, {Longitude: -0.08, Latitude: 51.52}, {Longitude: -0.12, Latitude: 51.52}, {Longitude: -0.12, Latitude: 51.50}, }, } ``` -------------------------------- ### Start a transaction in Golang Source: https://surrealdb.com/docs/reference/golang/concepts/transactions Initiate a transaction using the Begin method. Always use defer to ensure the transaction is cancelled if an error occurs or the function returns early. ```go tx, err := db.Begin(ctx) if err != nil { log.Fatal(err) } defer tx.Cancel(ctx) ``` -------------------------------- ### Start a live query Source: https://surrealdb.com/docs/reference/golang/api/core/db Initiates a live query on a specified table. Requires a context, a database or session sender, and a boolean flag for JSON Patch diffs. ```go liveID, err := surrealdb.Live(ctx, s, table, diff) ``` -------------------------------- ### Get Database Version Source: https://surrealdb.com/docs/reference/golang/api/core/session Retrieves version information from the SurrealDB instance. ```go ver, err := session.Version(ctx) ``` -------------------------------- ### Initialize and use CustomDateTime Source: https://surrealdb.com/docs/reference/golang/api/values/datetime Example of initializing a CustomDateTime instance and using it within a struct definition. ```go import "github.com/surrealdb/surrealdb.go/pkg/models" now := models.CustomDateTime{Time: time.Now()} type Event struct { ID *models.RecordID `json:"id,omitempty"` CreatedAt models.CustomDateTime `json:"created_at"` } ``` -------------------------------- ### db.Begin() Source: https://surrealdb.com/docs/reference/golang/api/core/db Starts a new interactive transaction on the default session. Transactions are only supported on WebSocket connections (SurrealDB v3+). ```APIDOC ## .Begin() ### Description Starts a new interactive transaction on the default session. Transactions are only supported on WebSocket connections (SurrealDB v3+). ### Syntax `tx, err := db.Begin(ctx)` ### Returns `(*Transaction, error)` ``` -------------------------------- ### Usage of CustomDuration Source: https://surrealdb.com/docs/reference/golang/api/values/duration Example of initializing a CustomDuration and using it within a struct. ```go import "github.com/surrealdb/surrealdb.go/pkg/models" dur := models.CustomDuration{Duration: 2*time.Hour + 30*time.Minute} fmt.Println(dur.String()) // "2h30m" type Session struct { ID *models.RecordID `json:"id,omitempty"` Timeout models.CustomDuration `json:"timeout"` } ``` -------------------------------- ### Connect to SurrealDB via WebSocket or HTTPS Source: https://surrealdb.com/docs/reference/golang/api/core/db Examples of initializing a connection using specific URL schemes. ```go db, err := surrealdb.FromEndpointURLString(ctx, "ws://localhost:8000") ``` ```go db, err := surrealdb.FromEndpointURLString(ctx, "https://cloud.surrealdb.com") ``` -------------------------------- ### SignInWithRefresh syntax and examples Source: https://surrealdb.com/docs/reference/golang/api/core/db Signs in using a TYPE RECORD access method with WITH REFRESH enabled, returning both access and refresh tokens. Requires SurrealDB v3+. ```go tokens, err := db.SignInWithRefresh(ctx, authData) ``` ```go tokens, err := db.SignInWithRefresh(ctx, map[string]any{ "NS": "my_ns", "DB": "my_db", "AC": "user_access", "user": "tobie", "pass": "s3cret", }) ``` ```go newTokens, err := db.SignInWithRefresh(ctx, map[string]any{ "NS": "my_ns", "DB": "my_db", "AC": "user_access", "refresh": tokens.Refresh, }) ``` -------------------------------- ### Get SurrealQL representation Source: https://surrealdb.com/docs/reference/golang/api/values/record-id Syntax for retrieving the SurrealQL-formatted string representation of a RecordID. ```go s := id.SurrealString() ``` -------------------------------- ### surrealdb.Live Source: https://surrealdb.com/docs/reference/golang/api/core/db Starts a live query on a specified table. Returns a UUID for the live query or an error. ```APIDOC ## surrealdb.Live ### Description Starts a live query on a table. Only available on *DB and *Session. ### Syntax `liveID, err := surrealdb.Live(ctx, s, table, diff)` ### Parameters - **ctx** (context.Context) - Required - Context for the operation. - **s** (*DB | *Session) - Required - The sender (not *Transaction). - **table** (models.Table) - Required - The table to watch. - **diff** (bool) - Required - If true, notifications contain JSON Patch diffs. ### Returns (*models.UUID, error) ``` -------------------------------- ### Get string representation Source: https://surrealdb.com/docs/reference/golang/api/values/record-id Syntax for retrieving the 'table:id' string representation of a RecordID. ```go s := id.String() ``` -------------------------------- ### Initialize DB with FromConnection Source: https://surrealdb.com/docs/reference/golang/api/core/db Syntax for creating a new DB instance from a custom connection implementation. ```go db, err := surrealdb.FromConnection(ctx, conn) ``` -------------------------------- ### Initialize DB with FromEndpointURLString Source: https://surrealdb.com/docs/reference/golang/api/core/db Syntax for creating a new DB instance using a connection URL string. ```go db, err := surrealdb.FromEndpointURLString(ctx, connectionURL) ``` -------------------------------- ### Get Session ID Source: https://surrealdb.com/docs/reference/golang/api/core/session Retrieves the unique identifier for the current session. ```go id := session.ID() ``` -------------------------------- ### Create and configure a session in Go Source: https://surrealdb.com/docs/reference/golang/concepts/multiple-sessions Initializes a new session using Attach, then authenticates and selects a namespace and database for that specific session context. ```go session, err := db.Attach(ctx) if err != nil { log.Fatal(err) } defer session.Detach(ctx) _, err = session.SignIn(ctx, surrealdb.Auth{ Username: "root", Password: "root", }) if err != nil { log.Fatal(err) } if err := session.Use(ctx, "my_ns", "my_db"); err != nil { log.Fatal(err) } ``` -------------------------------- ### Create a database instance from a connection Source: https://surrealdb.com/docs/reference/golang/concepts/reliable-connections Uses the established connection to initialize the SurrealDB database client. ```go db, err := surrealdb.FromConnection(ctx, conn) if err != nil { log.Fatal(err) } defer db.Close(ctx) ``` -------------------------------- ### SignUp syntax Source: https://surrealdb.com/docs/reference/golang/api/core/db Signs up a new record user. ```go token, err := db.SignUp(ctx, authData) ``` -------------------------------- ### Select namespace and database Source: https://surrealdb.com/docs/reference/golang/api/core/db Sets the target namespace and database for subsequent operations. ```go err := db.Use(ctx, ns, database) ``` -------------------------------- ### Set Namespace and Database Source: https://surrealdb.com/docs/reference/golang/api/core/session Configures the target namespace and database for the session. ```go err := session.Use(ctx, ns, database) ``` -------------------------------- ### Use RecordID in a struct Source: https://surrealdb.com/docs/reference/golang/api/values/record-id Example of embedding a RecordID within a struct for automatic CBOR marshaling. ```go type Person struct { ID *models.RecordID `json:"id,omitempty"` Name string `json:"name"` } ``` -------------------------------- ### Begin Transaction Source: https://surrealdb.com/docs/reference/golang/api/core/session Initiates an interactive transaction within the session. ```go tx, err := session.Begin(ctx) ``` -------------------------------- ### Sign in as a system user Source: https://surrealdb.com/docs/reference/golang/concepts/authentication Use the Auth struct to authenticate as a root, namespace, or database user by providing the required credentials. ```go token, err := db.SignIn(ctx, surrealdb.Auth{ Username: "root", Password: "root", }) ``` ```go token, err := db.SignIn(ctx, surrealdb.Auth{ Namespace: "my_ns", Database: "my_db", Username: "db_user", Password: "db_pass", }) ``` -------------------------------- ### Select namespace and database Source: https://surrealdb.com/docs/reference/golang/concepts/connecting-to-surrealdb Use the Use method to specify the target namespace and database for subsequent operations. This can be called multiple times to switch contexts on an existing connection. ```go if err := db.Use(ctx, "my_namespace", "my_database"); err != nil { log.Fatal(err) } ``` -------------------------------- ### Creating records Source: https://surrealdb.com/docs/reference/golang/concepts/query-builder Use Create to build a CREATE query, setting fields individually or providing a map of content. ```go surrealql.Create("users"). Set("name", "Alice"). Set("age", 30) // CREATE users SET name = $set_1, age = $set_2 surrealql.Create("users").Content(map[string]any{ "name": "Alice", "age": 30, }) // CREATE users CONTENT $content_1 ``` -------------------------------- ### Building Text-Based Transactions Source: https://surrealdb.com/docs/reference/golang/concepts/query-builder Shows how to compose multiple statements into an atomic transaction using the Begin and Then methods. ```go q := surrealql.Begin(). Then(surrealql.Create("users").Set("name", "Alice")). Then(surrealql.Create("users").Set("name", "Bob")) sql, vars := q.Build() // BEGIN TRANSACTION; CREATE users SET name = $set_1; CREATE users SET name = $set_2; COMMIT TRANSACTION; ``` -------------------------------- ### Using Return Clauses in Mutations Source: https://surrealdb.com/docs/reference/golang/concepts/query-builder Demonstrates how to append return clauses to Create, Update, and Delete operations to control the returned data. ```go surrealql.Create("users").Set("name", "Alice").ReturnNone() // CREATE users SET name = $set_1 RETURN NONE surrealql.Update("users").Set("active", true).Return("AFTER") // UPDATE users SET active = $set_1 RETURN AFTER surrealql.Delete("sessions").ReturnBefore() // DELETE sessions RETURN BEFORE ``` -------------------------------- ### Sign Up User Source: https://surrealdb.com/docs/reference/golang/api/core/session Registers a new record user within the session. ```go token, err := session.SignUp(ctx, authData) ``` -------------------------------- ### Querying using a session Source: https://surrealdb.com/docs/reference/golang/concepts/multiple-sessions Demonstrates executing a query using a session object, which satisfies the sendable constraint. ```go results, err := surrealdb.Query[[]Person](ctx, session, "SELECT * FROM persons", nil, ) ``` -------------------------------- ### session.Use() Source: https://surrealdb.com/docs/reference/golang/api/core/session Selects the namespace and database for this session. ```APIDOC ## session.Use() ### Description Selects the namespace and database for this session. ### Signature `err := session.Use(ctx, ns, database)` ### Returns `error` ``` -------------------------------- ### Targeting tables and records in Go Source: https://surrealdb.com/docs/reference/golang/concepts/data-manipulation Demonstrates how to use Table and RecordID types to scope database operations to either all records or a specific record. ```go import "github.com/surrealdb/surrealdb.go/pkg/models" all, err := surrealdb.Select[[]Person](ctx, db, models.Table("persons")) one, err := surrealdb.Select[Person](ctx, db, models.NewRecordID("persons", "tobie")) ``` -------------------------------- ### session.SignUp() Source: https://surrealdb.com/docs/reference/golang/api/core/session Signs up a new record user within this session. ```APIDOC ## session.SignUp() ### Description Signs up a new record user within this session. ### Signature `token, err := session.SignUp(ctx, authData)` ### Returns `(string, error)` ``` -------------------------------- ### Building and executing queries Source: https://surrealdb.com/docs/reference/golang/concepts/query-builder Use the Build method to generate a query string and parameter map for use with the surrealdb.Query function. ```go q := surrealql.Select("users").Where("age > ?", 18).Limit(10) sql, vars := q.Build() results, err := surrealdb.Query[[]User](ctx, db, sql, vars) ``` -------------------------------- ### Sign up a new record user Source: https://surrealdb.com/docs/reference/golang/concepts/authentication Creates a new record user using a defined access method. Requires the access method to be defined as TYPE RECORD beforehand. ```go token, err := db.SignUp(ctx, map[string]any{ "NS": "my_ns", "DB": "my_db", "AC": "user_access", "user": "new_user", "pass": "s3cret", "email": "user@example.com", }) ``` -------------------------------- ### Execute a basic query Source: https://surrealdb.com/docs/reference/golang/concepts/executing-queries Executes a SurrealQL query and iterates over the returned results. ```go results, err := surrealdb.Query[[]Person](ctx, db, "SELECT * FROM persons WHERE age > $min_age", map[string]any{"min_age": 18}, ) if err != nil { log.Fatal(err) } for _, qr := range *results { fmt.Println(qr.Status, qr.Result) } ``` -------------------------------- ### Sign In User Source: https://surrealdb.com/docs/reference/golang/api/core/session Authenticates an existing user within the session. ```go token, err := session.SignIn(ctx, authData) ``` -------------------------------- ### SignUpWithRefresh syntax Source: https://surrealdb.com/docs/reference/golang/api/core/db Signs up using a TYPE RECORD access method with WITH REFRESH enabled. Requires SurrealDB v3+. ```go tokens, err := db.SignUpWithRefresh(ctx, authData) ``` -------------------------------- ### db.SignUp Source: https://surrealdb.com/docs/reference/golang/concepts/authentication Creates a new record user using a defined access method. ```APIDOC ## db.SignUp(ctx, vars) ### Description Creates a new record user using a `DEFINE ACCESS ... TYPE RECORD` access method. ### Parameters - **ctx** (context.Context) - Required - The context for the operation. - **vars** (map[string]any) - Required - A map containing authentication details including NS, DB, AC, and user credentials. ### Example ```go token, err := db.SignUp(ctx, map[string]any{ "NS": "my_ns", "DB": "my_db", "AC": "user_access", "user": "new_user", "pass": "s3cret", "email": "user@example.com", }) ``` ``` -------------------------------- ### Execute a transaction workflow Source: https://surrealdb.com/docs/reference/golang/api/core/transaction Demonstrates creating a record within a transaction and committing the changes. ```go tx, err := db.Begin(ctx) if err != nil { log.Fatal(err) } defer tx.Cancel(ctx) _, err = surrealdb.Create[any](ctx, tx, models.Table("events"), map[string]any{ "type": "transfer", "amount": 100, }) if err != nil { log.Fatal(err) } if err := tx.Commit(ctx); err != nil { log.Fatal(err) } ``` -------------------------------- ### Connect to SurrealDB using FromEndpointURLString Source: https://surrealdb.com/docs/reference/golang/concepts/connecting-to-surrealdb Initializes a new client connection to a SurrealDB instance. Ensure the connection is closed using defer to prevent resource leaks. ```go ctx := context.Background() db, err := surrealdb.FromEndpointURLString(ctx, "ws://localhost:8000") if err != nil { log.Fatal(err) } defer db.Close(ctx) ``` -------------------------------- ### VersionData Struct Source: https://surrealdb.com/docs/reference/golang/api/types Contains version, build, and timestamp information returned by the Version method. ```go type VersionData struct { Version string `json:"version"` Build string `json:"build"` Timestamp string `json:"timestamp"` } ``` -------------------------------- ### Define a variable with .Let() Source: https://surrealdb.com/docs/reference/golang/api/core/db Use this method to set a variable on the connection for use in subsequent queries. The key should not include the $ prefix. ```go err := db.Let(ctx, key, val) ``` -------------------------------- ### Initialize CustomDateTime Source: https://surrealdb.com/docs/reference/golang/concepts/value-types Wraps Go's time.Time to ensure correct CBOR encoding with nanosecond precision. ```go now := models.CustomDateTime{Time: time.Now()} ``` -------------------------------- ### session.SignUpWithRefresh() Source: https://surrealdb.com/docs/reference/golang/api/core/session Signs up with refresh token support within this session. ```APIDOC ## session.SignUpWithRefresh() ### Description Signs up with refresh token support within this session. SurrealDB v3+ only. ### Signature `tokens, err := session.SignUpWithRefresh(ctx, authData)` ### Returns `(*Tokens, error)` ``` -------------------------------- ### Selecting records Source: https://surrealdb.com/docs/reference/golang/concepts/query-builder Construct SELECT queries using fluent methods like Fields, Where, and GroupBy. ```go surrealql.Select("users") // SELECT * FROM users surrealql.Select("users").Fields("name", "email").Where("active = ?", true) // SELECT name, email FROM users WHERE active = $param_1 surrealql.Select("users"). Field(surrealql.Expr("count()").As("total")). GroupBy("department") // SELECT count() AS total FROM users GROUP BY department ``` -------------------------------- ### db.Use(ctx, ns, database) Source: https://surrealdb.com/docs/reference/golang/api/core/db Selects the namespace and database to use for subsequent operations. ```APIDOC ## db.Use(ctx, ns, database) ### Description Selects the namespace and database to use for subsequent operations. ### Syntax `err := db.Use(ctx, ns, database)` ### Parameters - **ctx** (context.Context) - Required - Context for the operation. - **ns** (string) - Required - The namespace to use. - **database** (string) - Required - The database to use. ### Returns - **error** ``` -------------------------------- ### Initialize a reliable WebSocket connection Source: https://surrealdb.com/docs/reference/golang/concepts/reliable-connections Constructs a rews.Connection using a factory function, check interval, and CBOR codec. ```go import ( "context" "net/url" "time" surrealdb "github.com/surrealdb/surrealdb.go" "github.com/surrealdb/surrealdb.go/contrib/rews" "github.com/surrealdb/surrealdb.go/pkg/connection" "github.com/surrealdb/surrealdb.go/pkg/connection/gorillaws" "github.com/surrealdb/surrealdb.go/surrealcbor" ) endpoint, _ := url.Parse("ws://localhost:8000/rpc") codec := surrealcbor.New() conn := rews.New( func(ctx context.Context) (*gorillaws.WebSocket, error) { conf := connection.NewConfig(endpoint) conf.Marshaler = codec conf.Unmarshaler = codec return gorillaws.New(conf), nil }, 5*time.Second, codec, nil, ) ``` -------------------------------- ### Importing the query builder Source: https://surrealdb.com/docs/reference/golang/concepts/query-builder Include the contrib package in your Go project to access query builder functionality. ```go import "github.com/surrealdb/surrealdb.go/contrib/surrealql" ``` -------------------------------- ### Connect to and query an embedded SurrealDB instance Source: https://surrealdb.com/docs/reference/golang/embedding Demonstrates opening an in-memory SurrealDB instance, defining a table, and deserializing results into a Go struct. ```go 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, "main", "main") 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) } } ``` -------------------------------- ### Send raw RPC request in Go Source: https://surrealdb.com/docs/reference/golang/api/core/db Use this method to execute raw RPC commands against the database. It requires a context, database instance, result container, method name, and parameters. ```go err := surrealdb.Send[Result](ctx, db, res, method, params...) ``` -------------------------------- ### Construct a RecordID Source: https://surrealdb.com/docs/reference/golang/api/values/record-id Syntax for creating a new RecordID instance. ```go id := models.NewRecordID(tableName, id) ``` -------------------------------- ### Import SurrealDB SDK and Models Source: https://surrealdb.com/docs/reference/golang/installation Include these imports in your Go files to access the client and value types. ```go import ( surrealdb "github.com/surrealdb/surrealdb.go" "github.com/surrealdb/surrealdb.go/pkg/models" ) ``` -------------------------------- ### FromConnection Source: https://surrealdb.com/docs/reference/golang/api/core/db Creates a new DB client instance from a custom connection implementation and automatically initiates the connection. ```APIDOC ## func FromConnection(ctx context.Context, conn connection.Connection) (*DB, error) ### Description Creates a new `*DB` from a custom `connection.Connection` implementation. Calls `.Connect(ctx)` automatically. ### Parameters - **ctx** (context.Context) - Required - Context for canceling the connection attempt. - **conn** (connection.Connection) - Required - A connection implementation (e.g., gorillaws.New(conf) or http.New(conf)). ### Returns - **(*DB, error)** - A pointer to the DB instance or an error if the connection fails. ``` -------------------------------- ### Creating records in Go Source: https://surrealdb.com/docs/reference/golang/concepts/data-manipulation Creates new records using Create, supporting both random ID generation via Table and explicit ID assignment via RecordID. ```go person, err := surrealdb.Create[Person](ctx, db, models.Table("persons"), Person{ Name: "Tobie", Surname: "Morgan Hitchcock", }) specific, err := surrealdb.Create[Person](ctx, db, models.NewRecordID("persons", "tobie"), map[string]any{ "name": "Tobie", "surname": "Morgan Hitchcock", }) ``` -------------------------------- ### Authenticate syntax Source: https://surrealdb.com/docs/reference/golang/api/core/db Authenticates the current connection using a provided JWT token. ```go err := db.Authenticate(ctx, token) ``` -------------------------------- ### Create Records Source: https://surrealdb.com/docs/reference/golang/concepts/query-builder Methods for building CREATE queries using .Set() or .Content(). ```APIDOC ## surrealql.Create(table string) ### Description Builds a CREATE query for the specified table. ### Methods - **Set(field string, value any)**: Sets a specific field value. - **Content(data map[string]any)**: Sets the entire record content. ## surrealql.CreateOnly(table string) ### Description Builds a CREATE ONLY query for the specified table. ``` -------------------------------- ### db.SignUpWithRefresh() Source: https://surrealdb.com/docs/reference/golang/api/core/db Signs up using a TYPE RECORD access method with WITH REFRESH enabled. ```APIDOC ## .SignUpWithRefresh() ### Description Signs up using a TYPE RECORD access method with WITH REFRESH enabled. SurrealDB v3+ only. ### Syntax `tokens, err := db.SignUpWithRefresh(ctx, authData)` ### Returns - **(*Tokens, error)** - The tokens object. ``` -------------------------------- ### Create a new record Source: https://surrealdb.com/docs/reference/golang/api/core/db Creates a new record in the database with the provided data. ```go result, err := surrealdb.Create[TResult](ctx, s, what, data) ``` -------------------------------- ### Sign in as a record user Source: https://surrealdb.com/docs/reference/golang/concepts/authentication Authenticate at the record level by specifying the Access method, or use a map for additional custom fields. ```go token, err := db.SignIn(ctx, surrealdb.Auth{ Namespace: "my_ns", Database: "my_db", Access: "user_access", Username: "tobie", Password: "s3cret", }) ``` ```go token, err := db.SignIn(ctx, map[string]any{ "NS": "my_ns", "DB": "my_db", "AC": "user_access", "user": "tobie", "pass": "s3cret", }) ``` -------------------------------- ### Define Auth credentials Source: https://surrealdb.com/docs/reference/golang/api/types Use this struct to define authentication credentials for namespace, database, or record-level sign-in. ```go type Auth struct { Namespace string `json:"NS,omitempty"` Database string `json:"DB,omitempty"` Scope string `json:"SC,omitempty"` Access string `json:"AC,omitempty"` Username string `json:"user,omitempty"` Password string `json:"pass,omitempty"` } ``` -------------------------------- ### Managing connection variables with Let and Unset Source: https://surrealdb.com/docs/reference/golang/concepts/executing-queries Define persistent variables on a connection using Let and remove them with Unset. ```go if err := db.Let(ctx, "app_version", "1.0.0"); err != nil { log.Fatal(err) } results, err := surrealdb.Query[[]any](ctx, db, "RETURN $app_version", nil, ) db.Unset(ctx, "app_version") ``` -------------------------------- ### Create Source: https://surrealdb.com/docs/reference/golang/api/core/db Creates a new record. ```APIDOC ## Create ### Description Creates a new record. ### Syntax `result, err := surrealdb.Create[TResult](ctx, s, what, data)` ### Parameters - **ctx** (context.Context) - Required - Context for the operation. - **s** (*DB | *Session | *Transaction) - Required - The sender. - **what** (string | Table | RecordID) - Required - The table or record ID to create. - **data** (any) - Required - The record data (struct or map). ### Returns `(*TResult, error)` ``` -------------------------------- ### Ordering and pagination Source: https://surrealdb.com/docs/reference/golang/concepts/query-builder Apply ordering and pagination modifiers to query results. ```go surrealql.Select("users"). OrderByDesc("created_at"). Limit(20). Start(40) // SELECT * FROM users ORDER BY created_at DESC LIMIT 20 START 40 ``` -------------------------------- ### FromEndpointURLString Source: https://surrealdb.com/docs/reference/golang/api/core/db Creates a new DB client instance and connects to a SurrealDB instance using the provided URL. The URL scheme determines whether a WebSocket or HTTP connection is established. ```APIDOC ## func FromEndpointURLString(ctx context.Context, connectionURL string) (*DB, error) ### Description Creates a new `*DB` and connects to a SurrealDB instance. The URL scheme determines the connection type (WebSocket or HTTP). ### Parameters - **ctx** (context.Context) - Required - Context for canceling the connection attempt. - **connectionURL** (string) - Required - The endpoint URL. Supported schemes: ws://, wss://, http://, https://. ### Returns - **(*DB, error)** - A pointer to the DB instance or an error if the connection fails. ### Example ```go db, err := surrealdb.FromEndpointURLString(ctx, "ws://localhost:8000") ``` ``` -------------------------------- ### Sign Up With Refresh Token Source: https://surrealdb.com/docs/reference/golang/api/core/session Registers a new user with refresh token support. Requires SurrealDB v3+. ```go tokens, err := session.SignUpWithRefresh(ctx, authData) ``` -------------------------------- ### Creating records with ONLY Source: https://surrealdb.com/docs/reference/golang/concepts/query-builder Use CreateOnly to generate a CREATE ONLY query. ```go surrealql.CreateOnly("users").Set("name", "Alice").ReturnNone() // CREATE ONLY users SET name = $set_1 RETURN NONE ``` -------------------------------- ### session.SignIn() Source: https://surrealdb.com/docs/reference/golang/api/core/session Signs in an existing user within this session. ```APIDOC ## session.SignIn() ### Description Signs in an existing user within this session. ### Signature `token, err := session.SignIn(ctx, authData)` ### Returns `(string, error)` ``` -------------------------------- ### Process notifications in a goroutine Source: https://surrealdb.com/docs/reference/golang/concepts/live-queries Demonstrates handling live query notifications asynchronously within a separate goroutine. ```go 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) } } }() ``` -------------------------------- ### Attach a new session Source: https://surrealdb.com/docs/reference/golang/api/core/session Initializes a new session on an existing WebSocket connection. Returns ErrSessionsNotSupported if the connection type is not WebSocket. ```go session, err := db.Attach(ctx) ``` -------------------------------- ### Configure a custom connection Source: https://surrealdb.com/docs/reference/golang/concepts/connecting-to-surrealdb Use FromConnection to pass a manually configured connection, such as a custom WebSocket implementation, to the SurrealDB client. ```go import ( "net/url" "github.com/surrealdb/surrealdb.go/pkg/connection" "github.com/surrealdb/surrealdb.go/pkg/connection/gorillaws" ) endpoint, _ := url.Parse("ws://localhost:8000/rpc") conf := connection.NewConfig(endpoint) conn := gorillaws.New(conf) db, err := surrealdb.FromConnection(ctx, conn) ``` -------------------------------- ### Isolating multiple sessions Source: https://surrealdb.com/docs/reference/golang/concepts/multiple-sessions Shows how to attach multiple independent sessions to a database connection and configure them with different authentication and namespace settings. ```go sessionA, _ := db.Attach(ctx) defer sessionA.Detach(ctx) sessionB, _ := db.Attach(ctx) defer sessionB.Detach(ctx) sessionA.SignIn(ctx, surrealdb.Auth{Username: "admin", Password: "admin"}) sessionA.Use(ctx, "ns_a", "db_a") sessionB.SignIn(ctx, surrealdb.Auth{Namespace: "ns_b", Database: "db_b", Access: "user_access", Username: "user1", Password: "pass1"}) sessionB.Use(ctx, "ns_b", "db_b") ``` -------------------------------- ### Use expressions Source: https://surrealdb.com/docs/reference/golang/concepts/query-builder Creates parameterized expressions for complex queries or graph traversals. ```go surrealql.Select("users"). Field(surrealql.Expr("math::mean([?, ?, ?])", 1, 2, 3).As("avg")) // SELECT math::mean([$param_1, $param_2, $param_3]) AS avg FROM users ``` ```go surrealql.Select(surrealql.Expr("?->knows->users", models.NewRecordID("users", "tobie"))) // SELECT * FROM $from_param_1->knows->users ``` -------------------------------- ### db.Let(ctx, key, val) Source: https://surrealdb.com/docs/reference/golang/api/core/db Defines a variable on the connection that can be used in subsequent queries. ```APIDOC ## db.Let(ctx, key, val) ### Description Defines a variable on the connection that can be used in subsequent queries. ### Parameters - **ctx** (context.Context) - Required - Context for the operation. - **key** (string) - Required - The variable name (without $ prefix). - **val** (any) - Required - The value to assign. ### Returns - **error** - Returns an error if the operation fails. ``` -------------------------------- ### Parameterize queries Source: https://surrealdb.com/docs/reference/golang/concepts/executing-queries Uses parameters to prevent injection attacks and ensure correct CBOR encoding. Pass nil for the variables map when no parameters are required. ```go results, err := surrealdb.Query[[]Person](ctx, db, "SELECT * FROM persons WHERE name = $name AND age > $age", map[string]any{ "name": "Tobie", "age": 25, }, ) ``` ```go results, err := surrealdb.Query[[]Person](ctx, db, "SELECT * FROM persons", nil, ) ``` -------------------------------- ### Execute Query Source: https://surrealdb.com/docs/reference/golang/api/core/db Executes a SurrealQL query string and returns typed results. Requires a context, a sender, the query string, and a map of variables. ```go results, err := surrealdb.Query[TResult](ctx, s, sql, vars) ``` ```go results, err := surrealdb.Query[[]Person](ctx, db, "SELECT * FROM persons WHERE age > $min", map[string]any{"min": 18}, ) ``` -------------------------------- ### Select Source: https://surrealdb.com/docs/reference/golang/api/core/db Retrieves records from the database. ```APIDOC ## Select ### Description Retrieves records from the database. ### Syntax `result, err := surrealdb.Select[TResult](ctx, s, what)` ### Parameters - **TResult** (type parameter) - Use a slice type for tables, a single type for record IDs. - **ctx** (context.Context) - Required - Context for the operation. - **s** (*DB | *Session | *Transaction) - Required - The sender. - **what** (string | Table | RecordID) - Required - The table or record to select. ### Returns `(*TResult, error)` ``` -------------------------------- ### db.SignIn() Source: https://surrealdb.com/docs/reference/golang/api/core/db Signs in an existing user. The fields provided in authData determine the authentication level (root, namespace, database, or record). ```APIDOC ## .SignIn() ### Description Signs in an existing user. The fields provided in authData determine the authentication level (root, namespace, database, or record). ### Syntax `token, err := db.SignIn(ctx, authData)` ### Parameters - **ctx** (context.Context) - Required - Context for the operation. - **authData** (any) - Required - An Auth struct or map[string]any with credentials. ### Returns - **(string, error)** - The JWT token string. ``` -------------------------------- ### Configure exponential backoff retry behavior Source: https://surrealdb.com/docs/reference/golang/concepts/reliable-connections Sets up an exponential backoff strategy to handle connection failures with configurable limits. ```go retryer := rews.NewExponentialBackoffRetryer() retryer.MaxRetries = 10 retryer.InitialDelay = 1 * time.Second retryer.MaxDelay = 30 * time.Second conn.Retryer = retryer ``` -------------------------------- ### Convert Table to String Source: https://surrealdb.com/docs/reference/golang/api/values/table Use the String method to retrieve the underlying table name as a plain string. ```go s := table.String() ``` -------------------------------- ### Sign in with refresh tokens Source: https://surrealdb.com/docs/reference/golang/concepts/authentication Authenticates a user and retrieves both access and refresh tokens. Requires TYPE RECORD access methods with WITH REFRESH enabled. ```go tokens, err := db.SignInWithRefresh(ctx, map[string]any{ "NS": "my_ns", "DB": "my_db", "AC": "user_access", "user": "tobie", "pass": "s3cret", }) ``` -------------------------------- ### session.Version() Source: https://surrealdb.com/docs/reference/golang/api/core/session Returns the SurrealDB version information. ```APIDOC ## session.Version() ### Description Returns the SurrealDB version information. ### Signature `ver, err := session.Version(ctx)` ### Returns `(*VersionData, error)` ``` -------------------------------- ### session.SignInWithRefresh() Source: https://surrealdb.com/docs/reference/golang/api/core/session Signs in with refresh token support within this session. ```APIDOC ## session.SignInWithRefresh() ### Description Signs in with refresh token support within this session. SurrealDB v3+ only. ### Signature `tokens, err := session.SignInWithRefresh(ctx, authData)` ### Returns `(*Tokens, error)` ``` -------------------------------- ### db.Version(ctx) Source: https://surrealdb.com/docs/reference/golang/api/core/db Retrieves version information about the connected SurrealDB instance. ```APIDOC ## db.Version(ctx) ### Description Returns version information about the connected SurrealDB instance. ### Syntax `ver, err := db.Version(ctx)` ### Returns - **(*VersionData, error)** - Returns version data or an error. ``` -------------------------------- ### Execute Raw Query Batch Source: https://surrealdb.com/docs/reference/golang/api/core/db Composes and executes a batch of query statements with results written back to each statement. ```go err := surrealdb.QueryRaw(ctx, s, queries) ``` -------------------------------- ### Retrieve user information in Go Source: https://surrealdb.com/docs/reference/golang/concepts/authentication Returns the record of the currently authenticated user; only available when signed in as a record user. ```go info, err := db.Info(ctx) if err != nil { log.Fatal(err) } fmt.Println(info) ``` -------------------------------- ### Connect to SurrealDB with a timeout Source: https://surrealdb.com/docs/reference/golang/concepts/connecting-to-surrealdb Limits the connection attempt duration using a context with a timeout. This is recommended for unreliable network environments. ```go ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() db, err := surrealdb.FromEndpointURLString(ctx, "ws://localhost:8000") ``` -------------------------------- ### Helper Functions Source: https://surrealdb.com/docs/reference/golang/api/values/duration Utility functions for formatting and parsing SurrealDB duration strings. ```APIDOC ## FormatDuration ### Description Formats nanoseconds into SurrealDB duration syntax. ### Syntax `s := models.FormatDuration(ns)` ### Returns `string` ## ParseDuration ### Description Parses a SurrealDB duration string into nanoseconds. Supported units: y, w, d, h, m, s, ms, us/µs, ns. ### Syntax `ns, err := models.ParseDuration("1d2h30m")` ### Returns `(int64, error)` ``` -------------------------------- ### Handle insert conflicts Source: https://surrealdb.com/docs/reference/golang/concepts/query-builder Uses OnDuplicateKeyUpdateRaw to handle conflicts during insertion. ```go surrealql.Insert("products"). Fields("id", "stock"). Values("products:apple", 10). OnDuplicateKeyUpdateRaw("stock += $input.stock") ``` -------------------------------- ### Upserting records in Go Source: https://surrealdb.com/docs/reference/golang/concepts/data-manipulation Creates a record if it does not exist, or replaces it entirely if it does. ```go person, err := surrealdb.Upsert[Person](ctx, db, models.NewRecordID("persons", "tobie"), Person{ Name: "Tobie", Surname: "Morgan Hitchcock", }) ``` -------------------------------- ### Receive live query notifications Source: https://surrealdb.com/docs/reference/golang/concepts/live-queries Retrieves a channel for a specific live query ID to listen for incoming data changes. ```go 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) } ``` -------------------------------- ### Handle ServerError with errors.As Source: https://surrealdb.com/docs/reference/golang/api/errors Extracting structured error information from a returned error using errors.As. ```go import "errors" _, err := surrealdb.Select[Person](ctx, db, models.NewRecordID("persons", "missing")) if err != nil { var se *surrealdb.ServerError if errors.As(err, &se) { fmt.Println("Kind:", se.Kind) fmt.Println("Message:", se.Message) if se.Details != nil { fmt.Println("Details:", se.Details) } } } ``` -------------------------------- ### Executing batch queries with QueryRaw Source: https://surrealdb.com/docs/reference/golang/concepts/executing-queries Use QueryRaw to execute multiple QueryStmt objects and retrieve individual results using GetResult. ```go stmts := []surrealdb.QueryStmt{ {SQL: "CREATE person:alice SET name = $name", Vars: map[string]any{"name": "Alice"}}, {SQL: "SELECT * FROM person", Vars: nil}, } if err := surrealdb.QueryRaw(ctx, db, &stmts); err != nil { log.Fatal(err) } var persons []Person if err := stmts[1].GetResult(&persons); err != nil { log.Fatal(err) } ``` -------------------------------- ### Subscribe to table changes with Live Source: https://surrealdb.com/docs/reference/golang/concepts/live-queries Initiates a live query on a specified table. The diff parameter determines whether notifications return full records or JSON Patch diffs. ```go liveID, err := surrealdb.Live(ctx, db, models.Table("persons"), false) if err != nil { log.Fatal(err) } ``` -------------------------------- ### session.Let() Source: https://surrealdb.com/docs/reference/golang/api/core/session Defines a variable scoped to this session. ```APIDOC ## session.Let() ### Description Defines a variable scoped to this session. ### Signature `err := session.Let(ctx, key, val)` ### Returns `error` ``` -------------------------------- ### Sign In With Refresh Token Source: https://surrealdb.com/docs/reference/golang/api/core/session Authenticates a user with refresh token support. Requires SurrealDB v3+. ```go tokens, err := session.SignInWithRefresh(ctx, authData) ``` -------------------------------- ### Create relations Source: https://surrealdb.com/docs/reference/golang/concepts/query-builder Constructs a RELATE query to link two records with optional data. ```go surrealql.Relate( models.NewRecordID("users", "tobie"), "wrote", models.NewRecordID("posts", "first"), ).Set("created_at", "2026-01-01") ``` -------------------------------- ### Format CustomDateTime as SurrealQL string Source: https://surrealdb.com/docs/reference/golang/api/values/datetime Retrieves the datetime formatted for use in SurrealQL queries. ```go s := dt.SurrealString() ``` -------------------------------- ### Retrieve transaction properties Source: https://surrealdb.com/docs/reference/golang/api/core/transaction Methods to inspect the transaction state and identity. ```go id := tx.ID() ``` ```go sessionID := tx.SessionID() ``` ```go closed := tx.IsClosed() ``` -------------------------------- ### Selecting records in Go Source: https://surrealdb.com/docs/reference/golang/concepts/data-manipulation Retrieves records from the database using Select with either a table or a specific record ID. ```go persons, err := surrealdb.Select[[]Person](ctx, db, models.Table("persons")) if err != nil { log.Fatal(err) } tobie, err := surrealdb.Select[Person](ctx, db, models.NewRecordID("persons", "tobie")) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Retrieve live query UUID Source: https://surrealdb.com/docs/reference/golang/api/values/uuid UUIDs are typically returned by SDK functions like live queries rather than being constructed manually. ```go liveID, err := surrealdb.Live(ctx, db, models.Table("persons"), false) fmt.Println(liveID.String()) ``` -------------------------------- ### session.LiveNotifications() Source: https://surrealdb.com/docs/reference/golang/api/core/session Returns the notification channel for a live query. ```APIDOC ## session.LiveNotifications() ### Description Returns the notification channel for a live query. ### Signature `ch, err := session.LiveNotifications(liveQueryID)` ### Returns `(chan connection.Notification, error)` ``` -------------------------------- ### db.Attach() Source: https://surrealdb.com/docs/reference/golang/api/core/db Creates a new session on the WebSocket connection. Sessions are only supported on WebSocket connections (SurrealDB v3+). ```APIDOC ## .Attach() ### Description Creates a new session on the WebSocket connection. Sessions are only supported on WebSocket connections (SurrealDB v3+). ### Syntax `session, err := db.Attach(ctx)` ### Returns `(*Session, error)` ``` -------------------------------- ### Authenticate with an existing token in Go Source: https://surrealdb.com/docs/reference/golang/concepts/authentication Applies a previously obtained JWT to the connection to restore a session or transfer authentication. ```go if err := db.Authenticate(ctx, token); err != nil { log.Fatal(err) } ``` -------------------------------- ### Implement a custom retry strategy Source: https://surrealdb.com/docs/reference/golang/concepts/reliable-connections Defines the interface required to implement custom retry logic for connection management. ```go type Retryer interface { NextDelay(attempt int, lastErr error) (time.Duration, bool) Reset() } ``` -------------------------------- ### Notification Struct Source: https://surrealdb.com/docs/reference/golang/api/types Represents a live query notification received through a notification channel, containing the action and result data. ```go type Notification struct { ID *models.UUID `json:"id,omitempty"` Action Action `json:"action"` Result interface{} `json:"result"` } ``` -------------------------------- ### surrealql.Insert Source: https://surrealdb.com/docs/reference/golang/concepts/query-builder Constructs an INSERT query for adding records to a table, supporting bulk inserts and conflict handling. ```APIDOC ## surrealql.Insert(table string) ### Description Builds an INSERT query for the specified table. ### Methods - **Value(data map[string]any)**: Inserts a single record from a map. - **Fields(fields ...string)**: Specifies the fields for the insert operation. - **Values(values ...any)**: Adds a row of values corresponding to the specified fields. - **Relation()**: Configures the insert as a relation insert. - **OnDuplicateKeyUpdateRaw(query string)**: Adds an ON DUPLICATE KEY UPDATE clause to handle conflicts. ``` -------------------------------- ### session.Authenticate() Source: https://surrealdb.com/docs/reference/golang/api/core/session Authenticates this session with a JWT token. ```APIDOC ## session.Authenticate() ### Description Authenticates this session with a JWT token. ### Signature `err := session.Authenticate(ctx, token)` ### Returns `error` ``` -------------------------------- ### db.Info(ctx) Source: https://surrealdb.com/docs/reference/golang/concepts/authentication Returns the record of the currently authenticated user. This is only available when signed in as a record user. ```APIDOC ## db.Info(ctx) ### Description Returns the record of the currently authenticated user. This is only available when signed in as a record user. ### Method `db.Info(ctx context.Context) (interface{}, error)` ```