Core Module (dataspector.core)#

Core data-source abstraction and integrity check execution engine.

Provides GenericData to unify metadata queries and chunked streaming across CSV, delimited/fixed-width text, Excel, Parquet, JSON/JSONL, SQLite, SQL Server / MS Access (optional ODBC), and COBOL copybook + data files, together with CheckeredHistory and the high-level runners run_checks_on_location() and load_and_run_checks().

class dataspector.core.CheckeredHistory(location, checklist)[source]#

Bases: object

Track and execute a list of integrity checks against a single data source.

Parameters:
location

Target data source locator.

checklist

Sequence of check specifications — check names or tuples (checkname, kwargs[, severity[, reader_options]]).

Parameters:
property all_passed: bool#

True if every check completed with True and no exceptions occurred.

property record_level_checks_remain: bool#

True if any pending checks require streaming records.

apply_record_level_checks(chunksize=500)[source]#

Stream records from the source and execute all pending record-level checks.

Parameters:
chunksize

Number of rows requested per streamed chunk.

Parameters:

chunksize (int)

Return type:

None

apply_source_level_checks()[source]#

Execute all pending source-level checks.

Return type:

None

class dataspector.core.DataSourceSpec(uri, format=None, table=None, data=None, options=<factory>)[source]#

Bases: object

Explicit, unified specification for a single file, COBOL pair, or database table.

Parameters:
uri

Filesystem path, COBOL copybook path, or database connection URL.

format

Optional explicit format or database flavour (e.g. "csv", "tsv", "fwf", "excel", "parquet", "json", "jsonl", "hdf5", "cobol", "sqlite", "postgres", "mysql", "mariadb", "mssql", "oracle", "duckdb", "access").

table

Database table name (optionally "schema.table"), Excel sheet name, or HDF5 key.

data

Accompanying data extract file path when format is "cobol" (or uri points to a COBOL copybook).

options

Optional reader or connection options forwarded to GenericData.

Parameters:
uri: str | Path#
format: str | None#
table: str | None#
data: str | Path | None#
options: dict[str, Any]#
class dataspector.core.GenericData(location, reader_options=None)[source]#

Bases: object

Format-agnostic wrapper exposing unified metadata and chunked reading.

Parameters:
location

Locator describing a file, directory, COBOL pair, or database table.

reader_options

Optional keyword arguments forwarded to the underlying reader (e.g. {"widths": [10, 20]} for fixed-width files or {"encoding": "cp500"} for COBOL files).

Attributes:
path

Local file path or parsed Copybook.

engine

Database handle, or COBOL data file path when path is a copybook.

table

Database table or Excel sheet name, if applicable.

Parameters:
close()[source]#

Dispose any open SQLAlchemy engine pool or pyodbc connection.

Return type:

None

property columns: list[Any] | None#

Column (field) names present in this data source.

property exists: bool#

True if the underlying file, COBOL pair, or database table exists.

property fields: list[Any] | None#

Alias for columns.

property last_modified: datetime | None#

UTC timestamp of when this data source was last modified.

property list_of_tables: list[str] | None#

List of tables (database) or worksheets (Excel), or None if not applicable.

property number_of_records: int#

Total number of records in this source (cached after first computation).

determine_delimiter(delimiters=(',', '|', '\t'), nlines=10)[source]#

Infer the most frequent delimiter across the first nlines lines of a text file.

Parameters:
delimiters

Candidate delimiter characters to count.

nlines

Number of leading lines to sample.

Returns:
str | None

Most frequent candidate delimiter, or None if none appear or the source is not a local file.

Parameters:
Return type:

str | None

determine_delimeter(delimiters=(',', '|', '\t'), nlines=10)#

Infer the most frequent delimiter across the first nlines lines of a text file.

Parameters:
delimiters

Candidate delimiter characters to count.

nlines

Number of leading lines to sample.

Returns:
str | None

Most frequent candidate delimiter, or None if none appear or the source is not a local file.

Parameters:
Return type:

str | None

fuzzy_find(pattern)[source]#

Search for pattern in directory paths, Excel sheet names, or database tables.

Parameters:
pattern

Shell-style wildcard pattern (e.g. "*.csv" or "*users*").

Returns:
list[str] | None

Matching paths, sheet names, or table names, or None when pattern search does not apply to this source.

Parameters:

pattern (str)

Return type:

list[str] | None

is_modified_recently(days_ago)[source]#

Return True if the source was modified within days_ago days of now.

Parameters:
days_ago

