Skip to content
Closed
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
13 changes: 13 additions & 0 deletions changelog.d/ITL-1457.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
### Added

- `SpiralDBTableSource(..., connector=<SpiralDBConnector>)`: sources of one project and
dataset that are given one connector use its SDK client, so they sign in once (ITL-1457).
Only the client is shared: each source reads the dataset's schema table and makes every
other call as before, so no row, order, hash or refusal changes. It is part of no identity
and is not saved. Without the argument a source makes its own connector, as before.

### Fixed

- `SpiralDBConnector` copies the `overrides` it is given, and `to_config()` returns a copy, so
changing either dictionary later cannot make it save or report another service address than
the one it reads (ITL-1457).
19 changes: 19 additions & 0 deletions docs/concepts/sources.md
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,25 @@ print(sessions.output_schema())
sessions.as_df() # also as_polars_df(), as_pandas_df(), as_lazy_frame(), as_table()
```

Each source signs in by itself. Give several sources of one project and dataset one connector
and they sign in once:

<!-- docs-test: skip -->
```python
with SpiralDBConnector("edi-sample-v1-855632") as spiral:
sessions = SpiralDBTableSource("edi-sample-v1-855632", "session", connector=spiral)
experiments = SpiralDBTableSource("edi-sample-v1-855632", "experiment", connector=spiral)
experiments.as_table() # works after the connector is closed
```

Only the client is shared. Each source makes the calls a source that makes its own connector
makes, the reads of the dataset's schema table included, so the rows, ids, hashes and refusals
are the same, and closing the connector or one source does not affect the others. The sources
read as whoever the connector signed in as, also after the environment or the saved login
changed: make a new connector to sign in again. A connector
cannot be used after a fork. The connector is not saved with a job: a loaded source makes its
own.

Things to know about Spiral tables:

- **The schema is recorded beside the tables.** See
Expand Down
60 changes: 59 additions & 1 deletion src/orcapod/core/sources/spiraldb_table_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@
"my-project-123456", "spike_event", tags_as_data={"timestamp": "spike_time_us"}
)

# Several sources that use one client, and so one sign-in
with SpiralDBConnector("my-project-123456") as connector:
units = SpiralDBTableSource("my-project-123456", "unit", connector=connector)
trials = SpiralDBTableSource("my-project-123456", "trial", connector=connector)

# Explicit dataset, tag columns overridden
source = SpiralDBTableSource(
"my-project-123456", "spike_event", dataset="prod", tag_columns=["unit_id"]
Expand Down Expand Up @@ -157,6 +162,44 @@ def _checked_conditions(
return check_equality_conditions(conditions, schema)


def _overrides_of(
connector: SpiralDBConnector,
project_id: str,
dataset: str,
overrides: dict[str, str] | None,
) -> dict[str, str] | None:
"""Return the overrides of a given connector, which must be of the source's place.

Args:
connector: The given connector.
project_id: The source's project.
dataset: Its dataset.
overrides: Its overrides, if any were given.

Raises:
TypeError: If ``connector`` is not a ``SpiralDBConnector``.
ValueError: If it is of another project, dataset or service address.
RuntimeError: If it is closed, or was made in another process.
"""
if not isinstance(connector, SpiralDBConnector):
raise TypeError(
f"connector must be a SpiralDBConnector, got {type(connector).__name__}"
)
place = connector.to_config()
if (place["project_id"], place["dataset"]) != (project_id, dataset):
raise ValueError(
f"the connector given is of SpiralDB project {place['project_id']!r}, dataset "
f"{place['dataset']!r}; the source is of project {project_id!r}, dataset "
f"{dataset!r}"
)
if overrides is not None and dict(overrides) != (place["overrides"] or {}):
raise ValueError(
f"overrides {overrides!r} differ from those of the connector given, "
f"{place['overrides']!r}: leave overrides out"
)
return place["overrides"]


SPIRALDB_SOURCE_ID_HAS_TABLE_ID = True
"""Whether a SpiralDB default source id ends in ``@<table id>`` (ITL-1154).

Expand Down Expand Up @@ -275,13 +318,22 @@ class SpiralDBTableSource(RootSource):
tags_as_data: Maps a key column that is a tag column of this source to the
name of a data column that receives a copy of it, as in
``DerivedSource``. ``None`` (default) or an empty mapping copies nothing.
connector: A ``SpiralDBConnector`` of this project and dataset whose SDK client
the source uses, so that sources given one connector sign in once (ITL-1457).
Only the client is shared: each source reads the dataset's schema table and
makes every other call as a source that makes its own connector does. Whose
sign-in it is was decided when the connector was made. The source holds its own reference: closing the connector, the source
or another source given it affects no other. It is part of no identity and is
not saved. ``None`` (default): the source makes its own. Keyword-only.

Raises:
ValueError: If the table is not found, has no key schema, a tag column or a
``where`` column is not in the table, a ``where`` value is ``None``, or
``limit``, ``max_rows`` or ``batch_rows`` is not a positive integer.
Or if ``connector`` is of another project, dataset or service address.
RuntimeError: If ``connector`` is closed, or was made before a fork.
TypeError: If a ``where`` value is not exactly of its column's Python type or
does not fit its Arrow type.
does not fit its Arrow type, or ``connector`` is not a ``SpiralDBConnector``.
InputValidationError: If ``tags_as_data`` names a column that is not a tag
column or not a key column, or a new name that is already a column, is
given twice, or is reserved for system columns.
Expand Down Expand Up @@ -322,6 +374,7 @@ def __init__(
*,
tag_only_columns: TagOnlyColumns = (),
record_id_columns: str | Collection[str] | None = None,
connector: SpiralDBConnector | None = None,
) -> None:
given_key = normalize_record_id_columns(record_id_columns)
if given_key == ():
Expand All @@ -345,6 +398,9 @@ def __init__(
f"batch_rows must be a positive integer, got {batch_rows!r}"
)

if connector is not None:
overrides = _overrides_of(connector, project_id, dataset, overrides)

super().__init__(
source_id=source_id, label=label, data_context=data_context, config=config
)
Expand All @@ -365,6 +421,8 @@ def __init__(
location = f"SpiralDB project {project_id!r}, dataset {dataset!r}"

try:
if connector is not None:
self._connection = connector._for_source() # pyright: ignore[reportPrivateUsage] # for sources
try:
table = self._connector().lookup_table(table_name)
except SpiralDBTableNotFoundError as exc:
Expand Down
30 changes: 25 additions & 5 deletions src/orcapod/databases/spiraldb_connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -634,14 +634,21 @@ def __init__(
) -> None:
self._project_id = project_id
self._dataset = dataset
self._overrides = overrides
# A copy, so that what is saved and checked stays the address the client was
# made with, whatever the caller does with theirs.
self._overrides = None if overrides is None else dict(overrides)
self._closed = False
self._client = _new_client(overrides)
self._client = _new_client(self._overrides)
self._pid = os.getpid()
# Shared by every connector on this client (``share_client``).
self._counts: dict[tuple[str, str], tuple[int, bool]] = {}
client = self._client
self._schemas = SchemaTable(
self._schemas = self._new_schema_table()

def _new_schema_table(self) -> SchemaTable:
"""Return a ``SchemaTable`` of this connector's dataset, read through its client,
that has read nothing yet."""
client, project_id, dataset = self._client, self._project_id, self._dataset
return SchemaTable(
project_id,
dataset,
lambda: _open_keyed_table(client, project_id, dataset, SCHEMA_TABLE),
Expand All @@ -659,6 +666,19 @@ def share_client(self) -> SpiralDBConnector:
self._require_open()
return copy(self)

def _for_source(self) -> SpiralDBConnector:
"""Return ``share_client()`` for a source that is given this connector (ITL-1457).

Only the client is shared. What one source counted is not taken as counted by
another, and each source reads the schema table as a source that makes its own
connector does, so a connector that already read a version skips no call and no
check of it (no refusal is missed).
"""
shared = self.share_client()
shared._counts = {}
shared._schemas = shared._new_schema_table()
return shared

def _qualified(self, table_name: str) -> str:
"""Return ``"<project>/<dataset>/<table>"``, the table as errors name it."""
return f"{self._project_id}/{self._dataset}/{table_name}"
Expand Down Expand Up @@ -1077,7 +1097,7 @@ def to_config(self) -> dict[str, Any]:
"connector_type": "spiraldb",
"project_id": self._project_id,
"dataset": self._dataset,
"overrides": self._overrides,
"overrides": None if self._overrides is None else dict(self._overrides),
}

@classmethod
Expand Down
Loading
Loading