55 lines
2.6 KiB
Python
55 lines
2.6 KiB
Python
import clickhouse_connect
|
|
from dotenv import load_dotenv
|
|
import os
|
|
|
|
load_dotenv()
|
|
|
|
# ----- สร้าง Table ถ้ายังไม่มี -----
|
|
def air_quality_forecast():
|
|
try:
|
|
# อ่านค่าจาก .env
|
|
ch_host = os.getenv("CLICKHOUSE_HOST").replace("https://", "")
|
|
ch_user = os.getenv("CLICKHOUSE_USER")
|
|
ch_password = os.getenv("CLICKHOUSE_PASSWORD")
|
|
|
|
# สร้าง client ด้วย clickhouse-connect
|
|
client = clickhouse_connect.get_client(
|
|
host=ch_host, # ระบุ Host โดยไม่ต้องใช้ https:// อีก
|
|
port=443, # ใช้พอร์ต HTTPS 443
|
|
username=ch_user, # ชื่อผู้ใช้
|
|
password=ch_password, # รหัสผ่าน
|
|
secure=True # ใช้การเชื่อมต่อที่ปลอดภัย (HTTPS)
|
|
)
|
|
|
|
# สร้าง Table ด้วยคำสั่ง SQL
|
|
create_table_sql = """
|
|
CREATE TABLE IF NOT EXISTS air_quality_forecast (
|
|
predicted_for_date Date, -- วันที่ที่ทำการทำนาย
|
|
predicted_aqi Int32, -- ค่า AQI ที่ทำนายได้
|
|
aqi_explain String, -- คำอธิบายหรือเหตุผลจากโมเดล
|
|
predicted_at DateTime DEFAULT now() -- วันที่-เวลาที่สร้างบันทึกนี้
|
|
) ENGINE = MergeTree()
|
|
ORDER BY predicted_for_date;
|
|
"""
|
|
client.command(create_table_sql)
|
|
verify_air_quality_forecast(client)
|
|
|
|
except Exception as e:
|
|
print("❌ ClickHouse Error:", e)
|
|
|
|
def verify_air_quality_forecast(client):
|
|
try:
|
|
verify_table_sql = """
|
|
SHOW TABLES LIKE 'air_quality_forecast'
|
|
"""
|
|
result = client.command(verify_table_sql)
|
|
|
|
if result.strip():
|
|
print("✅ Table 'air_quality_forecast' exists.")
|
|
else:
|
|
print("❌ Table 'air_quality_forecast' not found.")
|
|
except Exception as e:
|
|
print("❌ Error while verifying table:", e)
|
|
|
|
if __name__ == '__main__':
|
|
air_quality_forecast() |