ari.lt/migrations/1.py
Ari Archer e1b09fd02a Implement score and hash tokens.
Signed-off-by: Ari Archer <ari@ari.lt>
2024-08-26 04:50:39 +03:00

55 lines
1.9 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Migration of token => token_digest"""
import hashlib
import os
from warnings import filterwarnings as filter_warnings
from sqlalchemy import MetaData, Table, create_engine
from sqlalchemy.engine import Engine
from sqlalchemy.orm import Session as SessionType
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql import Select, text
def main() -> int:
"""entry / main function"""
engine: Engine = create_engine(os.environ["DB"])
Session: SessionType = sessionmaker(bind=engine) # type: ignore
metadata: MetaData = MetaData()
print("Migrating token_digest...")
with Session() as session: # type: ignore
session.execute(text("ALTER TABLE comment ADD COLUMN token_digest tinyblob")) # type: ignore
metadata.clear()
comment_table = Table("comment", metadata, autoload_with=engine)
with Session() as session: # type: ignore
with session.begin(): # type: ignore
comments = session.execute(Select(comment_table)).all() # type: ignore
for comment in comments: # type: ignore
token_digest: bytes = hashlib.sha3_256(comment[-2].encode()).digest() # type: ignore
session.execute( # type: ignore
comment_table.update().where(comment_table.c.id == comment.id).values(token_digest=token_digest) # type: ignore
)
with Session() as session: # type: ignore
session.execute(text("ALTER TABLE comment DROP COLUMN token")) # type: ignore
session.execute(text("ALTER TABLE comment ADD COLUMN score INTEGER DEFAULT 0")) # type: ignore
print("token_digest has been migrated.")
return 0
if __name__ == "__main__":
assert main.__annotations__.get("return") is int, "main() should return an integer"
filter_warnings("error", category=Warning)
raise SystemExit(main())