Skip to content

API Reference

/

Core

Surreal

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

Open a blocking connection.

Syntax
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.

Open an asynchronous connection. It takes the same arguments as Surreal(), and auth can also be a coroutine function.

Syntax
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: ...

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

urlstr

The address to connect to. The scheme chooses the connection class: see

URL schemes

.

streamingbool

Let queries over a WebSocket arrive as a stream from SurrealDB 3.3 and later. Defaults to

True

.

False

puts

query()

back on the buffered path, and an explicit

.rows()

still streams. See

Streaming results

.

ping_intervalfloat | None

Seconds between keepalive pings on an idle WebSocket. Defaults to

30

.

None

sends no pings.

ping_timeoutfloat | None

Seconds to wait for the answer to a ping before the connection counts as lost. Defaults to

10

.

None

waits indefinitely.

timeoutfloat | None

Seconds to wait for the reply to each request. Defaults to

30

.

None

waits indefinitely.

timeout()

changes it for a block of code.

version_checkbool

Refuse a server outside the supported versions, SurrealDB 2.x, 3.x and 4.x, with

UnsupportedVersionError

. Defaults to

True

.

reconnectbool | ReconnectOptions

Open a new WebSocket when the socket drops, and restore the namespace, database, variables, authentication, sessions and live queries. Defaults to

True

. Pass

ReconnectOptions

to change the attempts and the delay between them, or

False

to turn it off.

authdict | 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_accessbool

Renew the access token shortly before it expires, with the refresh token or else with

auth

. Defaults to

True

.

Options
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.

SchemeConnectionClass
ws://, wss://WebSocket, with every featureBlockingWsSurrealConnection, AsyncWsSurrealConnection
http://, https://HTTP, one request at a timeBlockingHttpSurrealConnection, AsyncHttpSurrealConnection
mem://, memory://, memoryEmbedded, in memoryBlockingEmbeddedSurrealConnection, AsyncEmbeddedSurrealConnection
file://, surrealkv://Embedded, on diskas above
surrealkv+versioned://Embedded, on disk, with versioned recordsas 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.

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.

Syntax
db.connect(url=None)

Parameter

Type

Description

urlstr | 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 the connection and release its resources. Calling it on a closed connection does nothing.

Syntax
db.close()

Returns: None

Select the namespace and database for the requests that follow.

Syntax
db.use(namespace=None, database=None)

Parameter

Type

Description

namespacestr | Null | None

The namespace.

None

keeps the current one and

Null

clears it.

databasestr | Null | None

The database.

None

keeps the current one and

Null

clears it.

Returns: None

db.use("surrealdb", "docs")
db.use(database="staging")

Return the version of the server, or of the engine on an embedded connection.

Syntax
db.version()

Returns: str, such as "surrealdb-4.0.0"

Ask the server's /health endpoint whether the server is healthy. A WebSocket connection asks over HTTP. Not available on an embedded connection.

Syntax
db.health()

Returns: None. Raises ConnectionUnavailableError when the server is unhealthy or cannot be reached.

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.

Syntax
with db.timeout(seconds):
    ...

Parameter

Type

Description

secondsfloat | None

Seconds to wait for each reply.

None

waits 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()

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")

Call a function each time a WebSocket connection changes state.

Syntax
db.subscribe(event, listener)

Parameter

Type

Description

eventstr

One of the events in the table below.

listenerCallable

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.

EventArguments
"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()

The version the server reported when the connection opened, such as "4.0.0", or None before that. A property.

Return whether the server offers a feature. Call it after the connection has opened, because it reads the version the server reported.

Syntax
db.is_feature_supported(feature)

Parameter

Type

Description

featureFeature

A member of

Features

:

LIVE_QUERIES

,

SESSIONS

,

API

,

REFRESH_TOKENS

,

TRANSACTIONS

,

IMPORT_FAILURE_REPORTING

or

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.

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.

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.

See Authentication for the sign-in levels and the auth option.

Sign up a record user through a record access method, and sign the connection in as that user.

Syntax
db.signup(vars)

Parameter

Type

Description

varsdict[str, Value]namespace

,

database

,

access

, and the

variables

that the access method's

SIGNUP

clause reads.

Returns: Tokens

