Update to use new-style db abstractions, some super stuff.

This commit is contained in:
James Vega 2004-09-17 04:21:32 +00:00
parent 90d30f6bf1
commit 0f182d67e4
9 changed files with 108 additions and 92 deletions

View File

@ -66,35 +66,36 @@ conf.registerChannelValue(conf.supybot.plugins.Dunno, 'prefixNick',
registry.Boolean(True, """Determines whether the bot will prefix the nick registry.Boolean(True, """Determines whether the bot will prefix the nick
of the user giving an invalid command to the "dunno" response.""")) of the user giving an invalid command to the "dunno" response."""))
class DunnoRecord(object):
__metaclass__ = dbi.Record
__fields__ = [
'at',
'by',
'text',
]
class DbiDunnoDB(object): class DbiDunnoDB(object):
class DunnoDB(dbi.DB): class DunnoDB(dbi.DB):
class Record(object): Record = DunnoRecord
__metaclass__ = dbi.Record
__fields__ = [ def __init__(self, filename):
'at', self.dbs = ircutils.IrcDict()
'by', self.filename = filename
'text',
]
def __init__(self):
self.filenames = sets.Set()
def _getDb(self, channel): def _getDb(self, channel):
# Why cache? It gains very little. filename = plugins.makeChannelFilename(self.filename, channel)
filename = plugins.makeChannelFilename('Dunno.db', channel) if channel in self.dbs:
self.filenames.add(filename) return self.dbs[channel]
return self.DunnoDB(filename) self.dbs[channel] = self.DunnoDB(filename)
return self.dbs[channel]
def close(self): def close(self):
for filename in self.filenames: for db in self.dbs.itervalues():
try: db.close()
db = self.DunnoDB(filename)
db.close()
except EnvironmentError:
pass
def flush(self): def flush(self):
pass pass
def add(self, channel, text, by, at): def add(self, channel, text, by, at):
db = self._getDb(channel) db = self._getDb(channel)
return db.add(db.Record(at=at, by=by, text=text)) return db.add(db.Record(at=at, by=by, text=text))
@ -112,7 +113,7 @@ class DbiDunnoDB(object):
dunno = db.get(id) dunno = db.get(id)
dunno.text = f(dunno.text) dunno.text = f(dunno.text)
db.set(id, dunno) db.set(id, dunno)
def random(self, channel): def random(self, channel):
db = self._getDb(channel) db = self._getDb(channel)
return random.choice(db) return random.choice(db)
@ -120,17 +121,17 @@ class DbiDunnoDB(object):
def search(self, channel, p): def search(self, channel, p):
db = self._getDb(channel) db = self._getDb(channel)
return db.select(p) return db.select(p)
def size(self, channel): def size(self, channel):
try: try:
db = self._getDb(channel) db = self._getDb(channel)
return itertools.ilen(db) return itertools.ilen(db)
except EnvironmentError, e: except EnvironmentError, e:
return 0 return 0
def DunnoDB(): DunnoDB = plugins.DB('Dunno',
return DbiDunnoDB() {'flat': DbiDunnoDB})
class Dunno(callbacks.Privmsg): class Dunno(callbacks.Privmsg):
"""This plugin was written initially to work with MoobotFactoids, the two """This plugin was written initially to work with MoobotFactoids, the two
of them to provide a similar-to-moobot-and-blootbot interface for factoids. of them to provide a similar-to-moobot-and-blootbot interface for factoids.
@ -139,11 +140,12 @@ class Dunno(callbacks.Privmsg):
responses.""" responses."""
callAfter = ['MoobotFactoids'] callAfter = ['MoobotFactoids']
def __init__(self): def __init__(self):
callbacks.Privmsg.__init__(self) super(Dunno, self).__init__()
self.db = DunnoDB() self.db = DunnoDB()
def die(self): def die(self):
self.db.close() self.db.close()
super(Dunno, self).die()
def invalidCommand(self, irc, msg, tokens): def invalidCommand(self, irc, msg, tokens):
channel = msg.args[0] channel = msg.args[0]

View File

