From e1fee8b2e5a22f36394fa05f441b9e4dc6015602 Mon Sep 17 00:00:00 2001 From: suti7yk5032 Date: Sun, 7 Jul 2024 18:00:49 +0900 Subject: [PATCH] =?UTF-8?q?csv=E5=87=BA=E5=8A=9B=E3=81=AE=E3=82=B3?= =?UTF-8?q?=E3=83=BC=E3=83=89=E3=82=92=E4=BF=AE=E6=AD=A3=E3=81=9D=E3=81=AE?= =?UTF-8?q?3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dislocker.py | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/dislocker.py b/dislocker.py index e11da35..0181355 100644 --- a/dislocker.py +++ b/dislocker.py @@ -2,6 +2,7 @@ import json import discord import os import psycopg2 +from psycopg2 import sql import hashlib import string import random @@ -198,23 +199,24 @@ class Bot(discord.Client): def report_export(self, **kwargs): try: + cursor = dislocker.db.cursor() csv_file_path = self.export_dir_path + "pc_usage_history.csv" main_table = "pc_usage_history" related_table = "club_member" - cursor = dislocker.db.cursor() + # メインテーブルの列情報を取得(user_idを除く) - cursor.execute(psycopg2.sql.SQL("SELECT * FROM {} LIMIT 0").format(psycopg2.sql.Identifier(main_table))) + cursor.execute(sql.SQL("SELECT * FROM {} LIMIT 0").format(sql.Identifier(main_table))) main_columns = [desc[0] for desc in cursor.description if desc[0] != 'member_id'] # クエリを作成(列名を明確に指定) - query = psycopg2.sql.SQL(""" + query = sql.SQL(""" SELECT {main_columns}, {related_table}.name FROM {main_table} LEFT JOIN {related_table} ON {main_table}.member_id = {related_table}.id """).format( - main_columns=psycopg2.sql.SQL(', ').join([psycopg2.sql.SQL("{}.{}").format(psycopg2.sql.Identifier(main_table), psycopg2.sql.Identifier(col)) for col in main_columns]), - main_table=psycopg2.sql.Identifier(main_table), - related_table=psycopg2.sql.Identifier(related_table) + main_columns=sql.SQL(', ').join([sql.SQL("{}.{}").format(sql.Identifier(main_table), sql.Identifier(col)) for col in main_columns]), + main_table=sql.Identifier(main_table), + related_table=sql.Identifier(related_table) ) cursor.execute(query) @@ -230,9 +232,9 @@ class Bot(discord.Client): for row in rows: # nameを2番目に移動 - formatted_row = [format_datetime(row[0])] + [row[-1]] + [format_datetime(field) if field is not None else '' for field in row[1:-1]] + formatted_row = [self.format_datetime(row[0])] + [row[-1]] + [self.format_datetime(field) if field is not None else '' for field in row[1:-1]] csvwriter.writerow(formatted_row) - + print(f"テーブル '{main_table}' の内容を '{csv_file_path}' に出力しました。") result = {"result": "ok", "file_path": csv_file_path}