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:
objectTrack 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:
location (str | pathlib.Path | DataSourceSpec | Mapping[str, Any] | GenericData)
- class dataspector.core.DataSourceSpec(uri, format=None, table=None, data=None, options=<factory>)[source]#
Bases:
objectExplicit, 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:
- class dataspector.core.GenericData(location, reader_options=None)[source]#
Bases:
objectFormat-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:
location (str | pathlib.Path | DataSourceSpec | Mapping[str, Any] | GenericData)
- property list_of_tables: list[str] | None#
List of tables (database) or worksheets (Excel), or
Noneif 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.
- determine_delimeter(delimiters=(',', '|', '\t'), nlines=10)#
Infer the most frequent delimiter across the first nlines lines of a text file.
- fuzzy_find(pattern)[source]#
Search for pattern in directory paths, Excel sheet names, or database tables.
- is_modified_recently(days_ago)[source]#
Return
Trueif the source was modified within days_ago days of now.
- storage_size_roughly(rough_size, tolerance=0.2)[source]#
Return
Trueif file byte size is within tolerance of rough_size.
- 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.jsonloutputs to keep memory bounded on large sources.
- 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 overyield_data()directly instead.- Parameters:
- nrows
Optional maximum number of records to return (
Nonereads all).- chunksize
Number of rows requested per internal streaming chunk.
- Returns:
- pandas.DataFrame
Materialized records (empty DataFrame if source has no rows).
- Parameters:
- Return type:
- yield_data(chunksize=500)[source]#
Stream records from this data source as
pandas.DataFramechunks.
- 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 bycobol://locators).
- Returns:
- tuple[Copybook | None, pathlib.Path | None]
Parsed copybook and resolved data file path, or
Noneentries if invalid/missing.
- Parameters:
- Return type:
- dataspector.core.connect_to_embedded_db(database)[source]#
Connect to an embedded SQLite, DuckDB, or MS Access database file.
- 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'), orDataSourceSpec.
- Returns:
- tuple[pathlib.Path | Copybook | None, Any, str | None]
(path, engine, table)triple describing the resolved data source.
- Parameters:
- Return type:
- dataspector.core.connect_to_server(server, database)[source]#
Try ODBC connection templates to connect to a remote SQL Server database.
- dataspector.core.connect_to_sqlalchemy_url(url)[source]#
Create a SQLAlchemy
Enginefrom 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
Noneif engine creation fails.
- Parameters:
url (str)
- Return type:
Engine | None
- dataspector.core.interpolate_env_vars(text)[source]#
Expand
${VAR_NAME}placeholders in text fromos.environ.
- 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:
- dataspector.core.load_driverfile(driver)[source]#
Load an Excel driver workbook containing
Location DetailsandChecks to Runsheets.- 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:
- 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
Noneif empty/unparseable.
- Parameters:
- Return type:
- 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:
results (CheckeredHistory | Sequence[CheckeredHistory])
maxlen (int)
- Return type:
- 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.datorcobol://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
DataSourceSpecordictspecificationsPlain file paths with optional
#Sheet/#Tablefragment
- dataspector.core.run_checks_on_location(location, checklist)[source]#
Run all checks in checklist against location.
- Parameters:
- location
Target data source locator or
GenericDatainstance.- checklist
Comma-separated check names or sequence of check specifications.
- Returns:
- CheckeredHistory
Populated history containing results, notes, and any exceptions.
- Parameters:
location (str | Path | DataSourceSpec | Mapping[str, Any] | GenericData)
- Return type:
- dataspector.core.version_adder(fout, extension=None)[source]#
Return a non-colliding output path, appending
_v01,_v02, … if needed.
- 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()orload_and_run_checks().- excel_file_name
Target
.xlsxoutput path (auto-versioned if it already exists).
- Returns:
- pathlib.Path
Path to the written Excel report.
- Parameters:
results (CheckeredHistory | Sequence[CheckeredHistory])
excel_file_name (str | pathlib.Path)
- Return type: