diff --git a/docs/modules/ROOT/pages/how-to/agent-memory.adoc b/docs/modules/ROOT/pages/how-to/agent-memory.adoc index 8690853..04ab4d0 100644 --- a/docs/modules/ROOT/pages/how-to/agent-memory.adoc +++ b/docs/modules/ROOT/pages/how-to/agent-memory.adoc @@ -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 diff --git a/docs/modules/ROOT/pages/how-to/databases-and-queries.adoc b/docs/modules/ROOT/pages/how-to/databases-and-queries.adoc index 8b1e578..d5c5456 100644 --- a/docs/modules/ROOT/pages/how-to/databases-and-queries.adoc +++ b/docs/modules/ROOT/pages/how-to/databases-and-queries.adoc @@ -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 @@ -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 <>. * `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. diff --git a/docs/modules/ROOT/pages/upgrading.adoc b/docs/modules/ROOT/pages/upgrading.adoc index 950a173..77f7701 100644 --- a/docs/modules/ROOT/pages/upgrading.adoc +++ b/docs/modules/ROOT/pages/upgrading.adoc @@ -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: diff --git a/src/arcadedb/_native/database.py b/src/arcadedb/_native/database.py index 917f2b3..ab6b540 100644 --- a/src/arcadedb/_native/database.py +++ b/src/arcadedb/_native/database.py @@ -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 @@ -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( diff --git a/src/arcadedb/_native/server.py b/src/arcadedb/_native/server.py index 25af9f9..fa82f7d 100644 --- a/src/arcadedb/_native/server.py +++ b/src/arcadedb/_native/server.py @@ -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 @@ -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 diff --git a/src/arcadedb/_paths.py b/src/arcadedb/_paths.py new file mode 100644 index 0000000..d0312c0 --- /dev/null +++ b/src/arcadedb/_paths.py @@ -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()) diff --git a/src/arcadedb/core.py b/src/arcadedb/core.py index 12f477c..f6b8141 100644 --- a/src/arcadedb/core.py +++ b/src/arcadedb/core.py @@ -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, @@ -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"} """ @@ -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.""" @@ -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"} """ @@ -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 @@ -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 @@ -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() diff --git a/src/arcadedb/server.py b/src/arcadedb/server.py index 40e7880..2121311 100644 --- a/src/arcadedb/server.py +++ b/src/arcadedb/server.py @@ -11,6 +11,7 @@ import jpype +from ._paths import absolute_path from .core import Database from .exceptions import ArcadeDBError from .jvm import start_jvm @@ -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: @@ -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 diff --git a/tests/test_docs_agent_memory_page.py b/tests/test_docs_agent_memory_page.py index 57f8ec3..3035401 100644 --- a/tests/test_docs_agent_memory_page.py +++ b/tests/test_docs_agent_memory_page.py @@ -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 diff --git a/tests/test_relative_paths.py b/tests/test_relative_paths.py new file mode 100644 index 0000000..0d28fe0 --- /dev/null +++ b/tests/test_relative_paths.py @@ -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()