Skip to content

Commit

Permalink
Update readme and examples (#125)
Browse files Browse the repository at this point in the history
  • Loading branch information
remade authored Dec 2, 2024
1 parent d5bcfeb commit 3d7d6a7
Show file tree
Hide file tree
Showing 24 changed files with 517 additions and 157 deletions.
78 changes: 63 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,49 @@ await db.connect()
await db.use("namespace", "database_name")
```

### Example Usage
```python
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
Expand Down Expand Up @@ -122,14 +165,15 @@ db = SurrealDB("mem://")
db = SurrealDB("memory://")
```

## Usage Examples
## Additional Examples
### Insert and Retrieve Data
```python
from surrealdb import SurrealDB

db = SurrealDB("ws://localhost:8080")
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}
Expand All @@ -147,12 +191,18 @@ db.close()
```python
from surrealdb import AsyncSurrealDB

async with AsyncSurrealDB(url="ws://localhost:8080") as db:
query = "SELECT * FROM users WHERE age > $min_age"
variables = {"min_age": 25}
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}")

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

### Manage Authentication
Expand Down Expand Up @@ -201,15 +251,13 @@ asyncio.run(handle_notifications())
```python
from surrealdb.surrealdb import SurrealDB

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

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

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

## Contributing
Expand Down
22 changes: 22 additions & 0 deletions examples/async/basic_auth_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import asyncio

from surrealdb import AsyncSurrealDB


async def main():
async with AsyncSurrealDB(url="ws://localhost:8000") as db:
# Sign up a new user
token = await db.sign_up(username="new_user", password="secure_password")
print(f"New User Token: {token}")

# Sign in as an existing user
token = await db.sign_in(username="existing_user", password="secure_password")
print(f"Signed In Token: {token}")

# Authenticate using a token
await db.authenticate(token=token)
print("Authentication successful!")


if __name__ == '__main__':
asyncio.run(main())
57 changes: 38 additions & 19 deletions examples/basic_async_example.py → examples/async/basic_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,31 @@ async def main():
await db.sign_in("root", "root")

print("Using methods")
print("create: ", await db.create(
"person",
{
"user": "me",
"pass": "safe",
"marketing": True,
"tags": ["python", "documentation"],
},
))
print(
"create: ",
await db.create(
"person",
{
"user": "me",
"pass": "safe",
"marketing": True,
"tags": ["python", "documentation"],
},
),
)
print("read: ", await db.select("person"))
print("update: ", await db.update("person", {
"user": "you",
"pass": "very_safe",
"marketing": False,
"tags": ["Awesome"]
}))
print(
"update: ",
await db.update(
"person",
{
"user": "you",
"pass": "very_safe",
"marketing": False,
"tags": ["Awesome"],
},
),
)
print("delete: ", await db.delete("person"))

# You can also use the query method
Expand All @@ -32,24 +41,34 @@ async def main():
# In SurrealQL you can do a direct insert
# and the table will be created if it doesn't exist
print("Using justawait db.query")
print("create: ", await db.query("""
print(
"create: ",
await db.query(
"""
insert into person {
user: 'me',
pass: 'very_safe',
tags: ['python', 'documentation']
};
"""))
"""
),
)
print("read: ", await db.query("select * from person"))

print("update: ", await db.query("""
print(
"update: ",
await db.query(
"""
update person content {
user: 'you',
pass: 'more_safe',
tags: ['awesome']
};
"""))
"""
),
)
print("delete: ", await db.query("delete person"))


Expand Down
25 changes: 25 additions & 0 deletions examples/async/basic_insert_and_retrieve.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import asyncio

from surrealdb import AsyncSurrealDB


async def main():
db = AsyncSurrealDB("ws://localhost:8000")
await db.connect()
await db.use("example_ns", "example_db")
await db.sign_in("root", "root")

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

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

await db.close()


if __name__ == '__main__':
asyncio.run(main())
17 changes: 17 additions & 0 deletions examples/async/basic_query_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import asyncio
from surrealdb import AsyncSurrealDB


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())
15 changes: 15 additions & 0 deletions examples/async/basic_upsert_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import asyncio

from surrealdb import AsyncSurrealDB

async def main():
async with AsyncSurrealDB("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}")

if __name__ == '__main__':
asyncio.run(main())
50 changes: 0 additions & 50 deletions examples/basic_example.py

This file was deleted.

10 changes: 4 additions & 6 deletions examples/notebook_example.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,10 @@
"metadata": {},
"outputs": [],
"source": [
"await db.update(\"person\", {\n",
" \"user\":\"you\",\n",
" \"pass\":\"very_safe\",\n",
" \"marketing\": False,\n",
" \"tags\": [\"Awesome\"]\n",
"})"
"await db.update(\n",
" \"person\",\n",
" {\"user\": \"you\", \"pass\": \"very_safe\", \"marketing\": False, \"tags\": [\"Awesome\"]},\n",
")"
]
},
{
Expand Down
20 changes: 20 additions & 0 deletions examples/sync/basic_auth_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from surrealdb import SurrealDB


def main():
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!")


if __name__ == '__main__':
main()
Loading

0 comments on commit 3d7d6a7

Please sign in to comment.