Debian Codegraph @

tools/ibus-table-query

raw symbols SCIP
1 #!/usr/bin/python3
2 # vim:fileencoding=utf-8:sw=4:et
3
4 # query-ibus-table
5 #
6 # Copyright (c) 2012 mozbugbox <[email protected]>
7 #
8 # This library is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU Lesser General Public
10 # License as published by the Free Software Foundation; either
11 # version 3.0 of the License, or (at your option) any later version.
12 #
13 # This library is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 # Lesser General Public License for more details.
17 #
18 # You should have received a copy of the GNU Lesser General Public
19 # License along with this library; if not, write to the Free Software
20 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
22 from __future__ import print_function, unicode_literals, absolute_import
23 import sys
24 import os
25 import io
26 import logging as log
27 import sqlite3
28
29 TABLE_DIR = "/usr/share/ibus-table/tables/"
30
31 def list_tables(cursor):
32 """List sql tables in a given sqlite database"""
33 tables = cursor.execute("SELECT * FROM sqlite_master WHERE type='table';")
34 for row in tables:
35 log.debug("Table: {}".format(" ".join(row[1:3])))
36 log.debug(row[4])
37
38 def get_table_sql(cursor, name):
39 """Given a table name, return the creation sql statement of the table."""
40 tables = cursor.execute("SELECT * FROM sqlite_master WHERE type='table' AND tbl_name = ? ;", [name])
41 sql = None
42 for row in tables:
43 sql = row[4]
44 return sql
45
46 def get_table_path(name):
47 """Given a filename, return the full path to the ibus table sqlite file."""
48 if name.startswith("/"):
49 if os.path.exists(name):
50 return name
51 else:
52 return None
53 else:
54 tablename = None
55 for fname in os.listdir(TABLE_DIR):
56 if fname.startswith(name) and fname.endswith('.db'):
57 tablename = fname
58 break
59 if not tablename or (
60 os.path.splitext(tablename)[0] != os.path.splitext(name)[0]):
61 print("Known tables:")
62 for fname in os.listdir(TABLE_DIR):
63 print(" {}".format(fname))
64 if not tablename:
65 print("No table: {}".format(name))
66 sys.exit(2)
67 return os.path.join(TABLE_DIR, tablename)
68
69 def query_keys(cursor, tabkeys):
70 sqlstr = '''
71 SELECT tabkeys, phrase, freq, user_freq FROM main.phrases
72 WHERE tabkeys LIKE :tabkeys
73 ORDER BY phrase ASC, freq DESC;
74 '''
75 sqlargs = {'tabkeys': tabkeys+'%%'}
76 log.debug("sqlstr: {}".format(sqlstr))
77 log.debug("sqlargs: {}".format(sqlargs))
78
79 result = cursor.execute(sqlstr, sqlargs)
80 return list(result)
81
82 def print_result(table_sql, result):
83 """@result: sqlite execute result.
84 @table_sql: table creation sql statement
85 """
86 pidx = table_sql.find("(") + 1
87 pidx2 = table_sql.find(")", pidx)
88 headers = [x.split()[0] for x in table_sql[pidx:pidx2].split(",")][1:]
89 format_str = "{}".format("{:16s}"*4)
90 headers = format_str.format(*headers)
91 print(headers)
92 print("="*len(headers.rstrip()))
93 for row in result:
94 row = list(row)
95 row_str = [str(x).strip() for x in row]
96 if len(row_str[1]) == 1:
97 row_str[1] += "[U+{:X}]".format(ord(row_str[1]))
98 line = format_str.format(*row_str)
99 print(line)
100
101 def parse_args():
102 import argparse
103 parser = argparse.ArgumentParser(description="Query ibus table database")
104 parser.add_argument("--debug", action="store_true", help="DEBUG")
105 parser.add_argument("-t", "--table-name", required=True,
106 help="table database name")
107 parser.add_argument("keys", metavar="Input-Keys", nargs=1,
108 help="a string of input keys, e.g. hjik")
109 args = parser.parse_args()
110 return args
111
112 NATIVE=sys.getfilesystemencoding()
113 def main():
114 args = parse_args()
115 log_level = log.INFO
116 if args.debug:
117 log_level = log.DEBUG
118 log.basicConfig(format="%(levelname)s>> %(message)s", level=log_level)
119
120 table_prefix = args.table_name
121 keys = args.keys[0]
122 if type(keys) != type(u''):
123 keys = keys.decode(NATIVE)
124
125 table_path = get_table_path(table_prefix)
126 if not table_path:
127 print('Table "{}" does not exist.'.format(table_prefix))
128 sys.exit(1)
129 print("Using table: {}".format(table_path))
130 log.debug("table path: {}".format(table_path))
131
132 db = sqlite3.connect(table_path)
133 cursor = db.cursor()
134 #list_tables(cursor)
135
136 table_sql = get_table_sql(cursor, "phrases")
137 result = query_keys(cursor, keys)
138
139 print_result(table_sql, result)
140
141 if __name__ == '__main__':
142 main()
143