69 lines
2.7 KiB
Python
69 lines
2.7 KiB
Python
import clickhouse_connect
|
|
from dotenv import load_dotenv
|
|
import os
|
|
|
|
load_dotenv()
|
|
|
|
# ----- สร้าง Table ถ้ายังไม่มี -----
|
|
def create_air_quality_table():
|
|
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_db (
|
|
station_id String,
|
|
station_nameTH String,
|
|
station_nameEN String,
|
|
areaTH String,
|
|
areaEN String,
|
|
station_type String,
|
|
latitude Float64,
|
|
longitude Float64,
|
|
pm25 Float32,
|
|
pm10 Float32,
|
|
o3 Float32,
|
|
co Float32,
|
|
no2 Float32,
|
|
so2 Float32,
|
|
aqi Int32,
|
|
main_pollutant String,
|
|
record_time DateTime
|
|
) ENGINE = MergeTree()
|
|
ORDER BY (station_id, record_time)
|
|
"""
|
|
client.command(create_table_sql)
|
|
verify_air_quality_table(client)
|
|
|
|
except Exception as e:
|
|
print("❌ ClickHouse Error:", e)
|
|
|
|
def verify_air_quality_table(client):
|
|
try:
|
|
verify_table_sql = """
|
|
SHOW TABLES LIKE 'air_quality_db'
|
|
"""
|
|
result = client.command(verify_table_sql)
|
|
|
|
if result.strip():
|
|
print("✅ Table 'air_quality_db' exists.")
|
|
else:
|
|
print("❌ Table 'air_quality_db' not found.")
|
|
except Exception as e:
|
|
print("❌ Error while verifying table:", e)
|
|
|
|
if __name__ == '__main__':
|
|
create_air_quality_table()
|