#!/usr/bin/python import psycopg2 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 def add_item(db_settings, itemid, skuid, choice, attributes): connection = connect_db(db_settings) cursor = connection.cursor() cursor.execute(""" INSERT INTO item (itemid, skuid, choice, attributes) VALUES (%s, %s, %s, %s) """, (itemid, skuid, choice, attributes)) connection.commit() connection.close() def add_history_entry(db_settings, itemid, skuid, choice, attributes, 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: add_item(db_settings, itemid, skuid, choice, attributes) 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() 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[], 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")