1+ ---
2+ description: This rule provides information using SurrealDB embedded in python
3+ alwaysApply: false
4+ ---
5+
6+ The data can be stored:
7+
8+ - in-memory with `Surreal("mem://")` and `AsyncSurreal("mem://")`
9+ - persistence with `Surreal(f"file://{db_path}")` and `AsyncSurreal(f"file://{db_path}")`
10+
11+ ## Example:
12+
13+ ```python
14+ """File-based persistent embedded SurrealDB example."""
15+
16+ import asyncio
17+ import tempfile
18+ from pathlib import Path
19+
20+ from surrealdb import AsyncSurreal
21+
22+
23+ async def main() -> None:
24+ """Run persistent file-based database operations."""
25+ # Create a temporary directory for the database
26+ with tempfile.TemporaryDirectory() as tmpdir:
27+ db_path = Path(tmpdir) / "mydb"
28+ db_url = f"file://{db_path}"
29+
30+ print(f"Using database at: {db_path}")
31+
32+ # First connection: create data
33+ print("\n=== First connection: Creating data ===")
34+ async with AsyncSurreal(db_url) as db:
35+ await db.use("test", "test")
36+
37+ # Create some records
38+ await db.create(
39+ "company", {"name": "Acme Corp", "founded": 2020, "employees": 100}
40+ )
41+
42+ await db.create(
43+ "company", {"name": "TechStart Inc", "founded": 2021, "employees": 50}
44+ )
45+
46+ companies = await db.select("company")
47+ print(f"Created companies: {companies}")
48+
49+ # Second connection: verify persistence
50+ print("\n=== Second connection: Verifying persistence ===")
51+ async with AsyncSurreal(db_url) as db:
52+ await db.use("test", "test")
53+
54+ # Query the persisted data
55+ companies = await db.select("company")
56+ print(f"Loaded companies from disk: {companies}")
57+
58+ # Update a company
59+ updated = await db.query("""
60+ UPDATE company SET employees = employees + 10 WHERE name = "Acme Corp"
61+ """)
62+ print(f"Updated company: {updated}")
63+
64+ # Verify the update
65+ all_companies = await db.select("company")
66+ print(f"All companies after update: {all_companies}")
67+
68+ print("\n=== Database file will be cleaned up automatically ===")
69+
70+
71+ if __name__ == "__main__":
72+ asyncio.run(main())
73+ ```
0 commit comments