From fb52f76de3bca93d7559d582c0c6e71b0cffacb6 Mon Sep 17 00:00:00 2001 From: Elizio Martins Cezarino <78484991+ElizioMartins@users.noreply.github.com> Date: Tue, 19 May 2026 22:27:43 -0300 Subject: [PATCH] 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 --- example/README.md | 32 ++++++++++ example/open-existing-db/main.py | 106 +++++++++++++++++++++++++++++++ 2 files changed, 138 insertions(+) create mode 100644 example/open-existing-db/main.py diff --git a/example/README.md b/example/README.md index f747f9f..e351fbf 100644 --- a/example/README.md +++ b/example/README.md @@ -13,6 +13,7 @@ The following examples are available from this directory: - `tasks`: CRUD Example (see below for details) - `vectorsearch-cities`: VectorSearch Example (see below for details) +- `open-existing-db`: Opening an Existing Database Example (see below for details) - `ollama`: LLM + VectorSearch Embeddings Script Example (See [ollama/README.md](./ollama/README.md) for details) @@ -94,3 +95,34 @@ ID Name Latitude Longitude Score 164 San Salvador 13.69 -89.22 1261.12 67 Havana 23.11 -82.37 1317.73 ``` + +## Example: Opening an Existing Database + +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. + +This is useful when: +- You want to read a database written by a previous run of your program +- 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 + +``` +cd open-existing-db + +# Step 1: write sample data (creates the database) +$ python main.py write +Wrote 3 notes to 'notes-db'. +Run 'python main.py read' to open the same database and list them. + +# Step 2: open the SAME database and read it back +$ python main.py read +Found 3 note(s) in 'notes-db': + + ID Priority Title Body +---------------------------------------------------------------------- + 1 1 Buy groceries Milk, eggs, bread + 2 2 Read ObjectBox docs https://docs.objectbox.io + 3 3 Open-source contribution Submit a pull request today! + +# Reset: delete the database so you can start fresh +$ python main.py reset +Removed 'notes-db'. Run 'python main.py write' to start fresh. +``` diff --git a/example/open-existing-db/main.py b/example/open-existing-db/main.py new file mode 100644 index 0000000..48b4842 --- /dev/null +++ b/example/open-existing-db/main.py @@ -0,0 +1,106 @@ +"""Example: Opening an Existing ObjectBox Database + +This example demonstrates that ObjectBox transparently opens an existing +database when the given directory already contains one (data.mdb), and +creates a new one if it doesn't. This means any program that uses the +same entity model can read a database written by another program or even +another ObjectBox SDK (e.g. Android/Java, Swift, Dart), as long as the +model is compatible. + +Usage: + # Step 1 – write some data (creates the database on disk) + python main.py write + + # Step 2 – open the same database and read the data back + python main.py read + + # Reset: remove the database directory and start fresh + python main.py reset +""" + +import os +import sys +import shutil + +from objectbox import Entity, Id, Int32, String, Store + +DB_DIRECTORY = "notes-db" + + +@Entity() +class Note: + id = Id() + title = String() + body = String() + priority = Int32() + + +def open_store() -> Store: + """Open (or create) the ObjectBox store in DB_DIRECTORY. + + ObjectBox will: + - Create the directory and a brand-new database if it does not exist yet. + - Open the existing database transparently if it already exists. + """ + return Store(directory=DB_DIRECTORY) + + +def write_data(): + """Insert sample notes into the database.""" + store = open_store() + box = store.box(Note) + + notes = [ + Note(title="Buy groceries", body="Milk, eggs, bread", priority=1), + Note(title="Read ObjectBox docs", body="https://docs.objectbox.io", priority=2), + Note(title="Open-source contribution", body="Submit a pull request today!", priority=3), + ] + + for note in notes: + box.put(note) + + print(f"Wrote {len(notes)} notes to '{DB_DIRECTORY}'.") + print("Run 'python main.py read' to open the same database and list them.") + store.close() + + +def read_data(): + """Open the existing database and print all stored notes.""" + if not os.path.isdir(DB_DIRECTORY): + print(f"Database directory '{DB_DIRECTORY}' not found.") + print("Run 'python main.py write' first to create and populate it.") + sys.exit(1) + + store = open_store() + box = store.box(Note) + notes = box.get_all() + + if not notes: + print("No notes found in the database.") + else: + print(f"Found {len(notes)} note(s) in '{DB_DIRECTORY}':\n") + print(f"{'ID':>3} {'Priority':>8} {'Title':<30} Body") + print("-" * 70) + for note in notes: + print(f"{note.id:>3} {note.priority:>8} {note.title:<30} {note.body}") + + store.close() + + +def reset_data(): + """Delete the database directory so the example can be run from scratch.""" + if os.path.isdir(DB_DIRECTORY): + shutil.rmtree(DB_DIRECTORY) + print(f"Removed '{DB_DIRECTORY}'. Run 'python main.py write' to start fresh.") + else: + print(f"Nothing to reset – '{DB_DIRECTORY}' does not exist.") + + +if __name__ == "__main__": + commands = {"write": write_data, "read": read_data, "reset": reset_data} + + if len(sys.argv) != 2 or sys.argv[1] not in commands: + print("Usage: python main.py ") + sys.exit(1) + + commands[sys.argv[1]]()