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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ This prints `Name: Alice` (the engine also logs to standard error). `create_data
- Columnar results with `to_columns()`, `to_arrow()` and `to_dataframe()`.
- Faceted queries: the `FACETS` clause of a `SELECT` with a `COLUMNAR` index, and the counts as a dict in `ResultSet.facets` (needs engine 26.12.1 or later).
- An optional in-process HTTP server (`create_server()`), off until you call it, for other processes that need the same data.
- Type hints on every public class and function, and a `py.typed` marker in both packages, so editors and type checkers read them (PEP 561).

<!-- REMOVE WHEN: the old arcadedb-embedded* shims are retired and two releases have shipped with the two-package layout allow-old-name -->

Expand Down
2 changes: 1 addition & 1 deletion native/wheel/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,4 @@ Repository = "https://github.com/ArcadeData/arcadedb-python"
where = ["src"]

[tool.setuptools.package-data]
arcadedb = ["_native/*.so", "_native/*.dylib", "_native/*.dll"]
arcadedb = ["py.typed", "_native/*.so", "_native/*.dylib", "_native/*.dll"]
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ include-package-data = true

[tool.setuptools.package-data]
arcadedb = [
"py.typed", # PEP 561: the package carries type hints (issue 476)
"jars/*.jar",
"jre/**/*",
]
Expand Down
14 changes: 10 additions & 4 deletions src/arcadedb/_native/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -966,7 +966,7 @@ def _rollback_state(self) -> int:
return self._tx_state(2, "Failed to rollback transaction")

def transaction(self) -> TransactionContext:
return TransactionContext(self)
return TransactionContext(self) # type: ignore[arg-type] # the native database has the Database surface

def is_transaction_active(self) -> bool:
return bool(self._tx_state(3, "Failed to check transaction status") & 1)
Expand Down Expand Up @@ -1588,7 +1588,13 @@ def export_database(
from ..exporter import export_database

return export_database(
self, file_path, format, overwrite, include_types, exclude_types, verbose
self, # type: ignore[arg-type]
file_path,
format,
overwrite,
include_types,
exclude_types,
verbose,
)

def export_to_csv(
Expand Down Expand Up @@ -1659,7 +1665,7 @@ def insert_dataframe(
self._check_not_closed()
table = to_arrow_table(df, what="insert_dataframe()")
return insert_table(
self,
self, # type: ignore[arg-type]
type_name,
table,
batch_size=batch_size,
Expand All @@ -1678,7 +1684,7 @@ def insert_arrow(
self._check_not_closed()
arrow_table = to_arrow_table(table, what="insert_arrow()")
return insert_table(
self,
self, # type: ignore[arg-type]
type_name,
arrow_table,
batch_size=batch_size,
Expand Down
18 changes: 11 additions & 7 deletions src/arcadedb/aio.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,11 @@
import contextvars
import functools
from concurrent.futures import ThreadPoolExecutor
from typing import Any, Callable, Dict, List, Optional
from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, Tuple

if TYPE_CHECKING:
from .core import Database
from .vector import VectorIndex

__all__ = ["AsyncDatabase"]

Expand All @@ -45,7 +49,7 @@ class AsyncDatabase:
Use it as ``async with AsyncDatabase(db) as adb:`` or call ``await adb.close()`` yourself.
"""

def __init__(self, db, max_workers: int = _DEFAULT_MAX_WORKERS):
def __init__(self, db: "Database", max_workers: int = _DEFAULT_MAX_WORKERS):
if (
isinstance(max_workers, bool)
or not isinstance(max_workers, int)
Expand All @@ -60,7 +64,7 @@ def __init__(self, db, max_workers: int = _DEFAULT_MAX_WORKERS):
self._closed = False

@property
def database(self):
def database(self) -> "Database":
"""The wrapped ``Database``."""
return self._db

Expand Down Expand Up @@ -133,14 +137,14 @@ async def run_in_transaction(

async def find_nearest(
self,
index,
query_vector,
index: "VectorIndex",
query_vector: Any,
k: int = 10,
ef_search: Optional[int] = None,
allowed_rids=None,
allowed_rids: Optional[Iterable[Any]] = None,
*,
include_vector: bool = True,
):
) -> List[Tuple[Any, float]]:
"""``index.find_nearest(...)`` on a worker: a list of ``(record, distance)``, nearest first.

``index`` is the ``VectorIndex`` that ``db.create_vector_index(...)`` or ``db.schema.get_vector_index(...)`` returns. A search
Expand Down
50 changes: 28 additions & 22 deletions src/arcadedb/async_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@

import threading
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, Callable, Optional, Sequence, Union
from types import TracebackType
from typing import TYPE_CHECKING, Any, Callable, Optional, Sequence, Type, Union

import jpype

Expand Down Expand Up @@ -264,7 +265,7 @@ class AsyncExecutor:
>>> async_exec.wait_completion()
"""

def __init__(self, java_async_executor, owner: Optional["Database"] = None):
def __init__(self, java_async_executor: Any, owner: Optional["Database"] = None):
"""
Initialize AsyncExecutor wrapper.

Expand All @@ -275,10 +276,15 @@ def __init__(self, java_async_executor, owner: Optional["Database"] = None):
self._owner = owner
self._closed = False

def __enter__(self):
def __enter__(self) -> "AsyncExecutor":
return self

def __exit__(self, exc_type, exc_val, exc_tb):
def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
self.close()

def is_closed(self) -> bool:
Expand Down Expand Up @@ -433,7 +439,7 @@ def is_processing(self) -> bool:
log_swallowed_exception(_LOGGER, "while polling isProcessing()")
return False

def kill(self):
def kill(self) -> None:
self._java_async.kill()

def set_back_pressure(self, percentage: int) -> "AsyncExecutor":
Expand Down Expand Up @@ -467,10 +473,10 @@ def set_back_pressure(self, percentage: int) -> "AsyncExecutor":

def create_record(
self,
document,
document: Any,
callback: Optional[Callable] = None,
error_callback: Optional[Callable[[Exception], None]] = None,
):
) -> None:
"""Queue a document for asynchronous creation.

The engine's parallel bucket writers persist it off the calling
Expand Down Expand Up @@ -508,13 +514,13 @@ def _create_new_record_callback(self, python_callback):

def new_edge(
self,
source_vertex,
source_vertex: Any,
edge_type: str,
destination_vertex_or_rid,
destination_vertex_or_rid: Any,
light: bool = False,
callback: Optional[Callable[[Any, bool, bool], None]] = None,
**properties,
):
**properties: Any,
) -> None:
source_vertex = self._unwrap_record(source_vertex)
destination_rid = self._to_java_rid(destination_vertex_or_rid)
java_callback = self._create_new_edge_callback(callback) if callback else None
Expand All @@ -541,8 +547,8 @@ def new_edge_by_keys(
bidirectional: bool,
light: bool,
callback: Optional[Callable[[Any, bool, bool], None]] = None,
**properties,
):
**properties: Any,
) -> None:
java_callback = self._create_new_edge_callback(callback) if callback else None
props = self._to_java_varargs(properties)

Expand Down Expand Up @@ -611,7 +617,7 @@ def append_samples(
timestamps: Sequence[int],
*column_values: Sequence[Any],
primitive: bool = False,
):
) -> Any:
"""Columnar bulk append into a native TIMESERIES type.

Columns are positional and must follow the type's declaration order:
Expand Down Expand Up @@ -781,8 +787,8 @@ def query(
callback: Callable[[Any], None],
args: Optional[Sequence[Any]] = None,
error_callback: Optional[Callable[[Exception], None]] = None,
**params,
):
**params: Any,
) -> None:
"""
Execute async query with callback for each result.

Expand Down Expand Up @@ -830,8 +836,8 @@ def command(
callback: Optional[Callable[[Any], None]] = None,
args: Optional[Sequence[Any]] = None,
error_callback: Optional[Callable[[Exception], None]] = None,
**params,
):
**params: Any,
) -> None:
"""
Execute async command with optional callback.

Expand Down Expand Up @@ -900,7 +906,7 @@ def scan_type(
callback: Callable[[Any], bool],
polymorphic: bool = True,
error_callback: Optional[Callable[[Any, Exception], bool]] = None,
):
) -> None:
java_doc_callback = self._create_document_callback(callback)
if error_callback is None:
self._java_async.scanType(type_name, polymorphic, java_doc_callback)
Expand All @@ -920,7 +926,7 @@ def transaction(
ok_callback: Optional[Callable[[], None]] = None,
error_callback: Optional[Callable[[Exception], None]] = None,
slot: Optional[int] = None,
):
) -> None:
java_tx = self._create_transaction_scope(tx_block)

if (
Expand Down Expand Up @@ -953,7 +959,7 @@ def transaction(

# Control flow

def wait_completion(self, timeout_ms: Optional[int] = None):
def wait_completion(self, timeout_ms: Optional[int] = None) -> None:
"""
Wait for all async operations to complete.

Expand Down Expand Up @@ -1025,7 +1031,7 @@ def is_pending(self) -> bool:
"""
return self.is_processing()

def close(self):
def close(self) -> None:
"""
Close the async executor and shutdown worker threads.

Expand Down
28 changes: 22 additions & 6 deletions src/arcadedb/callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,18 @@
import threading
import traceback
import weakref
from typing import Callable, Optional, Tuple
from types import TracebackType
from typing import TYPE_CHECKING, Any, Callable, Optional, Tuple, Type

import jpype

from ._logging import get_logger
from .exceptions import ArcadeDBError
from .type_conversion import convert_java_to_python, convert_python_to_java

if TYPE_CHECKING:
from .core import Database

_LOGGER = get_logger(__name__)

EVENTS = (
Expand Down Expand Up @@ -285,7 +289,7 @@ class FunctionRegistration:
it registered to remove them when it is closed.
"""

def __init__(self, database):
def __init__(self, database: "Database"):
# Weak: the Database holds this registry, and a strong reference back would make a
# cycle that keeps the Database (and its engine instance) alive until a gc pass
# instead of releasing it with its last result (tests/test_results_after_close.py).
Expand Down Expand Up @@ -356,7 +360,12 @@ class EventHandle:
"""

def __init__(
self, events, event: str, type_name: Optional[str], java_handle, proxy
self,
events: Any,
event: str,
type_name: Optional[str],
java_handle: Any,
proxy: Any,
):
self._events = events
self._java_handle = java_handle
Expand All @@ -382,10 +391,15 @@ def remove(self) -> None:
except Exception as e:
raise ArcadeDBError(f"Failed to remove '{self.event}' callback: {e}") from e

def __enter__(self):
def __enter__(self) -> "EventHandle":
return self

def __exit__(self, exc_type, exc_val, exc_tb):
def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
self.remove()

def __repr__(self) -> str:
Expand All @@ -394,7 +408,9 @@ def __repr__(self) -> str:
return f"<EventHandle {self.event}{scope} ({state})>"


def register_event(database, event: str, fn: Callable, type_name: Optional[str]):
def register_event(
database: "Database", event: str, fn: Callable, type_name: Optional[str]
) -> "EventHandle":
"""Register ``fn`` for ``event`` on the database, or on one type, and return its handle."""
check_event(event, fn)
java_db = database.get_java_database()
Expand Down
Loading
Loading