Skip to content

Commit 6bc02c3

Browse files
author
Johannes Gijsbers
committed
First checkin of tsearch2 "backend". Miscellaneous notes:
* We override the testTransactions method, as it relies on FileStorage for its transaction testing. * importing/exporting doesn't work right yet. * Filtering of text/plain mime-types is an ugly hack right now.
1 parent cc0f0ab commit 6bc02c3

File tree

5 files changed

+1062
-6
lines changed

5 files changed

+1062
-6
lines changed

roundup/backends/back_tsearch2.py

Lines changed: 215 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,215 @@
1+
import re
2+
3+
import psycopg
4+
5+
from roundup import hyperdb
6+
from roundup.backends import back_postgresql, tsearch2_setup, indexer_rdbms
7+
from roundup.backends.back_postgresql import db_create, db_nuke, db_command
8+
from roundup.backends.back_postgresql import pg_command, db_exists, Class, IssueClass, FileClass
9+
10+
# XXX: Should probably be on the Class class.
11+
def _indexedProps(spec):
12+
"""Get a list of properties to be indexed on 'spec'."""
13+
return [prop for prop, propclass in spec.getprops().items()
14+
if isinstance(propclass, hyperdb.String) and propclass.indexme]
15+
16+
def _getQueryDict(spec):
17+
"""Get a convenience dictionary for creating tsearch2 indexes."""
18+
query_dict = {'classname': spec.classname,
19+
'indexedColumns': ['_' + prop for prop in _indexedProps(spec)]}
20+
query_dict['tablename'] = "_%(classname)s" % query_dict
21+
query_dict['triggername'] = "%(tablename)s_tsvectorupdate" % query_dict
22+
return query_dict
23+
24+
def _isLink(propclass):
25+
return (isinstance(propclass, hyperdb.Link) or
26+
isinstance(propclass, hyperdb.Multilink))
27+
28+
class Database(back_postgresql.Database):
29+
def __init__(self, config, journaltag=None):
30+
back_postgresql.Database.__init__(self, config, journaltag)
31+
self.indexer = Indexer(self)
32+
33+
def create_version_2_tables(self):
34+
back_postgresql.Database.create_version_2_tables(self)
35+
tsearch2_setup.setup(self.cursor)
36+
37+
def create_class_table_indexes(self, spec):
38+
back_postgresql.Database.create_class_table_indexes(self, spec)
39+
self.cursor.execute("""CREATE INDEX _%(classname)s_idxFTI_idx
40+
ON %(tablename)s USING gist(idxFTI);""" %
41+
_getQueryDict(spec))
42+
43+
self.create_tsearch2_trigger(spec)
44+
45+
def create_tsearch2_trigger(self, spec):
46+
d = _getQueryDict(spec)
47+
if d['indexedColumns']:
48+
49+
d['joined'] = " || ' ' ||".join(d['indexedColumns'])
50+
query = """UPDATE %(tablename)s
51+
SET idxFTI = to_tsvector('default', %(joined)s)""" % d
52+
self.cursor.execute(query)
53+
54+
d['joined'] = ", ".join(d['indexedColumns'])
55+
query = """CREATE TRIGGER %(triggername)s
56+
BEFORE UPDATE OR INSERT ON %(tablename)s
57+
FOR EACH ROW EXECUTE PROCEDURE
58+
tsearch2(idxFTI, %(joined)s);""" % d
59+
self.cursor.execute(query)
60+
61+
def drop_tsearch2_trigger(self, spec):
62+
# Check whether the trigger exists before trying to drop it.
63+
query_dict = _getQueryDict(spec)
64+
self.sql("""SELECT tgname FROM pg_catalog.pg_trigger
65+
WHERE tgname = '%(triggername)s'""" % query_dict)
66+
if self.cursor.fetchall():
67+
self.sql("""DROP TRIGGER %(triggername)s ON %(tablename)s""" %
68+
query_dict)
69+
70+
def update_class(self, spec, old_spec, force=0):
71+
result = back_postgresql.Database.update_class(self, spec, old_spec, force)
72+
73+
# Drop trigger...
74+
self.drop_tsearch2_trigger(spec)
75+
76+
# and recreate if necessary.
77+
self.create_tsearch2_trigger(spec)
78+
79+
return result
80+
81+
def determine_all_columns(self, spec):
82+
cols, mls = back_postgresql.Database.determine_all_columns(self, spec)
83+
cols.append(('idxFTI', 'tsvector'))
84+
return cols, mls
85+
86+
class Indexer:
87+
def __init__(self, db):
88+
self.db = db
89+
90+
def force_reindex(self):
91+
pass
92+
93+
def should_reindex(self):
94+
pass
95+
96+
def save_index(self):
97+
pass
98+
99+
def add_text(self, identifier, text, mime_type=None):
100+
pass
101+
102+
def close(self):
103+
pass
104+
105+
def search(self, search_terms, klass, ignore={},
106+
dre=re.compile(r'([^\d]+)(\d+)')):
107+
'''Display search results looking for [search, terms] associated
108+
with the hyperdb Class "klass". Ignore hits on {class: property}.
109+
110+
"dre" is a helper, not an argument.
111+
'''
112+
# do the index lookup
113+
hits = self.find(search_terms, klass)
114+
if not hits:
115+
return {}
116+
117+
designator_propname = {}
118+
for nm, propclass in klass.getprops().items():
119+
if (isinstance(propclass, hyperdb.Link)
120+
or isinstance(propclass, hyperdb.Multilink)):
121+
designator_propname[propclass.classname] = nm
122+
123+
# build a dictionary of nodes and their associated messages
124+
# and files
125+
nodeids = {} # this is the answer
126+
propspec = {} # used to do the klass.find
127+
for propname in designator_propname.values():
128+
propspec[propname] = {} # used as a set (value doesn't matter)
129+
130+
for classname, nodeid in hits:
131+
# if it's a property on klass, it's easy
132+
if classname == klass.classname:
133+
if not nodeids.has_key(nodeid):
134+
nodeids[nodeid] = {}
135+
continue
136+
137+
# make sure the class is a linked one, otherwise ignore
138+
if not designator_propname.has_key(classname):
139+
continue
140+
141+
# it's a linked class - set up to do the klass.find
142+
linkprop = designator_propname[classname] # eg, msg -> messages
143+
propspec[linkprop][nodeid] = 1
144+
145+
# retain only the meaningful entries
146+
for propname, idset in propspec.items():
147+
if not idset:
148+
del propspec[propname]
149+
150+
# klass.find tells me the klass nodeids the linked nodes relate to
151+
for resid in klass.find(**propspec):
152+
resid = str(resid)
153+
if not nodeids.has_key(id):
154+
nodeids[resid] = {}
155+
node_dict = nodeids[resid]
156+
# now figure out where it came from
157+
for linkprop in propspec.keys():
158+
for nodeid in klass.get(resid, linkprop):
159+
if propspec[linkprop].has_key(nodeid):
160+
# OK, this node[propname] has a winner
161+
if not node_dict.has_key(linkprop):
162+
node_dict[linkprop] = [nodeid]
163+
else:
164+
node_dict[linkprop].append(nodeid)
165+
return nodeids
166+
167+
def find(self, search_terms, klass):
168+
if not search_terms:
169+
return None
170+
171+
nodeids = self.tsearchQuery(klass.classname, search_terms)
172+
designator_propname = {}
173+
174+
for nm, propclass in klass.getprops().items():
175+
if _isLink(propclass):
176+
nodeids.extend(self.tsearchQuery(propclass.classname, search_terms))
177+
178+
return nodeids
179+
180+
def tsearchQuery(self, classname, search_terms):
181+
query = """SELECT id FROM _%(classname)s
182+
WHERE idxFTI @@ to_tsquery('default', '%(terms)s')"""
183+
184+
query = query % {'classname': classname,
185+
'terms': ' & '.join(search_terms)}
186+
self.db.cursor.execute(query)
187+
klass = self.db.getclass(classname)
188+
nodeids = [str(row[0]) for row in self.db.cursor.fetchall()]
189+
190+
# filter out files without text/plain mime type
191+
# XXX: files without text/plain shouldn't be indexed at all, we
192+
# should take care of this in the trigger
193+
if 'type' in klass.getprops():
194+
nodeids = [nodeid for nodeid in nodeids
195+
if klass.get(nodeid, 'type') == 'text/plain']
196+
197+
return [(classname, nodeid) for nodeid in nodeids]
198+
199+
# XXX: we can't reuse hyperdb.FileClass for importing/exporting, so file
200+
# contents will end up in CSV exports for now. Not sure whether this is
201+
# truly a problem. If it is, we should write an importer/exporter that
202+
# converts from the database to the filesystem and vice versa
203+
class FileClass(Class):
204+
def __init__(self, db, classname, **properties):
205+
'''The newly-created class automatically includes the "content" property.,
206+
'''
207+
properties['content'] = hyperdb.String(indexme='yes')
208+
Class.__init__(self, db, classname, **properties)
209+
210+
default_mime_type = 'text/plain'
211+
def create(self, **propvalues):
212+
# figure the mime type
213+
if not propvalues.get('type'):
214+
propvalues['type'] = self.default_mime_type
215+
return Class.create(self, **propvalues)

