]> git.openstreetmap.org Git - osqa.git/blob - forum_modules/mysqlfulltext/startup.py
e2bc7efc91a6f36c34097a3036353b3c5f00cf9a
[osqa.git] / forum_modules / mysqlfulltext / startup.py
1 from django.db import connection, transaction
2 import os, settings
3
4 import re
5 from django.db import connection, transaction, models
6 from django.db.models import Q
7 from forum.models.question import Question, QuestionManager
8 from forum.models.node import Node
9 from forum.modules import decorate
10
11 VERSION = 2
12
13 f_name = None
14
15 if not bool(settings.MYSQL_FTS_INSTALLED):
16     f_name = os.path.join(os.path.dirname(__file__), 'fts_install.sql')
17 elif int(settings.MYSQL_FTS_VERSION < VERSION):
18     f_name = os.path.join(os.path.dirname(__file__), 'fts_update.sql')
19
20 if f_name:
21     f = open(f_name, 'r')
22
23     try:
24         cursor = connection.cursor()
25         cursor.execute(f.read())
26         transaction.commit_unless_managed()
27
28         settings.MYSQL_FTS_INSTALLED.set_value(True)
29         settings.MYSQL_FTS_VERSION.set_value(VERSION)
30
31     except Exception, e:
32         #import sys, traceback
33         #traceback.print_exc(file=sys.stdout)
34         pass
35     finally:
36         cursor.close()
37
38     f.close()
39
40 word_re = re.compile(r'\w+', re.UNICODE)
41
42 @decorate(QuestionManager.search, needs_origin=False)
43 def question_search(self, keywords):
44     keywords = keywords.upper()
45
46     return '-ranking', self.filter(
47             models.Q(ftsindex__body__search=keywords) or models.Q(ftsindex__title__search=keywords) or models.Q(ftsindex__tagnames__search=keywords)
48
49     ).extra(
50         select={
51             'ranking': """
52                 match(forum_mysqlftsindex.tagnames) against (%s in boolean mode) * 4 +
53                 match(forum_mysqlftsindex.title) against (%s in boolean mode) * 2 +
54                 match(forum_mysqlftsindex.body) against (%s in boolean mode) * 1
55                                 """,
56             },
57         select_params=[keywords, keywords, keywords]
58     )