Skip to content

Commit be1990b

Browse files
authored
Merge pull request CloudBotIRC#162 from linuxdaemon/gonzobot+sqlalchemy-queries
Switch most DB queries to SQLAlchemy syntax
2 parents 65b8a4a + 7218d7d commit be1990b

4 files changed

Lines changed: 87 additions & 77 deletions

File tree

plugins/history.py

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import time
44
from collections import deque
55

6-
from sqlalchemy import Table, Column, String, PrimaryKeyConstraint, Float
6+
from sqlalchemy import Table, Column, String, PrimaryKeyConstraint, Float, select
77

88
from cloudbot import hook
99
from cloudbot.event import EventType
@@ -27,11 +27,19 @@ def track_seen(event, db):
2727
:type db: sqlalchemy.orm.Session
2828
"""
2929
# keep private messages private
30+
now = time.time()
3031
if event.chan[:1] == "#" and not re.findall('^s/.*/.*/$', event.content.lower()):
31-
db.execute(
32-
"insert or replace into seen_user(name, time, quote, chan, host) values(:name,:time,:quote,:chan,:host)",
33-
{'name': event.nick.lower(), 'time': time.time(), 'quote': event.content, 'chan': event.chan,
34-
'host': event.mask})
32+
res = db.execute(
33+
table.update().values(time=now, quote=event.content, host=str(event.mask))
34+
.where(table.c.name == event.nick.lower()).where(table.c.chan == event.chan)
35+
)
36+
if res.rowcount == 0:
37+
db.execute(
38+
table.insert().values(
39+
name=event.nick.lower(), time=now, quote=event.content, chan=event.chan, host=str(event.mask)
40+
)
41+
)
42+
3543
db.commit()
3644

3745

@@ -98,18 +106,13 @@ def seen(text, nick, chan, db, event, is_nick_valid):
98106
if not is_nick_valid(text):
99107
return "I can't look up that name, its impossible to use!"
100108

101-
if '_' in text:
102-
text = text.replace("_", "/_")
103-
104-
last_seen = db.execute("SELECT name, time, quote FROM seen_user WHERE name LIKE :name ESCAPE '/' AND chan = :chan",
105-
{'name': text, 'chan': chan}).fetchone()
106-
107-
text = text.replace("/", "")
109+
last_seen = db.execute(
110+
select([table.c.name, table.c.time, table.c.quote])
111+
.where(table.c.name == text.lower()).where(table.c.chan == chan)
112+
).fetchone()
108113

109114
if last_seen:
110115
reltime = timeformat.time_since(last_seen[1])
111-
if last_seen[0] != text.lower(): # for glob matching
112-
text = last_seen[0]
113116
if last_seen[2][0:1] == "\x01":
114117
return '{} was last seen {} ago: * {} {}'.format(text, reltime, text, last_seen[2][8:-1])
115118
else:

plugins/horoscope.py

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import requests
44
from bs4 import BeautifulSoup
5-
from sqlalchemy import Table, String, Column
5+
from sqlalchemy import Table, String, Column, select
66

77
from cloudbot import hook
88
from cloudbot.util import database
@@ -15,6 +15,22 @@
1515
)
1616

1717

18+
def get_sign(db, nick):
19+
row = db.execute(select([table.c.sign]).where(table.c.nick == nick.lower())).fetchone()
20+
if not row:
21+
return None
22+
23+
return row[0]
24+
25+
26+
def set_sign(db, nick, sign):
27+
res = db.execute(table.update().values(sign=sign.lower()).where(table.c.nick == nick.lower()))
28+
if res.rowcount == 0:
29+
db.execute(table.insert().values(nick=nick.lower(), sign=sign.lower()))
30+
31+
db.commit()
32+
33+
1834
@hook.command(autohelp=False)
1935
def horoscope(text, db, bot, nick, notice, notice_doc, reply, message):
2036
"""[sign] - get your horoscope"""
@@ -43,11 +59,11 @@ def horoscope(text, db, bot, nick, notice, notice_doc, reply, message):
4359
sign = text.strip().lower()
4460

4561
if not sign:
46-
sign = db.execute("SELECT sign FROM horoscope WHERE "
47-
"nick=lower(:nick)", {'nick': nick}).fetchone()
62+
sign = get_sign(db, nick)
4863
if not sign:
4964
notice_doc()
5065
return
66+
5167
sign = sign[0].strip().lower()
5268

5369
if sign not in signs:
@@ -70,11 +86,9 @@ def horoscope(text, db, bot, nick, notice, notice_doc, reply, message):
7086
soup = BeautifulSoup(request.text)
7187

7288
horoscope_text = soup.find("div", class_="horoscope-content").find("p").text
73-
result = "\x02{}\x02 {}".format(text, horoscope_text)
89+
result = "\x02{}\x02 {}".format(sign, horoscope_text)
7490

7591
if text and not dontsave:
76-
db.execute("insert or replace into horoscope(nick, sign) values (:nick, :sign)",
77-
{'nick': nick.lower(), 'sign': sign})
78-
db.commit()
92+
set_sign(db, nick, sign)
7993

8094
message(result)

plugins/karma.py

Lines changed: 45 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from collections import defaultdict
44

55
import sqlalchemy
6-
from sqlalchemy import Table, String, Column, Integer, PrimaryKeyConstraint
6+
from sqlalchemy import Table, String, Column, Integer, PrimaryKeyConstraint, select, and_
77

88
from cloudbot import hook
99
from cloudbot.util import database
@@ -29,28 +29,28 @@ def remove_non_channel_points(db):
2929
db.commit()
3030

3131

32-
@hook.command("pp", "addpoint")
33-
def addpoint(text, nick, chan, db):
34-
"""<thing> - adds a point to the <thing>"""
32+
def update_score(nick, chan, thing, score, db):
3533
if nick.casefold() == chan.casefold():
3634
# This is a PM, don't set points in a PM
3735
return
3836

39-
text = text.strip()
40-
karma = db.execute("select score from karma where name = :name and chan = :chan and thing = :thing",
41-
{'name': nick, 'chan': chan, 'thing': text.lower()}).fetchone()
37+
thing = thing.strip()
38+
clause = and_(karma_table.c.name == nick, karma_table.c.chan == chan, karma_table.c.thing == thing.lower())
39+
karma = db.execute(select([karma_table.c.score]).where(clause)).fetchone()
4240
if karma:
43-
score = int(karma[0])
44-
score += 1
45-
db.execute("insert or replace into karma(name, chan, thing, score) values (:name, :chan, :thing, :score)",
46-
{'name': nick, 'chan': chan, 'thing': text.lower(), 'score': score})
47-
db.commit()
48-
# return "{} is now worth {} in {}'s eyes.".format(text, score, nick)
41+
score += int(karma[0])
42+
query = karma_table.update().values(score=score).where(clause)
4943
else:
50-
db.execute("insert or replace into karma(name, chan, thing, score) values (:name, :chan, :thing, :score)",
51-
{'name': nick, 'chan': chan, 'thing': text.lower(), 'score': 1})
52-
db.commit()
53-
# return "{} is now worth 1 in {}'s eyes.".format(text, nick)
44+
query = karma_table.insert().values(name=nick, chan=chan, thing=thing.lower(), score=score)
45+
46+
db.execute(query)
47+
db.commit()
48+
49+
50+
@hook.command("pp", "addpoint")
51+
def addpoint(text, nick, chan, db):
52+
"""<thing> - adds a point to the <thing>"""
53+
update_score(nick, chan, text, 1, db)
5454

5555

5656
@hook.regex(karmaplus_re)
@@ -59,56 +59,41 @@ def re_addpt(match, nick, chan, db, notice):
5959
thing = match.group().split('++')[0]
6060
if thing:
6161
addpoint(thing, nick, chan, db)
62-
# return out
6362
else:
6463
notice(pluspts(nick, chan, db))
6564

6665

6766
@hook.command("mm", "rmpoint")
6867
def rmpoint(text, nick, chan, db):
6968
"""<thing> - subtracts a point from the <thing>"""
70-
if nick.casefold() == chan.casefold():
71-
# This is a PM, don't set points in a PM
72-
return
73-
74-
text = text.strip()
75-
karma = db.execute("select score from karma where name = :name and chan = :chan and thing = :thing",
76-
{'name': nick, 'chan': chan, 'thing': text.lower()}).fetchone()
77-
if karma:
78-
score = int(karma[0])
79-
score -= 1
80-
db.execute("insert or replace into karma(name, chan, thing, score) values (:name, :chan, :thing, :score)",
81-
{'name': nick, 'chan': chan, 'thing': text.lower(), 'score': score})
82-
db.commit()
83-
# return "{} is now worth {} in {}'s eyes.".format(text, score, nick)
84-
else:
85-
db.execute("insert or replace into karma(name, chan, thing, score) values (:name, :chan, :thing, :score)",
86-
{'name': nick, 'chan': chan, 'thing': text.lower(), 'score': -1})
87-
db.commit()
88-
# return "{} is now worth -1 in {}'s eyes.".format(text, nick)
69+
update_score(nick, chan, text, -1, db)
8970

9071

9172
@hook.command("pluspts", autohelp=False)
9273
def pluspts(nick, chan, db):
9374
"""- prints the things you have liked and their scores"""
9475
output = ""
95-
likes = db.execute(
96-
"select thing, score from karma where name = :name and chan = :chan and score >= 0 order by score desc",
97-
{'name': nick, 'chan': chan}).fetchall()
76+
clause = and_(karma_table.c.name == nick, karma_table.c.chan == chan, karma_table.c.score >= 0)
77+
query = select([karma_table.c.thing, karma_table.c.score]).where(clause).order_by(karma_table.c.score.desc())
78+
likes = db.execute(query).fetchall()
79+
9880
for like in likes:
99-
output = output + str(like[0]) + " has " + str(like[1]) + " points "
81+
output += "{} has {} points ".format(like[0], like[1])
82+
10083
return output
10184

10285

10386
@hook.command("minuspts", autohelp=False)
10487
def minuspts(nick, chan, db):
10588
"""- prints the things you have disliked and their scores"""
10689
output = ""
107-
likes = db.execute(
108-
"select thing, score from karma where name = :name and chan = :chan and score <= 0 order by score",
109-
{'name': nick, 'chan': chan}).fetchall()
90+
clause = and_(karma_table.c.name == nick, karma_table.c.chan == chan, karma_table.c.score <= 0)
91+
query = select([karma_table.c.thing, karma_table.c.score]).where(clause).order_by(karma_table.c.score)
92+
likes = db.execute(query).fetchall()
93+
11094
for like in likes:
111-
output = output + str(like[0]) + " has " + str(like[1]) + " points "
95+
output += "{} has {} points ".format(like[0], like[1])
96+
11297
return output
11398

11499

@@ -118,7 +103,6 @@ def re_rmpt(match, nick, chan, db, notice):
118103
thing = match.group().split('--')[0]
119104
if thing:
120105
rmpoint(thing, nick, chan, db)
121-
# return out
122106
else:
123107
notice(minuspts(nick, chan, db))
124108

@@ -128,13 +112,15 @@ def points(text, chan, db):
128112
"""<thing> - will print the total points for <thing> in the channel."""
129113
score = 0
130114
thing = ""
131-
if text.endswith("-global") or text.endswith(" global"):
115+
if text.endswith(("-global", " global")):
132116
thing = text[:-7].strip()
133-
karma = db.execute("select score from karma where thing = :thing", {'thing': thing.lower()}).fetchall()
117+
query = select([karma_table.c.score]).where(karma_table.c.thing == thing.lower())
134118
else:
135119
text = text.strip()
136-
karma = db.execute("select score from karma where thing = :thing and chan = :chan",
137-
{'thing': text.lower(), 'chan': chan}).fetchall()
120+
query = select([karma_table.c.score]).where(karma_table.c.thing == thing.lower()).where(
121+
karma_table.c.chan == chan)
122+
123+
karma = db.execute(query).fetchall()
138124
if karma:
139125
pos = 0
140126
neg = 0
@@ -157,11 +143,14 @@ def pointstop(text, chan, db):
157143
"""- prints the top 10 things with the highest points in the channel. To see the top 10 items in all of the channels the bot sits in use .topten global."""
158144
points = defaultdict(int)
159145
if text == "global" or text == "-global":
160-
items = db.execute("select thing, score from karma").fetchall()
146+
items = db.execute(select([karma_table.c.thing, karma_table.c.score])).fetchall()
161147
out = "The top {} favorite things in all channels are: "
162148
else:
163-
items = db.execute("select thing, score from karma where chan = :chan", {'chan': chan}).fetchall()
149+
items = db.execute(
150+
select([karma_table.c.thing, karma_table.c.score]).where(karma_table.c.chan == chan)
151+
).fetchall()
164152
out = "The top {} favorite things in {} are: "
153+
165154
if items:
166155
for item in items:
167156
thing = item[0]
@@ -184,10 +173,12 @@ def pointsbottom(text, chan, db):
184173
"""- prints the top 10 things with the lowest points in the channel. To see the bottom 10 items in all of the channels the bot sits in use .bottomten global."""
185174
points = defaultdict(int)
186175
if text == "global" or text == "-global":
187-
items = db.execute("select thing, score from karma").fetchall()
176+
items = db.execute(select([karma_table.c.thing, karma_table.c.score])).fetchall()
188177
out = "The {} most hated things in all channels are: "
189178
else:
190-
items = db.execute("select thing, score from karma where chan = :chan", {'chan': chan}).fetchall()
179+
items = db.execute(
180+
select([karma_table.c.thing, karma_table.c.score]).where(karma_table.c.chan == chan)
181+
).fetchall()
191182
out = "The {} most hated things in {} are: "
192183
if items:
193184
for item in items:

plugins/librefm.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,8 +123,10 @@ def librefm(text, nick, db, notice):
123123
out += ending
124124

125125
if text and not dontsave:
126-
db.execute("insert or replace into librefm(nick, acc) values (:nick, :account)",
127-
{'nick': nick.lower(), 'account': user})
126+
res = db.execute(table.update().values(acc=user).where(table.c.nick == nick.lower()))
127+
if res.rowcount <= 0:
128+
db.execute(table.insert().values(nick=nick.lower(), acc=user))
129+
128130
db.commit()
129131
load_cache(db)
130132
return out

0 commit comments

Comments
 (0)