roundup/backends/rdbms_common.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# $Id: rdbms_common.py,v 1.142 2004-12-03 22:11:06 richard Exp $
1+
# $Id: rdbms_common.py,v 1.143 2004-12-16 22:22:55 jlgijsbers Exp $
22
''' Relational database (SQL) backend common code.
33
44
Basics:
@@ -454,14 +454,21 @@ def update_class(self, spec, old_spec, force=0):
454454

455455
return 1
456456

457-
def create_class_table(self, spec):
458-
'''Create the class table for the given Class "spec". Creates the
459-
indexes too.'''
460-
cols, mls = self.determine_columns(spec.properties.items())
457+
def determine_all_columns(self, spec):
458+
"""Figure out the columns from the spec and also add internal columns
461459
460+
"""
461+
cols, mls = self.determine_columns(spec.properties.items())
462+
462463
# add on our special columns
463464
cols.append(('id', 'INTEGER PRIMARY KEY'))
464465
cols.append(('__retired__', 'INTEGER DEFAULT 0'))
466+
return cols, mls
467+
468+
def create_class_table(self, spec):
469+
'''Create the class table for the given Class "spec". Creates the
470+
indexes too.'''
471+
cols, mls = self.determine_all_columns(spec)
465472

466473
# create the base table
467474
scols = ','.join(['%s %s'%x for x in cols])

0 commit comments

Comments
 (0)