db Module (stx.db)

Database operations module for scitex.

PostgreSQL support is optional and requires psycopg2. All public symbols are imported lazily via PEP 562 __getattr__ so that import scitex_db stays under the §10 cold-start budget — Click runs the CLI once per Tab press, and slow imports break tab-completion.

class scitex.db.PostgreSQL(dbname=None, user=None, password=None, host='localhost', port=5432)[source]

Bases: _BackupMixin, _BatchMixin, _ConnectionMixin, _ImportExportMixin, _IndexMixin, _MaintenanceMixin, _QueryMixin, _RowMixin, _SchemaMixin, _TableMixin, _TransactionMixin, _BlobMixin

__call__(return_summary=False, print_summary=True, table_names=None, verbose=True, limit=5)[source]

Display or return database summary.

property summary

Property to quickly access database summary.

class scitex.db.SQLite3(db_path, use_temp=False, compress_by_default=False, autocommit=False, mode='rwc', timeout=60.0)[source]

Bases: _ArrayMixin, _ConnectionMixin, _QueryMixin, _TransactionMixin, _ColumnMixin, _TableMixin, _IndexMixin, _RowMixin, _BatchMixin, _BlobMixin, _ImportExportMixin, _MaintenanceMixin, _GitMixin

SQLite database manager with automatic metadata handling, numpy array storage, and compression.

This class provides a comprehensive interface for SQLite database operations with automatic compression, thread-safe operations, and specialized numpy array handling.

Features:
  • Automatic compression for BLOB data (70-90% reduction)

  • Thread-safe operations with proper connection management

  • Metadata handling for BLOB columns

  • Batch processing support

  • Context manager support for proper resource cleanup

Examples

Basic usage with context manager (recommended):

>>> with SQLite3("data.db", compress_by_default=True) as db:
...     db.create_table("experiments", {"id": "INTEGER PRIMARY KEY", "data": "BLOB"})
...     data = np.random.random((1000, 100))
...     db.save_array("experiments", data, column="data", additional_columns={"id": 1})

Array storage and retrieval:

>>> with SQLite3("data.db") as db:
...     # Save numpy array
...     db.save_array(
...         table_name="measurements",
...         data=np.random.random((1000, 100)),
...         column="data",
...         additional_columns={"name": "experiment_1", "timestamp": 1234567890}
...     )
...     # Load array
...     loaded = db.load_array("measurements", "data", where="name = 'experiment_1'")

Generic object storage:

>>> with SQLite3("data.db") as db:
...     db.save_blob(
...         table_name="objects",
...         data={"weights": array, "params": {"lr": 0.001}},
...         key="model_v1"
...     )
...     loaded_obj = db.load_blob("objects", key="model_v1")

Notes

  • Always use context manager (with statement) for proper resource cleanup

  • BLOB columns automatically get metadata columns: {column}_dtype, {column}_shape, {column}_compressed

  • Compression is enabled by default for arrays > 1KB

  • Thread-safe operations are supported

__init__(db_path, use_temp=False, compress_by_default=False, autocommit=False, mode='rwc', timeout=60.0)[source]

Initialize SQLite database manager.

Parameters:
  • db_path (str) – Path to the SQLite database file

  • use_temp (bool) – Whether to use a temporary copy of the database, by default False

  • compress_by_default (bool) – Whether to compress BLOB data by default when not explicitly specified, by default False

  • autocommit (bool) – Whether to automatically commit transactions, by default False

  • mode (str) – SQLite URI open mode, by default "rwc" — opens existing files for read-write and creates the file if missing. This preserves the previous behaviour (sqlite3.connect(path) without URI auto-created missing files). "rw" is the same minus auto-create (file must already exist). "ro" is read-only — useful when scanning inventory databases that must not be mutated.

  • timeout (float) – sqlite3.connect timeout= value (seconds), by default 60.0 (the previous hardcoded value). Use a smaller value when probing many DBs and you’d rather fail fast than wait on a lock.

Warning

UserWarning

If not used with context manager, warns about potential resource leaks

Raises:

ValueError – If mode is not one of {"ro", "rw", "rwc"}.

__enter__()[source]

Enter context manager.

