yomichan/ext/bg/js/database.js

622 lines
21 KiB
JavaScript
Raw Normal View History

2016-03-20 02:32:35 +00:00
/*
* Copyright (C) 2016-2020 Yomichan Authors
2016-03-20 02:32:35 +00:00
*
* 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 3 of the License, 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
2020-01-01 17:00:31 +00:00
* along with this program. If not, see <https://www.gnu.org/licenses/>.
2016-03-20 02:32:35 +00:00
*/
2020-03-11 02:30:36 +00:00
/* global
* dictFieldSplit
*/
2016-03-20 02:32:35 +00:00
2016-11-07 16:29:21 +00:00
class Database {
2016-03-21 00:15:40 +00:00
constructor() {
2016-09-12 05:47:08 +00:00
this.db = null;
2020-02-18 00:43:44 +00:00
this._schemas = new Map();
2016-08-21 20:32:36 +00:00
}
2020-02-17 21:16:08 +00:00
// Public
2017-07-10 20:16:24 +00:00
async prepare() {
2019-11-03 21:13:40 +00:00
if (this.db !== null) {
2019-10-08 00:46:02 +00:00
throw new Error('Database already initialized');
2016-09-13 22:59:18 +00:00
}
2019-11-10 01:48:30 +00:00
try {
this.db = await Database._open('dict', 6, (db, transaction, oldVersion) => {
2020-02-17 21:16:08 +00:00
Database._upgrade(db, transaction, oldVersion, [
2019-11-10 01:48:30 +00:00
{
version: 2,
stores: {
terms: {
primaryKey: {keyPath: 'id', autoIncrement: true},
indices: ['dictionary', 'expression', 'reading']
},
kanji: {
primaryKey: {autoIncrement: true},
indices: ['dictionary', 'character']
},
tagMeta: {
primaryKey: {autoIncrement: true},
indices: ['dictionary']
},
dictionaries: {
primaryKey: {autoIncrement: true},
indices: ['title', 'version']
}
}
2019-11-10 01:48:30 +00:00
},
{
version: 3,
stores: {
termMeta: {
primaryKey: {autoIncrement: true},
indices: ['dictionary', 'expression']
},
kanjiMeta: {
primaryKey: {autoIncrement: true},
indices: ['dictionary', 'character']
},
tagMeta: {
primaryKey: {autoIncrement: true},
indices: ['dictionary', 'name']
}
}
2019-11-10 01:48:30 +00:00
},
{
version: 4,
stores: {
terms: {
primaryKey: {keyPath: 'id', autoIncrement: true},
indices: ['dictionary', 'expression', 'reading', 'sequence']
}
}
2019-11-24 02:48:24 +00:00
},
{
version: 5,
stores: {
terms: {
primaryKey: {keyPath: 'id', autoIncrement: true},
indices: ['dictionary', 'expression', 'reading', 'sequence', 'expressionReverse', 'readingReverse']
}
}
},
{
version: 6,
stores: {
media: {
primaryKey: {keyPath: 'id', autoIncrement: true},
indices: ['dictionary', 'path']
}
}
}
2019-11-10 01:48:30 +00:00
]);
});
return true;
} catch (e) {
2020-04-05 22:27:53 +00:00
logError(e);
2019-11-10 01:48:30 +00:00
return false;
}
2016-03-21 00:15:40 +00:00
}
2020-02-20 00:59:24 +00:00
async close() {
2020-02-22 17:45:50 +00:00
this._validate();
2020-02-20 00:59:24 +00:00
this.db.close();
this.db = null;
}
2020-03-31 00:27:44 +00:00
isPrepared() {
return this.db !== null;
}
2017-07-10 20:16:24 +00:00
async purge() {
2020-02-17 21:16:08 +00:00
this._validate();
2016-11-14 03:10:28 +00:00
this.db.close();
2020-02-17 21:16:08 +00:00
await Database._deleteDatabase(this.db.name);
2017-07-10 20:16:24 +00:00
this.db = null;
await this.prepare();
2016-11-14 03:10:28 +00:00
}
async deleteDictionary(dictionaryName, onProgress, progressSettings) {
2020-02-17 21:16:08 +00:00
this._validate();
const targets = [
['dictionaries', 'title'],
['kanji', 'dictionary'],
['kanjiMeta', 'dictionary'],
['terms', 'dictionary'],
['termMeta', 'dictionary'],
['tagMeta', 'dictionary']
];
const promises = [];
const progressData = {
count: 0,
processed: 0,
storeCount: targets.length,
storesProcesed: 0
};
let progressRate = (typeof progressSettings === 'object' && progressSettings !== null ? progressSettings.rate : 0);
if (typeof progressRate !== 'number' || progressRate <= 0) {
progressRate = 1000;
}
for (const [objectStoreName, index] of targets) {
2019-11-03 21:13:40 +00:00
const dbTransaction = this.db.transaction([objectStoreName], 'readwrite');
const dbObjectStore = dbTransaction.objectStore(objectStoreName);
const dbIndex = dbObjectStore.index(index);
const only = IDBKeyRange.only(dictionaryName);
2020-02-17 21:16:08 +00:00
promises.push(Database._deleteValues(dbObjectStore, dbIndex, only, onProgress, progressData, progressRate));
}
await Promise.all(promises);
}
2020-02-15 20:01:21 +00:00
async findTermsBulk(termList, dictionaries, wildcard) {
2020-02-17 21:16:08 +00:00
this._validate();
2019-10-19 03:04:06 +00:00
2019-08-31 01:06:21 +00:00
const promises = [];
2020-02-15 17:31:11 +00:00
const visited = new Set();
2019-08-31 01:06:21 +00:00
const results = [];
const processRow = (row, index) => {
2020-02-15 20:01:21 +00:00
if (dictionaries.has(row.dictionary) && !visited.has(row.id)) {
2020-02-15 17:31:11 +00:00
visited.add(row.id);
2020-02-17 21:16:08 +00:00
results.push(Database._createTerm(row, index));
}
};
2019-08-31 01:06:21 +00:00
2019-11-24 02:48:24 +00:00
const useWildcard = !!wildcard;
const prefixWildcard = wildcard === 'prefix';
2019-11-03 21:13:40 +00:00
const dbTransaction = this.db.transaction(['terms'], 'readonly');
2019-08-31 01:06:21 +00:00
const dbTerms = dbTransaction.objectStore('terms');
2019-11-24 02:48:24 +00:00
const dbIndex1 = dbTerms.index(prefixWildcard ? 'expressionReverse' : 'expression');
const dbIndex2 = dbTerms.index(prefixWildcard ? 'readingReverse' : 'reading');
2019-08-31 01:06:21 +00:00
2019-10-19 14:09:18 +00:00
for (let i = 0; i < termList.length; ++i) {
2019-11-24 02:48:24 +00:00
const term = prefixWildcard ? stringReverse(termList[i]) : termList[i];
const query = useWildcard ? IDBKeyRange.bound(term, `${term}\uffff`, false, false) : IDBKeyRange.only(term);
2019-08-31 01:06:21 +00:00
promises.push(
2020-02-17 21:16:08 +00:00
Database._getAll(dbIndex1, query, i, processRow),
Database._getAll(dbIndex2, query, i, processRow)
2019-08-31 01:06:21 +00:00
);
}
await Promise.all(promises);
return results;
}
2020-02-15 20:01:21 +00:00
async findTermsExactBulk(termList, readingList, dictionaries) {
2020-02-17 21:16:08 +00:00
this._validate();
2019-10-19 14:09:18 +00:00
const promises = [];
const results = [];
const processRow = (row, index) => {
2020-02-15 20:01:21 +00:00
if (row.reading === readingList[index] && dictionaries.has(row.dictionary)) {
2020-02-17 21:16:08 +00:00
results.push(Database._createTerm(row, index));
2019-10-19 14:09:18 +00:00
}
};
2019-11-03 21:13:40 +00:00
const dbTransaction = this.db.transaction(['terms'], 'readonly');
2019-10-19 14:09:18 +00:00
const dbTerms = dbTransaction.objectStore('terms');
const dbIndex = dbTerms.index('expression');
for (let i = 0; i < termList.length; ++i) {
const only = IDBKeyRange.only(termList[i]);
2020-02-17 21:16:08 +00:00
promises.push(Database._getAll(dbIndex, only, i, processRow));
2019-10-19 14:09:18 +00:00
}
await Promise.all(promises);
return results;
}
async findTermsBySequenceBulk(sequenceList, mainDictionary) {
2020-02-17 21:16:08 +00:00
this._validate();
2019-10-19 03:04:06 +00:00
2019-08-31 01:06:21 +00:00
const promises = [];
const results = [];
const processRow = (row, index) => {
2019-10-19 14:09:18 +00:00
if (row.dictionary === mainDictionary) {
2020-02-17 21:16:08 +00:00
results.push(Database._createTerm(row, index));
}
};
2019-08-31 01:06:21 +00:00
2019-11-03 21:13:40 +00:00
const dbTransaction = this.db.transaction(['terms'], 'readonly');
2019-10-19 14:09:18 +00:00
const dbTerms = dbTransaction.objectStore('terms');
const dbIndex = dbTerms.index('sequence');
2019-08-31 01:06:21 +00:00
2019-10-19 14:09:18 +00:00
for (let i = 0; i < sequenceList.length; ++i) {
const only = IDBKeyRange.only(sequenceList[i]);
2020-02-17 21:16:08 +00:00
promises.push(Database._getAll(dbIndex, only, i, processRow));
2019-08-31 01:06:21 +00:00
}
await Promise.all(promises);
return results;
}
2020-02-15 20:01:21 +00:00
async findTermMetaBulk(termList, dictionaries) {
return this._findGenericBulk('termMeta', 'expression', termList, dictionaries, Database._createTermMeta);
2019-10-19 14:09:18 +00:00
}
2020-02-15 20:01:21 +00:00
async findKanjiBulk(kanjiList, dictionaries) {
return this._findGenericBulk('kanji', 'character', kanjiList, dictionaries, Database._createKanji);
2019-10-19 14:09:18 +00:00
}
2020-02-15 20:01:21 +00:00
async findKanjiMetaBulk(kanjiList, dictionaries) {
return this._findGenericBulk('kanjiMeta', 'character', kanjiList, dictionaries, Database._createKanjiMeta);
2019-10-19 14:09:18 +00:00
}
2017-09-13 03:20:03 +00:00
2017-09-14 01:03:55 +00:00
async findTagForTitle(name, title) {
2020-02-17 21:16:08 +00:00
this._validate();
2016-09-12 05:47:08 +00:00
let result = null;
2019-11-03 21:13:40 +00:00
const dbTransaction = this.db.transaction(['tagMeta'], 'readonly');
const dbTerms = dbTransaction.objectStore('tagMeta');
const dbIndex = dbTerms.index('name');
const only = IDBKeyRange.only(name);
2020-02-17 21:16:08 +00:00
await Database._getAll(dbIndex, only, null, (row) => {
if (title === row.dictionary) {
result = row;
}
});
2017-09-14 00:26:02 +00:00
2017-09-13 23:42:04 +00:00
return result;
2016-08-24 05:22:09 +00:00
}
2016-08-24 03:33:04 +00:00
async getDictionaryInfo() {
2020-02-17 21:16:08 +00:00
this._validate();
const results = [];
2019-11-03 21:13:40 +00:00
const dbTransaction = this.db.transaction(['dictionaries'], 'readonly');
const dbDictionaries = dbTransaction.objectStore('dictionaries');
2020-02-17 21:16:08 +00:00
await Database._getAll(dbDictionaries, null, null, (info) => results.push(info));
return results;
}
async getDictionaryCounts(dictionaryNames, getTotal) {
2020-02-17 21:16:08 +00:00
this._validate();
const objectStoreNames = [
'kanji',
'kanjiMeta',
'terms',
'termMeta',
'tagMeta'
];
2019-11-03 21:13:40 +00:00
const dbCountTransaction = this.db.transaction(objectStoreNames, 'readonly');
const targets = [];
for (const objectStoreName of objectStoreNames) {
targets.push([
objectStoreName,
dbCountTransaction.objectStore(objectStoreName).index('dictionary')
]);
}
2019-11-10 01:49:44 +00:00
// Query is required for Edge, otherwise index.count throws an exception.
const query1 = IDBKeyRange.lowerBound('', false);
2020-02-17 21:16:08 +00:00
const totalPromise = getTotal ? Database._getCounts(targets, query1) : null;
const counts = [];
const countPromises = [];
for (let i = 0; i < dictionaryNames.length; ++i) {
counts.push(null);
const index = i;
2019-11-10 01:49:44 +00:00
const query2 = IDBKeyRange.only(dictionaryNames[i]);
2020-02-17 21:16:08 +00:00
const countPromise = Database._getCounts(targets, query2).then((v) => counts[index] = v);
countPromises.push(countPromise);
}
await Promise.all(countPromises);
const result = {counts};
if (totalPromise !== null) {
result.total = await totalPromise;
}
return result;
}
2020-03-31 00:27:37 +00:00
async dictionaryExists(title) {
this._validate();
const transaction = this.db.transaction(['dictionaries'], 'readonly');
const index = transaction.objectStore('dictionaries').index('title');
const query = IDBKeyRange.only(title);
const count = await Database._getCount(index, query);
return count > 0;
}
2020-03-31 00:19:39 +00:00
bulkAdd(objectStoreName, items, start, count) {
return new Promise((resolve, reject) => {
const transaction = this.db.transaction([objectStoreName], 'readwrite');
const objectStore = transaction.objectStore(objectStoreName);
if (start + count > items.length) {
count = items.length - start;
}
if (count <= 0) {
resolve();
return;
}
const end = start + count;
let completedCount = 0;
const onError = (e) => reject(e);
const onSuccess = () => {
if (++completedCount >= count) {
resolve();
}
};
for (let i = start; i < end; ++i) {
const request = objectStore.add(items[i]);
request.onerror = onError;
request.onsuccess = onSuccess;
}
});
}
2020-02-17 21:16:08 +00:00
// Private
_validate() {
2019-10-08 00:46:02 +00:00
if (this.db === null) {
throw new Error('Database not initialized');
}
}
2020-02-15 20:01:21 +00:00
async _findGenericBulk(tableName, indexName, indexValueList, dictionaries, createResult) {
2020-02-17 21:16:08 +00:00
this._validate();
const promises = [];
const results = [];
const processRow = (row, index) => {
2020-02-15 20:01:21 +00:00
if (dictionaries.has(row.dictionary)) {
2020-02-17 21:16:08 +00:00
results.push(createResult(row, index));
}
};
const dbTransaction = this.db.transaction([tableName], 'readonly');
const dbTerms = dbTransaction.objectStore(tableName);
const dbIndex = dbTerms.index(indexName);
for (let i = 0; i < indexValueList.length; ++i) {
const only = IDBKeyRange.only(indexValueList[i]);
promises.push(Database._getAll(dbIndex, only, i, processRow));
}
await Promise.all(promises);
return results;
}
static _createTerm(row, index) {
return {
2019-08-31 01:06:21 +00:00
index,
expression: row.expression,
reading: row.reading,
definitionTags: dictFieldSplit(row.definitionTags || row.tags || ''),
termTags: dictFieldSplit(row.termTags || ''),
rules: dictFieldSplit(row.rules),
glossary: row.glossary,
score: row.score,
dictionary: row.dictionary,
id: row.id,
sequence: typeof row.sequence === 'undefined' ? -1 : row.sequence
};
}
2019-08-31 01:06:21 +00:00
2020-02-17 21:16:08 +00:00
static _createKanji(row, index) {
return {
index,
character: row.character,
onyomi: dictFieldSplit(row.onyomi),
kunyomi: dictFieldSplit(row.kunyomi),
tags: dictFieldSplit(row.tags),
glossary: row.meanings,
stats: row.stats,
dictionary: row.dictionary
};
}
2020-02-17 21:16:08 +00:00
static _createTermMeta({expression, mode, data, dictionary}, index) {
return {expression, mode, data, dictionary, index};
}
2020-02-17 21:16:08 +00:00
static _createKanjiMeta({character, mode, data, dictionary}, index) {
return {character, mode, data, dictionary, index};
2019-08-31 01:06:21 +00:00
}
2020-02-17 21:16:08 +00:00
static _getAll(dbIndex, query, context, processRow) {
const fn = typeof dbIndex.getAll === 'function' ? Database._getAllFast : Database._getAllUsingCursor;
return fn(dbIndex, query, context, processRow);
2019-08-31 01:06:21 +00:00
}
2020-02-17 21:16:08 +00:00
static _getAllFast(dbIndex, query, context, processRow) {
2019-08-31 01:06:21 +00:00
return new Promise((resolve, reject) => {
const request = dbIndex.getAll(query);
request.onerror = (e) => reject(e);
request.onsuccess = (e) => {
for (const row of e.target.result) {
processRow(row, context);
2019-08-31 01:06:21 +00:00
}
resolve();
};
});
}
2020-02-17 21:16:08 +00:00
static _getAllUsingCursor(dbIndex, query, context, processRow) {
2019-08-31 01:06:21 +00:00
return new Promise((resolve, reject) => {
const request = dbIndex.openCursor(query, 'next');
request.onerror = (e) => reject(e);
request.onsuccess = (e) => {
const cursor = e.target.result;
if (cursor) {
processRow(cursor.value, context);
2019-08-31 01:06:21 +00:00
cursor.continue();
} else {
resolve();
}
};
});
}
2020-02-17 21:16:08 +00:00
static _getCounts(targets, query) {
const countPromises = [];
const counts = {};
for (const [objectStoreName, index] of targets) {
const n = objectStoreName;
2020-02-17 21:16:08 +00:00
const countPromise = Database._getCount(index, query).then((count) => counts[n] = count);
countPromises.push(countPromise);
}
return Promise.all(countPromises).then(() => counts);
}
2020-02-17 21:16:08 +00:00
static _getCount(dbIndex, query) {
return new Promise((resolve, reject) => {
const request = dbIndex.count(query);
request.onerror = (e) => reject(e);
request.onsuccess = (e) => resolve(e.target.result);
});
}
2020-02-17 21:16:08 +00:00
static _getAllKeys(dbIndex, query) {
const fn = typeof dbIndex.getAllKeys === 'function' ? Database._getAllKeysFast : Database._getAllKeysUsingCursor;
return fn(dbIndex, query);
}
2020-02-17 21:16:08 +00:00
static _getAllKeysFast(dbIndex, query) {
return new Promise((resolve, reject) => {
const request = dbIndex.getAllKeys(query);
request.onerror = (e) => reject(e);
request.onsuccess = (e) => resolve(e.target.result);
});
}
2020-02-17 21:16:08 +00:00
static _getAllKeysUsingCursor(dbIndex, query) {
return new Promise((resolve, reject) => {
const primaryKeys = [];
const request = dbIndex.openKeyCursor(query, 'next');
request.onerror = (e) => reject(e);
request.onsuccess = (e) => {
const cursor = e.target.result;
if (cursor) {
primaryKeys.push(cursor.primaryKey);
cursor.continue();
} else {
resolve(primaryKeys);
}
};
});
}
2020-02-17 21:16:08 +00:00
static async _deleteValues(dbObjectStore, dbIndex, query, onProgress, progressData, progressRate) {
const hasProgress = (typeof onProgress === 'function');
2020-02-17 21:16:08 +00:00
const count = await Database._getCount(dbIndex, query);
++progressData.storesProcesed;
progressData.count += count;
if (hasProgress) {
onProgress(progressData);
}
const onValueDeleted = (
hasProgress ?
() => {
const p = ++progressData.processed;
if ((p % progressRate) === 0 || p === progressData.count) {
onProgress(progressData);
}
} :
() => {}
);
const promises = [];
2020-02-17 21:16:08 +00:00
const primaryKeys = await Database._getAllKeys(dbIndex, query);
for (const key of primaryKeys) {
2020-02-17 21:16:08 +00:00
const promise = Database._deleteValue(dbObjectStore, key).then(onValueDeleted);
promises.push(promise);
}
await Promise.all(promises);
}
2020-02-17 21:16:08 +00:00
static _deleteValue(dbObjectStore, key) {
return new Promise((resolve, reject) => {
const request = dbObjectStore.delete(key);
request.onerror = (e) => reject(e);
request.onsuccess = () => resolve();
});
}
2020-02-17 21:16:08 +00:00
static _open(name, version, onUpgradeNeeded) {
return new Promise((resolve, reject) => {
const request = window.indexedDB.open(name, version * 10);
request.onupgradeneeded = (event) => {
try {
request.transaction.onerror = (e) => reject(e);
onUpgradeNeeded(request.result, request.transaction, event.oldVersion / 10, event.newVersion / 10);
} catch (e) {
reject(e);
}
};
request.onerror = (e) => reject(e);
request.onsuccess = () => resolve(request.result);
});
}
2020-02-17 21:16:08 +00:00
static _upgrade(db, transaction, oldVersion, upgrades) {
for (const {version, stores} of upgrades) {
if (oldVersion >= version) { continue; }
const objectStoreNames = Object.keys(stores);
for (const objectStoreName of objectStoreNames) {
const {primaryKey, indices} = stores[objectStoreName];
2020-02-17 20:21:30 +00:00
const objectStoreNames2 = transaction.objectStoreNames || db.objectStoreNames;
const objectStore = (
2020-02-17 20:21:30 +00:00
Database._listContains(objectStoreNames2, objectStoreName) ?
transaction.objectStore(objectStoreName) :
db.createObjectStore(objectStoreName, primaryKey)
);
for (const indexName of indices) {
2020-02-17 21:16:08 +00:00
if (Database._listContains(objectStore.indexNames, indexName)) { continue; }
objectStore.createIndex(indexName, indexName, {});
}
}
}
}
2020-02-17 21:16:08 +00:00
static _deleteDatabase(dbName) {
return new Promise((resolve, reject) => {
const request = indexedDB.deleteDatabase(dbName);
request.onerror = (e) => reject(e);
request.onsuccess = () => resolve();
});
}
2019-11-10 01:48:30 +00:00
2020-02-17 21:16:08 +00:00
static _listContains(list, value) {
2019-11-10 01:48:30 +00:00
for (let i = 0, ii = list.length; i < ii; ++i) {
if (list[i] === value) { return true; }
}
return false;
}
2016-03-20 02:32:35 +00:00
}