tokens = db.signup({
    "namespace": "surrealdb",
    "database": "docs",
    "access": "account",
    "variables": {"email": "info@surrealdb.com", "pass": "hunter123"},
})

Sign the connection in.

Syntax
db.signin(vars)

Parameter

Type

Description

varsdict[str, Value]username

and

password

for a system user, with

namespace

and

database

for a namespace or database user. For a record user:

namespace

,

database

,

access

and

variables

.

Returns: Tokens. tokens.refresh is set when the access method is defined WITH REFRESH.

tokens = db.signin({"username": "root", "password": "secret"})

Sign the connection in with an access token.

Syntax
db.authenticate(token)

Parameter

Type

Description

tokenstr

The access token, such as

tokens.access

from an earlier sign-in.

Returns: None

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.

Syntax
db.refresh(tokens=None)

Parameter

Type

Description

tokensTokens | None

The tokens to refresh. Defaults to the tokens the connection holds.

Returns: Tokens, the new pair

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.

Syntax
db.revoke(tokens=None)

Parameter

Type

Description

tokensTokens | None

The tokens whose refresh token to revoke. Defaults to the tokens the connection holds.

Returns: None

Sign the connection out. Later requests run without authentication.

Syntax
db.invalidate()

Returns: None

Return the session to how it started, with no namespace, database, variables or authentication. Needs SurrealDB 3.0 or later.

Syntax
db.reset()

Returns: None

Return the record of the signed-in record user.

Syntax
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.

Define a variable that the later queries of the session can read as $name. set() is another name for let().

Syntax
db.let(key, value)

Parameter

Type

Description

keystr

The name of the variable, without the

$

.

valueValue

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.

Remove a variable that let() defined.

Syntax
db.unset(key)

Returns: None

See Executing queries for longer examples.

Build a SurrealQL query. Nothing is sent until you run the builder.

Syntax
db.query(query, vars=None)

Parameter

Type

Description

querystr

One or more SurrealQL statements.

varsdict[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:

MethodReturns
.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()
Output
[1, 2]
people = db.query(
    "SELECT * FROM person WHERE age > $age",
    {"age": 18},
).first()
Note

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.

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.

Syntax
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"])
Output
OK 1
ERR An error occurred: stop

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.

Syntax
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.

Call a function, such as a function defined with DEFINE FUNCTION or a built-in function.

Syntax
db.run(name, args=None, version=None)

Parameter

Type

Description

namestr

The name of the function, such as

"fn::double"

or

"string::uppercase"

.

argslist[Value] | None

The arguments, in order.

versionstr | None

The version of the function to call.

Returns: Value, the result of the function

db.run("string::uppercase", ["surrealdb"])
Output
'SURREALDB'

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.

Syntax
db.api(path, *, method="get", body=None, headers=None, query=None)

Parameter

Type

Description

pathstr

The path of the endpoint, starting with

/

.

methodstr

The HTTP method. Defaults to

"get"

.

bodyValue

The request body.

headersMapping[str, str] | None

Request headers.

queryMapping[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)
Output
200 {'hello': 'world'}

Run an ISO GQL query. Needs a server that offers GQL, such as SurrealDB 4.0.

Syntax
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")
Output
[[{'p.name': 'Tobie'}]]

Run a GraphQL query. The database must have GraphQL turned on, for example with DEFINE CONFIG GRAPHQL AUTO.

Syntax
db.graphql(query, variables=None, operation_name=None)

Returns: dict[str, Value], the data and errors that the server returned

The CRUD methods take a target, which decides what they work on:

TargetMeaningA read returns
RecordID("person", "tobie")One recordThe record, or None
StringRecordId("person:tobie")One record, written as SurrealQL text for the server to parseThe record, or None
RecordID("person", Range(...))Every record in a range of idsA list
Table("person") or "person"Every record in the tableA list
Important

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 clauseSurrealQL
.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.

Read records.

Syntax
db.select(record, *, fields=None, into=None)

Parameter

Type

Description

recordRecordID | StringRecordId | Table | str

The record or table to read.

fieldsSequence[str] | None

The fields to return, such as

["name", "address.city"]

.

id

is returned only when you name it.

intotype | 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 a record. A table target gives the record a random id.

Syntax
db.create(record, data=..., *, into=None)

Parameter

Type

Description

recordRecordID | StringRecordId | Table | str

The record to create, or the table to create it in.

dataValue

The content of the record. Without it, a blocking connection returns a builder.

intotype | None

A class to map the record onto.

Returns: the created record, as a dict

db.create(RecordID("person", "tobie"), {"name": "Tobie", "age": 35})
Output
{
	'age': 35,
	'id': RecordID(table_name=person, record_id='tobie'),
	'name': 'Tobie',
}

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.

Syntax
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})

