nexusLIMS.tui.common.db_utils#

Database utilities for NexusLIMS TUI applications.

Provides common database query patterns.

Module Contents#

Functions#

check_uniqueness

Check if a value is unique for a given field.

get_session_log_count

Get count of session_log entries for an instrument.

find_conflicting_instrument

Find an instrument that conflicts with a unique field value.

API#

nexusLIMS.tui.common.db_utils.check_uniqueness(session: sqlmodel.Session, model: type, field_name: str, value: Any, exclude_pk: Any | None = None) bool[source]#

Check if a value is unique for a given field.

Parameters:
  • session (Session) – Active database session

  • model (type) – SQLModel model class (e.g., Instrument)

  • field_name (str) – Field name to check (e.g., “api_url”)

  • value (Any) – Value to check for uniqueness

  • exclude_pk (Any | None) – Primary key value to exclude (for edit operations)

Returns:

True if unique, False if duplicate exists

Return type:

bool

Examples:

>>> from nexusLIMS.db.models import Instrument
>>> with get_db_session() as session:
...     is_unique = check_uniqueness(
...         session, Instrument, "api_url",
...         "https://example.com/api/tools/?id=42"
...     )
nexusLIMS.tui.common.db_utils.get_session_log_count(session: sqlmodel.Session, instrument_pid: str) int[source]#

Get count of session_log entries for an instrument.

Useful for warning users before deleting an instrument with associated data.

Parameters:
  • session (Session) – Active database session

  • instrument_pid (str) – Instrument primary key

Returns:

Number of session_log entries

Return type:

int

Examples:

>>> with get_db_session() as session:
...     count = get_session_log_count(session, "FEI-Titan-TEM")
...     if count > 0:
...         print(f"Warning: {count} session logs will be orphaned")
nexusLIMS.tui.common.db_utils.find_conflicting_instrument(session: sqlmodel.Session, field_name: str, value: Any, exclude_pid: str | None = None) Instrument | None[source]#

Find an instrument that conflicts with a unique field value.

Parameters:
  • session (Session) – Active database session

  • field_name (str) – Unique field name (e.g., api_url)

  • value (Any) – Value to search for

  • exclude_pid (str | None) – Instrument PID to exclude (for edit operations)

Returns:

Conflicting instrument, or None if no conflict

Return type:

Instrument | None

Examples:

>>> with get_db_session() as session:
...     conflict = find_conflicting_instrument(
...         session, "api_url", "https://example.com/api"
...     )
...     if conflict:
...         print(f"Already used by {conflict.instrument_pid}")