Freshness window in days.

Returns:
bool | None

True if modified within the window, False otherwise, or None if modification time is unavailable.

Parameters:

days_ago (float)

Return type:

bool | None

storage_size_roughly(rough_size, tolerance=0.2)[source]#

Return True if file byte size is within tolerance of rough_size.

Parameters:
rough_size

Expected file size in bytes.

tolerance

Allowed relative deviation (default 0.2 for ±20%).

Returns:
bool

True when the actual file size falls within tolerance, else False.

Parameters:
Return type:

bool

convert(output, chunksize=5000)[source]#

Convert this data source into CSV, TSV, JSONL, JSON, Excel, or Parquet.

Streams chunk-by-chunk via yield_data() for .csv, .tsv, and .jsonl outputs to keep memory bounded on large sources.

Parameters:
output

Destination file path whose extension selects the output format.

chunksize

Number of rows per streaming chunk.

Returns:
pathlib.Path

Path to the written output file.

Parameters:
Return type:

Path

to_dataframe(nrows=None, chunksize=500)[source]#

Load records from this data source into a single pandas.DataFrame.

Reads internally via chunked streaming (yield_data()) and stops early once nrows rows are collected. For sources larger than memory, iterate over yield_data() directly instead.

Parameters:
nrows

Optional maximum number of records to return (None reads all).

chunksize

Number of rows requested per internal streaming chunk.

Returns:
pandas.DataFrame

Materialized records (empty DataFrame if source has no rows).

Parameters:
  • nrows (int | None)

  • chunksize (int)

Return type:

DataFrame

yield_data(chunksize=500)[source]#

Stream records from this data source as pandas.DataFrame chunks.

Parameters:
chunksize

Maximum number of rows per yielded chunk for chunkable formats.

Yields:
pandas.DataFrame | str

Decoded DataFrame chunks (or raw text lines for unrecognized formats).

Parameters:

chunksize (int)

Return type:

Iterator[Any]

dataspector.core.connect_to_copybook(layout, data=None, force=False)[source]#

Attempt to parse layout as a COBOL copybook and resolve data.

Parameters:
layout

Path to the COBOL copybook file.

data

Optional path to the accompanying COBOL data file.

force

