Skip to content

Database

Create SQLite database from CSV files.

make_database(assays, people, specimens, output=None)

Create a SQLite database from CSV files.

Parameters:

Name Type Description Default
assays Path | str

Path to assays CSV file

required
people Path | str

Path to people CSV file

required
specimens Path | str

Path to specimens CSV file

required
output Path | str | None

Path to database file to create or None for in-memory database

None

Returns:

Type Description
Connection | None

sqlite3.Connection: Database connection if database is in-memory or None otherwise

Source code in src/snailz/database.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def make_database(
    assays: Path | str,
    people: Path | str,
    specimens: Path | str,
    output: Path | str | None = None,
) -> sqlite3.Connection | None:
    """Create a SQLite database from CSV files.

    Parameters:
        assays: Path to assays CSV file
        people: Path to people CSV file
        specimens: Path to specimens CSV file
        output: Path to database file to create or None for in-memory database

    Returns:
        sqlite3.Connection: Database connection if database is in-memory or None otherwise
    """
    if output is None:
        conn = sqlite3.connect(":memory:")
    else:
        Path(output).unlink(missing_ok=True)
        conn = sqlite3.connect(output)

    cursor = conn.cursor()

    for filepath, header, create, insert in (
        (assays, ASSAYS_HEADER, ASSAYS_CREATE, ASSAYS_INSERT),
        (people, PEOPLE_HEADER, PEOPLE_CREATE, PEOPLE_INSERT),
        (specimens, SPECIMENS_HEADER, SPECIMENS_CREATE, SPECIMENS_INSERT),
    ):
        with open(filepath, "r") as stream:
            data = [row for row in csv.reader(stream)]
            assert data[0] == header
            cursor.execute(create)
            cursor.executemany(insert, data[1:])

    conn.commit()

    if output is None:
        return conn
    else:
        conn.close()
        return None