From 7fedaaf4b1bbe159a958ad60723d25ff4741aa81 Mon Sep 17 00:00:00 2001
From: Christian Heller <c.heller@plomlompom.de>
Date: Wed, 8 Jan 2025 14:55:17 +0100
Subject: [PATCH] Add field Day.days_since_millennium as step towards new
 Day.id_ system.

---
 migrations/6_add_Day_days_since_millennium.sql |  2 ++
 migrations/{init_5.sql => init_6.sql}          |  3 ++-
 plomtask/days.py                               |  9 +++++++--
 plomtask/db.py                                 | 15 +++++++++++++--
 tests/utils.py                                 |  3 ++-
 5 files changed, 26 insertions(+), 6 deletions(-)
 create mode 100644 migrations/6_add_Day_days_since_millennium.sql
 rename migrations/{init_5.sql => init_6.sql} (98%)

diff --git a/migrations/6_add_Day_days_since_millennium.sql b/migrations/6_add_Day_days_since_millennium.sql
new file mode 100644
index 0000000..75ac83d
--- /dev/null
+++ b/migrations/6_add_Day_days_since_millennium.sql
@@ -0,0 +1,2 @@
+ALTER TABLE days ADD COLUMN days_since_millennium INTEGER NOT NULL DEFAULT 0;
+
diff --git a/migrations/init_5.sql b/migrations/init_6.sql
similarity index 98%
rename from migrations/init_5.sql
rename to migrations/init_6.sql
index d539446..6de27da 100644
--- a/migrations/init_5.sql
+++ b/migrations/init_6.sql
@@ -18,7 +18,8 @@ CREATE TABLE conditions (
 );
 CREATE TABLE days (
     id TEXT PRIMARY KEY,
-    comment TEXT NOT NULL
+    comment TEXT NOT NULL,
+    days_since_millennium INTEGER NOT NULL DEFAULT 0
 );
 CREATE TABLE process_blockers (
     process INTEGER NOT NULL,
diff --git a/plomtask/days.py b/plomtask/days.py
index 1fe90ee..68bc6db 100644
--- a/plomtask/days.py
+++ b/plomtask/days.py
@@ -11,16 +11,21 @@ from plomtask.dating import valid_date
 class Day(BaseModel):
     """Individual days defined by their dates."""
     table_name = 'days'
-    to_save_simples = ['comment']
+    to_save_simples = ['comment', 'days_since_millennium']
     add_to_dict = ['todos']
     can_create_by_id = True
 
-    def __init__(self, date: str, comment: str = '') -> None:
+    def __init__(self,
+                 date: str,
+                 comment: str = '',
+                 days_since_millennium: int = -1
+                 ) -> None:
         id_ = valid_date(date)
         super().__init__(id_)
         self.date = datetime_date.fromisoformat(self.date_str)
         self.comment = comment
         self.todos: list[Todo] = []
+        self.days_since_millennium = days_since_millennium
 
     def __lt__(self, other: Self) -> bool:
         return self.date_str < other.date_str
diff --git a/plomtask/db.py b/plomtask/db.py
index fd393b8..efcc497 100644
--- a/plomtask/db.py
+++ b/plomtask/db.py
@@ -10,7 +10,7 @@ from plomtask.exceptions import (HandledException, NotFoundException,
                                  BadFormatException)
 from plomtask.dating import valid_date
 
-EXPECTED_DB_VERSION = 5
+EXPECTED_DB_VERSION = 6
 MIGRATIONS_DIR = 'migrations'
 FILENAME_DB_SCHEMA = f'init_{EXPECTED_DB_VERSION}.sql'
 PATH_DB_SCHEMA = f'{MIGRATIONS_DIR}/{FILENAME_DB_SCHEMA}'
@@ -85,7 +85,18 @@ class DatabaseMigration:
         conn.execute(f'{SQL_FOR_DB_VERSION} = {self._target_version}')
 
 
-MIGRATION_STEPS_POST_SQL: dict[int, Callable[[SqlConnection], None]] = {}
+def _mig_6_calc_days_since_millennium(conn: SqlConnection) -> None:
+    # pylint: disable=import-outside-toplevel
+    from datetime import date as dt_date
+    rows = conn.execute('SELECT * FROM days').fetchall()
+    for row in [list(r) for r in rows]:
+        row[-1] = (dt_date.fromisoformat(row[0]) - dt_date(2000, 1, 1)).days
+        conn.execute('REPLACE INTO days VALUES (?, ?, ?)', tuple(row))
+
+
+MIGRATION_STEPS_POST_SQL: dict[int, Callable[[SqlConnection], None]] = {
+    6: _mig_6_calc_days_since_millennium
+}
 
 
 class DatabaseFile:
diff --git a/tests/utils.py b/tests/utils.py
index ad31f17..41037c9 100644
--- a/tests/utils.py
+++ b/tests/utils.py
@@ -663,7 +663,8 @@ class Expected:
     @staticmethod
     def day_as_dict(date: str, comment: str = '') -> dict[str, object]:
         """Return JSON of Day to expect."""
-        return {'id': date, 'comment': comment, 'todos': []}
+        return {'id': date, 'comment': comment, 'todos': [],
+                'days_since_millennium': -1}
 
     def set_day_from_post(self, date: str, d: dict[str, Any]) -> None:
         """Set Day of date in library based on POST dict d."""
-- 
2.30.2