57 lines
2 KiB
Python
Executable file
57 lines
2 KiB
Python
Executable file
#!/usr/bin/env python3
|
|
|
|
from datetime import datetime
|
|
from pathlib import Path
|
|
|
|
from psycopg2 import connect
|
|
from yaml import safe_load
|
|
|
|
|
|
base_directory = Path(__file__).parent.parent
|
|
data_directory = base_directory / "data"
|
|
configuration_file = data_directory / "config.yml"
|
|
archive_directory = data_directory / "archive"
|
|
|
|
|
|
if __name__ == "__main__":
|
|
exit_code = 0
|
|
try:
|
|
# read config
|
|
with configuration_file.open("r") as f:
|
|
config = safe_load(f)
|
|
# connect to database
|
|
connection = connect(
|
|
user = config["db"]["user"],
|
|
password = config["db"]["password"],
|
|
host = config["db"]["host"],
|
|
port = config["db"]["port"],
|
|
database = config["db"]["database"]
|
|
)
|
|
cur = connection.cursor()
|
|
# copy data from database
|
|
timestamp = datetime.now().strftime("%Y-%m-%d-%H%M%S")
|
|
orders_archive_path = archive_directory / f"orders-archive-{timestamp}.csv"
|
|
transactions_archive_path = archive_directory / f"transactions-archive-{timestamp}.csv"
|
|
print(f"Copying data...")
|
|
with orders_archive_path.open("w") as of:
|
|
cur.copy_expert(
|
|
"copy (select * from app_order) to STDOUT with csv delimiter ';'", of)
|
|
print(str(orders_archive_path))
|
|
with transactions_archive_path.open("w") as tf:
|
|
cur.copy_expert(
|
|
"copy (select * from app_registertransaction) to STDOUT with csv delimiter ';'", tf)
|
|
print(str(transactions_archive_path))
|
|
# delete data from database
|
|
print("Deleting data from database...")
|
|
cur.execute("delete from app_order;")
|
|
cur.execute("delete from app_registertransaction;")
|
|
connection.commit()
|
|
print("done.")
|
|
except (Error, Exception) as err:
|
|
connection.rollback()
|
|
print(f"An error occured while upgrading the database at {os.environ['PGDB_HOST']}:\n{err}")
|
|
exit_code = 1
|
|
finally:
|
|
cur.close()
|
|
connection.close()
|
|
exit(exit_code)
|