@ -54,35 +54,33 @@ import supybot.privmsgs as privmsgs
import supybot.registry as registry import supybot.registry as registry
import supybot.callbacks as callbacks import supybot.callbacks as callbacks
class FunDBRecord(object):
__metaclass__ = dbi.Record
__fields__ = [
'by',
'text',
]
class DbiFunDBDB(object): class DbiFunDBDB(object):
class FunDBDB(dbi.DB): class FunDBDB(dbi.DB):
class Record(object): Record = FunDBRecord
__metaclass__ = dbi.Record
__fields__ = [
'by',
'text',
]
def __init__(self): def __init__(self, filename):
self.dbs = ircutils.IrcDict() self.dbs = ircutils.IrcDict()
self.filenames = sets.Set() self.filename = filename
def close(self): def close(self):
for filename in self.filenames: for type in self.dbs.itervalues():
try: for db in type.itervalues():
db = self.FunDBDB(filename)
db.close() db.close()
except EnvironmentError:
pass
def _getDb(self, channel, type): def _getDb(self, channel, type):
type = type.lower() type = type.lower()
if channel not in self.dbs: if channel not in self.dbs:
self.dbs[channel] = {} self.dbs[channel] = {}
if type not in self.dbs[channel]: if type not in self.dbs[channel]:
filename = type.capitalize() + '.db' filename = self.filename.replace('db', '%s.db' % type.capitalize())
filename = plugins.makeChannelFilename(filename, channel) filename = plugins.makeChannelFilename(filename, channel)
self.filenames.add(filename)
self.dbs[channel][type] = self.FunDBDB(filename) self.dbs[channel][type] = self.FunDBDB(filename)
return self.dbs[channel][type] return self.dbs[channel][type]
@ -112,8 +110,8 @@ class DbiFunDBDB(object):
db = self._getDb(channel, type) db = self._getDb(channel, type)
return itertools.ilen(db) return itertools.ilen(db)
def FunDBDB(): FunDBDB = plugins.DB('FunDB',
return DbiFunDBDB() {'flat': DbiFunDBDB})
conf.registerPlugin('FunDB') conf.registerPlugin('FunDB')
conf.registerChannelValue(conf.supybot.plugins.FunDB, 'showIds', conf.registerChannelValue(conf.supybot.plugins.FunDB, 'showIds',
@ -127,11 +125,12 @@ class FunDB(callbacks.Privmsg):
""" """
_types = ('insult', 'lart', 'praise') _types = ('insult', 'lart', 'praise')
def __init__(self): def __init__(self):
callbacks.Privmsg.__init__(self) super(FunDB, self).__init__()
self.db = FunDBDB() self.db = FunDBDB()
def die(self): def die(self):
self.db.close() self.db.close()
super(FunDB, self).die()
def _getBy(self, by): def _getBy(self, by):
try: try:

View File

@ -88,7 +88,7 @@ conf.registerChannelValue(conf.supybot.plugins.Herald, 'throttleTimeAfterPart',
class Herald(callbacks.Privmsg): class Herald(callbacks.Privmsg):
def __init__(self): def __init__(self):
callbacks.Privmsg.__init__(self) super(Herald, self).__init__()
self.db = HeraldDB(filename) self.db = HeraldDB(filename)
world.flushers.append(self.db.flush) world.flushers.append(self.db.flush)
self.lastParts = plugins.ChannelUserDictionary() self.lastParts = plugins.ChannelUserDictionary()
@ -98,7 +98,7 @@ class Herald(callbacks.Privmsg):
if self.db.flush in world.flushers: if self.db.flush in world.flushers:
world.flushers.remove(self.db.flush) world.flushers.remove(self.db.flush)
self.db.close() self.db.close()
callbacks.Privmsg.die(self) super(Herald, self).die()
def doJoin(self, irc, msg): def doJoin(self, irc, msg):
channel = msg.args[0] channel = msg.args[0]

View File

@ -385,6 +385,7 @@ class Infobot(callbacks.PrivmsgCommandAndRegexp):
self.addressed = False self.addressed = False
def die(self): def die(self):
super(Infobot, self).die()
self.db.close() self.db.close()
def _error(self, s): def _error(self, s):

View File

@ -227,10 +227,11 @@ KarmaDB = plugins.DB('Karma',
class Karma(callbacks.Privmsg): class Karma(callbacks.Privmsg):
callBefore = ('Factoids', 'MoobotFactoids', 'Infobot') callBefore = ('Factoids', 'MoobotFactoids', 'Infobot')
def __init__(self): def __init__(self):
self.db = KarmaDB()
super(Karma, self).__init__() super(Karma, self).__init__()
self.db = KarmaDB()
def die(self): def die(self):
super(Karma, self).die()
self.db.close() self.db.close()
def _normalizeThing(self, thing): def _normalizeThing(self, thing):

View File

@ -36,14 +36,13 @@ users that can be retrieved later.
__revision__ = "$Id$" __revision__ = "$Id$"
import supybot.plugins as plugins
import csv import csv
import sets import sets
import time import time
import getopt import getopt
import os.path import os.path
import operator import operator
from itertools import imap from itertools import imap
import supybot.dbi as dbi import supybot.dbi as dbi
@ -83,19 +82,21 @@ class Ignores(registry.SpaceSeparatedListOfStrings):
conf.registerUserValue(conf.users.plugins.Note, 'ignores', Ignores([], '')) conf.registerUserValue(conf.users.plugins.Note, 'ignores', Ignores([], ''))
class NoteRecord(object):
__metaclass__ = dbi.Record
__fields__ = [
'frm',
'to',
'at',
'notified',
'read',
'public',
'text',
]
class DbiNoteDB(dbi.DB): class DbiNoteDB(dbi.DB):
Mapping = 'flat' Mapping = 'flat'
class Record(object): Record = NoteRecord
__metaclass__ = dbi.Record
__fields__ = [
'frm',
'to',
'at',
'notified',
'read',
'public',
'text',
]
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
dbi.DB.__init__(self, *args, **kwargs) dbi.DB.__init__(self, *args, **kwargs)
@ -121,7 +122,7 @@ class DbiNoteDB(dbi.DB):
self.unRead[record.to].remove(record.id) self.unRead[record.to].remove(record.id)
except (KeyError, ValueError): except (KeyError, ValueError):
pass pass
def setRead(self, id): def setRead(self, id):
n = self.get(id) n = self.get(id)
n.read = True n.read = True
@ -153,20 +154,18 @@ class DbiNoteDB(dbi.DB):
id = self.add(n) id = self.add(n)
self._addCache(n) self._addCache(n)
return id return id
NoteDB = plugins.DB('Note', {'flat': DbiNoteDB}) NoteDB = plugins.DB('Note', {'flat': DbiNoteDB})
## def NoteDB():
## # XXX This should eventually be smarter.
## return DbiNoteDB(conf.supybot.directories.data.dirize('Note.db'))
class Note(callbacks.Privmsg): class Note(callbacks.Privmsg):
def __init__(self): def __init__(self):
callbacks.Privmsg.__init__(self) super(Note, self).__init__()
self.db = NoteDB() self.db = NoteDB()
def die(self): def die(self):
super(Note, self).die()
self.db.close() self.db.close()
def doPrivmsg(self, irc, msg): def doPrivmsg(self, irc, msg):
@ -318,7 +317,7 @@ class Note(callbacks.Privmsg):
assert note.frm == to, 'Odd, userid isn\'t frm either.' assert note.frm == to, 'Odd, userid isn\'t frm either.'
recipient = ircdb.users.getUser(note.to).name recipient = ircdb.users.getUser(note.to).name
return '%s (Sent to %s %s ago)' % (note.text, recipient, elapsed) return '%s (Sent to %s %s ago)' % (note.text, recipient, elapsed)
def note(self, irc, msg, args): def note(self, irc, msg, args):
"""<note id> """<note id>
@ -411,7 +410,7 @@ class Note(callbacks.Privmsg):
except KeyError: except KeyError:
irc.errorNotRegistered() irc.errorNotRegistered()
return return
def p(note): def p(note):
return not note.read and note.to == userid return not note.read and note.to == userid
if sender: if sender:

View File

@ -35,8 +35,6 @@ Maintains a Quotes database for each channel.
__revision__ = "$Id$" __revision__ = "$Id$"
import supybot.plugins as plugins
import re import re
import time import time
import getopt import getopt
@ -46,16 +44,12 @@ import supybot.dbi as dbi
import supybot.conf as conf import supybot.conf as conf
import supybot.utils as utils import supybot.utils as utils
import supybot.ircdb as ircdb import supybot.ircdb as ircdb
import supybot.plugins as plugins
import supybot.ircutils as ircutils
import supybot.privmsgs as privmsgs import supybot.privmsgs as privmsgs
import supybot.registry as registry import supybot.registry as registry
import supybot.callbacks as callbacks import supybot.callbacks as callbacks
try:
import sqlite
except ImportError:
raise callbacks.Error, 'You need to have PySQLite installed to use this '\
'plugin. Download it at <http://pysqlite.sf.net/>'
conf.registerPlugin('Quotes') conf.registerPlugin('Quotes')
conf.registerGlobalValue(conf.supybot.plugins.Quotes, 'requireRegistration', conf.registerGlobalValue(conf.supybot.plugins.Quotes, 'requireRegistration',
registry.Boolean(False, """Determines whether the bot should require people registry.Boolean(False, """Determines whether the bot should require people
@ -81,13 +75,31 @@ class QuoteRecord(object):
time.strftime(format, time.localtime(float(self.at)))) time.strftime(format, time.localtime(float(self.at))))
class SqliteQuotesDB(object): class SqliteQuotesDB(object):
def __init__(self, filename):
self.dbs = ircutils.IrcDict()
self.filename = filename
def close(self):
for db in self.dbs.itervalues():
db.close()
def _getDb(self, channel): def _getDb(self, channel):
filename = plugins.makeChannelFilename('Quotes.db', channel) try:
import sqlite
except ImportError:
raise callbacks.Error, 'You need to have PySQLite installed to ' \
'use this plugin. Download it at ' \
'<http://pysqlite.sf.net/>'
filename = plugins.makeChannelFilename(self.filename, channel)
if channel in self.dbs:
return self.dbs[channel]
if os.path.exists(filename): if os.path.exists(filename):
return sqlite.connect(db=filename, mode=0755, self.dbs[channel] = sqlite.connect(db=filename, mode=0755,
converters={'bool': bool}) converters={'bool': bool})
return self.dbs[channel]
#else: #else:
db = sqlite.connect(db=filename, mode=0755, coverters={'bool': bool}) db = sqlite.connect(db=filename, mode=0755, coverters={'bool': bool})
self.dbs[channel] = db
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""CREATE TABLE quotes ( cursor.execute("""CREATE TABLE quotes (
id INTEGER PRIMARY KEY, id INTEGER PRIMARY KEY,
@ -184,13 +196,17 @@ class SqliteQuotesDB(object):
raise dbi.NoRecordError, id raise dbi.NoRecordError, id
db.commit() db.commit()
def QuotesDB(): QuotesDB = plugins.DB('Quotes',
return SqliteQuotesDB() {'sqlite': SqliteQuotesDB})
class Quotes(callbacks.Privmsg): class Quotes(callbacks.Privmsg):
def __init__(self): def __init__(self):
super(Quotes, self).__init__()
self.db = QuotesDB() self.db = QuotesDB()
callbacks.Privmsg.__init__(self)
def die(self):
super(Quotes, self).die()
self.db.close()
def add(self, irc, msg, args): def add(self, irc, msg, args):
"""[<channel>] <quote> """[<channel>] <quote>

View File

@ -35,8 +35,6 @@ Keeps track of the last time a user was seen on a channel.
__revision__ = "$Id$" __revision__ = "$Id$"
import supybot.plugins as plugins
import os import os
import re import re
import sets import sets
@ -88,7 +86,7 @@ class Seen(callbacks.Privmsg):
def __init__(self): def __init__(self):
self.db = SeenDB(filename) self.db = SeenDB(filename)
world.flushers.append(self.db.flush) world.flushers.append(self.db.flush)
callbacks.Privmsg.__init__(self) super(Seen, self).__init__()
def die(self): def die(self):
if self.db.flush in world.flushers: if self.db.flush in world.flushers:
@ -96,7 +94,7 @@ class Seen(callbacks.Privmsg):
else: else:
self.log.debug('Odd, no flush in flushers: %r', world.flushers) self.log.debug('Odd, no flush in flushers: %r', world.flushers)
self.db.close() self.db.close()
callbacks.Privmsg.die(self) super(Seen, self).die()
def doPrivmsg(self, irc, msg): def doPrivmsg(self, irc, msg):
if ircutils.isChannel(msg.args[0]): if ircutils.isChannel(msg.args[0]):
@ -166,7 +164,7 @@ class Seen(callbacks.Privmsg):
(name, utils.timeElapsed(time.time()-when), said)) (name, utils.timeElapsed(time.time()-when), said))
except KeyError: except KeyError:
irc.reply('I have not seen %s.' % name) irc.reply('I have not seen %s.' % name)
Class = Seen Class = Seen

View File

@ -71,7 +71,7 @@ class WordStatsDB(plugins.ChannelUserDB):
def close(self): def close(self):
if self.channelWords: if self.channelWords:
plugins.ChannelUserDB.close(self) plugins.ChannelUserDB.close(self)
def serialize(self, v): def serialize(self, v):
L = [] L = []
for (word, count) in v.iteritems(): for (word, count) in v.iteritems():
@ -178,7 +178,7 @@ filename=os.path.join(conf.supybot.directories.data(), 'WordStats.db')
class WordStats(callbacks.Privmsg): class WordStats(callbacks.Privmsg):
noIgnore = True noIgnore = True
def __init__(self): def __init__(self):
callbacks.Privmsg.__init__(self) super(WordStats, self).__init__()
self.db = WordStatsDB(filename) self.db = WordStatsDB(filename)
self.queried = False self.queried = False
world.flushers.append(self.db.flush) world.flushers.append(self.db.flush)
@ -187,7 +187,7 @@ class WordStats(callbacks.Privmsg):
if self.db.flush in world.flushers: if self.db.flush in world.flushers:
world.flushers.remove(self.db.flush) world.flushers.remove(self.db.flush)
self.db.close() self.db.close()
callbacks.Privmsg.die(self) super(WordStats, self).die()
def callCommand(self, *args, **kwargs): def callCommand(self, *args, **kwargs):
self.queried = True self.queried = True