Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/modules/ROOT/pages/how-to/agent-memory.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ for statement in [
db.command("sql", statement)
----

Every statement says `IF NOT EXISTS`, so the agent can run this at each start. If your program changes its working directory (`os.chdir`), give the database an absolute path. The unique indexes on `Memory.key` and `Entity.name` are what `UPSERT` needs. The index on `Memory.user` serves the filtered search below. `dimensions` must match the length of your embeddings.
Every statement says `IF NOT EXISTS`, so the agent can run this at each start. A relative path such as `./agent_memory` is taken from the current directory of your program at the time of the call, so give an absolute path if the agent must find the same memory wherever it is started. The unique indexes on `Memory.key` and `Entity.name` are what `UPSERT` needs. The index on `Memory.user` serves the filtered search below. `dimensions` must match the length of your embeddings.

== Store a fact, or update it by key

Expand Down
5 changes: 3 additions & 2 deletions docs/modules/ROOT/pages/how-to/databases-and-queries.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@ print("Exists after drop:", arcadedb.database_exists("./myapp"))

[source,text]
----
Created at: ./mydb
Created at: /path/to/workdir/mydb
Exists: True
DatabaseExistsError: [database_exists] A database already exists at this path: open it with `open_database(path)`, or choose another path. Failed to create database: com.arcadedb.exception.DatabaseOperationException: Database './mydb' already exists
DatabaseExistsError: [database_exists] A database already exists at this path: open it with `open_database(path)`, or choose another path. Failed to create database: com.arcadedb.exception.DatabaseOperationException: Database '/path/to/workdir/mydb' already exists
Name: mydb
Alice
Transaction active: False
Expand All @@ -67,6 +67,7 @@ Notes on the script:

* `create_database(path)` creates the directory and opens the database for reading and writing. It raises `DatabaseExistsError` (a subclass of `ArcadeDBError`, with the code `database_exists`) if the path already holds a database, as the third output line shows. The codes of all errors are on xref:how-to/errors.adoc[Errors: codes, hints and classes].
* `open_database(path)` opens an existing database. `database_exists(path)` tells the two cases apart.
* A relative path such as `./mydb` is taken from the current directory of your program (`os.getcwd()`) at the time of the call, so it follows `os.chdir`. A `DatabaseFactory` and a server (`root_path`) keep the directory that was current when you made them. `db.get_database_path()` and the error messages show the absolute path: `/path/to/workdir` in the output above stands for the directory the script ran in.
* `open_or_create_database(path)` opens the database when it exists and creates it when it does not, so a script that keeps its data in one database runs the same way the first time and every time after. See <<open-or-create>>.
* `with` closes the database when the block ends, also when an exception leaves it. On close, active transactions roll back. You can call `db.close()` yourself, inside `try`/`finally`, but the context manager is the recommended way.
* `db.drop()` deletes all files of the database. It cannot be undone.
Expand Down
4 changes: 4 additions & 0 deletions docs/modules/ROOT/pages/upgrading.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ Before, `db.run_in_transaction(fn)` and `with db.transaction():` raised `Conflic

See xref:how-to/errors.adoc#partial-commit[A block that already committed part of its work].

=== A relative path is taken from the current directory

Before, a relative database path, or a relative `root_path` of `ArcadeDBServer`, did not name one directory once your program had changed its directory with `os.chdir`, because the engine resolved a part of the path against the directory in which it had started. For example, `database_exists` could answer `False` for a database that you had just created, and a second database with the same relative path in another directory was refused as already in use. Now both packages take a relative path from the current directory at the time of the call. `db.get_database_path()` and the error messages show the absolute path, also when you passed a relative one. See xref:how-to/databases-and-queries.adoc[Databases and queries].

=== Engine 26.12.1

The engine that the 26.12.1 packages carry changes some behaviour that the other pages describe:
Expand Down
3 changes: 2 additions & 1 deletion src/arcadedb/_native/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from .. import _columnar
from .._open_or_create import open_or_create
from .._params import refuse_surplus_positionals
from .._paths import absolute_path
from ..exceptions import ArcadeDBError, _partial_commit_error
from ..transactions import TransactionContext
from ..type_conversion import bulk_row_ok, json_bulk_dumps_tagged
Expand Down Expand Up @@ -2075,7 +2076,7 @@ def __init__(self, path: str, jvm_kwargs: Optional[dict] = None):
"jvm_kwargs %s ignored: the native backend has no JVM",
sorted(jvm_kwargs),
)
self._path = os.fspath(path)
self._path = absolute_path(path)

def create(self) -> NativeDatabase:
return NativeDatabase._opened(
Expand Down
3 changes: 2 additions & 1 deletion src/arcadedb/_native/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from typing import Any, Dict, Optional

from .._paths import absolute_path
from ..exceptions import ArcadeDBError
from . import lib
from .database import NativeDatabase, _call
Expand All @@ -19,7 +20,7 @@ def __init__(
config: Optional[Dict[str, Any]] = None,
):
self._config = config or {}
self._root_path = root_path
self._root_path = absolute_path(root_path)
self._root_password = root_password
self._h = 0
self._started = False
Expand Down
31 changes: 31 additions & 0 deletions src/arcadedb/_paths.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"""A path of the caller, made absolute before the engine sees it, for both builds.

The engine resolves a part of the files of a relative path against the directory that was current when it started (Java reads
``user.dir`` once, and ``File.getAbsolutePath()`` uses it) and the rest against the current directory of the process. After
``os.chdir`` one relative path then named two directories. An absolute path has one meaning for both.
"""

from __future__ import annotations

import os
from pathlib import Path


def absolute_path(path) -> str:
"""``path`` (a ``str``, a path object, or a Java string) as an absolute ``str``, a relative one taken from ``os.getcwd()``.

An absolute path and an empty one (which the engine refuses) keep their text.
"""
if hasattr(path, "getClass"):
# the JVM build: a string that a Java call returned stays a Java object, which os.fspath does not take
path = str(path)
text = os.fspath(path)
# on Windows a path such as "\\data" names no drive, so it still depends on the current one
complete = os.path.isabs(text) and (os.name != "nt" or os.path.splitdrive(text)[0])
if not text.strip() or complete:
return text
if os.name == "nt":
# Windows resolves ".." by the text itself, and abspath knows a drive-relative path such as "D:db"
return os.path.abspath(text)
# pathlib keeps "..", which the operating system resolves after a symbolic link in front of it
return str(Path(text).absolute())
14 changes: 8 additions & 6 deletions src/arcadedb/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
from ._logging import get_logger
from ._open_or_create import open_or_create as _open_or_create
from ._params import refuse_surplus_positionals
from ._paths import absolute_path
from .callbacks import (
EventHandle,
FunctionRegistration,
Expand Down Expand Up @@ -2854,7 +2855,8 @@ def __init__(
):
"""
Args:
path: Database path
path: Database path. A relative path is taken from the current
directory (``os.getcwd()``) at the time the factory is made.
jvm_kwargs: Optional JVM args passed to start_jvm()
Example: {"heap_size": "8g"}
"""
Expand All @@ -2863,7 +2865,7 @@ def __init__(

JavaDatabaseFactory = jpype.JClass("com.arcadedb.database.DatabaseFactory")

self._java_factory = JavaDatabaseFactory(path)
self._java_factory = JavaDatabaseFactory(absolute_path(path))

def create(self) -> Database:
"""Create a new database."""
Expand Down Expand Up @@ -2918,7 +2920,7 @@ def create_database(
"""Create a new database at the given path.

Args:
path: Database path
path: Database path; a relative one is taken from the current directory
jvm_kwargs: Optional JVM args passed to start_jvm()
Example: {"heap_size": "8g"}
"""
Expand All @@ -2937,7 +2939,7 @@ def open_database(
"""Open an existing database at the given path.

Args:
path: Database path
path: Database path; a relative one is taken from the current directory
jvm_kwargs: Optional JVM args passed to start_jvm()
Example: {"heap_size": "8g"}
read_only: Open the database read-only. Writes and schema changes raise
Expand Down Expand Up @@ -2971,7 +2973,7 @@ def open_or_create_database(
``open_database`` are unchanged.

Args:
path: Database path
path: Database path; a relative one is taken from the current directory
jvm_kwargs: Optional JVM args passed to start_jvm() (ignored with a
warning by the native package, which has no JVM)
read_only: Open the database read-only. It never creates: a path that
Expand Down Expand Up @@ -3010,6 +3012,6 @@ def open_or_create_database(


def database_exists(path: str) -> bool:
"""Check if a database exists at the given path."""
"""Check if a database exists at the given path (a relative one is taken from the current directory)."""
factory = DatabaseFactory(path)
return factory.exists()
6 changes: 5 additions & 1 deletion src/arcadedb/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

import jpype

from ._paths import absolute_path
from .core import Database
from .exceptions import ArcadeDBError
from .jvm import start_jvm
Expand Down Expand Up @@ -78,7 +79,9 @@ def __init__(
Initialize ArcadeDB server.

Args:
root_path: Root directory for databases (default: ./databases)
root_path: Root directory for databases (default: ./databases). A
relative path is taken from the current directory when the
server is made.
root_password: Root user password (optional, recommended for
production)
config: Optional configuration dictionary with keys like:
Expand Down Expand Up @@ -133,6 +136,7 @@ def __init__(
JavaArcadeDBServer = jpype.JClass("com.arcadedb.server.ArcadeDBServer")

self._config = config or {}
root_path = absolute_path(root_path)
self._root_path = root_path
self._root_password = root_password
self._java_server: Any = None
Expand Down
3 changes: 1 addition & 2 deletions tests/test_docs_agent_memory_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@
its text says. The tests use no Java object, so they run on the JVM build and the native build alike.

The page opens ``./agent_memory``. The tests put an absolute path of their own in that place and do not change the working
directory: after ``os.chdir`` a relative database path did not name one directory on either build (a later test opened the database
of an earlier one, or one without its types), as if the engine keeps the working directory that it started in.
directory (tests/test_relative_paths.py covers a relative path after ``os.chdir``).
"""

import contextlib
Expand Down
155 changes: 155 additions & 0 deletions tests/test_relative_paths.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
"""A relative path names a place under Python's current directory, also after ``os.chdir``.

The engine resolves a part of the files of a relative path against the directory that was current when it started, so one
relative path could name two directories. Every test starts the engine first and changes the directory afterwards.
"""

import os

import pytest

import arcadedb
from tests.conftest import TEST_PASSWORD, free_port


@pytest.fixture
def two_dirs(tmp_path, monkeypatch):
"""Two empty directories, made after the engine has started somewhere else."""
monkeypatch.chdir(tmp_path)
with arcadedb.create_database(str(tmp_path / "engine_is_running")):
pass
first = tmp_path / "first"
second = tmp_path / "second"
first.mkdir()
second.mkdir()
return first, second


def _same(path, expected):
return os.path.realpath(path) == os.path.realpath(expected)


def _types(db):
return [name for name in ("InFirst", "InSecond") if db.schema.exists_type(name)]


def _create_with_type(path, type_name):
with arcadedb.create_database(path) as db:
db.command("sql", f"CREATE DOCUMENT TYPE {type_name}")
with db.transaction():
db.command("sql", f"INSERT INTO {type_name} SET n = 1")


def test_a_relative_path_names_the_database_of_the_current_directory(
two_dirs, monkeypatch
):
first, second = two_dirs
monkeypatch.chdir(first)
_create_with_type("./db", "InFirst")
monkeypatch.chdir(second)
_create_with_type("./db", "InSecond")

for directory, type_name in ((first, "InFirst"), (second, "InSecond")):
assert (directory / "db" / "schema.json").is_file()
monkeypatch.chdir(directory)
with arcadedb.open_database("./db") as db:
assert _types(db) == [type_name]
assert db.count_type(type_name) == 1

# still in the second directory
with arcadedb.open_database(os.path.join("..", "first", "db")) as db:
assert _types(db) == ["InFirst"]
# nothing appeared in the directory that the engine saw first
assert not (first.parent / "db").exists()


def test_exists_and_open_or_create_follow_the_current_directory(two_dirs, monkeypatch):
first, second = two_dirs
monkeypatch.chdir(first)
with arcadedb.open_or_create_database("db") as db:
db.command("sql", "CREATE DOCUMENT TYPE InFirst")
assert arcadedb.database_exists("db")

monkeypatch.chdir(second)
assert not arcadedb.database_exists("db")
with arcadedb.open_or_create_database("db") as db:
assert _types(db) == []

monkeypatch.chdir(first)
with arcadedb.open_or_create_database("db") as db:
assert _types(db) == ["InFirst"]


def test_one_relative_path_opens_two_databases_from_two_directories(
two_dirs, monkeypatch
):
first, second = two_dirs
monkeypatch.chdir(first)
with arcadedb.create_database("db") as in_first:
in_first.command("sql", "CREATE DOCUMENT TYPE InFirst")
monkeypatch.chdir(second)
with arcadedb.create_database("db") as in_second:
in_second.command("sql", "CREATE DOCUMENT TYPE InSecond")
assert _types(in_second) == ["InSecond"]
assert _types(in_first) == ["InFirst"]


def test_a_factory_keeps_the_directory_it_was_made_in(two_dirs, monkeypatch):
first, second = two_dirs
monkeypatch.chdir(first)
factory = arcadedb.DatabaseFactory("db")
monkeypatch.chdir(second)
assert not factory.exists()
factory.create().close()
assert factory.exists()
assert (first / "db" / "schema.json").is_file()
assert not (second / "db").exists()


def test_the_database_path_is_absolute(two_dirs, monkeypatch):
first, second = two_dirs
monkeypatch.chdir(first)
with arcadedb.create_database("./db") as db:
monkeypatch.chdir(second)
path = db.get_database_path()
assert os.path.isabs(path), path
assert _same(path, first / "db"), path


@pytest.mark.server
@pytest.mark.parametrize(
"make", [arcadedb.ArcadeDBServer, arcadedb.create_server], ids=lambda f: f.__name__
)
def test_a_relative_server_root_follows_the_current_directory(
two_dirs, monkeypatch, make
):
first, second = two_dirs
monkeypatch.chdir(first)
server = make(
root_path="./server_root",
root_password=TEST_PASSWORD,
config={"http_port": free_port()},
)
# the root is taken from the directory that is current when the server is made
monkeypatch.chdir(second)
with server:
database = server.create_database("served")
path = database.get_database_path()
assert _same(path, first / "server_root" / "databases" / "served"), path
assert (
first / "server_root" / "databases" / "served" / "schema.json"
).is_file()
assert not (second / "server_root").exists()


def test_relative_export_and_import_paths_follow_the_current_directory(
two_dirs, monkeypatch
):
first, second = two_dirs
monkeypatch.chdir(second)
(second / "rows.csv").write_text("name,n\nb,1\nc,2\n", encoding="utf-8")
with arcadedb.create_database(str(first / "db")) as db:
db.import_documents("rows.csv", document_type="Imported")
assert db.count_type("Imported") == 2
db.export_database("backup.jsonl.tgz")
assert (second / "exports" / "backup.jsonl.tgz").is_file()
Loading