### Run Example Command - Go Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/example%40v0.10 This command clones the SurrealDB Go SDK repository and runs the example application located in the cmd directory. It requires SurrealDB to be installed and running on port 8000. ```bash # Clone the repository git clone https://github.com/surrealdb/surrealdb.go.git cd surrealdb.go # Run the example go run ./example/cmd ``` -------------------------------- ### Run Tests: SurrealDB Go SDK Examples Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/example%40v1.3 This command shows how to run the testable examples within the SurrealDB Go SDK repository. These tests cover various SDK features, including query operations, transactions, and authentication. ```bash git clone https://github.com/surrealdb/surrealdb.go.git cd surrealdb.go go test -v ./ -run ExampleName ``` -------------------------------- ### Initialize and Use PostgresStore in Go Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealnote/pkg/store/postgres Demonstrates how to initialize a new PostgresStore instance with a connection string, defer its closure, migrate the schema, and then use it with an application. This example highlights the basic setup for integrating PostgresStore into a Go application. ```go store, err := postgres.NewPostgresStore("postgres://user:pass@localhost/db") if err != nil { return err } deffer store.Close() // Initialize schema if err := store.Migrate(ctx); err != nil { return err } // Use with application app := surrealnote.NewApp(store, config) ``` -------------------------------- ### Run Testable Examples - Go Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/example%40v0.10 This command clones the SurrealDB Go SDK repository and runs all testable examples using `go test`. The `-v` flag provides verbose output, and the `-run ExampleName` flag filters tests to only those matching the pattern. ```bash # Clone the repository git clone https://github.com/surrealdb/surrealdb.go.git cd surrealdb.go # Run the testable example go test -v ./ -run ExampleName ``` -------------------------------- ### SurrealDB Go Server Run Command Example Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealnote/pkg/surrealnote Demonstrates how to run the SurrealDB Go server using a context for graceful shutdown. This example initializes a RunCommand and starts the application, handling potential fatal errors. ```go ctx, cancel := context.WithCancel(context.Background()) def cancel() cmd := &RunCommand{} if err := app.Run(ctx, cmd); err != nil { log.Fatalf("Server failed: %v", err) } ``` -------------------------------- ### Install SurrealDB Go SDK Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/index This command installs the SurrealDB Go SDK using the go get command. It fetches the latest version of the package and makes it available for use in your Go projects. ```bash go get github.com/surrealdb/surrealdb.go ``` -------------------------------- ### Execute Run Command Examples Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealnote/pkg/surrealnote Demonstrates various ways to execute the 'run' command from the command line, including starting with default configuration, in read-only mode, or specifying a single database backend (PostgreSQL or SurrealDB). ```bash ./bin/surrealnote run ./bin/surrealnote -mode read_only run ./bin/surrealnote -postgres-only run ./bin/surrealnote -surreal-only run ``` -------------------------------- ### Start Continuous Sync (Go) Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealnote/pkg/store/cqrs Starts a background process for continuous synchronization of changes. This ensures that the secondary store is kept up-to-date with the primary store in near real-time. ```Go func (c *CQRSStore) StartContinuousSync(ctx context.Context, interval time.Duration) ``` -------------------------------- ### Start Server in Go Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/internal/fakesdb_tab=versions Starts the SurrealDB test server. This function should be called before making any requests to the server. Returns an error if the server fails to start. ```go func (s *Server) Start() error ``` -------------------------------- ### Example: Setting up a Backup and Restore Strategy Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealrestore%40v0.10 Provides a comprehensive example of setting up a backup and restore strategy using SurrealDB tools. It includes enabling change feeds, creating an initial full backup, and then generating subsequent incremental backups. ```bash # Enable Change Feeds first (required for incremental dumps) echo "DEFINE DATABASE OVERWRITE prod CHANGEFEED 1h" | surreal sql -e ws://localhost:8000 -u root -p root --ns myapp # Create initial full backup surrealdump -endpoint ws://localhost:8000 -namespace myapp -database prod -dir backups -output full-001.cbor # Create incremental backups (auto-detects base from directory) surrealdump -incremental -namespace myapp -database prod -dir backups -output inc-002.cbor surrealdump -incremental -namespace myapp -database prod -dir backups -output inc-003.cbor ``` -------------------------------- ### Go: Example SELECT Query Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealql Provides a basic example of constructing and executing a simple SELECT query using the `Select` builder and `surrealdb.Query`. ```go Output: SurrealQL: SELECT * FROM users Vars: map[] SurrealQL: SELECT id, name FROM users Vars: map[] ``` -------------------------------- ### StartContinuousSync Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealnote/pkg/store/cqrs Starts a background process that continuously syncs changes between stores. ```APIDOC ## POST /cqrs/sync/continuous ### Description Starts a background process that continuously synchronizes changes between the primary and secondary stores at a specified interval. ### Method POST ### Endpoint /cqrs/sync/continuous ### Parameters #### Query Parameters - **interval** (duration) - Required - The interval at which to perform continuous synchronization (e.g., '5s', '1m'). ### Request Body None ### Response #### Success Response (200) - **message** (string) - Indicates that continuous synchronization has been started. #### Response Example ```json { "message": "Continuous synchronization started with interval 1m." } ``` ``` -------------------------------- ### Go: Aggregate SELECT Examples Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealql Shows examples of using `Select` to build aggregate queries, such as calculating sum, average, minimum, and maximum values. ```go Output: Sum: SELECT math::sum(amount) FROM orders WHERE status = $param_1 Avg: SELECT math::mean(rating) FROM reviews WHERE product_id = $param_1 Min: SELECT math::min(price) FROM products WHERE category = $param_1 Max: SELECT math::max(price) FROM products ``` -------------------------------- ### Install and Run surrealnote Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealnote/pkg/surrealnote Instructions for cloning the repository, setting up SurrealDB and PostgreSQL, running migrations, and building/running the surrealnote application. ```bash # Clone the repository git clone https://github.com/surrealdb/surrealdb.go cd surrealdb.go/contrib/surrealnote # Start SurrealDB surreal start --user root --pass root # Start PostgreSQL (using Docker) make postgres-start # Run database migrations make migrate # Build and run the application make build ./bin/surrealnote ``` -------------------------------- ### Install surrealrestore using Go Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealrestore%40v0.10 Installs the surrealrestore command-line tool using the Go installation command. This makes the tool available in your system's PATH for direct execution. ```bash go install github.com/surrealdb/surrealdb.go/contrib/surrealrestore/cmd/surrealrestore@latest ``` -------------------------------- ### Transaction RETURN Example Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/index A simple example demonstrating the RETURN clause within a SurrealDB transaction using the Go driver. It shows how to return a boolean value after a successful operation. ```go package main import ( "fmt" "github.com/surrealdb/surrealdb.go" ) func main() { db, err := surrealdb.New("ws://localhost:8000/rpc") if err != nil { panic(err) } defer db.Close() // Sign in with a namespace, database, and Dream token _, err = db.Signin(map[string]interface{}{ "user": "root", "pass": "root", }) if err != nil { panic(err) } tx, err := db.Begin() if err != nil { panic(err) } // Perform an operation and return a boolean value result, err := tx.Query("RETURN true") if err != nil { panic(err) } fmt.Printf("Status: %s\n", result[0].Status) var success bool if err := surrealdb.Unmarshal(result, &success); err != nil { panic(err) } fmt.Printf("Result: %t\n", success) // Commit the transaction err = tx.Commit() if err != nil { panic(err) } } ``` -------------------------------- ### StartContinuousSync Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealnote%40v0.0.0-20260212031642-89d0f8d1b4c6/pkg/store/cqrs Starts a background process that continuously synchronizes changes. ```APIDOC ## POST /cqrs/continuous-sync/start ### Description Starts a background process that continuously synchronizes changes between primary and secondary stores. ### Method POST ### Endpoint /cqrs/continuous-sync/start ### Parameters #### Query Parameters - **interval** (duration) - Required - The interval at which to perform synchronization (e.g., "5s", "1m"). ### Request Example ```json { "interval": "1m" } ``` ### Response #### Success Response (200) - **message** (string) - Indicates that continuous synchronization has started. #### Response Example ```json { "message": "Continuous synchronization started with interval 1m." } ``` ``` -------------------------------- ### Start HTTP Server with API Endpoints Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealnote/pkg/surrealnote The Run method starts the HTTP server with comprehensive API endpoints for the note-taking application. It configures and launches the web server to handle user-facing operations. The server operates in single PostgreSQL, single SurrealDB, or CQRS dual-write modes. ```go func (a *App) Run(ctx context.Context, cmd *RunCommand) error { // ... implementation details ... } ``` -------------------------------- ### Build SELECT Query with Expr Examples (Go) Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealql Demonstrates various ways to use the Expr function in SELECT statements, including simple function calls with aliases, functions with value arguments, subqueries, and expressions with variables and values. These examples showcase the flexibility of Expr for constructing complex SELECT clauses. ```sql SELECT count(*) AS total, math::max(price) AS max_price, math::min(price) AS min_price FROM products ``` ```sql SELECT $base + $param_1 * 2 AS calculated FROM test Vars: param_1: 10 ``` ```sql SELECT math::sum((SELECT total FROM orders)) AS total FROM dummy ``` ```sql SELECT count(orders) AS total_orders, math::max(price) AS max_price FROM products ``` ```sql SELECT count(*) AS total, name FROM users ``` ```sql SELECT $param_1 * $param_2 + $param_3 AS calculation, math::mean([$param_4,$param_5,$param_6]) AS average FROM dummy Vars: param_1: 10 param_2: 20 param_3: 5 param_4: 1 param_5: 2 param_6: 3 ``` ```sql SELECT math::mean([$param_1,$param_2,$param_3]) AS average FROM dummy Vars: param_1=1 param_2=2 param_3=3 ``` ```sql SELECT math::mean([1,$two,3]) AS result FROM test ``` ```sql SELECT id, name, created_at FROM users ``` -------------------------------- ### CQRS Store Initialization and Migration Sequence (Go) Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealnote/pkg/store/cqrs Demonstrates how to set up a CQRS store with primary and secondary databases, configure synchronization, and execute a migration sequence through different modes. ```go // Setup CQRS store for migration primary, _ := postgres.NewPostgresStore(postgresDSN) secondary, _ := surrealdb.NewSurrealStoreCBOR(surrealURL, ns, db, user, pass) cqrsStore := cqrs.NewCQRSStore(primary, secondary, cqrs.ModeSingle) def smqrsStore.Close() // Configure sync strategy (change tracking or timestamp) cqrsStore.SetSyncStrategy(cqrs.SyncStrategyChangeTracking) // Start background synchronization cqrsStore.StartContinuousSync(ctx, 30*time.Second) // Use with application app := surrealnote.NewApp(cqrsStore, config) // Migration sequence: // 1. Let background sync run until caught up // 2. Switch to read-only mode for final sync cqrsStore.SetMode(cqrs.ModeReadOnly) time.Sleep(5 * time.Second) // Brief downtime for final sync // 3. Switch to secondary for reads cqrsStore.SetMode(cqrs.ModeSwitching) // 4. After validation, complete migration cqrsStore.SwapStores() cqrsStore.SetMode(cqrs.ModeSingle) ``` -------------------------------- ### Initialize PostgreSQL Store and App in Go Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealnote/pkg/store%40v0.0 Demonstrates how to initialize a PostgreSQL store using the 'postgres.NewPostgresStore' function and then create a new application instance with the store and configuration. This is a common pattern for single store implementations. ```go // Single store mode store, err := postgres.NewPostgresStore(dsn) app := surrealnote.NewApp(store, config) ``` -------------------------------- ### Get Transaction Session ID in Go Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/index The SessionID function returns the UUID of the session if the transaction was started within a session. It returns nil for transactions on the default session. ```go func (tx *Transaction) SessionID() *models.UUID ``` -------------------------------- ### Initialize SurrealDB Store in Go Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealnote/pkg/store/surrealdb Provides a Go code example for initializing the SurrealDB CBOR store. It shows how to establish a connection using WebSocket, authenticate, and defer closing the connection. Includes schema migration. ```go store, err := surrealdb.NewSurrealStoreCBOR( "ws://localhost:8000/rpc", "test", "test", "root", "root", ) if err != nil { return err } defer store.Close() // Initialize schema (minimal for SurrealDB) if err := store.Migrate(ctx); err != nil { return err } // Use with application app := surrealnote.NewApp(store, config) ``` -------------------------------- ### Run Virtual User Scenarios and Verify Data in Go Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealnote%40v0.0.0-20260212031642-89d0f8d1b4c6/pkg/surrealnotetesting Demonstrates how to initialize a virtual user, run a complete user scenario, and verify all data consistency using the SurrealDB Go testing utilities. This example is suitable for end-to-end testing of user workflows. ```go package main import ( "context" "sync" "testing" "github.com/surrealdb/surrealdb.go/testing" ) func main() { ctx := context.Background() tbaseURL := "http://localhost:8080" // Single virtual user workflow vu := surrealnotetesting.NewVirtualUser(0, "http://localhost:8080") defer vu.Client.Close() // Run complete user scenario if err := vu.RunScenario(ctx); err != nil { // In a real test, you would use t.Fatalf panicf("Virtual user scenario failed: %v", err) } // Verify all data is consistent if err := vu.VerifyAllData(ctx); err != nil { // In a real test, you would use t.Fatalf panicf("Data verification failed: %v", err) } // Concurrent load testing numUsers := 10 var wg sync.WaitGroup for i := 0; i < numUsers; i++ { wg.Add(1) go func(userIndex int) { defer wg.Done() vu := surrealnotetesting.NewVirtualUser(userIndex, baseURL) _ = vu.RunScenario(ctx) // Error handling omitted for brevity in example }(i) } wg.Wait() } // Placeholder for panicf, as this is a main function example func panicf(format string, a ...interface{}) { panic(fmt.Sprintf(format, a...)) } ``` -------------------------------- ### CustomRecordID Type Definition Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/example%40v1.3 Defines a custom record ID type in Go, embedding SurrealDB's models.RecordID. This allows for custom handling or extension of record ID functionality. ```go type CustomRecordID struct { models.RecordID } ``` -------------------------------- ### Define PersonWithCustomID Struct in Go Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/example%40v0.11 Defines a PersonWithCustomID struct that uses the custom CustomRecordID type for its identifier. This allows for using the custom ID handling within the Person struct. ```go type PersonWithCustomID struct { ID CustomRecordID `json:"id,omitempty"` Name string `json:"name"` Surname string `json:"surname"` Location models.GeometryPoint `json:"location"` } ``` -------------------------------- ### Initialize CQRS Store and App in Go Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealnote/pkg/store%40v0.0 Illustrates setting up a CQRS (Command Query Responsibility Segregation) store for dual-write operations. It initializes both a primary PostgreSQL store and a secondary SurrealDB store, then combines them using 'cqrs.NewCQRSStore'. ```go // CQRS migration mode primary, _ := postgres.NewPostgresStore(postgresDSN) secondary, _ := surrealdb.NewSurrealStoreCBOR(surrealURL, ns, db, user, pass) cqrsStore := cqrs.NewCQRSStore(primary, secondary, cqrs.ModeDualWrite) app := surrealnote.NewApp(cqrsStore, config) ``` -------------------------------- ### PersonWithCustomID Struct Definition - Go Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/example%40v0.10 Defines the PersonWithCustomID struct, which is similar to the Person struct but uses the CustomRecordID type for its ID field. This allows for custom handling of record IDs. ```go type PersonWithCustomID struct { ID CustomRecordID `json:"id,omitempty"` Name string `json:"name"` Surname string `json:"surname"` Location models.GeometryPoint `json:"location"` } ``` -------------------------------- ### MarshalJSON Method for CustomRecordID - Go Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/example%40v0.10 Implements the MarshalJSON method for the CustomRecordID struct. This allows CustomRecordID instances to be serialized into JSON format, likely for use in API requests or responses. ```go func (r CustomRecordID) MarshalJSON() ([]byte, error) ``` -------------------------------- ### Sign Up User - Go Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealnote/pkg/surrealnotetesting The SignUp method creates an account for the virtual user. It requires a context.Context and returns an error upon failure. ```go func (vu *VirtualUser) SignUp(ctx context.Context) error { // Implementation details... return nil } ``` -------------------------------- ### CustomRecordID Struct Definition - Go Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/example%40v0.10 Defines a CustomRecordID struct that embeds models.RecordID. This is likely used to extend or customize record ID handling within the SurrealDB Go SDK. ```go type CustomRecordID struct { models.RecordID } ``` -------------------------------- ### Basic Client Setup and Authentication in Go Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealnote/pkg/client Demonstrates how to initialize the SurrealDB Go client, authenticate a user, and automatically include the authentication token in subsequent requests. ```go client := client.NewClient("http://localhost:8080") // Authenticate user authResp, err := client.SignIn(ctx, "user@example.com", "password") if err != nil { return err } // Client automatically includes auth token in subsequent requests workspaces, err := client.ListWorkspaces(ctx, authResp.User.ID) ``` -------------------------------- ### Person Struct Definition Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/example%40v1.3 Defines the Person struct, representing a person record in SurrealDB. It includes fields for ID, Name, Surname, and Location, with comments explaining their purpose and SurrealDB/Go SDK specific details. ```go type Person struct { // ID is the unique identifier for the person record. // // Any SurrealDB record has ID. // The SurrealDB Go SDK uses models.RecordID to represent record IDs. ID *models.RecordID `json:"id,omitempty"` // Name is the person's name. // // Many Go primitive types that can be serialized using CBOR // are supported. Name string `json:"name"` Surname string `json:"surname"` // Location is the person's location. // // Some SurrealDB-specific data types require custom structs // provided by this SDK. Location models.GeometryPoint `json:"location"` } ``` -------------------------------- ### SurrealDB SQL: UPSERT with SET and RETURN AFTER Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealql This example shows an UPSERT query using the SET clause to update fields and the RETURN AFTER clause to get the record's state after the update. Variables are used for the new field values. ```sql UPSERT product:desk SET name = $param_1, price = $param_2 RETURN AFTER Vars: param_1: Standing Desk param_2: 450 ``` -------------------------------- ### SurrealDB SQL: UPSERT with MERGE and RETURN DIFF Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealql This example shows an UPSERT query using the MERGE clause to partially update a record, and the RETURN DIFF clause to get the changes made. Variables are used to provide the merge data. ```sql UPSERT product:watch MERGE $upsert_merge_1 RETURN DIFF Variables: map[upsert_merge_1:map[available:true updated_at:2023-01-01]] ``` -------------------------------- ### Initialize SurrealDB Store in Go Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealnote%40v0.0.0-20260212031642-89d0f8d1b4c6/pkg/store Demonstrates how to initialize a SurrealDB store in Go for single store mode or CQRS migration mode. This involves creating new store instances with specific configurations. ```go // Single store mode store, err := postgres.NewPostgresStore(dsn) app := surrealnote.NewApp(store, config) // CQRS migration mode primary, _ := postgres.NewPostgresStore(postgresDSN) secondary, _ := surrealdb.NewSurrealStoreCBOR(surrealURL, ns, db, user, pass) cqrsStore := cqrs.NewCQRSStore(primary, secondary, cqrs.ModeDualWrite) app := surrealnote.NewApp(cqrsStore, config) ``` -------------------------------- ### SurrealDB SQL: UPSERT with SET and array operations Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealql This example shows an UPSERT query using the SET clause with array operations (+=, -=) to modify array fields, and RETURN AFTER to get the updated record. Variables are used for the array elements and values. ```sql UPSERT product:laptop SET categories += $param_1, stock -= $param_2, sales_count += $param_3, available = $param_4 RETURN AFTER Vars: param_1: [electronics computers] param_2: 1 param_3: 1 param_4: true ``` -------------------------------- ### Person Struct Definition Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/example%40v1.0 Defines the Person struct, representing a person record in SurrealDB. It includes fields for ID, Name, Surname, and Location, with JSON tags for serialization. The description highlights SurrealDB's use of CBOR and the flexibility of JSON tags. ```go type Person struct { // ID is the unique identifier for the person record. // // Any SurrealDB record has ID. // The SurrealDB Go SDK uses models.RecordID to represent record IDs. ID *models.RecordID `json:"id,omitempty"` // Name is the person's name. // // Many Go primitive types that can be serialized using CBOR // are supported. Name string `json:"name"` Surname string `json:"surname" // Location is the person's location. // // Some SurrealDB-specific data types require custom structs // provided by this SDK. Location models.GeometryPoint `json:"location" } ``` -------------------------------- ### CQRS Store Initialization and Migration in Go Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealnote%40v0.0.0-20260212031642-89d0f8d1b4c6/pkg/store/cqrs Demonstrates how to set up and use the CQRS store for migrating data between a primary PostgreSQL store and a secondary SurrealDB store using the Go driver. It covers store initialization, sync strategy configuration, starting background sync, and the sequence of mode transitions for a safe migration. ```go // Setup CQRS store for migration primary, _ := postgres.NewPostgresStore(postgresDSN) secondary, _ := surrealdb.NewSurrealStoreCBOR(surrealURL, ns, db, user, pass) cqrsStore := cqrs.NewCQRSStore(primary, secondary, cqrs.ModeSingle) defer cqrsStore.Close() // Configure sync strategy (change tracking or timestamp) cqrsStore.SetSyncStrategy(cqrs.SyncStrategyChangeTracking) // Start background synchronization cqrsStore.StartContinuousSync(ctx, 30*time.Second) // Use with application app := surrealnote.NewApp(cqrsStore, config) // Migration sequence: // 1. Let background sync run until caught up // 2. Switch to read-only mode for final sync cqrsStore.SetMode(cqrs.ModeReadOnly) time.Sleep(5 * time.Second) // Brief downtime for final sync // 3. Switch to secondary for reads cqrsStore.SetMode(cqrs.ModeSwitching) // 4. After validation, complete migration cqrsStore.SwapStores() cqrsStore.SetMode(cqrs.ModeSingle) ``` -------------------------------- ### SurrealDB SQL: UPSERT with SET, raw array operations, and RETURN AFTER Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealql This example demonstrates an UPSERT query using the SET clause with raw array operations (+=) to add elements to an array field, and RETURN AFTER to get the updated record. A variable is used for a boolean field. ```sql UPSERT product:laptop SET categories += ['electronics', 'computers'], stock -= 1, sales_count += 1, available = $param_1 RETURN AFTER Vars: param_1: true ``` -------------------------------- ### Sign Up New User (Go) Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealnote/pkg/client The SignUp function creates a new user account with the provided email, password, and name. It requires a context and returns an AuthResponse with authentication details upon successful creation, or an error if the registration fails. ```go func (c *Client) SignUp(ctx context.Context, email, password, name string) (*AuthResponse, error) ``` -------------------------------- ### Set Start Clause for Select Query (Go) Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealql The Start method sets the START clause for the SELECT query, specifying the starting offset for the results. This is often used in conjunction with LIMIT for pagination. ```go func (q *SelectQuery) Start(start int) *SelectQuery ``` -------------------------------- ### Initialize SurrealDB Connection from Config (Go) Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/testenv Methods to establish a SurrealDB connection using a `Config` object. `New` returns a `surrealdb.DB` instance and an error, while `MustNew` returns a `surrealdb.DB` instance and panics if an error occurs during initialization. These are crucial for interacting with the database. ```Go func (c *Config) MustNew() *surrealdb.DB ``` ```Go func (c *Config) New() (*surrealdb.DB, error) ``` -------------------------------- ### Create Workspace, Page, and Block with Typed IDs (Go) Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealnote/pkg/models Demonstrates how to create a workspace, a page with hierarchical relationships, and content blocks using typed IDs in Go. This example showcases the basic entity creation process within the SurrealDB Go package. ```go // Create a workspace with typed IDs workspace := &models.Workspace{ ID: models.NewWorkspaceID(), Name: "My Workspace", OwnerID: userID, } // Create a page with hierarchical relationship page := &models.Page{ ID: models.NewPageID(), WorkspaceID: workspace.ID, ParentPageID: &parentPageID, // Optional: nil for root pages Title: "Meeting Notes", CreatedBy: userID, } // Create content blocks block := &models.Block{ ID: models.NewBlockID(), PageID: page.ID, Type: models.BlockTypeText, Content: models.JSONMap{"text": "Meeting agenda"}, Order: 0, } ``` -------------------------------- ### SurrealDB Go Driver: Virtual User Workflow and Load Testing Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealnote/pkg/surrealnotetesting Demonstrates how to use the `VirtualUser` to simulate a single user workflow, including running a scenario and verifying data. It also shows how to perform concurrent load testing by launching multiple virtual users simultaneously. ```go // Single virtual user workflow vu := surrealnotetesting.NewVirtualUser(0, "http://localhost:8080") defer vu.Client.Close() // Run complete user scenario if err := vu.RunScenario(ctx); err != nil { t.Fatalf("Virtual user scenario failed: %v", err) } // Verify all data is consistent if err := vu.VerifyAllData(ctx); err != nil { t.Fatalf("Data verification failed: %v", err) } // Concurrent load testing numUsers := 10 var wg sync.WaitGroup for i := 0; i < numUsers; i++ { wg.Add(1) go func(userIndex int) { defer wg.Done() vu := surrealnotetesting.NewVirtualUser(userIndex, baseURL) vu.RunScenario(ctx) }(i) } wg.Wait() ``` -------------------------------- ### SurrealStoreCBOR Initialization Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealnote/pkg/store/surrealdb Initializes a new SurrealStoreCBOR instance for connecting to SurrealDB. ```APIDOC ## NewSurrealStoreCBOR ### Description Initializes a new SurrealStoreCBOR instance for connecting to SurrealDB using CBOR encoding. ### Method `NewSurrealStoreCBOR` ### Parameters - **wsURL** (string) - Required - The WebSocket URL for the SurrealDB instance. - **namespace** (string) - Required - The SurrealDB namespace to connect to. - **database** (string) - Required - The SurrealDB database to connect to. - **username** (string) - Required - The username for authentication. - **password** (string) - Required - The password for authentication. ### Returns - `store.Store` - The initialized SurrealStoreCBOR instance. - `error` - An error if initialization fails. ``` -------------------------------- ### Start New Backup Chain Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealrestore%40v1.1 Start a new backup chain from the restored database. ```APIDOC ## Start New Backup Chain ### Description Start a new backup chain from the restored database. This command creates a full dump of the specified namespace and database. ### Method `surrealdump` (CLI command) ### Endpoint N/A (CLI command) ### Parameters #### Query Parameters - **-endpoint** (string) - Required - The SurrealDB endpoint (e.g., `ws://localhost:8001`). - **-namespace** (string) - Required - The namespace to dump. - **-database** (string) - Required - The database to dump. - **-dir** (string) - Required - The directory to store the dump. - **-output** (string) - Required - The filename for the dump. ### Request Example ```bash surrealdump -endpoint ws://localhost:8001 -namespace myapp -database prod -dir restored-backups -output full-001.cbor ``` ### Response N/A (CLI command output) #### Success Response (0) Full dump created successfully. #### Response Example N/A ``` -------------------------------- ### Basic transaction example (SurrealQL) Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealql This is a basic example of a SurrealDB transaction that updates balances for two accounts. It uses a variable `$transfer_amount` to define the amount to be transferred. ```SurrealQL BEGIN TRANSACTION; LET $transfer_amount = 300; UPDATE account:one SET balance += $transfer_amount; UPDATE account:two SET balance -= $transfer_amount; COMMIT TRANSACTION; ``` -------------------------------- ### Initialize Application (Go) Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealnote/pkg/surrealnote Creates a new application instance with the provided configuration. In a production environment, this function would typically accept a context for graceful shutdown, initialize monitoring and tracing, and perform thorough connection validation before returning. ```go func New(config *Config) (*App, error) ``` -------------------------------- ### Select With Expression Example in Go Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealql Shows how to use expressions within the field selection of a SELECT query. This example concatenates a text field with a string literal. ```go SELECT text + "b" AS aa FROM foo:5 ``` -------------------------------- ### Client Initialization Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealnote/pkg/client Provides details on how to initialize a new SurrealDB Go client. ```APIDOC ## NewClient ### Description Creates a new SurrealDB API client. ### Method `NewClient` ### Parameters #### Path Parameters - **baseURL** (string) - Required - The base URL for the SurrealDB instance (e.g., "http://localhost:8080"). Do not include a trailing slash or API path prefix. ### Response Returns a pointer to an initialized `Client` struct. ### Request Example ```go client := surrealdb.NewClient("http://localhost:8080") ``` ``` -------------------------------- ### Install surrealdump Tool (Go) Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealdump%40v1.2 Installs the surrealdump command-line tool using the Go package manager. This command fetches the latest version of the tool from the specified GitHub repository. ```go go install github.com/surrealdb/surrealdb.go/contrib/surrealdump/cmd/surrealdump@latest ``` -------------------------------- ### UPSERT Query Examples Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealql This section provides examples of UPSERT queries, demonstrating how to update or insert data into a table. It shows how to set values, unset fields, and apply conditions. ```SQL UPSERT product:smartphone SET name = $param_1, price = $param_2, in_stock = $param_3, created_at = $param_4, tags += $param_5, features += $param_6, view_count += $param_7, discount_percentage = $param_8 WHERE stock > $param_9 RETURN AFTER ``` ```SQL UPSERT product:cable SET name = $param_1 UNSET deprecated_field, legacy_data ``` ```SQL UPSERT product:speaker SET last_updated = $param_1, status = $param_2 WHERE price >= $param_3 RETURN DIFF ``` ```SQL UPSERT ONLY product:charger SET name = $param_1, available = $param_2 RETURN AFTER ``` -------------------------------- ### Create New Dumper Instance (Go) Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealdump%40v1.0 Creates a new Dumper instance. The provided `db` connection must have the namespace and database already selected using `db.Use(ctx, namespace, database)` before creating the Dumper. The `namespace` and `database` parameters are for metadata purposes and do not change the connection's context. Example: `db.Use(ctx, "myapp", "production"); dumper := surrealdump.New(db, "myapp", "production")` ```Go func New(db *surrealdb.DB, namespace, database string, tables ...string) *Dumper { // ... implementation details ... } ``` -------------------------------- ### Initialize SurrealDB Testing Environment in Go Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/testenv The `Init` function initializes the testing environment for SurrealDB. It cleans up specified tables within a given namespace and database. If no tables are provided, it cleans up all tables in the database, preparing a clean state for tests. ```go func Init(db *surrealdb.DB, namespace, database string, tables ...string) (*surrealdb.DB, error) ``` -------------------------------- ### Building and Querying UPSERT Statements in Go Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealql Covers the methods for finalizing and executing UPSERT queries, including `Build` to get the SQL and variables, `String` to get the SQL string, and `Where` to add conditions. ```go package main import ( "fmt" "github.com/surrealdb/surrealdb.go" ) func main() { // Example of building and querying UPSERT statements // Assuming 'db' is an initialized SurrealDB connection // var db *surrealdb.DB // upsertQuery := db.Query("UPSERT INTO users SET name = $name", map[string]any{"name": "Alice"}) // sql, vars := upsertQuery.Build() // fmt.Printf("SQL: %s, Vars: %v\n", sql, vars) // queryStr := upsertQuery.String() // fmt.Println("Query String:", queryStr) // whereQuery := upsertQuery.Where("id = $id", map[string]any{"id": "user123"}) // This is a placeholder to show the function signature, actual usage requires a DB connection fmt.Println("Build, String, and Where methods are used for query finalization and conditions.") } ``` -------------------------------- ### Dumper Initialization and Full Dump Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealdump%40v1.3 Explains how to create a Dumper instance and perform a full database dump. ```APIDOC ## Dumper ### Description Dumper handles the database dump process. It dumps the currently selected namespace and database that was set via db.Use(). To dump a specific namespace/database, call db.Use(ctx, namespace, database) before creating the dumper. ### Functions #### New() ##### Description New creates a new Dumper instance. The provided db connection MUST have the namespace and database already selected via db.Use(ctx, namespace, database) BEFORE creating the Dumper. The namespace and database parameters passed here are for metadata purposes only - they do NOT change the connection's current namespace/database context. The namespace and database parameters are required because SurrealDB doesn't provide an API to query the current context, so we need them for writing metadata. ##### Parameters - **db** (*surrealdb.DB) - The SurrealDB database connection. - **namespace** (string) - The namespace to dump (for metadata). - **database** (string) - The database to dump (for metadata). - **tables** (...string) - Optional specific tables to dump. ##### Returns - `*Dumper` - A pointer to a new Dumper instance. ##### Example ```go db.Use(ctx, "myapp", "production") // Set namespace/database first dumper := surrealdump.New(db, "myapp", "production") // Pass same values for metadata ``` #### Full() ##### Description Full performs a consistent full database dump to a file with mandatory manifest. The dump consists of two parts to ensure consistency: 1. An inconsistent full dump of all records (captured between vs_1 and vs_2) 2. All changes from vs_0 (before the dump started) to vs_2 (after the dump ended) By including the complete change history, we ensure that even if the inconsistent dump captured records at different points between vs_1 and vs_2, we can replay all changes up to vs_2 to get a consistent state. This approach guarantees that incremental dumps starting at vs_2 won't miss any changes. ##### Parameters - **ctx** (context.Context) - The context for the operation. - **filePath** (string) - The path to the file where the dump will be saved. ##### Returns - `error` - An error if the dump fails, otherwise nil. ##### Example ```go db.Use(ctx, "myapp", "production") dumper := surrealdump.New(db, "myapp", "production") dumper.Full(ctx, "/path/to/dump.cbor") ``` ``` -------------------------------- ### Transaction Commit Example (Issue #177) Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/index Demonstrates committing a transaction in SurrealDB using the Go driver, addressing issue #177. This example shows successful data insertion and retrieval within a transaction. ```go package main import ( "fmt" "github.com/surrealdb/surrealdb.go" ) type Result struct { ID string `json:"id,omitempty"` Name string `json:"name,omitempty"` } func main() { db, err := surrealdb.New("ws://localhost:8000/rpc") if err != nil { panic(err) } defer db.Close() // Sign in with a namespace, database, and Dream token _, err = db.Signin(map[string]interface{}{ "user": "root", "pass": "root", }) if err != nil { panic(err) } tx, err := db.Begin() if err != nil { panic(err) } // Insert data within the transaction _, err = tx.Query("CREATE test SET name = 'test1'") if err != nil { panic(err) } _, err = tx.Query("CREATE test SET name = 'test2'") if err != nil { panic(err) } // Return data from within the transaction before commit result, err := tx.Query("SELECT * FROM test") if err != nil { panic(err) } var results []Result if err := surrealdb.Unmarshal(result, &results); err != nil { panic(err) } fmt.Printf("Status: %s\n", result[0].Status) for i, r := range results { fmt.Printf("result[%d].id: %s\n", i, r.ID) fmt.Printf("result[%d].name: %s\n", i, r.Name) } // Commit the transaction err = tx.Commit() if err != nil { panic(err) } // Query again after commit to verify result, err = db.Query("SELECT * FROM test WHERE name = 'test1'") if err != nil { panic(err) } if err := surrealdb.Unmarshal(result, &results); err != nil { panic(err) } for _, r := range results { fmt.Printf("result[%d].name: %s\n", 0, r.Name) } } ``` -------------------------------- ### Initialize CQRS Store (Go) Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealnote/pkg/store/cqrs Creates a new CQRSStore instance. This store uses primary and secondary stores for read/write operations and supports migration modes. It requires instances of store.Store for both primary and secondary operations, along with a MigrationMode. ```go func NewCQRSStore(primary, secondary store.Store, mode MigrationMode) store.Store ``` -------------------------------- ### Go: Start an UPSERT query with Upsert function Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealql The `Upsert` function in the SurrealDB Go driver is used to start an UPSERT query. It accepts a variable number of target records and returns an `UpsertQuery` object for further manipulation. ```go func Upsert[T exprLike](targets ...T) *UpsertQuery ``` -------------------------------- ### SelectQuery Explain Method Example in Go Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealql Illustrates the `Explain` method for `SelectQuery`, which enables EXPLAIN mode for the query. This is used for performance analysis and query planning. ```go func (q *SelectQuery) Explain() *SelectQuery ``` -------------------------------- ### Application Initialization - func New Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealnote/pkg/surrealnote Creates a new application instance with the provided configuration. ```APIDOC #### func New ```go func New(config *Config) (*App, error) ``` ### Description New creates a new application instance. A production system would accept a context parameter, implement proper health checks, initialize monitoring/tracing, and validate all connections before returning. ``` -------------------------------- ### Example Marshaler Implementation for Temperature Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/surrealcbor This example demonstrates how to implement the Marshaler interface for a custom `Temperature` struct. It encodes the temperature value and unit into a compact CBOR array, requiring the fxamacker/cbor package for marshaling. ```go type Temperature struct { Value float64 Unit string // "C", "F", or "K" } func (t Temperature) MarshalCBOR() ([]byte, error) { // Encode to a compact format: [value, unit_code] // where unit_code is: 0=Celsius, 1=Fahrenheit, 2=Kelvin var unitCode uint64 switch t.Unit { case "C": unitCode = 0 case "F": unitCode = 1 case "K": unitCode = 2 default: return nil, fmt.Errorf("unknown unit: %s", t.Unit) } compact := []interface{}{t.Value, unitCode} // Note: This requires importing fxamacker/cbor for cbor.Marshal return cbor.Marshal(compact) } ``` -------------------------------- ### Manage Workspaces (Go) Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealnote/pkg/store/cqrs Offers functions to create, retrieve, delete, and list workspaces. It supports fetching a workspace by its ID and listing all workspaces owned by a specific user. ```go func (c *CQRSStore) CreateWorkspace(ctx context.Context, workspace *models.Workspace) error ``` ```go func (c *CQRSStore) DeleteWorkspace(ctx context.Context, id models.WorkspaceID) error ``` ```go func (c *CQRSStore) GetWorkspace(ctx context.Context, id models.WorkspaceID) (*models.Workspace, error) ``` ```go func (c *CQRSStore) ListModifiedWorkspaceIDs(ctx context.Context, since, until time.Time) ([]models.WorkspaceID, error) ``` ```go func (c *CQRSStore) ListWorkspaces(ctx context.Context, ownerID models.UserID) ([]*models.Workspace, error) ``` -------------------------------- ### Perform Full Database Dump (Go) Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealdump%40v1.0 Performs a consistent full database dump to a specified file path, including a mandatory manifest. It ensures consistency by capturing an inconsistent dump and all subsequent changes, allowing for a replay to achieve a consistent state. This guarantees that incremental dumps starting after the full dump will not miss any data. Example: `db.Use(ctx, "myapp", "production"); dumper := surrealdump.New(db, "myapp", "production"); dumper.Full(ctx, "/path/to/dump.cbor")` ```Go func (d *Dumper) Full(ctx context.Context, filePath string) error { // ... implementation details ... } ``` -------------------------------- ### SurrealDB Go Server Run Command Example Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealnote%40v0.0.0-20260212031642-89d0f8d1b4c6/pkg/surrealnote This Go code snippet demonstrates how to run the SurrealDB server using a context for graceful shutdown. It initializes a `RunCommand` and executes the `app.Run` method, which blocks until the context is cancelled or a fatal error occurs. The server allows a grace period for active requests upon shutdown. ```go ctx, cancel := context.WithCancel(context.Background()) defer cancel() cmd := &RunCommand{} if err := app.Run(ctx, cmd); err != nil { log.Fatalf("Server failed: %v", err) } ``` -------------------------------- ### Create PostgresStore with Change Tracking Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealnote/pkg/store/postgres Initializes a new PostgresStore with change tracking enabled. This configuration ensures that all write operations are logged in the change tracking table, providing an audit trail. ```go func NewPostgresStoreWithChangeTracking(dsn string) (*PostgresStore, error) { // Implementation details... } ``` -------------------------------- ### Example of Var Usage in SurrealQL (Go) Source: https://pkg.go.dev/github.com/surrealdb/surrealdb.go/contrib/surrealql This example demonstrates the difference between using a Var type for variable references and using plain string literals in SurrealQL. It shows how variables are substituted into the query. The output illustrates a CREATE statement with variable assignments. ```text With Var: CREATE users SET name = $name, prefix = $param_1 Vars: map[param_1:$user] ```