76 lines
1.8 KiB
Python
76 lines
1.8 KiB
Python
|
#!/usr/bin/env python3
|
||
|
|
||
|
import os, sys
|
||
|
|
||
|
from datetime import datetime
|
||
|
from pathlib import Path
|
||
|
|
||
|
from psycopg2 import connect
|
||
|
|
||
|
|
||
|
# archive (copy & delete) all entries in app_order and app_registertransaction
|
||
|
|
||
|
timestamp = datetime.now().strftime("%Y-%m-%d-%H%M%S")
|
||
|
|
||
|
archive_folder = Path("./archive")
|
||
|
orders_archive_path = archive_folder / ("orders-archive-" + timestamp + ".csv")
|
||
|
transactions_archive_path = archive_folder / ("transactions-archive-" + timestamp + ".csv")
|
||
|
|
||
|
|
||
|
if __name__ == "__main__":
|
||
|
|
||
|
exit_code = 0
|
||
|
|
||
|
try:
|
||
|
|
||
|
print(f"Starting archiving to {orders_archive_path.__str__()} and {transactions_archive_path.__str__()}...")
|
||
|
|
||
|
connection = connect(
|
||
|
user = os.environ["PGDB_USER"],
|
||
|
password = os.environ["PGDB_PASSWORD"],
|
||
|
host = os.environ["PGDB_HOST"],
|
||
|
port = os.environ["PGDB_PORT"],
|
||
|
database = os.environ["PGDB_DB"]
|
||
|
)
|
||
|
|
||
|
cur = connection.cursor()
|
||
|
|
||
|
|
||
|
# # # # #
|
||
|
|
||
|
# copy
|
||
|
|
||
|
with orders_archive_path.open("w") as of:
|
||
|
cur.copy_expert(
|
||
|
"copy (select * from app_order) to STDOUT with csv delimiter ';'",
|
||
|
of
|
||
|
)
|
||
|
|
||
|
with transactions_archive_path.open("w") as tf:
|
||
|
cur.copy_expert(
|
||
|
"copy (select * from app_registertransaction) to STDOUT with csv delimiter ';'",
|
||
|
tf
|
||
|
)
|
||
|
|
||
|
# delete
|
||
|
|
||
|
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)
|