Coverage for src/retrospeedlab/lake/results/postgres.py: 54%
26 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-12-02 22:44 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-12-02 22:44 +0000
1from typing import LiteralString
3import psycopg
4from psycopg import sql
5from pyspark.sql import DataFrame
6from pyspark.sql.types import (
7 BooleanType,
8 DataType,
9 DateType,
10 DoubleType,
11 IntegerType,
12 LongType,
13 StringType,
14 StructField,
15 TimestampType,
16)
18from retrospeedlab.lake.settings import PostgresSettings
20COLUMN_TYPES: dict[type[DataType], LiteralString] = {
21 StringType: "text",
22 IntegerType: "integer",
23 LongType: "bigint",
24 DoubleType: "double precision",
25 BooleanType: "boolean",
26 TimestampType: "timestamptz",
27 DateType: "date",
28}
29UTC_SESSION = "-c timezone=UTC"
32def column(field: StructField) -> sql.Composable:
33 kind = type(field.dataType)
34 if kind not in COLUMN_TYPES:
35 raise ValueError(f"the column {field.name} has the type {field.dataType}, which Postgres is not given")
36 return sql.SQL("{} {}").format(sql.Identifier(field.name), sql.SQL(COLUMN_TYPES[kind]))
39def replace_table(cursor: psycopg.Cursor[tuple[object, ...]], name: str, rows: DataFrame) -> int:
40 table = sql.Identifier(name)
41 columns = sql.SQL(", ").join(column(field) for field in rows.schema.fields)
42 cursor.execute(sql.SQL("DROP TABLE IF EXISTS {}").format(table))
43 cursor.execute(sql.SQL("CREATE TABLE {} ({})").format(table, columns))
44 collected = rows.collect()
45 with cursor.copy(sql.SQL("COPY {} FROM STDIN").format(table)) as copy:
46 for row in collected:
47 copy.write_row([row[name] for name in rows.columns])
48 return len(collected)
51def publish(database: PostgresSettings, tables: dict[str, DataFrame]) -> int:
52 with (
53 psycopg.connect(
54 host=database.host,
55 port=database.port,
56 dbname=database.name,
57 user=database.user,
58 password=database.password,
59 options=UTC_SESSION,
60 ) as connection,
61 connection.cursor() as cursor,
62 ):
63 return sum(replace_table(cursor, name, rows) for name, rows in tables.items())