summaryrefslogtreecommitdiffstats
path: root/src/PYTableDatabase.cc
blob: a6f82099eba49088b8931d485cab5a71f88f0195 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
/* vim:set et ts=4 sts=4:
 *
 * ibus-libpinyin - Intelligent Pinyin engine based on libpinyin for IBus
 *
 * Copyright (c) 2012 Peng Wu <alexepico@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#include "PYTableDatabase.h"

namespace PY {

std::unique_ptr<TableDatabase> TableDatabase::m_system_instance;
std::unique_ptr<TableDatabase> TableDatabase::m_user_instance;

void
TableDatabase::init ()
{
    /* system table database */
    if (m_system_instance.get () == NULL) {
        m_system_instance.reset (new TableDatabase ());
    }

    gboolean result = m_system_instance->openDatabase
        (".." G_DIR_SEPARATOR_S "data" G_DIR_SEPARATOR_S "table.db", FALSE) ||
        m_system_instance->openDatabase
        (PKGDATADIR G_DIR_SEPARATOR_S "db" G_DIR_SEPARATOR_S "table.db", FALSE);

    if (!result)
        g_warning ("can't open system table database.\n");

    /* user table database */
    if (m_user_instance.get () == NULL) {
        m_user_instance.reset (new TableDatabase ());
    }

    gchar *path = g_build_filename (g_get_user_cache_dir (),
                                    "ibus", "libpinyin", "table-user.db", NULL);

    if (!m_user_instance->isDatabaseExisted (path))
        result = m_user_instance->createDatabase (path);

    result = m_user_instance->openDatabase (path, TRUE);

    if (!result)
        g_warning ("can't open user table database.\n");
}

TableDatabase::TableDatabase(){
    m_sqlite = NULL;
    m_sql = "";
}

TableDatabase::~TableDatabase(){
    if (m_sqlite){
        sqlite3_close (m_sqlite);
        m_sqlite = NULL;
    }
    m_sql = "";
}

gboolean
TableDatabase::isDatabaseExisted(const char *filename) {
    gboolean result = g_file_test(filename, G_FILE_TEST_IS_REGULAR);
    if (!result)
        return FALSE;

    sqlite3 *tmp_db = NULL;
    if (sqlite3_open_v2 (filename, &tmp_db,
                         SQLITE_OPEN_READONLY, NULL) != SQLITE_OK){
        return FALSE;
    }

    /* Check the desc table */
    sqlite3_stmt *stmt = NULL;
    const char *tail = NULL;
    m_sql = "SELECT value FROM desc WHERE name = 'version';";
    result = sqlite3_prepare_v2 (tmp_db, m_sql.c_str(), -1, &stmt, &tail);
    if (result != SQLITE_OK)
        return FALSE;

    result = sqlite3_step (stmt);
    if (result != SQLITE_ROW)
        return FALSE;

    result = sqlite3_column_type (stmt, 0);
    if (result != SQLITE_TEXT)
        return FALSE;

    const char *version = (const char *) sqlite3_column_text (stmt, 0);
    if (strcmp("1.12.0", version) != 0)
        return FALSE;

    result = sqlite3_finalize (stmt);
    g_assert (result == SQLITE_OK);
    sqlite3_close (tmp_db);
    return TRUE;
}

gboolean
TableDatabase::createDatabase(const char *filename) {
    /* unlink the old database. */
    gboolean retval = g_file_test (filename, G_FILE_TEST_IS_REGULAR);
    if (retval) {
        int result = g_unlink (filename);
        if (result == -1)
            return FALSE;
    }

    char *dirname = g_path_get_dirname (filename);
    g_mkdir_with_parents (dirname, 0700);
    g_free (dirname);

    sqlite3 *tmp_db = NULL;
    if (sqlite3_open_v2 (filename, &tmp_db,
                         SQLITE_OPEN_READWRITE |
                         SQLITE_OPEN_CREATE, NULL) != SQLITE_OK) {
        return FALSE;
    }

    /* Create DESCription table */
    m_sql = "BEGIN TRANSACTION;\n";
    m_sql << "CREATE TABLE IF NOT EXISTS desc (name TEXT PRIMARY KEY, value TEXT);\n";
    m_sql << "INSERT OR IGNORE INTO desc VALUES ('version', '1.12.0');";
    m_sql << "COMMIT;\n";

    if (!executeSQL (tmp_db)) {
        sqlite3_close (tmp_db);
        return FALSE;
    }

    /* Create Schema */
    m_sql = "CREATE TABLE IF NOT EXISTS phrases ( "
        "id INTEGER PRIMARY KEY NOT NULL,"
        "tabkeys TEXT NOT NULL,"
        "phrase TEXT NOT NULL,"
        "freq INTEGER NOT NULL DEFAULT (10)"
        ");";
    if (!executeSQL (tmp_db)) {
        sqlite3_close (tmp_db);
        return FALSE;
    }

    sqlite3_close (tmp_db);
    return TRUE;
}

