#!/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())