Persist - Snailz Docs

Skip to content

# Persist

Database interface.

## `grids_to_csv(outdir, grids, tidy_grids)`

Save grids as CSV.

Source code in `src/snailz/persist.py`

    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    def grids_to_csv(outdir, grids, tidy_grids):
        """Save grids as CSV."""

        for g in grids:
            with utils.file_or_std(outdir, f"{g.grid_id}.csv", "w") as writer:
                print(g, file=writer)

        with utils.file_or_std(outdir, "grids.csv", "w") as stream:
            writer = csv.writer(stream)
            writer.writerows(tidy_grids)

## `grids_to_db(cnx, tidy_grids)`

Save all interesting grid cells in database.

Source code in `src/snailz/persist.py`

    47
    48
    49
    50
    51
    52
    def grids_to_db(cnx, tidy_grids):
        """Save all interesting grid cells in database."""

        cnx.execute(GRID_CREATE)
        cnx.executemany(GRID_INSERT, tidy_grids)
        cnx.commit()

## `objects_to_csv(stream, objects)`

Dump a list of Pydantic objects of the same class to a CSV.

Source code in `src/snailz/persist.py`

    55
    56
    57
    58
    59
    60
    61
    62
    63
    def objects_to_csv(stream, objects):
        """Dump a list of Pydantic objects of the same class to a CSV."""

        assert len(objects) > 0
        fields = _select_fields(objects[0])
        writer = csv.DictWriter(stream, fieldnames=fields)
        writer.writeheader()
        for obj in objects:
            writer.writerow(obj.model_dump(include=fields))