# `sc_crawler.utils`

> Utility functions, e.g. for hashing, database engines, and looking up tables and rows.

# `sc_crawler.utils`

**Classes:**

- [**HashLevels**](#hashlevels) – Granularity of [sc_crawler.utils.hash_database](#hash_database): one hash for the database, or one per table or row.

**Functions:**

- [**jsoned_hash**](#jsoned_hash) – Hash the JSON-dump of all positional and keyword arguments.
- [**sc_json_serializer**](#sc_json_serializer) – JSON serializer for SQLAlchemy engines writing Crawler JSON columns.
- [**create_sc_engine**](#create_sc_engine) – Create a SQLAlchemy engine that can persist typed JSON model fields.
- [**hash_database**](#hash_database) – Hash the content of a database.
- [**chunk_list**](#chunk_list) – Split a list into chunks of a specified size.
- [**scmodels_to_dict**](#scmodels_to_dict) – Creates a dict indexed by key(s) of the ScModels of the list.
- [**is_sqlite**](#is_sqlite) – Checks if a SQLModel session is binded to a SQLite database.
- [**is_postgresql**](#is_postgresql) – Checks if a SQLModel session is binded to a PostgreSQL-like database.
- [**float_inf_to_str**](#float_inf_to_str) – Transform to string if a float is inf.
- [**table_name_to_model**](#table_name_to_model) – Return the ScModel schema for a table name.
- [**get_row_by_pk**](#get_row_by_pk) – Get a row from a table definition by primary keys.
- [**nesteddefaultdict**](#nesteddefaultdict) – Recursive defaultdict.
- [**list_search**](#list_search) – Search for a dict in a list with the given key/value pair.
- [**convert_gb_to_mib**](#convert_gb_to_mib) – Convert gigabytes to mebibytes.

## func <code class="doc-name">jsoned_hash</code> [utils.py:31–44](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/utils.py#L31-L44)

```python
jsoned_hash(*args, **kwargs)
```

Hash the JSON-dump of all positional and keyword arguments.

**Examples:**

```pycon
>>> jsoned_hash(42)
'0211c62419aece235ba19582d3cf7fd8e25f837c'
>>> jsoned_hash(everything=42)
'8f8a7fcade8cb632b856f46fc64c1725ee387617'
>>> jsoned_hash(42, 42, everything=42)
'f04a77f000d85929b13de04b436c60a1272dfbf5'
```

## class <code class="doc-name">HashLevels</code> [utils.py:47–52](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/utils.py#L47-L52)

Bases: [`Enum`](https://docs.python.org/3/library/enum.html#enum.Enum)

Granularity of [sc_crawler.utils.hash_database](#hash_database): one hash for the database, or one per table or row.

## func <code class="doc-name">sc_json_serializer</code> [utils.py:55–57](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/utils.py#L55-L57)

```python
sc_json_serializer(x)
```

JSON serializer for SQLAlchemy engines writing Crawler JSON columns.

## func <code class="doc-name">create_sc_engine</code> [utils.py:60–63](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/utils.py#L60-L63)

```python
create_sc_engine(connection_string, **kwargs)
```

Create a SQLAlchemy engine that can persist typed JSON model fields.

## func <code class="doc-name">hash_database</code> [utils.py:66–108](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/utils.py#L66-L108)

```python
hash_database(connection_string, level=HashLevels.DATABASE, ignored=['observed_at'], progress=None, exclude_tables=[])
```

Hash the content of a database.

**Parameters:**

- **connection_string** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – SQLAlchemy connection string to connect to the database.
- **level** ([`HashLevels`](#hashlevels)) – The level at which to apply hashing. Possible values are 'DATABASE' (default), 'TABLE', or 'ROW'.
- **ignored** ([`List`](https://docs.python.org/3/library/typing.html#typing.List)`[`[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)`]`) – List of column names to be ignored during hashing.
- **progress** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)`[`[`Progress`](https://rich.readthedocs.io/en/stable/reference/progress.html#rich.progress.Progress)`]`) – Optional progress bar to track the status of the hashing.
- **exclude_tables** ([`List`](https://docs.python.org/3/library/typing.html#typing.List)`[`[`ScModel`](https://docs.sparecores.com/crawler/reference/table_bases.md#scmodel)`]`) – Optional list of tables not to be hashed.

**Returns:**

- [`Union`](https://docs.python.org/3/library/typing.html#typing.Union)`[`[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)`]` – A single SHA1 hash or dict of hashes, depending on the level.

## func <code class="doc-name">chunk_list</code> [utils.py:111–119](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/utils.py#L111-L119)

```python
chunk_list(items, size)
```

Split a list into chunks of a specified size.

**Examples:**

```pycon
>>> [len(x) for x in chunk_list(range(10), 3)]
[3, 3, 3, 1]
```

## func <code class="doc-name">scmodels_to_dict</code> [utils.py:122–147](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/utils.py#L122-L147)

```python
scmodels_to_dict(scmodels, keys)
```

Creates a dict indexed by key(s) of the ScModels of the list.

When multiple keys are provided, each ScModel instance will be stored in
the dict with all keys. If a key is a list, then each list element is
considered (not recursively, only at first level) as a key.
Conflict of keys is not checked.

**Parameters:**

- **scmodels** ([`List`](https://docs.python.org/3/library/typing.html#typing.List)`[`[`ScModel`](https://docs.sparecores.com/crawler/reference/table_bases.md#scmodel)`]`) – list of ScModel instances
- **keys** ([`List`](https://docs.python.org/3/library/typing.html#typing.List)`[`[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)`]`) – a list of strings referring to ScModel fields to be used as keys

**Examples:**

```pycon
>>> from sc_crawler.vendors import aws
>>> scmodels_to_dict([aws], keys=["vendor_id", "name"])
{'aws': Vendor...
```

## func <code class="doc-name">is_sqlite</code> [utils.py:150–152](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/utils.py#L150-L152)

```python
is_sqlite(session)
```

Checks if a SQLModel session is binded to a SQLite database.

## func <code class="doc-name">is_postgresql</code> [utils.py:155–159](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/utils.py#L155-L159)

```python
is_postgresql(session)
```

Checks if a SQLModel session is binded to a PostgreSQL-like database.

Dialect name is checked for PostgreSQL or CockroachDB.

## func <code class="doc-name">float_inf_to_str</code> [utils.py:162–164](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/utils.py#L162-L164)

```python
float_inf_to_str(x)
```

Transform to string if a float is inf.

## func <code class="doc-name">table_name_to_model</code> [utils.py:167–174](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/utils.py#L167-L174)

```python
table_name_to_model(table_name)
```

Return the ScModel schema for a table name.

## func <code class="doc-name">get_row_by_pk</code> [utils.py:177–191](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/utils.py#L177-L191)

```python
get_row_by_pk(session, model, pks)
```

Get a row from a table definition by primary keys.

**Parameters:**

- **session** (`Session`) – Connection for database connections.
- **model** ([`ScModel`](https://docs.sparecores.com/crawler/reference/table_bases.md#scmodel)) – An ScModel schema definition with table reference.
- **pks** ([`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)) – Dictionary of all the primary keys for the row,.

**Returns:**

- [`ScModel`](https://docs.sparecores.com/crawler/reference/table_bases.md#scmodel) – ScModel object read from the database.

## func <code class="doc-name">nesteddefaultdict</code> [utils.py:194–204](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/utils.py#L194-L204)

```python
nesteddefaultdict()
```

Recursive defaultdict.

**Examples:**

```pycon
>>> foo = nesteddefaultdict()
>>> foo["bar"]["baz"] = 43
>>> from json import dumps
>>> dumps(foo)
'{"bar": {"baz": 43}}'
```

## func <code class="doc-name">list_search</code> [utils.py:207–215](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/utils.py#L207-L215)

```python
list_search(items, key, values)
```

Search for a dict in a list with the given key/value pair.

When multiple values are provided, it will use the first field with a
matching name with either keys.

## func <code class="doc-name">convert_gb_to_mib</code> [utils.py:218–227](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/utils.py#L218-L227)

```python
convert_gb_to_mib(gb)
```

Convert gigabytes to mebibytes.

**Parameters:**

- **gb** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Size in gigabytes (GB, decimal: 10^9 bytes).

**Returns:**

- [`int`](https://docs.python.org/3/builtins/functions.html#int) – Size in mebibytes (MiB, binary: 2^20 bytes).
