From 13ca40eaf7289f04d7c3845764b7508806ae84f2 Mon Sep 17 00:00:00 2001 From: Val Lorentz Date: Tue, 20 Sep 2022 21:31:10 +0200 Subject: [PATCH] orm: Refactor INDEX generation --- opdb/db/orm.py | 26 +++++++++++++++----------- opdb/db/orm_test.py | 5 ++++- 2 files changed, 19 insertions(+), 12 deletions(-) diff --git a/opdb/db/orm.py b/opdb/db/orm.py index cedc995..198e92d 100644 --- a/opdb/db/orm.py +++ b/opdb/db/orm.py @@ -25,6 +25,7 @@ Features: import dataclasses import datetime import json +import textwrap import typing import psycopg @@ -154,15 +155,18 @@ class BaseModel: Returns SQL code suitable to initialize a table to store instances of this class. """ - return "\n".join( - [ - f"CREATE TABLE IF NOT EXISTS {cls.TABLE} (", - ",\n".join( - f" {field.name} {_type_to_sql(field.type)}" - for field in dataclasses.fields(cls) - ), - ");", - f"CREATE UNIQUE INDEX IF NOT EXISTS {cls.TABLE}_pk ON {cls.TABLE} " - f"({', '.join(cls.PK)});", - ] + + cols = ",\n ".join( + f"{field.name} {_type_to_sql(field.type)}" + for field in dataclasses.fields(cls) + ) + return textwrap.dedent( + f"""\ + CREATE TABLE IF NOT EXISTS {cls.TABLE} ( + {cols} + ); + CREATE UNIQUE INDEX IF NOT EXISTS {cls.TABLE}_pk ON {cls.TABLE} ( + {', '.join(cls.PK)} + ); + """ ) diff --git a/opdb/db/orm_test.py b/opdb/db/orm_test.py index acd51cd..bb657bf 100644 --- a/opdb/db/orm_test.py +++ b/opdb/db/orm_test.py @@ -34,5 +34,8 @@ def test_db_schema(): response_headers jsonb NOT NULL, content bytea NOT NULL ); - CREATE UNIQUE INDEX IF NOT EXISTS web_page_snapshot_pk ON web_page_snapshot (url, snapshot_date);""" # noqa + CREATE UNIQUE INDEX IF NOT EXISTS web_page_snapshot_pk ON web_page_snapshot ( + url, snapshot_date + ); + """ )