Skip to content

surrealdb/surrealdb.py

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

65 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

 

The official SurrealDB SDK for Python.


       

     

surrealdb.py

The official SurrealDB SDK for Python.

Documentation

View the SDK documentation here.

How to install

pip install surrealdb

Basic Usage

All examples assume SurrealDB is installed and running on port 8000.

Initialization

To start using the database, create an instance of SurrealDB, connect to your SurrealDB server, and specify the namespace and database you wish to work with. Always remember to close the db connection after use.

from surrealdb import SurrealDB

# Connect to the database
db = SurrealDB(url="ws://localhost:8000")
db.connect()
db.use("namespace", "database_name")
# Your DML code...
db.close()

Using context manager

The library supports Python’s context manager to manage connections automatically. This ensures that connections are properly closed when the block of code finishes executing.

from surrealdb import SurrealDB

with SurrealDB(url="ws://localhost:8000") as db:
    db.use("namespace", "database_name")
    # Your DML code...

Using Async

The AsyncSurrealDB supports asynchronous operations while retaining compatibility with synchronous workflows, ensuring flexibility for any range of use cases. The APIs do not differ

from surrealdb import AsyncSurrealDB

async with AsyncSurrealDB(url="ws://localhost:8000") as db:
    await db.use("namespace", "database_name")
    # Your DML code...

Without context manager:

from surrealdb import AsyncSurrealDB

# Connect to the database
db = AsyncSurrealDB(url="ws://localhost:8000")
await db.connect()
await db.use("namespace", "database_name")
# Your DML code...
await db.close()

Example Usage

from surrealdb import SurrealDB, GeometryPoint, Table

with SurrealDB(url="ws://localhost:8000") as db:
    db.use("test_ns", "test_db")
    auth_token = db.sign_in(username="root", password="root")

    # Check token validity. This is not necessary if you called `sign_in` before. This authenticates the
    # `db` instance too if `sign_in` was not previously called
    db.authenticate(auth_token)

    # Create an entry
    person = db.create(Table("persons"), {
        "Name": "John",
        "Surname": "Doe",
        "Location": GeometryPoint(-0.11, 22.00),
    })

    print("Created person with a map:", person)

    # Get entry by Record ID
    person = db.select(person.get("id"))
    print("Selected a person by record id: ", person)

    # Or retrieve the entire table
    persons = db.select(Table("persons"))
    print("Selected all in persons table: ", persons)

    # Delete an entry by ID
    _ = db.delete(persons[0].get("id"))

    # Delete all entries
    _ = db.delete(Table("persons"))

    # Confirm empty table
    persons = db.select(Table("persons"))
    print("No Selected person: ", persons)

    # And later, we can invalidate the token
    db.invalidate(auth_token)

Connection Engines

There are 3 available connection engines you can use to connect to SurrealDb backend. It can be via Websocket, HTTP or through embedded database connections. The connection types are simply determined by the url scheme provided in the connection url.

Via Websocket

Websocket url can be ws or wss for secure connection. For example ws://localhost:8000 and wss://localhost:8000. All functionalities are available via websockets.

Via HTTP

HTTP url can be http or https for secure connection. For example http://localhost:8000 and https://localhost:8000. There are some functions that are not available on RPC when using HTTP but are on Websocket. This includes all live query/notification methods.

Using SurrealKV and Memory

SurrealKV and In-Memory also do not support live notifications at this time. This would be updated in a later release.

For Surreal KV

from surrealdb import SurrealDB

db = SurrealDB("surrealkv://path/to/dbfile.kv")

For Memory

from surrealdb import SurrealDB

db = SurrealDB("mem://")
db = SurrealDB("memory://")

Additional Examples

Insert and Retrieve Data

from surrealdb import SurrealDB

db = SurrealDB("ws://localhost:8000")
db.connect()
db.use("example_ns", "example_db")
db.sign_in("root", "root")

# Insert a record
new_user = {"name": "Alice", "age": 30}
inserted_record = db.insert("users", new_user)
print(f"Inserted Record: {inserted_record}")

# Retrieve the record
retrieved_users = db.select("users")
print(f"Retrieved Users: {retrieved_users}")

db.close()

Perform a Custom Query

from surrealdb import AsyncSurrealDB
import asyncio


async def main():
    async with AsyncSurrealDB(url="ws://localhost:8000") as db:
        await db.sign_in("root", "root")
        await db.use("test", "test")

        query = "SELECT * FROM users WHERE age > min_age;"
        variables = {"min_age": 25}

        results = await db.query(query, variables)
        print(f"Query Results: {results}")

asyncio.run(main())

Manage Authentication

from surrealdb import SurrealDB

with SurrealDB(url="ws://localhost:8000") as db:
    # Sign up a new user
    token = db.sign_up(username="new_user", password="secure_password")
    print(f"New User Token: {token}")
    
    # Sign in as an existing user
    token = db.sign_in(username="existing_user", password="secure_password")
    print(f"Signed In Token: {token}")
    
    # Authenticate using a token
    db.authenticate(token=token)
    print("Authentication successful!")

Live Query Notifications

import asyncio
from surrealdb.surrealdb import SurrealDB

db = SurrealDB("ws://localhost:8000")
db.connect()
db.use("example_ns", "example_db")

# Start a live query
live_id = db.live("users")

# Process live notifications
notifications = db.live_notifications(live_id)

async def handle_notifications():
    while True:
        notification = await notifications.get()
        print(f"Live Notification: {notification}")

# Run the notification handler
asyncio.run(handle_notifications())

Upserting Records

from surrealdb.surrealdb import SurrealDB

with SurrealDB("ws://localhost:8000") as db:
    db.sign_in("root", "root")
    db.use("example_ns", "example_db")

    upsert_data = { "name": "Charlie", "age": 35}
    result = db.upsert("users", upsert_data)
    print(f"Upsert Result: {result}")

Contributing

Contributions to this library are welcome! If you encounter issues, have feature requests, or want to make improvements, feel free to open issues or submit pull requests.