Skip to content

Commit 5aec2d5

Browse files
authored
Merge pull request #4748 from dev-hato/update_psycopg_3
psycopgアップデート
2 parents 98d027d + 8ad1bf5 commit 5aec2d5

7 files changed

Lines changed: 92 additions & 107 deletions

File tree

create_env.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,20 @@
22
初回動かす必要のあるスクリプト
33
"""
44

5-
from library.database import Database
5+
from library.database import execute_sql
66

77

88
def create_table() -> None:
99
"""テーブルを作成する"""
1010

11-
with Database() as _db, open(
11+
with open(
1212
"postgres/docker-entrypoint-initdb.d/02_init.sql", encoding="UTF-8"
1313
) as init_sql:
1414
sql = ""
1515
for line in init_sql.readlines():
1616
sql += line
1717
if ";" in line:
18-
_db.execute_sql(sql)
18+
execute_sql(sql)
1919
sql = ""
2020

2121

library/database.py

Lines changed: 5 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -7,29 +7,14 @@
77
import slackbot_settings as conf
88

99

10-
class Database:
11-
"""DBを操作するためのベースクラス"""
10+
def execute_sql(sql: str) -> None:
11+
"""SQLを実行する"""
1212

13-
def __init__(self):
14-
try:
15-
self.conn = psycopg.connect(conf.DB_URL)
16-
except psycopg.Error as _e:
17-
print("Can not connect to database.")
18-
raise _e
19-
20-
def __enter__(self):
21-
return self
22-
23-
def __exit__(self, exc_type, exc_value, traceback):
24-
self.conn.close()
25-
26-
def execute_sql(self, sql: str) -> None:
27-
"""SQLを実行する"""
28-
29-
with self.conn.cursor() as cursor:
13+
with psycopg.connect(conf.DB_URL) as conn:
14+
with conn.cursor() as cursor:
3015
try:
3116
cursor.execute(sql)
32-
self.conn.commit()
17+
conn.commit()
3318
print(f"Execute: {sql}")
3419
except Exception as _e:
3520
print("Can not execute sql(create_table).")

library/vocabularydb.py

Lines changed: 38 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -4,61 +4,64 @@
44

55
import psycopg
66

7-
from library.database import Database
7+
import slackbot_settings as conf
88

99

10-
class VocabularyDatabase(Database):
11-
"""パワーワードを扱うDBを操作するためのクラス"""
12-
13-
def get_word_list(self):
14-
"""パワーワードの一覧をDBから取得する"""
15-
with self.conn.cursor() as cursor:
10+
def get_word_list():
11+
"""パワーワードの一覧をDBから取得する"""
12+
with psycopg.connect(conf.DB_URL) as conn:
13+
with conn.cursor() as cursor:
1614
try:
1715
cursor.execute("SELECT no, word FROM vocabulary ORDER BY no;")
1816
results = cursor.fetchall()
1917
except psycopg.Error:
2018
print("Can not execute sql(select_list).")
2119

22-
return results
20+
return results
21+
2322

24-
def get_random_word(self):
25-
"""パワーワードをDBからランダムで取得する"""
23+
def get_random_word():
24+
"""パワーワードをDBからランダムで取得する"""
2625

27-
with self.conn.cursor() as cursor:
26+
with psycopg.connect(conf.DB_URL) as conn:
27+
with conn.cursor() as cursor:
2828
try:
2929
cursor.execute("SELECT word FROM vocabulary ORDER BY random() LIMIT 1;")
3030
results = cursor.fetchone()
3131
except psycopg.Error:
3232
print("Can not execute sql(select_random).")
3333

34-
return results
34+
return results
35+
3536

36-
def add_word(self, word: str) -> None:
37-
"""パワーワードをDBに登録する"""
37+
def add_word(word: str) -> None:
38+
"""パワーワードをDBに登録する"""
3839

39-
with self.conn.cursor() as cursor:
40+
with psycopg.connect(conf.DB_URL) as conn:
41+
with conn.cursor() as cursor:
4042
try:
4143
cursor.execute("INSERT INTO vocabulary(word) VALUES(%s);", (word,))
42-
self.conn.commit()
44+
conn.commit()
4345
except psycopg.Error:
4446
print("Can not execute sql(add).")
4547

46-
def delete_word(self, word_id: int) -> None:
47-
"""指定したidのパワーワードをDBから削除する"""
4848

49-
with self.conn.cursor() as cursor:
49+
def delete_word(word_id: int) -> None:
50+
"""指定したidのパワーワードをDBから削除する"""
51+
52+
with psycopg.connect(conf.DB_URL) as conn:
53+
with conn.cursor() as cursor:
5054
try:
5155
cursor.execute("DELETE FROM vocabulary WHERE no = %s;", (word_id,))
52-
self.conn.commit()
56+
conn.commit()
5357
except psycopg.Error:
5458
print("Can not execute sql(delete).")
5559

5660

5761
def get_vocabularys():
5862
"""一覧を表示する"""
5963

60-
with VocabularyDatabase() as v_d:
61-
result = v_d.get_word_list()
64+
result = get_word_list()
6265

6366
if len(result) > 0:
6467
slack_msg = "```"
@@ -79,17 +82,15 @@ def get_vocabularys():
7982
def add_vocabulary(msg: str) -> None:
8083
"""追加する"""
8184

82-
with VocabularyDatabase() as v_d:
83-
v_d.add_word(msg)
85+
add_word(msg)
8486

8587

8688
def show_vocabulary(word_id: int) -> str:
8789
"""指定したものを表示する"""
8890

8991
slack_msg = "該当する番号は見つからなかったっぽ!"
9092

91-
with VocabularyDatabase() as v_d:
92-
result = v_d.get_word_list()
93+
result = get_word_list()
9394

9495
cnt = 1
9596
for row in result:
@@ -106,8 +107,7 @@ def show_random_vocabulary() -> str:
106107

107108
slack_msg = "鳩は唐揚げ!!"
108109

109-
with VocabularyDatabase() as v_d:
110-
result = v_d.get_random_word()
110+
result = get_random_word()
111111

112112
if result is not None and len(result) > 0:
113113
slack_msg = result[0]
@@ -120,16 +120,15 @@ def delete_vocabulary(word_id: int) -> str:
120120

121121
slack_msg = "該当する番号は見つからなかったっぽ!"
122122

123-
with VocabularyDatabase() as v_d:
124-
result = v_d.get_word_list()
125-
cnt = 1
126-
for row in result:
127-
row_id, _ = row
128-
if cnt == word_id:
129-
delete_id = row_id
130-
v_d.delete_word(delete_id)
131-
slack_msg = "忘れたっぽ!"
132-
break
133-
cnt += 1
123+
result = get_word_list()
124+
cnt = 1
125+
for row in result:
126+
row_id, _ = row
127+
if cnt == word_id:
128+
delete_id = row_id
129+
delete_word(delete_id)
130+
slack_msg = "忘れたっぽ!"
131+
break
132+
cnt += 1
134133

135134
return slack_msg

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ name = "hato-bot"
33
version = "3.0.5"
44
description = "愛嬌のあるBot"
55
requires-python = "==3.13.1"
6-
dependencies = [ "python-dotenv==1.0.1", "requests==2.32.3", "Pillow>=7.1.2", "opencv-python==4.11.0.86", "slack-bolt==1.22.0", "slack-sdk==3.34.0", "gitpython==3.1.44", "pandas==2.2.3", "matplotlib==3.10.0", "openai==1.60.2", "discord.py==2.4.0", "misskey.py==4.1.0", "websockets==14.2", "flask==3.1.0", "markupsafe==3.0.2", "numpy==2.2.2", "emoji==2.14.1", "puremagic==1.28", "audioop-lts==0.2.1", "psycopg[binary,pool]==3.2.3", "sudden-death==0.0.1",]
6+
dependencies = [ "python-dotenv==1.0.1", "requests==2.32.3", "Pillow>=7.1.2", "opencv-python==4.11.0.86", "slack-bolt==1.22.0", "slack-sdk==3.34.0", "gitpython==3.1.44", "pandas==2.2.3", "matplotlib==3.10.0", "openai==1.60.2", "discord.py==2.4.0", "misskey.py==4.1.0", "websockets==14.2", "flask==3.1.0", "markupsafe==3.0.2", "numpy==2.2.2", "emoji==2.14.1", "puremagic==1.28", "audioop-lts==0.2.1", "psycopg[binary,pool]==3.2.4", "sudden-death==0.0.1",]
77

88
[dependency-groups]
99
dev = [ "autopep8==2.3.2", "requests-mock==1.12.1", "pylint==3.3.4", "sqlfluff==3.3.0", "mypy==1.14.1", "flake8==7.1.1", "isort==6.0.0", "pre-commit==4.1.0", "importlib-metadata==8.6.1", "toml==0.10.2", "types-toml==0.10.8.20240310", "pyink==24.10.0",]

run.py

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from concurrent.futures import ThreadPoolExecutor
1313

1414
import discord
15+
import psycopg
1516
import slack_bolt
1617
import websockets
1718
from flask import Flask, jsonify, request
@@ -27,7 +28,6 @@
2728
MisskeyClient,
2829
SlackClient,
2930
)
30-
from library.database import Database
3131
from plugins import analyze
3232

3333
app = Flask(__name__)
@@ -52,27 +52,29 @@ def on_app_mention(body):
5252
print(f"authed_users: {authed_users}")
5353
print(f"client_msg_id: {client_msg_id}")
5454

55-
with Database() as _db, _db.conn.cursor() as cursor:
56-
cursor.execute(
57-
"SELECT client_msg_id FROM slack_client_msg_id WHERE client_msg_id = %s LIMIT 1",
58-
(client_msg_id,),
59-
)
60-
61-
if cursor.fetchone():
62-
print("skip")
63-
return
64-
65-
cursor.execute(
66-
"DELETE FROM slack_client_msg_id "
67-
"WHERE created_at < CURRENT_TIMESTAMP - interval '10 minutes'",
68-
(client_msg_id,),
69-
)
70-
cursor.execute(
71-
"INSERT INTO slack_client_msg_id(client_msg_id, created_at) "
72-
"VALUES(%s, CURRENT_TIMESTAMP)",
73-
(client_msg_id,),
74-
)
75-
_db.conn.commit()
55+
with psycopg.connect(conf.DB_URL) as conn:
56+
with conn.cursor() as cursor:
57+
cursor.execute(
58+
"SELECT client_msg_id FROM slack_client_msg_id WHERE client_msg_id = %s LIMIT 1",
59+
(client_msg_id,),
60+
)
61+
62+
if cursor.fetchone():
63+
print("skip")
64+
return
65+
66+
cursor.execute(
67+
"DELETE FROM slack_client_msg_id "
68+
"WHERE created_at < CURRENT_TIMESTAMP - interval '10 minutes'",
69+
(client_msg_id,),
70+
)
71+
cursor.execute(
72+
"INSERT INTO slack_client_msg_id(client_msg_id, created_at) "
73+
"VALUES(%s, CURRENT_TIMESTAMP)",
74+
(client_msg_id,),
75+
)
76+
77+
conn.commit()
7678

7779
with ThreadPoolExecutor(max_workers=3) as tpe:
7880
for block in blocks:

uv.lock

Lines changed: 18 additions & 18 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

wait_db.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
import psycopg
88

9-
from library.database import Database
9+
from library.database import execute_sql
1010

1111

1212
def wait_db() -> None:
@@ -16,9 +16,8 @@ def wait_db() -> None:
1616

1717
for i in range(max_attempt):
1818
try:
19-
with Database() as _db:
20-
_db.execute_sql("SELECT 1")
21-
break
19+
execute_sql("SELECT 1")
20+
break
2221
except psycopg.OperationalError as _e:
2322
if i == max_attempt - 1:
2423
raise _e

0 commit comments

Comments
 (0)