Surreal() and AsyncSurreal() open a connection to SurrealDB and choose the connection class from the scheme of the URL. This page is the reference for every method and property of the connections they return. For explanations and longer examples, follow the links to the concept pages in each section.
Surreal() returns a blocking connection and AsyncSurreal() returns an asynchronous one, with the same methods. The examples on this page use a blocking connection. On an asynchronous connection, put await before each method call, including the methods that return a builder, such as select() and query(). Five methods are not awaited: batch(), live_of(), subscribe(), timeout() and is_feature_supported(). Properties such as status are read without await.
Source: surrealdb.py
Factory functions
Surreal()
Open a blocking connection.
Surreal(
url,
*,
streaming=True,
ping_interval=30.0,
ping_timeout=10.0,
timeout=30.0,
version_check=True,
reconnect=True,
auth=None,
renew_access=True,
)Returns: BlockingSurrealConnection, which is a BlockingWsSurrealConnection, BlockingHttpSurrealConnection or BlockingEmbeddedSurrealConnection, depending on the URL scheme.
AsyncSurreal()
Open an asynchronous connection. It takes the same arguments as Surreal(), and auth can also be a coroutine function.
AsyncSurreal(url, *, ...)Returns: AsyncSurrealConnection, which is an AsyncWsSurrealConnection, AsyncHttpSurrealConnection or AsyncEmbeddedSurrealConnection.
Both functions only build the connection object. A WebSocket connection opens its socket when you call connect(), enter a with block, or send the first request.
from surrealdb import AsyncSurreal, Surreal
db = Surreal("ws://localhost:8000")
adb = AsyncSurreal("ws://localhost:8000", timeout=10)Surreal and AsyncSurreal are functions, so they cannot annotate a variable. Use the type aliases that the package exports:
from surrealdb import AsyncSurrealConnection, BlockingSurrealConnection
def report(db: BlockingSurrealConnection) -> None: ...Options
Every option is keyword-only. The embedded connection uses none of them, and the HTTP connection uses timeout, version_check, auth and renew_access only.
Parameter | Type | Description |
|---|---|---|
url | str | The address to connect to. The scheme chooses the connection class: see URL schemes . |
streaming | bool | Let queries over a WebSocket arrive as a stream from SurrealDB 3.3 and later. Defaults to True. Falseputs query()back on the buffered path, and an explicit .rows()still streams. See Streaming results . |
ping_interval | float | None | Seconds between keepalive pings on an idle WebSocket. Defaults to 30. Nonesends no pings. |
ping_timeout | float | None | Seconds to wait for the answer to a ping before the connection counts as lost. Defaults to 10. Nonewaits indefinitely. |
timeout | float | None | Seconds to wait for the reply to each request. Defaults to 30. Nonewaits indefinitely. timeout()changes it for a block of code. |
version_check | bool | Refuse a server outside the supported versions, SurrealDB 2.x, 3.x and 4.x, with UnsupportedVersionError. Defaults to True. |
reconnect | bool | ReconnectOptions | Open a new WebSocket when the socket drops, and restore the namespace, database, variables, authentication, sessions and live queries. Defaults to True. Pass ReconnectOptionsto change the attempts and the delay between them, or Falseto turn it off. |
auth | dict | str | Tokens | Callable | None | How the connection signs itself in: sign-in credentials, an access token, Tokens, or a function that returns one of those. See Authentication . |
renew_access | bool | Renew the access token shortly before it expires, with the refresh token or else with auth. Defaults to True. |
from surrealdb import ReconnectOptions, Surreal
db = Surreal(
"ws://localhost:8000",
timeout=60,
reconnect=ReconnectOptions(attempts=10, retry_delay_max=30.0),
auth={"username": "root", "password": "secret"},
)ReconnectOptions takes enabled (default True), attempts (default 5, or -1 for no limit), retry_delay (default 1.0), retry_delay_max (default 60.0), retry_delay_multiplier (default 2.0) and retry_delay_jitter (default 0.1). See Connecting to SurrealDB for what a reconnect restores.
URL schemes
| Scheme | Connection | Class |
|---|---|---|
ws://, wss:// | WebSocket, with every feature | BlockingWsSurrealConnection, AsyncWsSurrealConnection |
http://, https:// | HTTP, one request at a time | BlockingHttpSurrealConnection, AsyncHttpSurrealConnection |
mem://, memory://, memory | Embedded, in memory | BlockingEmbeddedSurrealConnection, AsyncEmbeddedSurrealConnection |
file://, surrealkv:// | Embedded, on disk | as above |
surrealkv+versioned:// | Embedded, on disk, with versioned records | as above |
The SDK adds /rpc to a remote URL, so ws://localhost:8000 and ws://localhost:8000/rpc are the same address. An embedded URL needs the embedded extra: see Embedded databases. An unknown scheme raises UnsupportedEngineError, and a URL that cannot be parsed raises InvalidUrlError.
Connection methods
.connect()
Open the connection. A WebSocket opens its socket, and an embedded connection opens its engine. An HTTP connection keeps no connection open, so its connect() only asks the server for its version.
db.connect(url=None)Parameter | Type | Description |
|---|---|---|
url | str | None | A different address to connect to. On an open WebSocket connection, a different URL moves the connection there, and the same URL does nothing. On an HTTP connection, any URL moves the connection and clears its sign-in. |
Returns: None
db = Surreal("ws://localhost:8000")
db.connect()A new socket is a new session on the server, so after close() and connect(), sign in and call use() again, unless the connection has an auth option.
.close()
Close the connection and release its resources. Calling it on a closed connection does nothing.
db.close()Returns: None
.use()
Select the namespace and database for the requests that follow.
db.use(namespace=None, database=None)Parameter | Type | Description |
|---|---|---|
namespace | str | Null | None | The namespace. Nonekeeps the current one and Nullclears it. |
database | str | Null | None | The database. Nonekeeps the current one and Nullclears it. |
Returns: None
db.use("surrealdb", "docs")
db.use(database="staging") .version()
Return the version of the server, or of the engine on an embedded connection.
db.version()Returns: str, such as "surrealdb-4.0.0"
.health()
Ask the server's /health endpoint whether the server is healthy. A WebSocket connection asks over HTTP. Not available on an embedded connection.
db.health()Returns: None. Raises ConnectionUnavailableError when the server is unhealthy or cannot be reached.
.timeout()
Change how long each request waits for its reply, for the code inside a with block only. The block can be on a connection, a session or a transaction. On an asynchronous connection it is a plain with, and tasks started inside the block keep the value.
with db.timeout(seconds):
...Parameter | Type | Description |
|---|---|---|
seconds | float | None | Seconds to wait for each reply. Nonewaits indefinitely. |
A request that waits longer raises TransportTimeoutError. The embedded engine accepts the block and ignores it.
with db.timeout(300):
report = db.query("SELECT * FROM order").execute()Connection state
.status and .is_connected
On a WebSocket connection, status is one of "disconnected", "connecting", "reconnecting" and "connected". is_connected is True when status is "connected". Both are properties. HTTP and embedded connections do not have them.
if db.status == "reconnecting":
print("Waiting for the server") .subscribe()
Call a function each time a WebSocket connection changes state.
db.subscribe(event, listener)Parameter | Type | Description |
|---|---|---|
event | str | One of the events in the table below. |
listener | Callable | The function to call with the event's arguments. On an asynchronous connection it can be a coroutine function. |
Returns: a function with no arguments that removes the listener.
| Event | Arguments |
|---|---|
"connecting" | none |
"connected" | the server version, such as "4.0.0" |
"reconnecting" | none |
"disconnected" | none |
"error" | the exception, for example from a failed token renewal |
"auth" | the new Tokens, or None after a sign-out, then the session id |
"using" | the namespace, the database, then the session id |
The session id is None for the connection's own session. An exception in a listener is logged and does not stop the connection.
unsubscribe = db.subscribe("reconnecting", lambda: print("Connection lost"))
unsubscribe() .server_version
The version the server reported when the connection opened, such as "4.0.0", or None before that. A property.
.is_feature_supported()
Return whether the server offers a feature. Call it after the connection has opened, because it reads the version the server reported.
db.is_feature_supported(feature)Parameter | Type | Description |
|---|---|---|
feature | Feature | A member of Features: LIVE_QUERIES, SESSIONS, API, REFRESH_TOKENS, TRANSACTIONS, IMPORT_FAILURE_REPORTINGor QUERY_STREAMING. |
Returns: bool
from surrealdb import Features
if db.is_feature_supported(Features.SESSIONS):
session = db.new_session()A method that needs a feature the server does not offer raises UnavailableFeatureError before it sends anything.
.wire_format
The CBOR format the connection uses: "cbor.2" with SurrealDB 4.0 and later, "cbor" with earlier servers. A property. An HTTP connection reads "cbor" until the first reply arrives.
.namespace, .database and .token
On a WebSocket connection, the namespace and database that its own session uses, and the access token it is signed in with. All three are properties.
Authentication methods
See Authentication for the sign-in levels and the auth option.
.signup()
Sign up a record user through a record access method, and sign the connection in as that user.
db.signup(vars)Parameter | Type | Description |
|---|---|---|
vars | dict[str, Value] | namespace, database, access, and the variablesthat the access method's SIGNUPclause reads. |
Returns: Tokens
tokens = db.signup({
"namespace": "surrealdb",
"database": "docs",
"access": "account",
"variables": {"email": "info@surrealdb.com", "pass": "hunter123"},
}) .signin()
Sign the connection in.
db.signin(vars)Parameter | Type | Description |
|---|---|---|
vars | dict[str, Value] | usernameand passwordfor a system user, with namespaceand databasefor a namespace or database user. For a record user: namespace, database, accessand variables. |
Returns: Tokens. tokens.refresh is set when the access method is defined WITH REFRESH.
tokens = db.signin({"username": "root", "password": "secret"}) .authenticate()
Sign the connection in with an access token.
db.authenticate(token)Parameter | Type | Description |
|---|---|---|
token | str | The access token, such as tokens.accessfrom an earlier sign-in. |
Returns: None
.refresh()
Exchange a refresh token for a new access token and refresh token, and sign the connection in with the new access token. The old refresh token cannot be used again. Needs SurrealDB 3.0 or later and an access method defined WITH REFRESH.
db.refresh(tokens=None)Parameter | Type | Description |
|---|---|---|
tokens | Tokens | None | The tokens to refresh. Defaults to the tokens the connection holds. |
Returns: Tokens, the new pair
.revoke()
Revoke a refresh token, so that it can never be exchanged again. The connection stays signed in with its access token until the token expires or you call invalidate(). Needs SurrealDB 3.0 or later.
db.revoke(tokens=None)Parameter | Type | Description |
|---|---|---|
tokens | Tokens | None | The tokens whose refresh token to revoke. Defaults to the tokens the connection holds. |
Returns: None
.invalidate()
Sign the connection out. Later requests run without authentication.
db.invalidate()Returns: None
.reset()
Return the session to how it started, with no namespace, database, variables or authentication. Needs SurrealDB 3.0 or later.
db.reset()Returns: None
.info()
Return the record of the signed-in record user.
db.info()Returns: Value. None for a system user such as root when a namespace and database are selected, and for a record user whose table permissions do not let them select their own record. Without a namespace and database, a system user gets ValidationError.
Variables
.let() and .set()
Define a variable that the later queries of the session can read as $name. set() is another name for let().
db.let(key, value)Parameter | Type | Description |
|---|---|---|
key | str | The name of the variable, without the $. |
value | Value | The value of the variable. |
Returns: None
db.let("min_age", 18)
adults = db.query("SELECT * FROM person WHERE age >= $min_age").first()A variable passed to query() with the same name takes the place of the let() value for that query.
.unset()
Remove a variable that let() defined.
db.unset(key)Returns: None
Query methods
See Executing queries for longer examples.
.query()
Build a SurrealQL query. Nothing is sent until you run the builder.
db.query(query, vars=None)Parameter | Type | Description |
|---|---|---|
query | str | One or more SurrealQL statements. |
vars | dict[str, Value] | None | Variables for the query, read as $name. The SDK sends them as values, never as query text. |
Returns: a query builder. Run it with one of these:
| Method | Returns |
|---|---|
.execute() | list[Value], one entry for each statement, also for one statement |
.first() | The result of the first statement, or None when the query has no statements |
.into(cls) | The statement results mapped in order onto the fields of cls |
.into(cls, rows=True) | list[cls], each record of the one statement mapped onto cls |
.rows(), .statements(), .stream() | The results as they arrive: see Streaming results |
On an asynchronous connection, await db.query(...) is the same as await db.query(...).execute().
db.query("RETURN 1; RETURN 2").execute()[1, 2]people = db.query(
"SELECT * FROM person WHERE age > $age",
{"age": 18},
).first() A SELECT without ONLY returns a list of records even when it names one record, so its result has two levels of lists: one for the statements and one for the records. .first() removes the outer one, and ONLY removes the inner one on the server.
.query_raw()
Run SurrealQL and return the raw response, with the status, time and result of each statement. A statement that fails is reported in the response, not raised.
db.query_raw(query, vars=None)Returns: dict[str, Any]. Its "result" key holds one entry for each statement, each with "status" ("OK" or "ERR"), "time" and "result".
raw = db.query_raw("RETURN 1; THROW 'stop'")
for statement in raw["result"]:
print(statement["status"], statement["result"])OK 1
ERR An error occurred: stop .batch()
Collect statements to send as one transaction in one request. All of them are applied, or none. Because nothing stays open on the server between requests, a batch works over HTTP, against SurrealDB 2.x, and in sessions. A transaction object has no batch(), because its statements already run in one transaction.
db.batch().query(query, vars=None).execute()Returns: a batch. .query() adds statements and returns the batch. .execute() sends them and returns one result for each statement, or raises the error of the statement that failed.
results = (
db.batch()
.query("UPDATE account:alice SET balance -= $amount", {"amount": 10})
.query("UPDATE account:bob SET balance += $amount")
.execute()
)The statements share their variables, so a name bound twice must have the same value. Only the last statement can be a RETURN, and a statement that begins, commits or cancels a transaction is refused with ValueError.
.run()
Call a function, such as a function defined with DEFINE FUNCTION or a built-in function.
db.run(name, args=None, version=None)Parameter | Type | Description |
|---|---|---|
name | str | The name of the function, such as "fn::double"or "string::uppercase". |
args | list[Value] | None | The arguments, in order. |
version | str | None | The version of the function to call. |
Returns: Value, the result of the function
db.run("string::uppercase", ["surrealdb"])'SURREALDB' .api()
Call an endpoint defined with DEFINE API. The SDK sends the call as a query, so it also works in sessions and transactions. Needs SurrealDB 3.0 or later.
db.api(path, *, method="get", body=None, headers=None, query=None)Parameter | Type | Description |
|---|---|---|
path | str | The path of the endpoint, starting with /. |
method | str | The HTTP method. Defaults to "get". |
body | Value | The request body. |
headers | Mapping[str, str] | None | Request headers. |
query | Mapping[str, str] | None | Query-string parameters. |
Returns: ApiResponse, with status, body, headers, and ok, which is True for a 2xx status
db.query("""
DEFINE API OVERWRITE "/greet" FOR get THEN {
{ status: 200, body: { hello: "world" } }
};
""").execute()
response = db.api("/greet")
print(response.status, response.body)200 {'hello': 'world'} .gql()
Run an ISO GQL query. Needs a server that offers GQL, such as SurrealDB 4.0.
db.gql(query, vars=None)Returns: list[Value], one result for each statement. Raises the error of the first statement that failed.
db.create(RecordID("person", "tobie"), {"name": "Tobie"})
db.gql("MATCH (p:person) RETURN p.name")[[{'p.name': 'Tobie'}]] .graphql()
Run a GraphQL query. The database must have GraphQL turned on, for example with DEFINE CONFIG GRAPHQL AUTO.
db.graphql(query, variables=None, operation_name=None)Returns: dict[str, Value], the data and errors that the server returned
CRUD methods
The CRUD methods take a target, which decides what they work on:
| Target | Meaning | A read returns |
|---|---|---|
RecordID("person", "tobie") | One record | The record, or None |
StringRecordId("person:tobie") | One record, written as SurrealQL text for the server to parse | The record, or None |
RecordID("person", Range(...)) | Every record in a range of ids | A list |
Table("person") or "person" | Every record in the table | A list |
A plain string is always a table name, also when it holds a colon. db.select("person:tobie") reads a table that is named person:tobie, and db.create("person:tobie", data) creates a record in that table. Use RecordID or StringRecordId to name a record.
Each method returns a CRUD builder. On a blocking connection, a write that you give its data runs at once and returns the result. select(), delete(), and a write without data return the builder, which you run with .execute(), with a data clause such as .merge(), or by iterating it. On an asynchronous connection, await runs every builder.
| Data clause | SurrealQL |
|---|---|
.content(data) | CONTENT, the whole content. create(target, data) and update(target, data) use it. |
.replace(data) | REPLACE |
.merge(data) | MERGE, which keeps the fields that data does not name |
.patch(operations) | PATCH, with a list of JSON Patch operations |
A builder also takes modifiers that become clauses of the statement: .where(condition, variables) on select, update, upsert and delete; .fetch(*paths), .limit(n), .start(n) and .version(at) on select; .output(mode) on the writes and insert; and .timeout(duration) on all of them. See Data manipulation.
Every CRUD method except relate() takes into=Model as a keyword argument. It maps each returned record onto a dataclass, a pydantic model, or any class that takes the fields as keyword arguments.
.select()
Read records.
db.select(record, *, fields=None, into=None)Parameter | Type | Description |
|---|---|---|
record | RecordID | StringRecordId | Table | str | The record or table to read. |
fields | Sequence[str] | None | The fields to return, such as ["name", "address.city"]. idis returned only when you name it. |
into | type | None | A class to map each record onto. |
Returns: a builder. Run, it gives the record or None for a record target, and a list for a table or a range.
tobie = db.select(RecordID("person", "tobie")).execute()
adults = db.select(Table("person")).where("age >= 18").limit(10).execute()
for person in db.select(Table("person")):
print(person["name"]) .create()
Create a record. A table target gives the record a random id.
db.create(record, data=..., *, into=None)Parameter | Type | Description |
|---|---|---|
record | RecordID | StringRecordId | Table | str | The record to create, or the table to create it in. |
data | Value | The content of the record. Without it, a blocking connection returns a builder. |
into | type | None | A class to map the record onto. |
Returns: the created record, as a dict
db.create(RecordID("person", "tobie"), {"name": "Tobie", "age": 35}){
'age': 35,
'id': RecordID(table_name=person, record_id='tobie'),
'name': 'Tobie',
} .update()
Update records. With data, the data becomes the whole content of each record, and fields that it does not name are removed. Use .merge() to keep them.
db.update(record, data=..., *, into=None)Returns: the updated record, or None when it does not exist, for a record target, and a list for a table
db.update(RecordID("person", "tobie"), {"name": "Tobie", "age": 36}) .upsert()
Update a record, or create it when it does not exist.
db.upsert(record, data=..., *, into=None)Returns: the record for a record target, and a list for a table
db.upsert(RecordID("person", "jaime"), {"name": "Jaime"}) .merge() clause
Chain .merge(data) on update(), upsert() or create() to send MERGE. The fields that data names are changed, and the other fields stay.
db.update(RecordID("person", "tobie")).merge({"vip": True}) .patch() clause
Chain .patch(operations) on update(), upsert() or create() to apply JSON Patch operations.
db.update(RecordID("person", "tobie")).patch([
{"op": "replace", "path": "/age", "value": 37},
]) .delete()
Delete records.
db.delete(record, *, into=None)Returns: a builder. Run, it gives the deleted record, or None when nothing was deleted, for a record target, and a list for a table.
db.delete(RecordID("person", "jaime")).execute() .insert()
Insert one or more records into a table.
db.insert(table, data=..., *, into=None, relation=False)Parameter | Type | Description |
|---|---|---|
table | Table | str | The table. A plain string must be a simple name, such as person. Use Table("my-table")for other names. |
data | dict | list[dict] | One record or a list of records. |
into | type | None | A class to map each record onto. |
relation | bool | Insert relations with INSERT RELATION. Defaults to False. |
Returns: list[dict], the inserted records, also for one record
db.insert(Table("person"), [{"name": "Dan"}, {"name": "Eve"}])Inserting relations
Pass relation=True, or chain .relation() on the builder, to insert relations. Each record needs in and out fields.
db.insert(Table("likes"), {
"in": RecordID("person", "tobie"),
"out": RecordID("post", 1),
}, relation=True) .relate()
Relate records through an edge table: RELATE from_->edge->to.
db.relate(from_, edge, to, data=...)Parameter | Type | Description |
|---|---|---|
from_ | RecordID | StringRecordId | list | The record the edge starts at, or a list of records. A plain string raises TypeError. |
edge | Table | str | RecordID | The edge table, or a RecordIDfor an edge with a chosen id. |
to | RecordID | StringRecordId | list | The record the edge ends at, or a list of records. With lists, every pair is related. |
data | Value | The content of the edge. Without it, a blocking connection returns a builder that takes .content(), .output()and .timeout(). |
Returns: the edge record, or a list of edges for lists of records
db.relate(
RecordID("person", "jaime"),
Table("likes"),
RecordID("post", 1),
{"at": "2026-11-04"},
)Live queries
Live queries need a WebSocket connection. On HTTP and embedded connections, these methods raise UnsupportedFeatureError. See Live queries.
.live()
Start a live query on a table.
db.live(table, diff=False)Parameter | Type | Description |
|---|---|---|
table | Table | str | The table to watch. |
diff | bool | Send JSON Patch operations in place of the whole record. Defaults to False. |
Returns: a LiveSubscription, or an AsyncLiveSubscription on an asynchronous connection. It is also the UUID of the live query.
with db.live("person") as people:
for change in people:
print(change["action"], change["result"])On an asynchronous connection, write async with await db.live("person") as people: and async for change in people:. Leaving the block kills the live query.
.live_of()
Attach to a live query that was started some other way, such as with LIVE SELECT through query(). A reconnect does not restart it, because the connection does not know its definition. This method is not awaited.
db.live_of(live_id)Returns: a LiveSubscription
live_id = db.query("LIVE SELECT * FROM person WHERE age > 18").first()
adults = db.live_of(live_id) .subscribe_live()
Iterate the notifications of a live query by its id. Iterating a subscription gives the same notifications.
db.subscribe_live(query_uuid)Returns: a generator of notifications. On an asynchronous connection, await the call to get an asynchronous generator: async for change in await db.subscribe_live(live_id):. Each notification is a dict with action ("CREATE", "UPDATE" or "DELETE"), result (the record), record (its RecordID) and id (the live query id).
.kill()
Stop a live query. Iteration over its subscription ends.
db.kill(query_uuid)Returns: None
Sessions
Sessions need a WebSocket connection and SurrealDB 3.0 or later. Each session has its own namespace, database, variables and authentication. See Multiple sessions.
.new_session()
Start a new session. It is signed in as the connection's user, and has no namespace or database.
db.new_session()Returns: a BlockingSurrealSession, or an AsyncSurrealSession on an asynchronous connection
session = db.new_session()
session.use("surrealdb", "staging") .fork_session()
Start a new session as a copy of another, with its namespace, database, variables and access token. The copy does not get the refresh token.
db.fork_session(session_id=None)Returns: a session. Defaults to a copy of the connection's own session.
.sessions()
Return the ids of the sessions that this connection has on the server, without its own session.
db.sessions()Returns: list[UUID]
.attach()
Create a session on the server and return its id, for use with the session_id= keyword that the connection methods take. new_session() does this and returns a session object.
db.attach()Returns: UUID
.detach()
Remove a session from the server.
db.detach(session_id)Returns: None
Transactions
Client-side transactions need a WebSocket connection and SurrealDB 3.0 or later. Over HTTP or against SurrealDB 2.x, use batch(). See Transactions.
.begin_transaction()
Begin a transaction on the connection's own session, or on another session.
db.begin_transaction(session_id=None)Returns: a BlockingSurrealTransaction, or an AsyncSurrealTransaction on an asynchronous connection
A transaction is a context manager that commits when the block finishes and cancels when the block raises an exception:
with db.begin_transaction() as txn:
txn.update(RecordID("account", "alice")).merge({"balance": 90})
txn.update(RecordID("account", "bob")).merge({"balance": 60})On an asynchronous connection, write async with await db.begin_transaction() as txn:.
.begin()
Begin a transaction and return its id, for use with the txn_id= keyword that the connection methods take. begin_transaction() does this and returns a transaction object.
db.begin(session_id=None)Returns: UUID
.commit()
Apply the changes of a transaction that begin() started.
db.commit(txn_id, session_id=None)Returns: None
.cancel()
Discard the changes of a transaction that begin() started.
db.cancel(txn_id, session_id=None)Returns: None
Import and export
These methods use the server's /export and /import endpoints, with the connection's token, namespace and database. They are not available on an embedded connection. See Import and export.
.export()
Export the selected database as SurrealQL.
db.export(options=None)Parameter | Type | Description |
|---|---|---|
options | ExportOptions | None | What the export includes. Without it, the server's default. SurrealDB 2.0 accepts no options, so the call raises UnsupportedFeatureErrorthere. |
Returns: str
from surrealdb import ExportOptions
schema = db.export(ExportOptions(records=False)) .export_to()
Export the selected database into a file or a binary file object, writing the export as it arrives. A file is replaced only when the whole export has arrived.
db.export_to(target, options=None)Returns: None
db.export_to("backup.surql") .import_()
Import SurrealQL into the selected database. A statement that fails does not stop the others.
db.import_(data)Parameter | Type | Description |
|---|---|---|
data | str | bytes | PathLike | The SurrealQL as stror bytes, or the path of a file as a pathlib.Path. A stris always SurrealQL, and a strthat names a file raises ValueError. |
Returns: None. Raises ImportFailedError, with each failure in failures, when any statement failed.
from pathlib import Path
db.import_(Path("backup.surql"))Files
The files property holds helpers that read and write files in a bucket, such as db.files.put(file, content) and db.files.get(file). Sessions and transactions have it too. See Files.
Context manager
A connection is a context manager. Entering the block connects, and leaving it closes the connection, also when the block raises an exception.
from surrealdb import Surreal
with Surreal("ws://localhost:8000") as db:
db.signin({"username": "root", "password": "secret"})
db.use("surrealdb", "docs")
people = db.select("person").execute()Availability by connection type
| Feature | WebSocket | HTTP | Embedded |
|---|---|---|---|
Queries, CRUD, relate(), run(), batch() | Yes | Yes | Yes |
api() | Yes | Yes | Yes |
gql(), graphql() | Yes | Yes | No |
| Live queries | Yes | No | No |
| Sessions | Yes | No | No |
| Client-side transactions | Yes | No | No |
| Streaming results | Yes, from SurrealDB 3.3 | No, results are buffered | No, results are buffered |
Import and export, health() | Yes | Yes | No |
| Reconnection, keepalive pings | Yes | Not needed | Not needed |
status, subscribe() | Yes | No | No |
| Factory options | All | timeout, version_check, auth, renew_access | None |
A method that a connection type does not support raises UnsupportedFeatureError.
See also
SurrealSession for the session methods
SurrealTransaction for the transaction methods
Builders for the CRUD, insert and query builders
LiveSubscription for live query subscriptions
Python types for
Value,Tokensand the option classesErrors for the error classes
Migrating to Python SDK 3.x for the changes from version 2