/* Self-learning is only in user table database file. */
gboolean
TableDatabase::openDatabase(const char *filename, gboolean writable) {
    int flags = SQLITE_OPEN_READONLY;

    if (writable)
        flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;

    /* open system database. */
    if (sqlite3_open_v2 (filename, &m_sqlite,
                         flags, NULL) != SQLITE_OK) {
        m_sqlite = NULL;
        return FALSE;
    }

    return TRUE;
}

/* List the phrases in frequency and id order. */
gboolean
TableDatabase::listPhrases(const char *prefix,
                           std::vector<std::string> & phrases){
    sqlite3_stmt *stmt = NULL;
    const char *tail = NULL;
    phrases.clear ();

    /* list phrases */
    const char *SQL_DB_LIST =
        "SELECT phrase FROM phrases "
        "WHERE tabkeys LIKE \"%s%\" GROUP by phrase "
        "ORDER BY LENGTH(phrase) ASC, SUM(freq) DESC, id ASC;";
    m_sql.printf (SQL_DB_LIST, prefix);
    int result = sqlite3_prepare_v2 (m_sqlite, m_sql.c_str(), -1, &stmt, &tail);
    if (result != SQLITE_OK)
        return FALSE;

    result = sqlite3_step (stmt);
    while (result == SQLITE_ROW){
        /* get the phrases. */
        result = sqlite3_column_type (stmt, 0);
        if (result != SQLITE_TEXT)
            return FALSE;

        const char *phrase = (const char *)sqlite3_column_text (stmt, 0);
        phrases.push_back (phrase);

        result = sqlite3_step (stmt);
    }

    sqlite3_finalize (stmt);
    if (result != SQLITE_DONE)
        return FALSE;
    return TRUE;
}

gboolean
TableDatabase::getPhraseInfo(const char *phrase, int & freq){
    sqlite3_stmt *stmt = NULL;
    const char *tail = NULL;

    /* get phrase info */
    const char *SQL_DB_SELECT =
        "SELECT freq FROM phrases WHERE phrase = \"%s\";";
    m_sql.printf (SQL_DB_SELECT, phrase);
    int result = sqlite3_prepare_v2 (m_sqlite, m_sql.c_str (), -1, &stmt, &tail);
    g_assert (result == SQLITE_OK);
    result = sqlite3_step (stmt);
    if (result != SQLITE_ROW)
        return FALSE;
    result = sqlite3_column_type (stmt, 0);
    if (result != SQLITE_INTEGER)
        return FALSE;
    freq = sqlite3_column_int (stmt, 0);
    result = sqlite3_finalize (stmt);
    g_assert (result == SQLITE_OK);
    return TRUE;
}

gboolean
TableDatabase::updatePhrase(const char *phrase, int freq){
    const char *SQL_DB_UPDATE =
        "UPDATE phrases SET freq = \"%d\" WHERE phrase = \"%s\";";
    m_sql.printf (SQL_DB_UPDATE, freq, phrase);
    gboolean retval = executeSQL (m_sqlite);
    return retval;
}

gboolean
TableDatabase::deletePhrase(const char *phrase, int freq){
    const char *SQL_DB_DELETE =
        "DELETE FROM phrases WHERE phrase = \"%s\";";
    m_sql.printf (SQL_DB_DELETE, phrase);
    gboolean retval = executeSQL (m_sqlite);
    return retval;
}