__exit__(exc_type, exc_val, exc_tb)[source]

Commit on a clean exit, roll back on an exception, then close.

THIS USED TO DISCARD EVERY UNCOMMITTED WRITE, SILENTLY. __exit__ called close(), and close() issues an explicit conn.rollback() – so with the default autocommit=False a block that wrote and then ended normally threw the work away. Measured 2026-07-31:

with SQLite3(p) as db:

db.execute(“INSERT INTO t VALUES (1)”) db.execute(“SELECT COUNT(*) FROM t”) -> 1 (inside)

fresh connection afterwards -> 0 (gone)

Two things made it dangerous rather than merely surprising. The context manager is MANDATORY here – _check_context_manager refuses to execute without one – so the API forced callers into the construct that lost their writes. And the loss is INVERTED: every read inside the block confirms the write landed, so a test that opens, writes and asserts in one block passes. Only a separate connection sees the truth.

Committing on a clean exit is the contract a mandatory context manager implies, and it matches sqlite3.Connection’s own. Rolling back on an exception keeps a half-applied write from surviving a failure.

A failing COMMIT is raised rather than swallowed – losing data quietly is the defect being fixed, so the fix must not have a quiet path of its own. During exception unwinding it is left alone, because masking the original error with a commit error would hide the cause.

__del__()[source]

Destructor with context manager usage warning.

__call__(return_summary=False, print_summary=True, table_names=None, verbose=True, limit=5)[source]

Display database summary information.

Parameters:
  • return_summary (bool, optional) – Whether to return summary dict, by default False

  • print_summary (bool, optional) – Whether to print summary to console, by default True

  • table_names (Optional[List[str]]) – Specific table names to summarize, by default None (all tables)

  • verbose (bool) – Whether to show detailed information, by default True

  • limit (int) – Maximum number of rows to display per table, by default 5

Returns:

Summary dictionary if return_summary=True, else None

Return type:

dict or None

property summary

Quick access to database summary.

scitex.db.batch_health_check(db_paths, verbose=False, fix_issues=False)[source]

Run health check on multiple databases

Parameters:
  • db_paths (List[str]) – List of database paths

  • verbose (bool) – Print results for each database

  • fix_issues (bool) – Attempt to fix issues

Returns:

Results for each database

Return type:

Dict[str, Dict[str, Any]]

scitex.db.check_health(db_path, verbose=True, fix_issues=False)[source]

Comprehensive health check for SQLite database

Parameters:
  • db_path (str) – Path to database file

  • verbose (bool) – Print detailed results

  • fix_issues (bool) – Attempt to fix detected issues

Returns:

Health check results

Return type:

Dict[str, Any]

scitex.db.delete_duplicates(*args, **kwargs)[source]

Delete duplicate entries from an SQLite database table.

Deprecated since version This: function is deprecated as it’s SQLite3-specific. Use scitex.db._sqlite3.delete_sqlite3_duplicates() instead.

scitex.db.delete_sqlite3_duplicates(lpath_db, table_name, columns='all', include_blob=False, chunk_size=10000, dry_run=True)[source]
Return type:

Tuple[Optional[int], Optional[int]]

scitex.db.inspect(lpath_db, table_names=None, sample_size=5, skip_count=False, verbose=True)[source]

Optimized database inspection.

Example: >>> inspect(‘path/to/database.db’) >>> inspect(‘path/to/database.db’, [‘table1’], skip_count=True)

Parameters:
  • lpath_db (str) – Path to the SQLite database file

  • table_names (Optional[List[str]]) – List of table names to inspect (None for all)

  • sample_size (int) – Number of sample rows to retrieve

  • skip_count (bool) – Skip row counting for large tables (much faster)

  • verbose (bool) – Print inspection results

Return type:

List[Dict[str, Any]]

Returns:

List of inspection results

scitex.db.register_post_load_hook(fn)[source]

Register a function to run after every successful scitex-db read.

Return type:

None

scitex.db.register_post_save_hook(fn)[source]

Register a function to run after every successful scitex-db write.

Hooks fire in registration order. They MUST NOT raise — exceptions are swallowed with logger.debug. A misbehaving observer must never break the host’s database access.

Return type:

None