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, port=443, username=ch_user, password=ch_password, secure=True ) # 🔥 ลบตารางเดิม (ถ้ามี) ก่อนสร้างใหม่ drop_table_sql = "DROP TABLE IF EXISTS air_quality_forecast" client.command(drop_table_sql) print("🗑️ Table 'air_quality_forecast' dropped (if existed).") # ✅ สร้าง Table ใหม่ที่ใช้ DateTime create_table_sql = """ CREATE TABLE air_quality_forecast ( predicted_for_date DateTime, -- วันที่-เวลาที่ทำการทำนาย predicted_aqi Int32, -- ค่า AQI ที่ทำนายได้ aqi_explain String, -- คำอธิบายหรือเหตุผลจากโมเดล predicted_at DateTime DEFAULT now() -- วันที่-เวลาที่สร้างบันทึกนี้ ) ENGINE = MergeTree() ORDER BY predicted_for_date; \ """ client.command(create_table_sql) print("✅ Table 'air_quality_forecast' created successfully.") verify_air_quality_forecast(client) except Exception as e: print("❌ ClickHouse Error:", e) # ----- ตรวจสอบการสร้าง Table ----- 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()