# (siggen) PS C:\Github\siggen> python .\Scripts\fetch_tables.py
import pyodbc
import os, json, csv
from tqdm import tqdm
from datetime import datetime

starting_time = datetime.now()

credentials_path = os.path.join(os.getcwd(), 'Scripts', 'credentials.json')
with open(credentials_path, 'r') as file:
    credentials = json.load(file)

DSNNAME = credentials["DSNNAME"]
DBUSER = credentials["DBUSER"]
DBPWD = credentials["DBPWD"]

# 데이터베이스 연결
cnxn = pyodbc.connect(f'DSN={DSNNAME};UID={DBUSER};PWD={DBPWD};charset=utf-8')
cursor = cnxn.cursor()

schema = 'snits_siggen'
tables = ['inter_info', 'plan']

base_dir = os.path.join(os.getcwd(), 'Data', 'fetched_tables')

for table in tables:
    # 테이블 데이터 다운로드
    cursor.execute(f"SELECT * FROM {schema}.{table}")

    csv_file_path = os.path.join(base_dir, f"{table}.csv")
    with open(csv_file_path, 'w', newline='', encoding='utf-8-sig') as csvfile:
        csv_writer = csv.writer(csvfile)
        columns = [column[0] for column in cursor.description]
        csv_writer.writerow(columns)
        for row in cursor.fetchall():
            csv_writer.writerow(row)

    cnxn.close()

print("elapsed time :", datetime.now() - starting_time)