109 lines
3.0 KiB
Python
Raw Normal View History

2023-12-28 13:38:21 +01:00
#!/usr/bin/python
import psycopg2
2024-01-13 23:13:11 +01:00
import csv
import os
2023-12-28 13:38:21 +01:00
def connect_db(db_settings):
conn = None
print("Connecting to the PostgreSQL database...")
try:
conn = psycopg2.connect(**db_settings)
print("Connection success")
except (Exception, psycopg2.DatabaseError) as error:
print(error)
return conn
2024-01-24 14:44:08 +01:00
def add_item(db_settings, itemid, skuid, choice, attributes, image):
connection = connect_db(db_settings)
cursor = connection.cursor()
cursor.execute("""
2024-01-24 14:44:08 +01:00
INSERT INTO item (itemid, skuid, choice, attributes, image)
VALUES (%s, %s, %s, %s, %s)
""", (itemid, skuid, choice, attributes, image))
connection.commit()
connection.close()
2024-01-24 14:44:08 +01:00
def add_history_entry(db_settings, itemid, skuid, choice, attributes, image, price, currency, quantity, discount_percentage):
connection = connect_db(db_settings)
cursor = connection.cursor()
cursor.execute("""
SELECT *
FROM item
WHERE itemid = %s
AND skuid = %s
""", (itemid, skuid))
if cursor.rowcount == 0:
2024-01-24 14:44:08 +01:00
add_item(db_settings, itemid, skuid, choice, attributes, image)
cursor.execute("""
INSERT INTO history (itemid, skuid, price, currency, quantity, discount_percentage, h_timestamp)
VALUES (%s, %s, %s, %s, %s, %s, (SELECT LOCALTIMESTAMP))
""", (itemid, skuid, price, currency, quantity, discount_percentage))
connection.commit()
connection.close()
2024-01-13 23:13:11 +01:00
def export_csv(db_settings):
connection = connect_db(db_settings)
cursor = connection.cursor()
cursor.execute("""
2024-01-24 14:44:08 +01:00
SELECT i.itemid, i.skuid, i.choice, i.attributes, i.image, h.quantity, h.discount_percentage, h.price, h.currency, h.h_timestamp
2024-01-13 23:13:11 +01:00
FROM item i, history h
WHERE i.itemid = h.itemid and i.skuid = h.skuid
""")
results = cursor.fetchall()
with open(os.path.dirname(os.path.realpath(__file__))+"/output.csv", 'w') as csv_file:
# Create a CSV writer
writer = csv.writer(csv_file)
# write the column names
writer.writerow([col[0] for col in cursor.description])
# write the query results
writer.writerows(results)
cursor.close()
connection.close()
def initialize(db_settings):
connection = connect_db(db_settings)
cursor = connection.cursor()
cursor.execute("""
DROP TABLE IF EXISTS history
""")
cursor.execute("""
DROP TABLE IF EXISTS item
""")
cursor.execute("""
CREATE TABLE item
(
itemid bigint,
skuid bigint,
choice boolean,
attributes text[],
2024-01-24 14:44:08 +01:00
image text,
primary key (itemid,skuid)
)
""")
cursor.execute("""
CREATE TABLE history
(
itemid bigint,
skuid bigint,
quantity integer,
discount_percentage numeric(2),
price money,
currency varchar(4),
h_timestamp timestamp,
foreign key (itemid,skuid) references item(itemid,skuid),
primary key (itemid,skuid,h_timestamp)
)
""")
connection.commit()
connection.close()
print("Database initialized")