When True, attempt to parse layout as a COBOL copybook regardless of its file extension (used by cobol:// locators).

Returns:
tuple[Copybook | None, pathlib.Path | None]

Parsed copybook and resolved data file path, or None entries if invalid/missing.

Parameters:
Return type:

tuple[Copybook | None, Path | None]

dataspector.core.connect_to_embedded_db(database)[source]#

Connect to an embedded SQLite, DuckDB, or MS Access database file.

Parameters:
database

Path to the embedded database file (.sqlite, .db, .duckdb, .mdb, .accdb).

Returns:
Engine | pyodbc.Connection | None

Active database handle, or None if unsupported/unavailable.

Parameters:

database (str | Path)

Return type:

Any

dataspector.core.connect_to_location(location)[source]#

Resolve location into a (path, engine, table) triple.

Parameters:
location

File/directory path, unified URI locator ('csv://...', 'excel://book.xlsx#Sheet1', 'cobol://layout.cbl::data.dat', 'postgresql+psycopg://...#table'), or DataSourceSpec.

Returns:
tuple[pathlib.Path | Copybook | None, Any, str | None]

(path, engine, table) triple describing the resolved data source.

Parameters:

location (str | Path | DataSourceSpec | Mapping[str, Any])

Return type:

tuple[Path | Copybook | None, Any, str | None]

dataspector.core.connect_to_server(server, database)[source]#

Try ODBC connection templates to connect to a remote SQL Server database.

Parameters:
server

Database server hostname or instance name.

database

Target database name.

Returns:
Engine | None

Connected SQLAlchemy engine, or None if no template succeeded.

Parameters:
Return type:

Engine | None

dataspector.core.connect_to_sqlalchemy_url(url)[source]#

Create a SQLAlchemy Engine from a database URL.

Normalizes common scheme aliases (postgres:// -> postgresql://, sqlite3:// -> sqlite://, sqlserver:// -> mssql+pyodbc://) and handles relative/absolute SQLite file paths cleanly.

Parameters:
url

SQLAlchemy-compatible database URL.

Returns:
Engine | None

Configured SQLAlchemy engine, or None if engine creation fails.

Parameters:

url (str)

Return type:

Engine | None

dataspector.core.interpolate_env_vars(text)[source]#

Expand ${VAR_NAME} placeholders in text from os.environ.

Parameters:
text

Input locator string or URL.

Returns:
str

String with known environment variables expanded.

Parameters:

text (str)

Return type:

str

dataspector.core.load_and_run_checks(driverfile, use_multiprocessing=False)[source]#

Load driverfile and execute all configured checks across all locations.

Parameters:
driverfile

Path to an Excel driver workbook listing data locations and checks.

use_multiprocessing

Execute checks across multiple locations concurrently using a process pool.

Returns:
list[CheckeredHistory]

Completed check histories, one per location in driverfile.

Parameters:
Return type:

list[CheckeredHistory]

dataspector.core.load_driverfile(driver)[source]#

Load an Excel driver workbook containing Location Details and Checks to Run sheets.

Parameters:
driver

Path to the Excel driver workbook.

Returns:
dict[str, list[tuple[str, dict[str, Any] | None, Any, dict[str, Any]]]]

Mapping of resolved source locator to list of (check_name, kwargs, severity, reader_args) tuples.

Parameters:

driver (str | Path)

Return type:

dict[str, list[tuple[str, dict[str, Any] | None, Any, dict[str, Any]]]]

dataspector.core.parse_cell_to_dict(cell, default_key=None)[source]#

Parse flexible Excel cell text (JSON, Python literal, key=val, or scalar) into a dict.

Parameters:
cell

Cell value read from an Excel driver workbook.

default_key

Key name assigned when cell holds a single scalar value.

Returns:
dict[str, Any] | None

Parsed keyword arguments dictionary, or None if empty/unparseable.

Parameters:
  • cell (Any)

  • default_key (str | None)

Return type:

dict[str, Any] | None

dataspector.core.pretty_print_results(results, maxlen=40)[source]#

Format and print check results as an aligned ASCII table.

Parameters:
results

Results to render.

maxlen

Maximum column width before wrapping onto additional lines.

Returns:
str

Rendered table text (also printed to stdout).

Parameters:
Return type:

str

dataspector.core.resolve_location_with_options(location)[source]#

Resolve location into (path, engine, table, inferred_options).

Supports the following unified locator styles:

  • Unified URI schemes for files (csv://path, tsv://path, fwf://path, excel://book.xlsx#Sheet1, parquet://path, json://path, jsonl://path, hdf5://store.h5#key)

  • Unified COBOL locators (cobol://layout.cbl::data.dat or cobol://layout.cbl?data=data.dat&encoding=cp500)

  • Unified SQL database URLs across any dialect (sqlite:///db.sqlite#Table1, postgresql+psycopg://${PG_USER}:${PG_PASS}@host:5432/db#public.users, mysql+pymysql://${MYSQL_USER}:${MYSQL_PASS}@host/db#orders, snowflake://${SF_USER}:${SF_PASS}@account/db/schema?warehouse=WH#table, mssql+pyodbc://server/db#accounts, duckdb:///file.duckdb#events, access://file.accdb#Orders)

  • Structured DataSourceSpec or dict specifications

  • Plain file paths with optional #Sheet / #Table fragment

Parameters:
location

Source locator in any supported representation.

Returns:
tuple[pathlib.Path | Copybook | None, Any, str | None, dict[str, Any]]

(path, engine, table, inferred_options) quadruple.

Parameters:

location (str | Path | DataSourceSpec | Mapping[str, Any])

Return type:

tuple[Path | Copybook | None, Any, str | None, dict[str, Any]]

dataspector.core.run_checks_on_location(location, checklist)[source]#

Run all checks in checklist against location.

Parameters:
location

Target data source locator or GenericData instance.

checklist

Comma-separated check names or sequence of check specifications.

Returns:
CheckeredHistory

Populated history containing results, notes, and any exceptions.

Parameters:
Return type:

CheckeredHistory

dataspector.core.version_adder(fout, extension=None)[source]#

Return a non-colliding output path, appending _v01, _v02, … if needed.

Parameters:
fout

Desired output file path.

extension

Optional required file extension (e.g. '.xlsx').

Returns:
str

Unique output path string.

Parameters:
Return type:

str

dataspector.core.write_excel_report(results, excel_file_name)[source]#

Write formatted check results to an Excel workbook with conditional highlighting.

Parameters:
results

Check results produced by run_checks_on_location() or load_and_run_checks().

excel_file_name

Target .xlsx output path (auto-versioned if it already exists).

Returns:
pathlib.Path

Path to the written Excel report.

Parameters:
Return type:

pathlib.Path