Update a record, or create it when it does not exist.

Syntax
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"})

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})

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 records.

Syntax
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 one or more records into a table.

Syntax
db.insert(table, data=..., *, into=None, relation=False)

Parameter

Type

Description

tableTable | str

The table. A plain string must be a simple name, such as

person

. Use

Table("my-table")

for other names.

datadict | list[dict]

One record or a list of records.

intotype | None

A class to map each record onto.

relationbool

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"}])

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 records through an edge table: RELATE from_->edge->to.

Syntax
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

.

edgeTable | str | RecordID

The edge table, or a

RecordID

for an edge with a chosen id.

toRecordID | StringRecordId | list

The record the edge ends at, or a list of records. With lists, every pair is related.

dataValue

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 need a WebSocket connection. On HTTP and embedded connections, these methods raise UnsupportedFeatureError. See Live queries.

Start a live query on a table.

Syntax
db.live(table, diff=False)

Parameter

Type

Description

tableTable | str

The table to watch.

diffbool

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.

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.

Syntax
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)

Iterate the notifications of a live query by its id. Iterating a subscription gives the same notifications.

Syntax
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).

Stop a live query. Iteration over its subscription ends.

Syntax
db.kill(query_uuid)

Returns: None

Sessions need a WebSocket connection and SurrealDB 3.0 or later. Each session has its own namespace, database, variables and authentication. See Multiple sessions.

Start a new session. It is signed in as the connection's user, and has no namespace or database.

Syntax
db.new_session()

Returns: a BlockingSurrealSession, or an AsyncSurrealSession on an asynchronous connection

session = db.new_session()
session.use("surrealdb", "staging")

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.

Syntax
db.fork_session(session_id=None)

Returns: a session. Defaults to a copy of the connection's own session.

Return the ids of the sessions that this connection has on the server, without its own session.

Syntax
db.sessions()

Returns: list[UUID]

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.

Syntax
db.attach()

Returns: UUID

Remove a session from the server.

Syntax
db.detach(session_id)

Returns: None

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 a transaction on the connection's own session, or on another session.

Syntax
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 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.

Syntax
db.begin(session_id=None)

Returns: UUID

Apply the changes of a transaction that begin() started.

Syntax
db.commit(txn_id, session_id=None)

Returns: None

Discard the changes of a transaction that begin() started.

Syntax
db.cancel(txn_id, session_id=None)

Returns: None

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 the selected database as SurrealQL.

Syntax
db.export(options=None)

Parameter

Type

Description

optionsExportOptions | None

What the export includes. Without it, the server's default. SurrealDB 2.0 accepts no options, so the call raises

UnsupportedFeatureError

there.

Returns: str

from surrealdb import ExportOptions

schema = db.export(ExportOptions(records=False))

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.

Syntax
db.export_to(target, options=None)

Returns: None

db.export_to("backup.surql")

Import SurrealQL into the selected database. A statement that fails does not stop the others.

Syntax
db.import_(data)

Parameter

Type

Description

datastr | bytes | PathLike

The SurrealQL as

str

or

bytes

, or the path of a file as a

pathlib.Path

. A

str

is always SurrealQL, and a

str

that 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"))

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.

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()
FeatureWebSocketHTTPEmbedded
Queries, CRUD, relate(), run(), batch()YesYesYes
api()YesYesYes
gql(), graphql()YesYesNo
Live queriesYesNoNo
SessionsYesNoNo
Client-side transactionsYesNoNo
Streaming resultsYes, from SurrealDB 3.3No, results are bufferedNo, results are buffered
Import and export, health()YesYesNo
Reconnection, keepalive pingsYesNot neededNot needed
status, subscribe()YesNoNo
Factory optionsAlltimeout, version_check, auth, renew_accessNone

A method that a connection type does not support raises UnsupportedFeatureError.

Was this page helpful?