Skip to content

Commit fb52f76

Browse files
committed
feat: add open-existing-db example to address issue #20
Adds a new example that demonstrates ObjectBox transparently opens an existing database when Store(directory=...) points to a directory that already contains a data.mdb file. No special API is required. The example covers a common question from users: how to open a database that was created by a previous run or by another ObjectBox SDK. Also updates example/README.md to list the new example. Closes #20
1 parent 9b38d97 commit fb52f76

2 files changed

Lines changed: 138 additions & 0 deletions

File tree

example/README.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ The following examples are available from this directory:
1313

1414
- `tasks`: CRUD Example (see below for details)
1515
- `vectorsearch-cities`: VectorSearch Example (see below for details)
16+
- `open-existing-db`: Opening an Existing Database Example (see below for details)
1617
- `ollama`: LLM + VectorSearch Embeddings Script Example (See [ollama/README.md](./ollama/README.md) for details)
1718

1819

@@ -94,3 +95,34 @@ ID Name Latitude Longitude Score
9495
164 San Salvador 13.69 -89.22 1261.12
9596
67 Havana 23.11 -82.37 1317.73
9697
```
98+
99+
## Example: Opening an Existing Database
100+
101+
This example shows that `Store(directory="...")` **opens an existing database transparently** — no special API is required. If the directory already contains an ObjectBox database (`data.mdb`), it is opened; otherwise a new one is created.
102+
103+
This is useful when:
104+
- You want to read a database written by a previous run of your program
105+
- You receive a database file created by another ObjectBox SDK (e.g. Android/Java, Swift, Dart) and want to read it with Python using the same entity model
106+
107+
```
108+
cd open-existing-db
109+
110+
# Step 1: write sample data (creates the database)
111+
$ python main.py write
112+
Wrote 3 notes to 'notes-db'.
113+
Run 'python main.py read' to open the same database and list them.
114+
115+
# Step 2: open the SAME database and read it back
116+
$ python main.py read
117+
Found 3 note(s) in 'notes-db':
118+
119+
ID Priority Title Body
120+
----------------------------------------------------------------------
121+
1 1 Buy groceries Milk, eggs, bread
122+
2 2 Read ObjectBox docs https://docs.objectbox.io
123+
3 3 Open-source contribution Submit a pull request today!
124+
125+
# Reset: delete the database so you can start fresh
126+
$ python main.py reset
127+
Removed 'notes-db'. Run 'python main.py write' to start fresh.
128+
```

example/open-existing-db/main.py

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
"""Example: Opening an Existing ObjectBox Database
2+
3+
This example demonstrates that ObjectBox transparently opens an existing
4+
database when the given directory already contains one (data.mdb), and
5+
creates a new one if it doesn't. This means any program that uses the
6+
same entity model can read a database written by another program or even
7+
another ObjectBox SDK (e.g. Android/Java, Swift, Dart), as long as the
8+
model is compatible.
9+
10+
Usage:
11+
# Step 1 – write some data (creates the database on disk)
12+
python main.py write
13+
14+
# Step 2 – open the same database and read the data back
15+
python main.py read
16+
17+
# Reset: remove the database directory and start fresh
18+
python main.py reset
19+
"""
20+
21+
import os
22+
import sys
23+
import shutil
24+
25+
from objectbox import Entity, Id, Int32, String, Store
26+
27+
DB_DIRECTORY = "notes-db"
28+
29+
30+
@Entity()
31+
class Note:
32+
id = Id()
33+
title = String()
34+
body = String()
35+
priority = Int32()
36+
37+
38+
def open_store() -> Store:
39+
"""Open (or create) the ObjectBox store in DB_DIRECTORY.
40+
41+
ObjectBox will:
42+
- Create the directory and a brand-new database if it does not exist yet.
43+
- Open the existing database transparently if it already exists.
44+
"""
45+
return Store(directory=DB_DIRECTORY)
46+
47+
48+
def write_data():
49+
"""Insert sample notes into the database."""
50+
store = open_store()
51+
box = store.box(Note)
52+
53+
notes = [
54+
Note(title="Buy groceries", body="Milk, eggs, bread", priority=1),
55+
Note(title="Read ObjectBox docs", body="https://docs.objectbox.io", priority=2),
56+
Note(title="Open-source contribution", body="Submit a pull request today!", priority=3),
57+
]
58+
59+
for note in notes:
60+
box.put(note)
61+
62+
print(f"Wrote {len(notes)} notes to '{DB_DIRECTORY}'.")
63+
print("Run 'python main.py read' to open the same database and list them.")
64+
store.close()
65+
66+
67+
def read_data():
68+
"""Open the existing database and print all stored notes."""
69+
if not os.path.isdir(DB_DIRECTORY):
70+
print(f"Database directory '{DB_DIRECTORY}' not found.")
71+
print("Run 'python main.py write' first to create and populate it.")
72+
sys.exit(1)
73+
74+
store = open_store()
75+
box = store.box(Note)
76+
notes = box.get_all()
77+
78+
if not notes:
79+
print("No notes found in the database.")
80+
else:
81+
print(f"Found {len(notes)} note(s) in '{DB_DIRECTORY}':\n")
82+
print(f"{'ID':>3} {'Priority':>8} {'Title':<30} Body")
83+
print("-" * 70)
84+
for note in notes:
85+
print(f"{note.id:>3} {note.priority:>8} {note.title:<30} {note.body}")
86+
87+
store.close()
88+
89+
90+
def reset_data():
91+
"""Delete the database directory so the example can be run from scratch."""
92+
if os.path.isdir(DB_DIRECTORY):
93+
shutil.rmtree(DB_DIRECTORY)
94+
print(f"Removed '{DB_DIRECTORY}'. Run 'python main.py write' to start fresh.")
95+
else:
96+
print(f"Nothing to reset – '{DB_DIRECTORY}' does not exist.")
97+
98+
99+
if __name__ == "__main__":
100+
commands = {"write": write_data, "read": read_data, "reset": reset_data}
101+
102+
if len(sys.argv) != 2 or sys.argv[1] not in commands:
103+
print("Usage: python main.py <write|read|reset>")
104+
sys.exit(1)
105+
106+
commands[sys.argv[1]]()

0 commit comments

Comments
 (0)