This merges an old branch i had for sqlite3 factoids+moobotfactoids.

fix up moobotfactoids+factoids to use the sqlite text_factory=str,
also fixed up a test for factoid search, since it now sorts keys alphabetically.
This commit is contained in:
Daniel Folkinshteyn 2010-03-21 02:25:11 -04:00 committed by Valentin Lorentz
parent c0ebdddb47
commit f71464adb3
4 changed files with 190 additions and 147 deletions

View File

@ -42,12 +42,21 @@ import supybot.callbacks as callbacks
from supybot.i18n import PluginInternationalization, internationalizeDocstring from supybot.i18n import PluginInternationalization, internationalizeDocstring
_ = PluginInternationalization('Factoids') _ = PluginInternationalization('Factoids')
#try:
#import sqlite3 as sqlite
#except ImportError:
#raise callbacks.Error, 'You need to have PySQLite installed to use this ' \
#'plugin. Download it at ' \
#'<http://code.google.com/p/pysqlite/>'
try: try:
import sqlite import sqlite3
except ImportError: except ImportError:
raise callbacks.Error, 'You need to have PySQLite installed to use this ' \ from pysqlite2 import dbapi2 as sqlite3 # for python2.4
'plugin. Download it at ' \
'<http://code.google.com/p/pysqlite/>' # these are needed cuz we are overriding getdb
import threading
import supybot.world as world
def getFactoid(irc, msg, args, state): def getFactoid(irc, msg, args, state):
assert not state.channel assert not state.channel
@ -85,8 +94,11 @@ class Factoids(callbacks.Plugin, plugins.ChannelDBHandler):
def makeDb(self, filename): def makeDb(self, filename):
if os.path.exists(filename): if os.path.exists(filename):
return sqlite.connect(filename) db = sqlite3.connect(filename)
db = sqlite.connect(filename) db.text_factory = str
return db
db = sqlite3.connect(filename)
db.text_factory = str
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""CREATE TABLE keys ( cursor.execute("""CREATE TABLE keys (
id INTEGER PRIMARY KEY, id INTEGER PRIMARY KEY,
@ -110,6 +122,20 @@ class Factoids(callbacks.Plugin, plugins.ChannelDBHandler):
db.commit() db.commit()
return db return db
# override this because sqlite3 doesn't have autocommit
# use isolation_level instead.
def getDb(self, channel):
"""Use this to get a database for a specific channel."""
currentThread = threading.currentThread()
if channel not in self.dbCache and currentThread == world.mainThread:
self.dbCache[channel] = self.makeDb(self.makeFilename(channel))
if currentThread != world.mainThread:
db = self.makeDb(self.makeFilename(channel))
else:
db = self.dbCache[channel]
db.isolation_level = None
return db
def getCommandHelp(self, command, simpleSyntax=None): def getCommandHelp(self, command, simpleSyntax=None):
method = self.getCommandMethod(command) method = self.getCommandMethod(command)
if method.im_func.func_name == 'learn': if method.im_func.func_name == 'learn':
@ -131,12 +157,14 @@ class Factoids(callbacks.Plugin, plugins.ChannelDBHandler):
def learn(self, irc, msg, args, channel, key, factoid): def learn(self, irc, msg, args, channel, key, factoid):
db = self.getDb(channel) db = self.getDb(channel)
cursor = db.cursor() cursor = db.cursor()
cursor.execute("SELECT id, locked FROM keys WHERE key LIKE %s", key) cursor.execute("SELECT id, locked FROM keys WHERE key LIKE ?", (key,))
if cursor.rowcount == 0: results = cursor.fetchall()
cursor.execute("""INSERT INTO keys VALUES (NULL, %s, 0)""", key) if len(results) == 0:
cursor.execute("""INSERT INTO keys VALUES (NULL, ?, 0)""", (key,))
db.commit() db.commit()
cursor.execute("SELECT id, locked FROM keys WHERE key LIKE %s",key) cursor.execute("SELECT id, locked FROM keys WHERE key LIKE ?", (key,))
(id, locked) = map(int, cursor.fetchone()) results = cursor.fetchall()
(id, locked) = map(int, results[0])
capability = ircdb.makeChannelCapability(channel, 'factoids') capability = ircdb.makeChannelCapability(channel, 'factoids')
if not locked: if not locked:
if ircdb.users.hasUser(msg.prefix): if ircdb.users.hasUser(msg.prefix):
@ -144,8 +172,8 @@ class Factoids(callbacks.Plugin, plugins.ChannelDBHandler):
else: else:
name = msg.nick name = msg.nick
cursor.execute("""INSERT INTO factoids VALUES cursor.execute("""INSERT INTO factoids VALUES
(NULL, %s, %s, %s, %s, %s)""", (NULL, ?, ?, ?, ?, ?)""",
id, name, int(time.time()), 0, factoid) (id, name, int(time.time()), 0, factoid))
db.commit() db.commit()
irc.replySuccess() irc.replySuccess()
else: else:
@ -165,9 +193,9 @@ class Factoids(callbacks.Plugin, plugins.ChannelDBHandler):
db = self.getDb(channel) db = self.getDb(channel)
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""SELECT factoids.fact, factoids.id FROM factoids, keys cursor.execute("""SELECT factoids.fact, factoids.id FROM factoids, keys
WHERE keys.key LIKE %s AND factoids.key_id=keys.id WHERE keys.key LIKE ? AND factoids.key_id=keys.id
ORDER BY factoids.id ORDER BY factoids.id
LIMIT 20""", key) LIMIT 20""", (key,))
return cursor.fetchall() return cursor.fetchall()
#return [t[0] for t in cursor.fetchall()] #return [t[0] for t in cursor.fetchall()]
@ -178,9 +206,9 @@ class Factoids(callbacks.Plugin, plugins.ChannelDBHandler):
for (fact,id) in factoids: for (fact,id) in factoids:
cursor.execute("""SELECT factoids.usage_count cursor.execute("""SELECT factoids.usage_count
FROM factoids FROM factoids
WHERE factoids.id=%s""", id) WHERE factoids.id=?""", (id,))
old_count = cursor.fetchall()[0][0] old_count = cursor.fetchall()[0][0]
cursor.execute("UPDATE factoids SET usage_count=%s WHERE id=%s", old_count + 1, id) cursor.execute("UPDATE factoids SET usage_count=? WHERE id=?", (old_count + 1, id,))
db.commit() db.commit()
def _replyFactoids(self, irc, msg, key, channel, factoids, def _replyFactoids(self, irc, msg, key, channel, factoids,
@ -257,7 +285,7 @@ class Factoids(callbacks.Plugin, plugins.ChannelDBHandler):
FROM keys, factoids FROM keys, factoids
WHERE factoids.key_id=keys.id WHERE factoids.key_id=keys.id
ORDER BY factoids.usage_count DESC ORDER BY factoids.usage_count DESC
LIMIT %s""", numfacts) LIMIT ?""", (numfacts,))
factkeys = cursor.fetchall() factkeys = cursor.fetchall()
s = [ "#%d %s (%d)" % (i+1, key[0], key[1]) for i, key in enumerate(factkeys) ] s = [ "#%d %s (%d)" % (i+1, key[0], key[1]) for i, key in enumerate(factkeys) ]
irc.reply(", ".join(s)) irc.reply(", ".join(s))
@ -273,7 +301,7 @@ class Factoids(callbacks.Plugin, plugins.ChannelDBHandler):
""" """
db = self.getDb(channel) db = self.getDb(channel)
cursor = db.cursor() cursor = db.cursor()
cursor.execute("UPDATE keys SET locked=1 WHERE key LIKE %s", key) cursor.execute("UPDATE keys SET locked=1 WHERE key LIKE ?", (key,))
db.commit() db.commit()
irc.replySuccess() irc.replySuccess()
lock = wrap(lock, ['channel', 'text']) lock = wrap(lock, ['channel', 'text'])
@ -288,7 +316,7 @@ class Factoids(callbacks.Plugin, plugins.ChannelDBHandler):
""" """
db = self.getDb(channel) db = self.getDb(channel)
cursor = db.cursor() cursor = db.cursor()
cursor.execute("UPDATE keys SET locked=0 WHERE key LIKE %s", key) cursor.execute("UPDATE keys SET locked=0 WHERE key LIKE ?", (key,))
db.commit() db.commit()
irc.replySuccess() irc.replySuccess()
unlock = wrap(unlock, ['channel', 'text']) unlock = wrap(unlock, ['channel', 'text'])
@ -317,32 +345,33 @@ class Factoids(callbacks.Plugin, plugins.ChannelDBHandler):
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""SELECT keys.id, factoids.id cursor.execute("""SELECT keys.id, factoids.id
FROM keys, factoids FROM keys, factoids
WHERE key LIKE %s AND WHERE key LIKE ? AND
factoids.key_id=keys.id""", key) factoids.key_id=keys.id""", (key,))
if cursor.rowcount == 0: results = cursor.fetchall()
if len(results) == 0:
irc.error(_('There is no such factoid.')) irc.error(_('There is no such factoid.'))
elif cursor.rowcount == 1 or number is True: elif len(results) == 1 or number is True:
(id, foo) = cursor.fetchone() (id, _) = results[0]
cursor.execute("""DELETE FROM factoids WHERE key_id=%s""", id) cursor.execute("""DELETE FROM factoids WHERE key_id=?""", (id,))
cursor.execute("""DELETE FROM keys WHERE key LIKE %s""", key) cursor.execute("""DELETE FROM keys WHERE key LIKE ?""", (key,))
db.commit() db.commit()
irc.replySuccess() irc.replySuccess()
else: else:
if number is not None: if number is not None:
results = cursor.fetchall() #results = cursor.fetchall()
try: try:
(foo, id) = results[number-1] (foo, id) = results[number-1]
except IndexError: except IndexError:
irc.error(_('Invalid factoid number.')) irc.error(_('Invalid factoid number.'))
return return
cursor.execute("DELETE FROM factoids WHERE id=%s", id) cursor.execute("DELETE FROM factoids WHERE id=?", (id,))
db.commit() db.commit()
irc.replySuccess() irc.replySuccess()
else: else:
irc.error(_('%s factoids have that key. ' irc.error(_('%s factoids have that key. '
'Please specify which one to remove, ' 'Please specify which one to remove, '
'or use * to designate all of them.') % 'or use * to designate all of them.') %
cursor.rowcount) len(results))
forget = wrap(forget, ['channel', many('something')]) forget = wrap(forget, ['channel', many('something')])
@internationalizeDocstring @internationalizeDocstring
@ -357,10 +386,11 @@ class Factoids(callbacks.Plugin, plugins.ChannelDBHandler):
cursor.execute("""SELECT fact, key_id FROM factoids cursor.execute("""SELECT fact, key_id FROM factoids
ORDER BY random() ORDER BY random()
LIMIT 3""") LIMIT 3""")
if cursor.rowcount != 0: results = cursor.fetchall()
if len(results) != 0:
L = [] L = []
for (factoid, id) in cursor.fetchall(): for (factoid, id) in results:
cursor.execute("""SELECT key FROM keys WHERE id=%s""", id) cursor.execute("""SELECT key FROM keys WHERE id=?""", (id,))
(key,) = cursor.fetchone() (key,) = cursor.fetchone()
L.append('"%s": %s' % (ircutils.bold(key), factoid)) L.append('"%s": %s' % (ircutils.bold(key), factoid))
irc.reply('; '.join(L)) irc.reply('; '.join(L))
@ -378,14 +408,15 @@ class Factoids(callbacks.Plugin, plugins.ChannelDBHandler):
""" """
db = self.getDb(channel) db = self.getDb(channel)
cursor = db.cursor() cursor = db.cursor()
cursor.execute("SELECT id, locked FROM keys WHERE key LIKE %s", key) cursor.execute("SELECT id, locked FROM keys WHERE key LIKE ?", (key,))
if cursor.rowcount == 0: results = cursor.fetchall()
if len(results) == 0:
irc.error(_('No factoid matches that key.')) irc.error(_('No factoid matches that key.'))
return return
(id, locked) = map(int, cursor.fetchone()) (id, locked) = map(int, results[0])
cursor.execute("""SELECT added_by, added_at FROM factoids cursor.execute("""SELECT added_by, added_at FROM factoids
WHERE key_id=%s WHERE key_id=?
ORDER BY id""", id) ORDER BY id""", (id,))
factoids = cursor.fetchall() factoids = cursor.fetchall()
L = [] L = []
counter = 0 counter = 0
@ -413,16 +444,17 @@ class Factoids(callbacks.Plugin, plugins.ChannelDBHandler):
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""SELECT factoids.id, factoids.fact cursor.execute("""SELECT factoids.id, factoids.fact
FROM keys, factoids FROM keys, factoids
WHERE keys.key LIKE %s AND WHERE keys.key LIKE ? AND
keys.id=factoids.key_id""", key) keys.id=factoids.key_id""", (key,))
if cursor.rowcount == 0: results = cursor.fetchall()
if len(results) == 0:
irc.error(format(_('I couldn\'t find any key %q'), key)) irc.error(format(_('I couldn\'t find any key %q'), key))
return return
elif cursor.rowcount < number: elif len(results) < number:
irc.errorInvalid(_('key id')) irc.errorInvalid('key id')
(id, fact) = cursor.fetchall()[number-1] (id, fact) = results[number-1]
newfact = replacer(fact) newfact = replacer(fact)
cursor.execute("UPDATE factoids SET fact=%s WHERE id=%s", newfact, id) cursor.execute("UPDATE factoids SET fact=? WHERE id=?", (newfact, id))
db.commit() db.commit()
irc.replySuccess() irc.replySuccess()
change = wrap(change, ['channel', 'something', change = wrap(change, ['channel', 'something',
@ -458,7 +490,7 @@ class Factoids(callbacks.Plugin, plugins.ChannelDBHandler):
db.create_function(predicateName, 1, p) db.create_function(predicateName, 1, p)
predicateName += 'p' predicateName += 'p'
for glob in globs: for glob in globs:
criteria.append('TARGET LIKE %s') criteria.append('TARGET LIKE ?')
formats.append(glob.translate(self._sqlTrans)) formats.append(glob.translate(self._sqlTrans))
cursor = db.cursor() cursor = db.cursor()
sql = """SELECT keys.key FROM %s WHERE %s""" % \ sql = """SELECT keys.key FROM %s WHERE %s""" % \
@ -474,8 +506,17 @@ class Factoids(callbacks.Plugin, plugins.ChannelDBHandler):
elif cursor.rowcount > 100: elif cursor.rowcount > 100:
irc.reply(_('More than 100 keys matched that query; ' irc.reply(_('More than 100 keys matched that query; '
'please narrow your query.')) 'please narrow your query.'))
results = cursor.fetchall()
if len(results) == 0:
irc.reply(_('No keys matched that query.'))
elif len(results) == 1 and \
self.registryValue('showFactoidIfOnlyOneMatch', channel):
self.whatis(irc, msg, [results[0][0]])
elif len(results) > 100:
irc.reply(_('More than 100 keys matched that query; '
'please narrow your query.'))
else: else:
keys = [repr(t[0]) for t in cursor.fetchall()] keys = [repr(t[0]) for t in results]
s = format('%L', keys) s = format('%L', keys)
irc.reply(s) irc.reply(s)
search = wrap(search, ['channel', search = wrap(search, ['channel',

View File

@ -99,8 +99,8 @@ if sqlite:
self.assertRegexp('factoids search --regexp m/^j/ *ss*', self.assertRegexp('factoids search --regexp m/^j/ *ss*',
'jamessan') 'jamessan')
self.assertRegexp('factoids search --regexp /^j/', self.assertRegexp('factoids search --regexp /^j/',
'jemfinch.*jamessan') 'jamessan.*jemfinch')
self.assertRegexp('factoids search j*', 'jemfinch.*jamessan') self.assertRegexp('factoids search j*', 'jamessan.*jemfinch')
self.assertRegexp('factoids search *ke*', self.assertRegexp('factoids search *ke*',
'inkedmn.*strike|strike.*inkedmn') 'inkedmn.*strike|strike.*inkedmn')
self.assertRegexp('factoids search ke', self.assertRegexp('factoids search ke',

View File

@ -100,19 +100,21 @@ class SqliteMoobotDB(object):
def _getDb(self, channel): def _getDb(self, channel):
try: try:
import sqlite import sqlite3
except ImportError: except ImportError:
raise callbacks.Error, \ from pysqlite2 import dbapi2 as sqlite3 # for python2.4
'You need to have PySQLite installed to use this ' \
'plugin. Download it at ' \
'<http://code.google.com/p/pysqlite/>'
if channel in self.dbs: if channel in self.dbs:
return self.dbs[channel] return self.dbs[channel]
filename = plugins.makeChannelFilename(self.filename, channel) filename = plugins.makeChannelFilename(self.filename, channel)
if os.path.exists(filename): if os.path.exists(filename):
self.dbs[channel] = sqlite.connect(filename) db = sqlite3.connect(filename)
return self.dbs[channel] db.text_factory = str
db = sqlite.connect(filename) self.dbs[channel] = db
return db
db = sqlite3.connect(filename)
db.text_factory = str
self.dbs[channel] = db self.dbs[channel] = db
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""CREATE TABLE factoids ( cursor.execute("""CREATE TABLE factoids (
@ -135,11 +137,12 @@ class SqliteMoobotDB(object):
db = self._getDb(channel) db = self._getDb(channel)
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""SELECT fact FROM factoids cursor.execute("""SELECT fact FROM factoids
WHERE key LIKE %s""", key) WHERE key LIKE ?""", (key,))
if cursor.rowcount == 0: results = cursor.fetchall()
if len(results) == 0:
return None return None
else: else:
return cursor.fetchall()[0] return results[0]
def getFactinfo(self, channel, key): def getFactinfo(self, channel, key):
db = self._getDb(channel) db = self._getDb(channel)
@ -149,63 +152,65 @@ class SqliteMoobotDB(object):
last_requested_by, last_requested_at, last_requested_by, last_requested_at,
requested_count, locked_by, locked_at requested_count, locked_by, locked_at
FROM factoids FROM factoids
WHERE key LIKE %s""", key) WHERE key LIKE ?""", (key,))
if cursor.rowcount == 0: results = cursor.fetchall()
if len(results) == 0:
return None return None
else: else:
return cursor.fetchone() return results[0]
def randomFactoid(self, channel): def randomFactoid(self, channel):
db = self._getDb(channel) db = self._getDb(channel)
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""SELECT fact, key FROM factoids cursor.execute("""SELECT fact, key FROM factoids
ORDER BY random() LIMIT 1""") ORDER BY random() LIMIT 1""")
if cursor.rowcount == 0: results = cursor.fetchall()
if len(results) == 0:
return None return None
else: else:
return cursor.fetchone() return results[0]
def addFactoid(self, channel, key, value, creator_id): def addFactoid(self, channel, key, value, creator_id):
db = self._getDb(channel) db = self._getDb(channel)
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""INSERT INTO factoids VALUES cursor.execute("""INSERT INTO factoids VALUES
(%s, %s, %s, NULL, NULL, NULL, NULL, (?, ?, ?, NULL, NULL, NULL, NULL,
NULL, NULL, %s, 0)""", NULL, NULL, ?, 0)""",
key, creator_id, int(time.time()), value) (key, creator_id, int(time.time()), value))
db.commit() db.commit()
def updateFactoid(self, channel, key, newvalue, modifier_id): def updateFactoid(self, channel, key, newvalue, modifier_id):
db = self._getDb(channel) db = self._getDb(channel)
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""UPDATE factoids cursor.execute("""UPDATE factoids
SET fact=%s, modified_by=%s, SET fact=?, modified_by=?,
modified_at=%s WHERE key LIKE %s""", modified_at=? WHERE key LIKE ?""",
newvalue, modifier_id, int(time.time()), key) (newvalue, modifier_id, int(time.time()), key))
db.commit() db.commit()
def updateRequest(self, channel, key, hostmask): def updateRequest(self, channel, key, hostmask):
db = self._getDb(channel) db = self._getDb(channel)
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""UPDATE factoids SET cursor.execute("""UPDATE factoids SET
last_requested_by = %s, last_requested_by = ?,
last_requested_at = %s, last_requested_at = ?,
requested_count = requested_count + 1 requested_count = requested_count + 1
WHERE key = %s""", WHERE key = ?""",
hostmask, int(time.time()), key) (hostmask, int(time.time()), key))
db.commit() db.commit()
def removeFactoid(self, channel, key): def removeFactoid(self, channel, key):
db = self._getDb(channel) db = self._getDb(channel)
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""DELETE FROM factoids WHERE key LIKE %s""", cursor.execute("""DELETE FROM factoids WHERE key LIKE ?""",
key) (key,))
db.commit() db.commit()
def locked(self, channel, key): def locked(self, channel, key):
db = self._getDb(channel) db = self._getDb(channel)
cursor = db.cursor() cursor = db.cursor()
cursor.execute ("""SELECT locked_by FROM factoids cursor.execute ("""SELECT locked_by FROM factoids
WHERE key LIKE %s""", key) WHERE key LIKE ?""", (key,))
if cursor.fetchone()[0] is None: if cursor.fetchone()[0] is None:
return False return False
else: else:
@ -215,17 +220,17 @@ class SqliteMoobotDB(object):
db = self._getDb(channel) db = self._getDb(channel)
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""UPDATE factoids cursor.execute("""UPDATE factoids
SET locked_by=%s, locked_at=%s SET locked_by=?, locked_at=?
WHERE key LIKE %s""", WHERE key LIKE ?""",
locker_id, int(time.time()), key) (locker_id, int(time.time()), key))
db.commit() db.commit()
def unlock(self, channel, key): def unlock(self, channel, key):
db = self._getDb(channel) db = self._getDb(channel)
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""UPDATE factoids cursor.execute("""UPDATE factoids
SET locked_by=%s, locked_at=%s SET locked_by=?, locked_at=?
WHERE key LIKE %s""", None, None, key) WHERE key LIKE ?""", (None, None, key))
db.commit() db.commit()
def mostAuthored(self, channel, limit): def mostAuthored(self, channel, limit):
@ -233,14 +238,14 @@ class SqliteMoobotDB(object):
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""SELECT created_by, count(key) FROM factoids cursor.execute("""SELECT created_by, count(key) FROM factoids
GROUP BY created_by GROUP BY created_by
ORDER BY count(key) DESC LIMIT %s""", limit) ORDER BY count(key) DESC LIMIT ?""", (limit,))
return cursor.fetchall() return cursor.fetchall()
def mostRecent(self, channel, limit): def mostRecent(self, channel, limit):
db = self._getDb(channel) db = self._getDb(channel)
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""SELECT key FROM factoids cursor.execute("""SELECT key FROM factoids
ORDER BY created_at DESC LIMIT %s""", limit) ORDER BY created_at DESC LIMIT ?""", (limit,))
return cursor.fetchall() return cursor.fetchall()
def mostPopular(self, channel, limit): def mostPopular(self, channel, limit):
@ -248,43 +253,35 @@ class SqliteMoobotDB(object):
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""SELECT key, requested_count FROM factoids cursor.execute("""SELECT key, requested_count FROM factoids
WHERE requested_count > 0 WHERE requested_count > 0
ORDER BY requested_count DESC LIMIT %s""", limit) ORDER BY requested_count DESC LIMIT ?""", (limit,))
if cursor.rowcount == 0: results = cursor.fetchall()
return [] return results
else:
return cursor.fetchall()
def getKeysByAuthor(self, channel, authorId): def getKeysByAuthor(self, channel, authorId):
db = self._getDb(channel) db = self._getDb(channel)
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""SELECT key FROM factoids WHERE created_by=%s cursor.execute("""SELECT key FROM factoids WHERE created_by=?
ORDER BY key""", authorId) ORDER BY key""", (authorId,))
if cursor.rowcount == 0: results = cursor.fetchall()
return [] return results
else:
return cursor.fetchall()
def getKeysByGlob(self, channel, glob): def getKeysByGlob(self, channel, glob):
db = self._getDb(channel) db = self._getDb(channel)
cursor = db.cursor() cursor = db.cursor()
glob = '%%%s%%' % glob glob = '%%%s%%' % glob
cursor.execute("""SELECT key FROM factoids WHERE key LIKE %s cursor.execute("""SELECT key FROM factoids WHERE key LIKE ?
ORDER BY key""", glob) ORDER BY key""", (glob,))
if cursor.rowcount == 0: results = cursor.fetchall()
return [] return results
else:
return cursor.fetchall()
def getKeysByValueGlob(self, channel, glob): def getKeysByValueGlob(self, channel, glob):
db = self._getDb(channel) db = self._getDb(channel)
cursor = db.cursor() cursor = db.cursor()
glob = '%%%s%%' % glob glob = '%%%s%%' % glob
cursor.execute("""SELECT key FROM factoids WHERE fact LIKE %s cursor.execute("""SELECT key FROM factoids WHERE fact LIKE ?
ORDER BY key""", glob) ORDER BY key""", (glob,))
if cursor.rowcount == 0: results = cursor.fetchall()
return [] return results
else:
return cursor.fetchall()
MoobotDB = plugins.DB('MoobotFactoids', {'sqlite': SqliteMoobotDB}) MoobotDB = plugins.DB('MoobotFactoids', {'sqlite': SqliteMoobotDB})

View File

@ -51,46 +51,51 @@ from supybot.commands import *
import supybot.ircutils as ircutils import supybot.ircutils as ircutils
import supybot.callbacks as callbacks import supybot.callbacks as callbacks
try: ## i think we don't need any of this with sqlite3
# We need to sweep away all that mx.* crap because our code doesn't account #try:
# for PySQLite's arbitrary use of it. Whoever decided to change sqlite's ## We need to sweep away all that mx.* crap because our code doesn't account
# behavior based on whether or not that module is installed was a *CRACK* ## for PySQLite's arbitrary use of it. Whoever decided to change sqlite's
# **FIEND**, plain and simple. ## behavior based on whether or not that module is installed was a *CRACK*
mxCrap = {} ## **FIEND**, plain and simple.
for (name, module) in sys.modules.items(): #mxCrap = {}
if name.startswith('mx'): #for (name, module) in sys.modules.items():
mxCrap[name] = module #if name.startswith('mx'):
sys.modules.pop(name) #mxCrap[name] = module
# Now that the mx crap is gone, we can import sqlite. #sys.modules.pop(name)
import sqlite ## Now that the mx crap is gone, we can import sqlite.
# And now we'll put it back, even though it sucks. #import sqlite3 as sqlite
sys.modules.update(mxCrap) ## And now we'll put it back, even though it sucks.
# Just in case, we'll do this as well. It doesn't seem to work fine by #sys.modules.update(mxCrap)
# itself, though, or else we'd just do this in the first place. ## Just in case, we'll do this as well. It doesn't seem to work fine by
sqlite.have_datetime = False ## itself, though, or else we'd just do this in the first place.
Connection = sqlite.Connection #sqlite.have_datetime = False
class MyConnection(sqlite.Connection): #Connection = sqlite.Connection
def commit(self, *args, **kwargs): #class MyConnection(sqlite.Connection):
if self.autocommit: #def commit(self, *args, **kwargs):
return #if self.autocommit:
else: #return
Connection.commit(self, *args, **kwargs) #else:
#Connection.commit(self, *args, **kwargs)
#def __del__(self):
#try:
#Connection.__del__(self)
#except AttributeError:
#pass
#except Exception, e:
#try:
#log.exception('Uncaught exception in __del__:')
#except:
#pass
#sqlite.Connection = MyConnection
##del Connection.__del__
#except ImportError:
#pass
def __del__(self):
try: try:
Connection.__del__(self) import sqlite3
except AttributeError:
pass
except Exception, e:
try:
log.exception('Uncaught exception in __del__:')
except:
pass
sqlite.Connection = MyConnection
#del Connection.__del__
except ImportError: except ImportError:
pass from pysqlite2 import dbapi2 as sqlite3 # for python2.4
class NoSuitableDatabase(Exception): class NoSuitableDatabase(Exception):
def __init__(self, suitable): def __init__(self, suitable):
@ -176,7 +181,7 @@ class ChannelDBHandler(object):
db = self.makeDb(self.makeFilename(channel)) db = self.makeDb(self.makeFilename(channel))
else: else:
db = self.dbCache[channel] db = self.dbCache[channel]
db.autocommit = 1 db.isolation_level = None
return db return db
def die(self): def die(self):