You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
kmftools/weather forecast/database.py

102 lines
3.8 KiB

import mysql.connector
from mysql.connector import Error
def create_db_connection(config, logger):
"""
Maakt verbinding met de MySQL-database.
:param config: Configuratie voor databaseverbinding.
:param logger: Logger object voor loggen.
:return: De databaseverbinding
"""
try:
connection = mysql.connector.connect(
host=config['host'],
port=config['port'],
user=config['user'],
password=config['password'],
database=config['database']
)
if connection.is_connected():
logger.debug("Successfully connected to the database.")
return connection
except Error as e:
logger.error(f"Error while connecting to MySQL: {e}")
raise e
def create_table_if_not_exists(cursor, logger):
"""
Maakt de tabel aan in de database als deze nog niet bestaat.
:param cursor: De database cursor
:param logger: Logger object voor loggen.
"""
try:
# SQL query om de tabel aan te maken
create_table_query = """
CREATE TABLE IF NOT EXISTS weather_forecast (
id INT AUTO_INCREMENT PRIMARY KEY,
utc DATETIME UNIQUE NOT NULL,
temperature FLOAT NOT NULL,
weather_description VARCHAR(255) NOT NULL,
wind_speed FLOAT NOT NULL,
rain FLOAT DEFAULT 0,
solar_performance FLOAT DEFAULT 0,
sunrise DATETIME NOT NULL,
sunset DATETIME NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
"""
cursor.execute(create_table_query)
logger.debug("Weather forecast table is ready (created or exists).")
except Error as e:
logger.error(f"Error creating table: {e}")
raise e
def insert_or_update_forecast_data(cursor, utc_dt, temp, weather, wind_speed, rain, solar_performance, sunrise, sunset, logger):
"""
Voegt een record toe aan de tabel of werkt het bij als het record al bestaat.
:param cursor: De database cursor
:param utc_dt: UTC-tijd van de voorspelling
:param temp: Temperatuur
:param weather: Weersomstandigheden
:param wind_speed: Windsnelheid
:param rain: Hoeveelheid regen
:param solar_performance: Schatting van de zonneprestaties
:param sunrise: Tijd van zonsopgang
:param sunset: Tijd van zonsondergang
:param logger: Logger object voor loggen.
"""
try:
# Check of het record al bestaat
check_query = """
SELECT id FROM weather_forecast WHERE utc = %s;
"""
cursor.execute(check_query, (utc_dt,))
result = cursor.fetchone()
if result:
# Als het record bestaat, werk het dan bij
update_query = """
UPDATE weather_forecast
SET temperature = %s, weather_description = %s, wind_speed = %s, rain = %s, solar_performance = %s, sunrise = %s, sunset = %s
WHERE utc = %s;
"""
cursor.execute(update_query, (temp, weather, wind_speed,
rain, solar_performance, sunrise, sunset, utc_dt))
logger.debug(f"Updated existing record for {utc_dt}.")
else:
# Als het record niet bestaat, voeg het dan toe
insert_query = """
INSERT INTO weather_forecast (utc, temperature, weather_description, wind_speed, rain, solar_performance, sunrise, sunset)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s);
"""
cursor.execute(insert_query, (utc_dt, temp, weather,
wind_speed, rain, solar_performance, sunrise, sunset))
logger.debug(f"Inserted new record for {utc_dt}.")
except Error as e:
logger.error(f"Error inserting or updating data for {utc_dt}: {e}")
raise e