gboolean
TableDatabase::importTable (const char *filename){
    /* Import the table into user database. */
    sqlite3_stmt *stmt = NULL;
    const char *tail = NULL;

    FILE *input = fopen (filename, "r");
    if (input == NULL)
        return FALSE;

    /* Get the next id, which is "MAX(id) + 1". */
    const char *SQL_DB_SELECT =
        "SELECT MAX(id) FROM phrases;";
    m_sql = SQL_DB_SELECT;
    int result = sqlite3_prepare_v2 (m_sqlite, m_sql.c_str (), -1, &stmt, &tail);
    if (result != SQLITE_OK)
        return FALSE;

    result = sqlite3_step (stmt);
    if (result != SQLITE_ROW)
        return FALSE;

    int id = 0;
    result = sqlite3_column_type (stmt, 0);
    if (result == SQLITE_INTEGER)
        id = sqlite3_column_int (stmt, 0);
    else if (result == SQLITE_NULL)
        id = 0;
    else
        g_warning ("Can't find id for user table database.");

    m_sql = "BEGIN TRANSACTION;";
    if (!executeSQL (m_sqlite))
        return FALSE;

    /* Open the table file with format:
       "tabkeys phrase freq". */
    while (!feof (input)) {
        ++id;
        char tabkeys[256], phrase[256];
        int freq = 10;
        fscanf (input, "%255s %255s %d\n", tabkeys, phrase, &freq);

        if (tabkeys[0] == '\0' || phrase[0] == '\0')
            break;

        const char *SQL_DB_REPLACE =
            "INSERT OR REPLACE INTO phrases (id, tabkeys, phrase, freq) "
            "VALUES (%d, \"%s\", \"%s\", %d);";

        m_sql.printf (SQL_DB_REPLACE, id, tabkeys, phrase, freq);
        gboolean retval = executeSQL (m_sqlite);
        if (!retval)
            break;
    }

    m_sql = "COMMIT;";
    if (!executeSQL (m_sqlite))
        return FALSE;

    fclose (input);
    return TRUE;
}

gboolean
TableDatabase::exportTable (const char *filename){
    /* Export the content of user database. */
    sqlite3_stmt *stmt = NULL;
    const char *tail = NULL;

    /* Get the content of phrases table by "id" order. */
    const char *SQL_DB_SELECT =
        "SELECT tabkeys, phrase, freq FROM phrases "
        "ORDER BY id ASC;";
    m_sql = SQL_DB_SELECT;
    int result = sqlite3_prepare_v2 (m_sqlite, m_sql.c_str (), -1, &stmt, &tail);
    if (result != SQLITE_OK)
        return FALSE;

    /* Write the table file with format:
       "tabkeys phrase freq". */
    FILE *output = fopen (filename, "w");
    if (output == NULL)
        return FALSE;

    result = sqlite3_step (stmt);
    while (result == SQLITE_ROW){
        /* write one line. */
        result = sqlite3_column_type (stmt, 0);
        if (result != SQLITE_TEXT)
            return FALSE;
        const char *tabkeys = (const char *)sqlite3_column_text (stmt, 0);

        result = sqlite3_column_type (stmt, 1);
        if (result != SQLITE_TEXT)
            return FALSE;
        const char *phrase = (const char *)sqlite3_column_text (stmt, 1);

        result = sqlite3_column_type (stmt, 2);
        if (result != SQLITE_INTEGER)
            return FALSE;
        const int freq = sqlite3_column_int (stmt, 2);

        fprintf (output, "%s\t%s\t%d\n", tabkeys, phrase, freq);

        result = sqlite3_step (stmt);
    }

    fclose (output);

    sqlite3_finalize (stmt);
    if (result != SQLITE_DONE)
        return FALSE;
    return TRUE;
}

gboolean
TableDatabase::clearTable (){
    const char *SQL_DB_DELETE =
        "DELETE FROM phrases;";
    m_sql = SQL_DB_DELETE;
    gboolean retval = executeSQL (m_sqlite);
    return retval;
}

gboolean
TableDatabase::executeSQL(sqlite3 *sqlite){
    gchar *errmsg = NULL;
    if (sqlite3_exec (sqlite, m_sql.c_str (), NULL, NULL, &errmsg)
        != SQLITE_OK) {
        g_warning ("%s: %s", errmsg, m_sql.c_str());
        sqlite3_free (errmsg);
        return FALSE;
    }
    m_sql.clear ();
    return TRUE;
}

#if 0

/* using static initializor to test table database here. */
static class TestTableDatabase{
public:
    TestTableDatabase (){
        TableDatabase *db = new TableDatabase ();
        bool retval = db->isDatabaseExisted ("../data/table.db");
        g_assert (retval);
        retval = db->openDatabase ("../data/table.db", FALSE);
        g_assert (retval);
        std::vector<std::string> phrases;
        std::vector<std::string>::iterator iter;
        db->listPhrases("hshshhh", phrases);
        printf ("characters:\t");
        for (iter = phrases.begin(); iter != phrases.end(); ++iter)
            printf ("%s ", iter->c_str());
        printf ("\n");
        phrases.clear ();
        delete db;

        db = new TableDatabase ();
        if (!db->isDatabaseExisted ("table.db"))
            db->createDatabase ("table.db");
        db->openDatabase ("table.db", TRUE);

        db->importTable ("table.txt");
        db->exportTable ("export.txt");
        db->listPhrases("a", phrases);
        printf ("characters:\t");
        for (iter = phrases.begin(); iter != phrases.end(); ++iter)
            printf ("%s ", iter->c_str());
        printf ("\n");
        printf ("table database test ok.\n");
    }
} test_table_database;

#endif

};