### Setup SurrealDB Python Project with uv Source: https://github.com/surrealdb/surrealdb.py/blob/main/README.md Commands to clone the SurrealDB Python SDK repository and set up the development environment using 'uv sync' to install development dependencies. This is part of the local development setup. ```bash git clone https://github.com/surrealdb/surrealdb.py.git cd surrealdb.py uv sync --group dev ``` -------------------------------- ### Start SurrealDB Instance for SDK Usage Source: https://github.com/surrealdb/surrealdb.py/blob/main/README.md Command to start a SurrealDB instance using the official Docker image, configured to be accessible for the Python SDK. It exposes port 8000 and allows all connections. ```bash docker run --rm -p 8000:8000 surrealdb/surrealdb:v2.3.6 start --allow-all ``` -------------------------------- ### Install dependencies with uv Source: https://github.com/surrealdb/surrealdb.py/blob/main/README.md Installs project dependencies using the uv sync command. Supports installing main dependencies or including development dependencies. ```bash # Install main dependencies uv sync # Install with dev dependencies (linting, type checking, testing) uv sync --group dev ``` -------------------------------- ### Install and Connect to SurrealDB (Python) Source: https://context7.com/surrealdb/surrealdb.py/llms.txt Demonstrates how to install the SurrealDB Python SDK using pip and establish both synchronous and asynchronous connections to a SurrealDB instance using WebSocket and HTTP protocols, respectively. Includes context manager usage and manual connection management. ```python # Install via pip # pip install surrealdb from surrealdb import Surreal, AsyncSurreal import asyncio # Synchronous connection with context manager (WebSocket) with Surreal("ws://localhost:8000/rpc") as db: db.signin({"username": "root", "password": "root"}) db.use("test_namespace", "test_database") result = db.query("SELECT * FROM person") print(result) # Asynchronous connection with context manager (HTTP) async def main(): async with AsyncSurreal("http://localhost:8000/rpc") as db: await db.signin({"username": "root", "password": "root"}) await db.use("test_namespace", "test_database") result = await db.query("SELECT * FROM person") print(result) asyncio.run(main()) # Manual connection management db = Surreal("ws://localhost:8000/rpc") db.connect("ws://localhost:8000/rpc") db.signin({"username": "root", "password": "root"}) db.use("test", "test") # ... operations ... db.close() ``` -------------------------------- ### Install SurrealDB SDK Source: https://github.com/surrealdb/surrealdb.py/blob/main/README.md Installs the surrealdb Python package using pip. This is the primary method for adding the SDK to a Python project. ```bash pip install surrealdb ``` -------------------------------- ### Bash: Running SurrealDB Docker Compose for Local Development Source: https://github.com/surrealdb/surrealdb.py/blob/main/README.md Provides commands to start and stop a SurrealDB instance using Docker Compose. This is essential for setting up a local development environment to run tests and interact with the database. ```bash # if the docker-compose binary is installed docker-compose up -d # if you are running docker compose directly through docker docker compose up -d ``` ```bash # if the docker-compose binary is installed docker-compose down # if you are running docker compose directly through docker docker compose down ``` -------------------------------- ### Install uv with curl Source: https://github.com/surrealdb/surrealdb.py/blob/main/README.md Installs the uv dependency manager using a curl command. This is a prerequisite for managing project dependencies. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Development with Docker Compose for SurrealDB Source: https://github.com/surrealdb/surrealdb.py/blob/main/README.md Docker Compose commands to manage SurrealDB instances for development and testing. This includes starting the latest version, a specific version, and viewing logs. ```bash # Start latest SurrealDB for development docker-compose up -d # Start specific version for testing SURREALDB_VERSION=v2.1.8 docker-compose up -d # View logs docker-compose logs -f surrealdb ``` -------------------------------- ### Manage SurrealDB Docker Compose Profiles Source: https://github.com/surrealdb/surrealdb.py/blob/main/README.md Docker Compose commands to start SurrealDB instances using specific profiles, each corresponding to a different SurrealDB version and running on a dedicated port. This is useful for testing compatibility with various SurrealDB releases. ```bash # Development (default - v2.3.6) docker compose up -d # Test specific v2.x versions docker compose --profile v2-0 up -d # v2.0.5 on port 8020 docker compose --profile v2-1 up -d # v2.1.8 on port 8021 docker compose --profile v2-2 up -d # v2.2.6 on port 8022 docker compose --profile v2-3 up -d # v2.3.6 on port 8023 ``` -------------------------------- ### Run local development tests Source: https://github.com/surrealdb/surrealdb.py/blob/main/README.md Starts a Docker Compose environment for SurrealDB and runs tests against the default or a specific version. This is used for local development testing. ```bash # Test with default version (latest stable) docker-compose up -d uv run scripts/run_tests.sh # Test against specific version ./scripts/test-versions.sh v2.1.8 # Test against different v2.x versions SURREALDB_VERSION=v2.0.5 uv run scripts/run_tests.sh SURREALDB_VERSION=v2.3.6 uv run scripts/run_tests.sh ``` -------------------------------- ### Bash: Entering SurrealDB Python Development Environment Source: https://github.com/surrealdb/surrealdb.py/blob/main/README.md A command to enter a pre-configured terminal session with all necessary dependencies installed and the PYTHONPATH configured for SurrealDB Python SDK development. ```bash bash scripts/term.sh ``` -------------------------------- ### SurrealDB Python Geometry Types Examples Source: https://context7.com/surrealdb/surrealdb.py/llms.txt Illustrates the use of Point, Line, and Polygon geometry types in the SurrealDB Python SDK. Includes examples for creating geometric objects and storing them in the database. ```python from surrealdb import Surreal, Geometry from surrealdb.data.types.geometry import ( GeometryPoint, GeometryLine, GeometryPolygon, GeometryMultiPoint, GeometryMultiLine, GeometryMultiPolygon, GeometryCollection ) with Surreal("ws://localhost:8000/rpc") as db: db.signin({"username": "root", "password": "root"}) db.use("test", "test") # Create a point (longitude, latitude) point = GeometryPoint(-73.935242, 40.730610) print(f"Point coordinates: {point.get_coordinates()}") # Parse point from coordinates point2 = GeometryPoint.parse_coordinates((-74.006, 40.7128)) print(f"Parsed point: {point2}") # Create a line with multiple points line = GeometryLine( GeometryPoint(-73.935242, 40.730610), GeometryPoint(-74.006, 40.7128), GeometryPoint(-73.9712, 40.7831) ) print(f"Line coordinates: {line.get_coordinates()}") # Create a polygon (must form closed shape) polygon = GeometryPolygon([ GeometryPoint(0.0, 0.0), GeometryPoint(10.0, 0.0), GeometryPoint(10.0, 10.0), GeometryPoint(0.0, 10.0), GeometryPoint(0.0, 0.0) # Closes the polygon ]) print(f"Polygon coordinates: {polygon.get_coordinates()}") # Use in database operations db.create("location:nyc", { "name": "New York City", "position": point }) db.create("route:manhattan", { "name": "Manhattan Route", "path": line }) ``` -------------------------------- ### Switch Namespace and Database - use() Source: https://context7.com/surrealdb/surrealdb.py/llms.txt Allows switching the active namespace and database for subsequent operations. Requires establishing a connection and signing in first. The `use()` method takes the namespace and database names as arguments. Example shows switching between 'production'/'users' and 'development'/'testing'. ```python from surrealdb import Surreal with Surreal("ws://localhost:8000/rpc") as db: db.signin({"username": "root", "password": "root"}) # Switch to production namespace and users database db.use("production", "users") users = db.select("person") # Switch to development namespace and testing database db.use("development", "testing") test_data = db.select("person") print(f"Production users: {users}") print(f"Development test data: {test_data}") ``` -------------------------------- ### SurrealDB Python Range Types Examples Source: https://context7.com/surrealdb/surrealdb.py/llms.txt Shows how to use the Range type in the SurrealDB Python SDK, including inclusive, exclusive, and mixed bounds. Demonstrates creating ranges and performing range-based queries. ```python from surrealdb import Surreal, Range from surrealdb.data.types.range import BoundIncluded, BoundExcluded with Surreal("ws://localhost:8000/rpc") as db: db.signin({"username": "root", "password": "root"}) db.use("test", "test") # Create range with inclusive bounds [10, 20] range1 = Range( begin=BoundIncluded(10), end=BoundIncluded(20) ) print(f"Inclusive range: {range1}") # Create range with exclusive bounds (10, 20) range2 = Range( begin=BoundExcluded(10), end=BoundExcluded(20) ) print(f"Exclusive range: {range2}") # Create mixed range [10, 20) range3 = Range( begin=BoundIncluded(10), end=BoundExcluded(20) ) print(f"Mixed range: {range3}") # Use in queries for range selection db.create("product:p1", {"name": "Widget A", "price": 15}) db.create("product:p2", {"name": "Widget B", "price": 25}) db.create("product:p3", {"name": "Widget C", "price": 12}) # Query with range (conceptual - actual syntax may vary) results = db.query(""" SELECT * FROM product WHERE price >= 10 AND price <= 20 """) print(f"Products in range: {results}") # Compare ranges range4 = Range(BoundIncluded(10), BoundIncluded(20)) print(f"Ranges equal: {range1 == range4}") # True ``` -------------------------------- ### Example Branch Name Format Source: https://github.com/surrealdb/surrealdb.py/blob/main/CONTRIBUTING.md Demonstrates the recommended branch naming convention for pull requests, which includes type, issue ID, and a descriptive summary. This format helps in organizing and contextualizing code changes. ```text TYPE-ISSUE_ID-DESCRIPTION bugfix-548-ensure-queries-execute-sequentially ``` -------------------------------- ### Get User Information in SurrealDB with Python Source: https://context7.com/surrealdb/surrealdb.py/llms.txt Provides Python code to retrieve information about the currently authenticated user in SurrealDB using the `info()` method. It demonstrates fetching info for the root user and a record-based user after signup. Ensure the SurrealDB connection is established. ```python from surrealdb import Surreal with Surreal("ws://localhost:8000/rpc") as db: db.signin({"username": "root", "password": "root"}) db.use("test", "test") # Get root user info root_info = db.info() print(f"Root info: {root_info}") # Create and signin as record user db.query(""" DEFINE ACCESS user ON DATABASE TYPE RECORD SIGNUP ( CREATE user SET email = $email, pass = crypto::argon2::generate($password) ) SIGNIN ( SELECT * FROM user WHERE email = $email AND crypto::argon2::compare(pass, $password) ) """) db.signup({ "namespace": "test", "database": "test", "access": "user", "variables": { "email": "user@example.com", "password": "pass123" } }) # Get record user info user_info = db.info() print(f"User info: {user_info}") # Returns user record data including email and other fields ``` -------------------------------- ### Commit Message Structure Guide Source: https://github.com/surrealdb/surrealdb.py/blob/main/CONTRIBUTING.md Provides guidance on crafting effective commit messages, emphasizing a concise summary line (max 50 characters) and a detailed body explaining the problem, solution, and reasoning. This facilitates easier code reviews. ```text Write a descriptive **summary**: The first line of your commit message should be a concise summary of the changes you are making. It should be no more than 50 characters and should describe the change in a way that is easy to understand. Provide more **details** in the body: The body of the commit message should provide more details about the changes you are making. Explain the problem you are solving, the changes you are making, and the reasoning behind those changes. ``` -------------------------------- ### SurrealDB Python Duration Type Examples Source: https://context7.com/surrealdb/surrealdb.py/llms.txt Demonstrates creating and manipulating time durations using the SurrealDB Python SDK. Supports various units like minutes, hours, days, milliseconds, and nanoseconds, and can be used in database queries. ```python from surrealdb import Surreal, Duration with Surreal("ws://localhost:8000/rpc") as db: db.signin({"username": "root", "password": "root"}) db.use("test", "test") # Create durations from strings duration1 = Duration.parse("5m") # 5 minutes duration2 = Duration.parse("2h") # 2 hours duration3 = Duration.parse("3d") # 3 days duration4 = Duration.parse("100ms") # 100 milliseconds duration5 = Duration.parse("500ns") # 500 nanoseconds print(f"5 minutes in nanoseconds: {duration1.nanoseconds}") print(f"5 minutes in seconds: {duration1.seconds}") print(f"2 hours in minutes: {duration2.minutes}") print(f"3 days in hours: {duration3.hours}") # Create from integer (seconds) duration6 = Duration.parse(60) # 60 seconds print(f"60 seconds duration: {duration6.to_string()}") # Access different units week_duration = Duration.parse("2w") print(f"Weeks: {week_duration.weeks}") print(f"Days: {week_duration.days}") print(f"Hours: {week_duration.hours}") # Get seconds and nanoseconds for storage sec, nsec = duration1.get_seconds_and_nano() print(f"Seconds: {sec}, Nanoseconds: {nsec}") # Use in queries db.query(""" CREATE task SET name = 'Process data', timeout = type::duration('5m'), created_at = time::now() """) ``` -------------------------------- ### Execute Raw Queries - query() Source: https://context7.com/surrealdb/surrealdb.py/llms.txt Facilitates the execution of raw SurrealQL statements. Supports single or multiple statements, and queries with or without variables. The `query()` method returns results corresponding to each executed statement. The example shows a simple SELECT, multiple CREATE and SELECT statements, and a parameterized query. ```python from surrealdb import Surreal with Surreal("ws://localhost:8000/rpc") as db: db.signin({"username": "root", "password": "root"}) db.use("test", "test") # Single statement query result = db.query("SELECT * FROM person WHERE age > 18") print(f"Adults: {result}") # Multiple statement query results = db.query(""" CREATE person SET name = 'Alice', age = 25; CREATE person SET name = 'Bob', age = 30; SELECT * FROM person; """) # Returns list of results for each statement print(f"Create result 1: {results[0]}") print(f"Create result 2: {results[1]}") print(f"Select result: {results[2]}") # Query with variables result = db.query( "SELECT * FROM type::table($table) WHERE age > $min_age", {"table": "person", "min_age": 21} ) print(f"Filtered result: {result}") ``` -------------------------------- ### Insert Relations in SurrealDB with Python Source: https://context7.com/surrealdb/surrealdb.py/llms.txt Demonstrates how to insert relation records between entities in SurrealDB using the Python SDK. It covers creating single and multiple relations, linking entities via their RecordIDs, and includes an example of querying these relations. Ensure SurrealDB is running and accessible. ```python from surrealdb import Surreal, RecordID with Surreal("ws://localhost:8000/rpc") as db: db.signin({"username": "root", "password": "root"}) db.use("test", "test") # Create person records person1 = db.create("person:alice", {"name": "Alice"}) person2 = db.create("person:bob", {"name": "Bob"}) # Create post records post1 = db.create("post:post1", {"content": "Hello World"}) # Insert single relation like1 = db.insert_relation("likes", { "in": RecordID("person", "alice"), "out": RecordID("post", "post1"), "created_at": "2024-01-15T10:00:00Z" }) print(f"Single relation: {like1}") # Insert multiple relations at once relations = db.insert_relation("likes", [ { "in": RecordID("person", "bob"), "out": RecordID("post", "post1") }, { "in": RecordID("person", "alice"), "out": RecordID("person", "bob"), "type": "follows" } ]) print(f"Multiple relations: {relations}") # Query relations alice_likes = db.query("SELECT * FROM likes WHERE in = person:alice") print(f"Alice's likes: {alice_likes}") ``` -------------------------------- ### Manage Variables - let() and unset() Source: https://context7.com/surrealdb/surrealdb.py/llms.txt Enables setting and unsetting variables for use within SurrealQL queries. The `let()` method assigns a value to a variable name, and `unset()` removes it. Variables are accessed using the '$' prefix. The example demonstrates setting string, integer, and object variables, using them in a CREATE statement, and then unsetting one, showing subsequent query failure. ```python from surrealdb import Surreal with Surreal("ws://localhost:8000/rpc") as db: db.signin({"username": "root", "password": "root"}) db.use("test", "test") # Set variables db.let("name", "John Doe") db.let("age", 30) db.let("user_data", { "first": "John", "last": "Doe", "email": "john@example.com" }) # Use variables in queries result = db.query(""" CREATE person SET name = $name, age = $age, email = $user_data.email """) print(f"Created: {result}") # Unset a variable db.unset("age") # This query will fail because $age is no longer defined try: db.query("CREATE person SET name = $name, age = $age") except Exception as e: print(f"Query failed: {e}") ``` -------------------------------- ### Create Records - create() Source: https://context7.com/surrealdb/surrealdb.py/llms.txt Used to create new records within a specified table. Records can be created with auto-generated IDs or with specific IDs provided as strings or `RecordID` objects. The `create()` method accepts the table name (or ID) and a dictionary of record data. The example shows creating records with auto-generated IDs, specific string IDs, `RecordID` objects, and creating an empty record. ```python from surrealdb import Surreal, RecordID with Surreal("ws://localhost:8000/rpc") as db: db.signin({"username": "root", "password": "root"}) db.use("test", "test") # Create record with auto-generated ID person1 = db.create("person", { "name": "John Doe", "email": "john@example.com", "age": 30, "tags": ["developer", "python"] }) print(f"Created: {person1}") # Create record with specific ID (string) person2 = db.create("person:alice", { "name": "Alice Smith", "email": "alice@example.com", "age": 25 }) print(f"Created with ID: {person2}") # Create record with specific ID (RecordID object) record_id = RecordID("person", "bob") person3 = db.create(record_id, { "name": "Bob Johnson", "email": "bob@example.com", "age": 35 }) print(f"Created with RecordID: {person3}") # Create empty record (auto-generated ID) empty_person = db.create("person") print(f"Empty record: {empty_person}") ``` -------------------------------- ### Select Records - select() Source: https://context7.com/surrealdb/surrealdb.py/llms.txt Retrieves records from a table or specific records by their ID. Can select all records from a table or a single record using its ID. Supports both string representations and dedicated object types (`RecordID`, `Table`) for specifying the target. The example demonstrates selecting all records and specific records using different identifier formats. ```python from surrealdb import Surreal, RecordID, Table with Surreal("ws://localhost:8000/rpc") as db: db.signin({"username": "root", "password": "root"}) db.use("test", "test") # Create some test data db.create("person", {"name": "Alice", "age": 25}) db.create("person", {"name": "Bob", "age": 30}) # Select all records from a table (string) all_people = db.select("person") print(f"All people: {all_people}") # Select using Table object all_people_table = db.select(Table("person")) print(f"All people (Table): {all_people_table}") # Select specific record by ID string specific_person = db.select("person:alice") print(f"Specific person: {specific_person}") # Select using RecordID object record_id = RecordID("person", "bob") specific_person_id = db.select(record_id) print(f"Specific person (RecordID): {specific_person_id}") ``` -------------------------------- ### SurrealDB Authentication: signup() (Python) Source: https://context7.com/surrealdb/surrealdb.py/llms.txt Illustrates how to register a new record user in SurrealDB using the `signup` method. This involves defining the access method and then providing user-specific variables for creation, enabling new users to register. ```python from surrealdb import Surreal with Surreal("ws://localhost:8000/rpc") as db: db.signin({"username": "root", "password": "root"}) db.use("test", "test") # Define access method first (this would be done via query or system setup) db.query(""" DEFINE ACCESS user ON DATABASE TYPE RECORD SIGNUP ( CREATE user SET email = $email, pass = crypto::argon2::generate($password) ) SIGNIN ( SELECT * FROM user WHERE email = $email AND crypto::argon2::compare(pass, $password) ) """) # Sign up a new user token = db.signup({ "namespace": "test", "database": "test", "access": "user", "variables": { "email": "newuser@example.com", "password": "securepass123" } }) print(f"Signup successful, token: {token}") ``` -------------------------------- ### Build and Publish Python Package Source: https://github.com/surrealdb/surrealdb.py/blob/main/README.md Commands to build the Python package using uv and publish it to PyPI. Publishing requires authentication and is typically done before a new release. ```bash # Build package uv build # Publish to PyPI (requires authentication) uv publish ``` -------------------------------- ### Connect and Query with SurrealDB Python SDK Source: https://github.com/surrealdb/surrealdb.py/blob/main/README.md An asynchronous Python script demonstrating how to connect to a SurrealDB instance, sign in, select a namespace and table, and perform create and select operations using the SurrealDB Python SDK. It requires Python 3.10+ and an active SurrealDB instance. ```python from surrealdb import Surreal async def main(): async with Surreal("ws://localhost:8000/rpc") as db: await db.signin({"user": "root", "pass": "root"}) await db.use("test", "test") # Create person = await db.create("person", {"name": "John", "age": 30}) print(person) # Query people = await db.select("person") print(people) import asyncio asyncio.run(main()) ``` -------------------------------- ### Build the project with uv Source: https://github.com/surrealdb/surrealdb.py/blob/main/README.md Builds the Python project using the uv build command. This command is used for packaging the project for distribution. ```bash uv build ``` -------------------------------- ### Initialize SurrealDB SDK Source: https://github.com/surrealdb/surrealdb.py/blob/main/README.md Imports and initializes the Surreal class from the surrealdb SDK. This is the first step in using the SDK for database interactions. ```python # Import the Surreal class from surrealdb import Surreal ``` -------------------------------- ### Bash: Testing SurrealDB with Different Versions via Docker Compose Source: https://github.com/surrealdb/surrealdb.py/blob/main/README.md Demonstrates how to use Docker Compose and environment variables to test the SurrealDB Python SDK against various SurrealDB versions, including specific v2.x releases and different profiles for port mapping. ```bash # Test with latest v2.x (default: v2.3.6) uv run scripts/run_tests.sh # Test with specific v2.x version SURREALDB_VERSION=v2.1.8 docker-compose up -d surrealdb uv run scripts/run_tests.sh # Use different profiles for testing specific v2.x versions docker-compose --profile v2-0 up -d # v2.0.5 on port 8020 docker-compose --profile v2-1 up -d # v2.1.8 on port 8021 docker-compose --profile v2-2 up -d # v2.2.6 on port 8022 docker-compose --profile v2-3 up -d # v2.3.6 on port 8023 ``` -------------------------------- ### Run Unit Tests with uv Source: https://github.com/surrealdb/surrealdb.py/blob/main/README.md Command to execute the project's unit tests using uv and Python's unittest module. It requires SurrealDB to be running and the SURREALDB_URL environment variable to be set. ```bash # Start SurrealDB v2.3.6 docker compose up -d # Run tests export SURREALDB_URL="http://localhost:8000" uv run python -m unittest discover -s tests ``` -------------------------------- ### Build and Run SurrealDB Python Docker Image Source: https://github.com/surrealdb/surrealdb.py/blob/main/README.md Commands to build the Docker image for the SurrealDB Python SDK and run it with uv for executing Python code or tests within a container. It assumes a Dockerfile is present in the current directory. ```bash # Build the image docker build -t surrealdb-python:latest . # Run with uv docker run -it surrealdb-python:latest uv run python -c "import surrealdb; print('Ready!')" # Run tests in container docker run -it surrealdb-python:latest uv run python -m unittest discover -s tests ``` -------------------------------- ### Activate Python Virtual Environment Source: https://github.com/surrealdb/surrealdb.py/blob/main/README.md Commands to activate the Python virtual environment created by uv. This ensures that subsequent commands use the project's specific dependencies. ```bash source .venv/bin/activate # On Windows: .venv\Scripts\activate ``` -------------------------------- ### SurrealDB Connection URL Schemes (Python) Source: https://context7.com/surrealdb/surrealdb.py/llms.txt Demonstrates the different connection URL schemes supported by the SurrealDB Python SDK, including WebSocket (ws, wss) and HTTP (http, https). It shows how to instantiate both synchronous (`Surreal`) and asynchronous (`AsyncSurreal`) connections using these URLs and highlights the difference in feature availability (e.g., live queries with WebSocket vs. HTTP). ```python from surrealdb import Surreal, AsyncSurreal # WebSocket connections (recommended for full features including live queries) sync_ws = Surreal("ws://localhost:8000/rpc") sync_wss = Surreal("wss://cloud.surrealdb.com/rpc") # Secure WebSocket # HTTP connections (simpler, no live query support) sync_http = Surreal("http://localhost:8000/rpc") sync_https = Surreal("https://cloud.surrealdb.com/rpc") # Secure HTTP # Async variants async_ws = AsyncSurreal("ws://localhost:8000/rpc") async_wss = AsyncSurreal("wss://cloud.surrealdb.com/rpc") async_http = AsyncSurreal("http://localhost:8000/rpc") async_https = AsyncSurreal("https://cloud.surrealdb.com/rpc") # The SDK automatically selects the correct connection class based on URL scheme with Surreal("ws://localhost:8000/rpc") as db_ws: # Uses BlockingWsSurrealConnection db_ws.signin({"username": "root", "password": "root"}) db_ws.use("test", "test") # Live queries available uuid = db_ws.live("person") with Surreal("http://localhost:8000/rpc") as db_http: # Uses BlockingHttpSurrealConnection db_http.signin({"username": "root", "password": "root"}) db_http.use("test", "test") # Live queries NOT available with HTTP people = db_http.select("person") ``` -------------------------------- ### SurrealDB Async Operations and Connection Patterns (Python) Source: https://context7.com/surrealdb/surrealdb.py/llms.txt Illustrates asynchronous database operations using `AsyncSurreal` in Python. This includes connecting, authenticating, performing concurrent record creation using `asyncio.gather`, querying data, and executing batch operations. It also shows how to use the `AsyncSurreal` class with an asynchronous context manager. Requires a running SurrealDB instance. ```python from surrealdb import AsyncSurreal import asyncio async def async_operations(): # Create async connection db = AsyncSurreal("ws://localhost:8000/rpc") try: # Connect and authenticate await db.connect("ws://localhost:8000/rpc") await db.signin({"username": "root", "password": "root"}) await db.use("test", "test") # Create records concurrently tasks = [ db.create("person", {"name": "Alice", "age": 25}), db.create("person", {"name": "Bob", "age": 30}), db.create("person", {"name": "Charlie", "age": 35}) ] results = await asyncio.gather(*tasks) print(f"Created {len(results)} records concurrently") # Query asynchronously people = await db.select("person") print(f"All people: {people}") # Batch operations await db.query(""" UPDATE person SET status = 'active'; CREATE analytics SET total_users = count(SELECT * FROM person); """) finally: await db.close() # Run async function asyncio.run(async_operations()) # Or use async context manager async def with_context_manager(): async with AsyncSurreal("ws://localhost:8000/rpc") as db: await db.signin({"username": "root", "password": "root"}) await db.use("test", "test") result = await db.query("SELECT * FROM person") print(result) asyncio.run(with_context_manager()) ``` -------------------------------- ### Bash: Running SurrealDB Python SDK Tests Source: https://github.com/surrealdb/surrealdb.py/blob/main/README.md Command to execute tests for the SurrealDB Python SDK, including code coverage reporting. This helps verify the SDK's functionality and ensure proper integration with the database. ```bash pytest --cov=src/surrealdb --cov-report=term-missing --cov-report=html ``` -------------------------------- ### SurrealDB Authentication: signin() (Python) Source: https://context7.com/surrealdb/surrealdb.py/llms.txt Shows how to authenticate with SurrealDB using the `signin` method. It covers authenticating as the root user and as a record user by providing credentials or access details and variables. This is crucial for accessing and manipulating data. ```python from surrealdb import Surreal with Surreal("ws://localhost:8000/rpc") as db: # Root user authentication token = db.signin({ "username": "root", "password": "root" }) print(f"Authenticated with token: {token}") db.use("test", "test") # Record user authentication (after namespace/database selection) user_token = db.signin({ "namespace": "test", "database": "test", "access": "user", "variables": { "email": "user@example.com", "password": "userpass123" } }) # Verify authentication info = db.info() print(f"User info: {info}") ``` -------------------------------- ### Run All Tests and Coverage Report (Bash) Source: https://github.com/surrealdb/surrealdb.py/blob/main/README.md Executes all tests for the surrealdb.py project and generates a terminal coverage summary. It also creates an HTML coverage report in the 'htmlcov/' directory. This command utilizes 'uv' for environment management and 'pytest' for testing. ```bash uv run scripts/run_tests.sh ``` -------------------------------- ### Run development tools with uv Source: https://github.com/surrealdb/surrealdb.py/blob/main/README.md Executes various development tools like linters, formatters, type checkers, and tests using the uv run command. These commands help maintain code quality and test functionality. ```bash # Run linting uv run ruff check src/ # Run formatting uv run ruff format src/ # Run type checking uv run mypy --explicit-package-bases src/ # Run tests (with coverage) uv run scripts/run_tests.sh # Or directly: uv run pytest --cov=src/surrealdb --cov-report=term-missing --cov-report=html ``` -------------------------------- ### Bash: Automated SurrealDB Version Testing Script Source: https://github.com/surrealdb/surrealdb.py/blob/main/README.md Utilizes a script to automate testing of the SurrealDB Python SDK against different SurrealDB versions. This includes options for testing the latest version, a specific version, or a particular test directory. ```bash # Test latest version with all tests ./scripts/test-versions.sh # Test specific version ./scripts/test-versions.sh v2.1.8 # Test specific test directory ./scripts/test-versions.sh v2.3.6 tests/unit_tests/data_types ``` -------------------------------- ### Test SurrealDB Python SDK Against Multiple Versions Source: https://github.com/surrealdb/surrealdb.py/blob/main/README.md Shell scripts to test the SurrealDB Python SDK against different SurrealDB versions. These scripts automate the process of spinning up specific SurrealDB versions and running the SDK's test suite. ```bash # Test latest v2.x versions ./scripts/test-versions.sh --v2-latest # Test specific version ./scripts/test-versions.sh v2.1.8 # Test all supported versions ./scripts/test-versions.sh --all ``` -------------------------------- ### Python: Connect, CRUD, and Query with SurrealDB SDK Source: https://github.com/surrealdb/surrealdb.py/blob/main/README.md Demonstrates basic CRUD operations and querying using the SurrealDB Python SDK. It utilizes a context manager for automatic connection and disconnection, and showcases both Pythonic method calls and direct SurrealQL queries for data manipulation. ```python # Using a context manger to automatically connect and disconnect with Surreal("ws://localhost:8000/rpc") as db: db.signin({"username": 'root', "password": 'root'}) db.use("namepace_test", "database_test") # Create a record in the person table db.create( "person", { "user": "me", "password": "safe", "marketing": True, "tags": ["python", "documentation"], }, ) # Read all the records in the table print(db.select("person")) # Update all records in the table print(db.update("person", { "user":"you", "password":"very_safe", "marketing": False, "tags": ["Awesome"] })) # Delete all records in the table print(db.delete("person")) # You can also use the query method # doing all of the above and more in SurrealQl # In SurrealQL you can do a direct insert # and the table will be created if it doesn't exist # Create db.query(""" insert into person { user: 'me', password: 'very_safe', tags: ['python', 'documentation'] }; """,) # Read print(db.query("select * from person")) # Update print(db.query(""" update person content { user: 'you', password: 'more_safe', tags: ['awesome'] }; """,)) # Delete print(db.query("delete person")) ``` -------------------------------- ### Run Specific Test File with Coverage (Bash) Source: https://github.com/surrealdb/surrealdb.py/blob/main/README.md Tests a single specified file (e.g., a unit test file) while also enabling coverage reporting for the 'src/surrealdb' module. This is useful for targeted testing and debugging. ```bash uv run pytest tests/unit_tests/connections/test_connection_constructor.py --cov=src/surrealdb ``` -------------------------------- ### Python Live Queries for Real-time Data Updates Source: https://context7.com/surrealdb/surrealdb.py/llms.txt Sets up a live query to monitor changes in the 'person' table and subscribes to real-time notifications. It demonstrates creating, updating, and deleting records to trigger these notifications. The query is then explicitly killed. ```python from surrealdb import Surreal import threading import time with Surreal("ws://localhost:8000/rpc") as db: db.signin({"username": "root", "password": "root"}) db.use("test", "test") # Start a live query query_uuid = db.live("person", diff=False) print(f"Live query UUID: {query_uuid}") # Subscribe to live notifications in a separate thread def listen_for_changes(): for notification in db.subscribe_live(query_uuid): print(f"Live notification: {notification}") # notification contains action ('CREATE', 'UPDATE', 'DELETE') and data if notification.get("action") == "CLOSE": break listener_thread = threading.Thread(target=listen_for_changes, daemon=True) listener_thread.start() # Make changes to trigger notifications time.sleep(1) db.create("person", {"name": "Alice", "age": 25}) time.sleep(1) db.update("person:alice", {"name": "Alice Smith", "age": 26}) time.sleep(1) db.delete("person:alice") time.sleep(1) # Kill the live query db.kill(query_uuid) print("Live query killed") listener_thread.join(timeout=2) ``` -------------------------------- ### Format and Lint Code with Ruff Source: https://github.com/surrealdb/surrealdb.py/blob/main/README.md Commands to format code using Ruff's formatter and check for linting errors. These are part of the code quality checks within the development workflow. ```bash # Format code uv run ruff format # Lint code uv run ruff check ``` -------------------------------- ### SurrealDB Table Type Operations (Python) Source: https://context7.com/surrealdb/surrealdb.py/llms.txt Demonstrates how to use the `Table` class for type-safe representation of database tables in SurrealDB. It covers creating `Table` objects, using them in select, insert, and delete operations, and comparing table instances. Requires a running SurrealDB instance and authentication. ```python from surrealdb import Surreal, Table with Surreal("ws://localhost:8000/rpc") as db: db.signin({"username": "root", "password": "root"}) db.use("test", "test") # Create Table objects person_table = Table("person") post_table = Table("post") print(f"Table name: {person_table.table_name}") print(f"Table string: {str(person_table)}") # Use in select operations people = db.select(person_table) print(f"All people: {people}") # Use in insert operations new_person = db.insert(person_table, { "name": "Alice", "age": 25 }) print(f"Inserted: {new_person}") # Use in delete operations deleted = db.delete(person_table) print(f"Deleted all from table: {deleted}") # Compare tables another_person_table = Table("person") print(f"Tables equal: {person_table == another_person_table}") # True print(f"Tables equal: {person_table == post_table}") # False ``` -------------------------------- ### Handle SurrealDB Connection and Query Errors in Python Source: https://context7.com/surrealdb/surrealdb.py/llms.txt This Python code snippet demonstrates how to handle various errors when interacting with SurrealDB using the Python SDK. It covers authentication failures, query syntax errors, invalid record IDs, missing variables, and connection errors. It utilizes `try-except` blocks to catch specific SurrealDB errors and general exceptions. ```python from surrealdb import Surreal from surrealdb.errors import SurrealDbError try: with Surreal("ws://localhost:8000/rpc") as db: # Authentication error try: db.signin({"username": "wrong", "password": "wrong"}) except Exception as auth_error: print(f"Authentication failed: {auth_error}") # Re-authenticate with correct credentials db.signin({"username": "root", "password": "root"}) db.use("test", "test") # Query syntax error try: db.query("SELCT * FROM person") # Typo in SELECT except Exception as query_error: print(f"Query error: {query_error}") # Invalid record ID try: from surrealdb import RecordID invalid_id = RecordID.parse("invalid_format") except ValueError as parse_error: print(f"Parse error: {parse_error}") # Missing variable error try: db.query("CREATE person SET name = $undefined_var") except Exception as var_error: print(f"Variable error: {var_error}") # Successful query result = db.query("SELECT * FROM person") print(f"Success: {result}") except ConnectionError as conn_error: print(f"Connection failed: {conn_error}") except Exception as e: print(f"Unexpected error: {e}") ``` -------------------------------- ### Perform Type Checking with Mypy Source: https://github.com/surrealdb/surrealdb.py/blob/main/README.md Command to run Mypy for static type checking on the project's source code. This helps catch type-related errors before runtime. ```bash uv run mypy src/ ``` -------------------------------- ### Bulk Insert Records in SurrealDB with Python Source: https://context7.com/surrealdb/surrealdb.py/llms.txt Shows how to perform bulk inserts into SurrealDB using the Python SDK. This includes inserting a single record, multiple records in one call, and using the `Table` object for insertion. Proper connection and authentication are required. ```python from surrealdb import Surreal, Table with Surreal("ws://localhost:8000/rpc") as db: db.signin({"username": "root", "password": "root"}) db.use("test", "test") # Insert single record single = db.insert("person", { "name": "Alice", "age": 25, "email": "alice@example.com" }) print(f"Single insert: {single}") # Insert multiple records at once multiple = db.insert("person", [ {"name": "Bob", "age": 30, "email": "bob@example.com"}, {"name": "Charlie", "age": 35, "email": "charlie@example.com"}, {"name": "Diana", "age": 28, "email": "diana@example.com"} ]) print(f"Multiple insert: {multiple}") # Insert using Table object table = Table("person") more_records = db.insert(table, [ {"name": "Eve", "age": 22}, {"name": "Frank", "age": 45} ]) print(f"Insert via Table: {more_records}") # Verify all inserts all_people = db.select("person") print(f"Total records: {len(all_people)}") ``` -------------------------------- ### Python Live Queries with JSON Patch Diffs Source: https://context7.com/surrealdb/surrealdb.py/llms.txt Demonstrates setting up a live query in diff mode to receive JSON Patch operations for record updates, instead of the full record. It subscribes to these diff notifications and shows how to process them. ```python from surrealdb import Surreal import threading import time with Surreal("ws://localhost:8000/rpc") as db: db.signin({"username": "root", "password": "root"}) db.use("test", "test") # Create initial record db.create("person:alice", {"name": "Alice", "age": 25, "status": "active"}) # Start live query with diff mode enabled query_uuid = db.live("person", diff=True) print(f"Live query UUID (diff mode): {query_uuid}") # Subscribe to notifications def listen_for_diffs(): for notification in db.subscribe_live(query_uuid): print(f"Notification action: {notification.get('action')}") if "result" in notification and isinstance(notification["result"], list): # In diff mode, result contains JSON Patch operations print(f"JSON Patch operations: {notification['result']}") if notification.get("action") == "CLOSE": break listener_thread = threading.Thread(target=listen_for_diffs, daemon=True) listener_thread.start() time.sleep(1) # Update will generate patch operations db.update("person:alice", {"name": "Alice Smith", "age": 26, "status": "active"}) time.sleep(2) db.kill(query_uuid) listener_thread.join(timeout=2) ``` -------------------------------- ### Run All Tests with Specific Coverage Options (Bash) Source: https://github.com/surrealdb/surrealdb.py/blob/main/README.md Runs all tests using pytest with specific coverage reporting flags. It displays missing coverage in the terminal and generates an HTML report. This command is useful for detailed coverage analysis. ```bash uv run pytest --cov=src/surrealdb --cov-report=term-missing --cov-report=html ```