Utilities
Row streaming, column-type inference, hashing, and SpatiaLite helpers for sqlite_minutils.
maximize_csv_field_size_limit
def maximize_csv_field_size_limit():
Increase the CSV field size limit to the maximum possible.
find_spatialite
def find_spatialite()->Optional[str]:
The [find_spatialite()](/api/utils.html#find_spatialite) function searches for the SpatiaLite <https://www.gaia-gis.it/fossil/libspatialite/index>__ SQLite extension in some common places. It returns a string path to the location, or None if SpatiaLite was not found.
You can use it in code like this:
.. code-block:: python
from fastlite import Database
from fastlite.utils import find_spatialite
db = Database("mydb.db")
spatialite = find_spatialite()
if spatialite:
db.conn.enable_load_extension(True)
db.conn.load_extension(spatialite)
# or use with db.init_spatialite like this
db.init_spatialite(find_spatialite())
suggest_column_types
def suggest_column_types(
records
):
types_for_column_types
def types_for_column_types(
all_column_types
):
column_affinity
def column_affinity(
column_type
):
decode_base64_values
def decode_base64_values(
doc
):
Format
def Format(
*args, **kwds
):
Create a collection of name/value pairs.
Example enumeration:
class Color(Enum):
… RED = 1 … BLUE = 2 … GREEN = 3
Access them by:
-
attribute access:
Color.RED
<Color.RED: 1>
-
value lookup:
Color(1)
<Color.RED: 1>
-
name lookup:
Color['RED']
<Color.RED: 1>
Enumerations can be iterated over, and know how many members they have:
len(Color)
3
list(Color)
[<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]
Methods can be added to enumerations, and members can have their own attributes – see the documentation for details.
RowsFromFileError
def RowsFromFileError(
*args, **kwargs
):
Common base class for all non-exit exceptions.
RowsFromFileBadJSON
def RowsFromFileBadJSON(
*args, **kwargs
):
Common base class for all non-exit exceptions.
RowError
def RowError(
*args, **kwargs
):
Common base class for all non-exit exceptions.
rows_from_file
def rows_from_file(
fp:<class 'BinaryIO'>, format:Optional[sqlite_minutils.utils.Format]=None,
dialect:Optional[Type[csv.Dialect]]=None, encoding:Optional[str]=None, ignore_extras:Optional[bool]=False,
extras_key:Optional[str]=None
)->Tuple[Iterable[dict], sqlite_minutils.utils.Format]:
Load a sequence of dictionaries from a file-like object containing one of four different formats.
.. code-block:: python
from fastlite.utils import rows_from_file
import io
rows, format = rows_from_file(io.StringIO("id,name\n1,Cleo")))
print(list(rows), format)
# Outputs [{'id': '1', 'name': 'Cleo'}] Format.CSV
This defaults to attempting to automatically detect the format of the data, or you can pass in an explicit format using the format= option.
Returns a tuple of (rows_generator, format_used) where rows_generator can be iterated over to return dictionaries, while format_used is a value from the fastlite.utils.Format enum:
.. code-block:: python
class Format(enum.Enum):
CSV = 1
TSV = 2
JSON = 3
NL = 4
If a CSV or TSV file includes rows with more fields than are declared in the header a fastlite.utils.RowError exception will be raised when you loop over the generator.
You can instead ignore the extra data by passing ignore_extras=True.
Or pass extras_key="rest" to put those additional values in a list in a key called rest.
:param fp: a file-like object containing binary data :param format: the format to use - omit this to detect the format :param dialect: the CSV dialect to use - omit this to detect the dialect :param encoding: the character encoding to use when reading CSV/TSV data :param ignore_extras: ignore any extra fields on rows :param extras_key: put any extra fields in a list with this key
TypeTracker
def TypeTracker():
Wrap an iterator of dictionaries and keep track of which SQLite column types are the most likely fit for each of their keys.
Example usage:
.. code-block:: python
from fastlite.utils import TypeTracker
import fastlite
db = fastlite.Database(memory=True)
tracker = TypeTracker()
rows = [{"id": "1", "name": "Cleo", "id": "2", "name": "Cardi"}]
db["creatures"].insert_all(tracker.wrap(rows))
print(tracker.types)
# Outputs {'id': 'integer', 'name': 'text'}
db["creatures"].transform(types=tracker.types)
TypeTracker.wrap
def wrap(
iterator:Iterable[dict]
)->Iterable[dict]:
Use this to loop through an existing iterator, tracking the column types as part of the iteration.
:param iterator: The iterator to wrap
TypeTracker.types
def types()->Dict[str, str]:
A dictionary mapping column names to their detected types. This can be passed to the db[table_name].transform(types=tracker.types) method.
ValueTracker
def ValueTracker():
ValueTracker.get_tests
def get_tests():
ValueTracker.test_integer
def test_integer(
value
):
ValueTracker.test_float
def test_float(
value
):
ValueTracker.guessed_type
def guessed_type():
ValueTracker.evaluate
def evaluate(
value
):
chunks
def chunks(
sequence:Iterable, size:int
)->Iterable[Iterable]:
Iterate over chunks of the sequence of the given size.
:param sequence: Any Python iterator :param size: The size of each chunk
hash_record
def hash_record(
record:Dict, keys:Optional[Iterable[str]]=None
):
record should be a Python dictionary. Returns a sha1 hash of the keys and values in that record.
If keys= is provided, uses just those keys to generate the hash.
Example usage::
from fastlite.utils import hash_record
hashed = hash_record({"name": "Cleo", "twitter": "CleoPaws"})
# Or with the keys= option:
hashed = hash_record(
{"name": "Cleo", "twitter": "CleoPaws", "age": 7},
keys=("name", "twitter")
)
:param record: Record to generate a hash for :param keys: Subset of keys to use for that hash
flatten
def flatten(
row:dict
)->dict:
Turn a nested dict e.g. {"a": {"b": 1}} into a flat dict: {"a_b": 1}
:param row: A Python dictionary, optionally with nested dictionaries