feat: add created_at and updated_at to wallets and accounts (#2177)

* feat: add `created_at` and `updated_at` to wallets and accounts

the title says it all :)

* fixup!

* nitpicks :)

* fixup!

* sqlite fix

* sqlite compat

* fixup!

* mypy

* revert db py

* motorinas suggestions

* int(time()) proper default values in migration

* uncomment migration

* use now = int(time()) idiom to make code more readable

also this fixes the issue where time() is called multiple times
providing different return values for multiple invocations

---------

Co-authored-by: Pavol Rusnak <pavol@rusnak.io>
This commit is contained in:
dni ⚡
2023-12-21 12:37:56 +00:00
committed by GitHub
co-authored by Pavol Rusnak
parent 4e55ea18e5
commit 815c3e61e4
4 changed files with 137 additions and 20 deletions
+67
View File
@@ -1,4 +1,5 @@
import datetime
from time import time
from loguru import logger
from sqlalchemy.exc import OperationalError
@@ -404,3 +405,69 @@ async def m016_add_username_column_to_accounts(db):
await db.execute("ALTER TABLE accounts ADD COLUMN extra TEXT")
except OperationalError:
pass
async def m017_add_timestamp_columns_to_accounts_and_wallets(db):
"""
Adds created_at and updated_at column to accounts and wallets.
"""
try:
await db.execute(
"ALTER TABLE accounts "
f"ADD COLUMN created_at TIMESTAMP DEFAULT {db.timestamp_column_default}"
)
await db.execute(
"ALTER TABLE accounts "
f"ADD COLUMN updated_at TIMESTAMP DEFAULT {db.timestamp_column_default}"
)
await db.execute(
"ALTER TABLE wallets "
f"ADD COLUMN created_at TIMESTAMP DEFAULT {db.timestamp_column_default}"
)
await db.execute(
"ALTER TABLE wallets "
f"ADD COLUMN updated_at TIMESTAMP DEFAULT {db.timestamp_column_default}"
)
# set their wallets created_at with the first payment
await db.execute(
"""
UPDATE wallets SET created_at = (
SELECT time FROM apipayments
WHERE apipayments.wallet = wallets.id
ORDER BY time ASC LIMIT 1
)
"""
)
# then set their accounts created_at with the wallet
await db.execute(
"""
UPDATE accounts SET created_at = (
SELECT created_at FROM wallets
WHERE wallets.user = accounts.id
ORDER BY created_at ASC LIMIT 1
)
"""
)
# set all to now where they are null
now = int(time())
await db.execute(
f"""
UPDATE wallets SET created_at = {db.timestamp_placeholder}
WHERE created_at IS NULL
""",
(now,),
)
await db.execute(
f"""
UPDATE accounts SET created_at = {db.timestamp_placeholder}
WHERE created_at IS NULL
""",
(now,),
)
except OperationalError as exc:
logger.error(f"Migration 17 failed: {exc}")
pass