yomichan/ext/bg/js/database.js

850 lines
29 KiB
JavaScript
Raw Normal View History

2016-03-20 02:32:35 +00:00
/*
2017-08-15 04:43:09 +00:00
* Copyright (C) 2016-2017 Alex Yatskov <alex@foosoft.net>
2016-03-20 02:32:35 +00:00
* Author: Alex Yatskov <alex@foosoft.net>
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
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;
2016-08-21 20:32:36 +00:00
}
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 {
2019-11-24 02:48:24 +00:00
this.db = await Database.open('dict', 5, (db, transaction, oldVersion) => {
2019-11-10 01:48:30 +00:00
Database.upgrade(db, transaction, oldVersion, [
{
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']
}
}
}
2019-11-10 01:48:30 +00:00
]);
});
return true;
} catch (e) {
console.error(e);
return false;
}
2016-03-21 00:15:40 +00:00
}
2017-07-10 20:16:24 +00:00
async purge() {
2019-10-08 00:46:02 +00:00
this.validate();
2016-11-14 03:10:28 +00:00
this.db.close();
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) {
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);
promises.push(Database.deleteValues(dbObjectStore, dbIndex, only, onProgress, progressData, progressRate));
}
await Promise.all(promises);
}
2019-11-05 01:52:08 +00:00
async findTermsBulk(termList, titles, wildcard) {
2019-10-19 03:04:06 +00:00
this.validate();
2019-08-31 01:06:21 +00:00
const promises = [];
const visited = {};
const results = [];
const processRow = (row, index) => {
if (titles.includes(row.dictionary) && !hasOwn(visited, row.id)) {
visited[row.id] = true;
2019-10-19 03:09:00 +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(
2019-11-05 01:52: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;
}
2019-10-19 14:09:18 +00:00
async findTermsExactBulk(termList, readingList, titles) {
this.validate();
const promises = [];
const results = [];
const processRow = (row, index) => {
if (row.reading === readingList[index] && titles.includes(row.dictionary)) {
results.push(Database.createTerm(row, index));
}
};
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]);
promises.push(Database.getAll(dbIndex, only, i, processRow));
}
await Promise.all(promises);
return results;
}
async findTermsBySequenceBulk(sequenceList, mainDictionary) {
2019-10-19 03:04:06 +00:00
this.validate();
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) {
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]);
promises.push(Database.getAll(dbIndex, only, i, processRow));
2019-08-31 01:06:21 +00:00
}
await Promise.all(promises);
return results;
}
2019-10-19 14:09:18 +00:00
async findTermMetaBulk(termList, titles) {
return this.findGenericBulk('termMeta', 'expression', termList, titles, Database.createMeta);
}
async findKanjiBulk(kanjiList, titles) {
return this.findGenericBulk('kanji', 'character', kanjiList, titles, Database.createKanji);
}
async findKanjiMetaBulk(kanjiList, titles) {
return this.findGenericBulk('kanjiMeta', 'character', kanjiList, titles, Database.createMeta);
}
async findGenericBulk(tableName, indexName, indexValueList, titles, createResult) {
this.validate();
const promises = [];
const results = [];
const processRow = (row, index) => {
if (titles.includes(row.dictionary)) {
results.push(createResult(row, index));
}
};
2019-11-03 21:13:40 +00:00
const dbTransaction = this.db.transaction([tableName], 'readonly');
2019-10-19 14:09:18 +00:00
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;
}
2017-09-13 03:20:03 +00:00
2017-09-14 01:03:55 +00:00
async findTagForTitle(name, title) {
2019-10-08 00:46:02 +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);
2019-11-27 03:01:54 +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() {
this.validate();
const results = [];
2019-11-03 21:13:40 +00:00
const dbTransaction = this.db.transaction(['dictionaries'], 'readonly');
const dbDictionaries = dbTransaction.objectStore('dictionaries');
2019-11-27 03:01:54 +00:00
await Database.getAll(dbDictionaries, null, null, (info) => results.push(info));
return results;
}
async getDictionaryCounts(dictionaryNames, getTotal) {
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);
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]);
2019-11-27 03:01:54 +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;
}
async importDictionary(archive, progressCallback, details) {
2019-10-08 00:46:02 +00:00
this.validate();
2016-08-24 05:22:09 +00:00
const errors = [];
const prefixWildcardsSupported = details.prefixWildcardsSupported;
2019-02-27 02:01:32 +00:00
const maxTransactionLength = 1000;
const bulkAdd = async (objectStoreName, items, total, current) => {
2019-11-03 21:13:40 +00:00
const db = this.db;
for (let i = 0; i < items.length; i += maxTransactionLength) {
2019-02-27 02:01:32 +00:00
if (progressCallback) {
progressCallback(total, current + i / items.length);
2019-02-27 02:01:32 +00:00
}
try {
const count = Math.min(maxTransactionLength, items.length - i);
const transaction = db.transaction([objectStoreName], 'readwrite');
const objectStore = transaction.objectStore(objectStoreName);
await Database.bulkAdd(objectStore, items, i, count);
2019-02-27 02:01:32 +00:00
} catch (e) {
errors.push(e);
2019-02-27 02:01:32 +00:00
}
}
};
2019-11-27 03:01:54 +00:00
const indexDataLoaded = async (summary) => {
2017-10-29 19:20:56 +00:00
if (summary.version > 3) {
2019-10-08 00:46:02 +00:00
throw new Error('Unsupported dictionary version');
2017-09-17 19:56:34 +00:00
}
2019-11-03 21:13:40 +00:00
const db = this.db;
const dbCountTransaction = db.transaction(['dictionaries'], 'readonly');
const dbIndex = dbCountTransaction.objectStore('dictionaries').index('title');
const only = IDBKeyRange.only(summary.title);
const count = await Database.getCount(dbIndex, only);
2017-09-11 04:49:37 +00:00
if (count > 0) {
2019-10-08 00:46:02 +00:00
throw new Error('Dictionary is already imported');
2017-07-10 20:16:24 +00:00
}
const transaction = db.transaction(['dictionaries'], 'readwrite');
const objectStore = transaction.objectStore('dictionaries');
await Database.bulkAdd(objectStore, [summary], 0, 1);
2016-11-05 23:44:29 +00:00
};
2016-08-24 03:33:04 +00:00
2017-09-17 19:56:34 +00:00
const termDataLoaded = async (summary, entries, total, current) => {
2016-11-05 23:44:29 +00:00
const rows = [];
2017-09-17 19:56:34 +00:00
if (summary.version === 1) {
for (const [expression, reading, definitionTags, rules, score, ...glossary] of entries) {
2017-09-17 19:56:34 +00:00
rows.push({
expression,
reading,
definitionTags,
2017-09-17 19:56:34 +00:00
rules,
score,
glossary,
dictionary: summary.title
2017-09-17 19:56:34 +00:00
});
}
} else {
for (const [expression, reading, definitionTags, rules, score, glossary, sequence, termTags] of entries) {
2017-09-17 19:56:34 +00:00
rows.push({
expression,
reading,
definitionTags,
2017-09-17 19:56:34 +00:00
rules,
score,
glossary,
sequence,
termTags,
dictionary: summary.title
2017-09-17 19:56:34 +00:00
});
}
2016-11-05 23:44:29 +00:00
}
2016-08-24 03:33:04 +00:00
if (prefixWildcardsSupported) {
for (const row of rows) {
row.expressionReverse = stringReverse(row.expression);
row.readingReverse = stringReverse(row.reading);
}
}
await bulkAdd('terms', rows, total, current);
2016-11-05 23:44:29 +00:00
};
2017-09-23 15:46:34 +00:00
const termMetaDataLoaded = async (summary, entries, total, current) => {
2017-09-13 01:29:16 +00:00
const rows = [];
2017-09-23 15:46:34 +00:00
for (const [expression, mode, data] of entries) {
2017-09-13 01:29:16 +00:00
rows.push({
expression,
2017-09-23 15:46:34 +00:00
mode,
data,
2017-09-17 19:56:34 +00:00
dictionary: summary.title
2017-09-13 01:29:16 +00:00
});
}
await bulkAdd('termMeta', rows, total, current);
2017-09-13 01:29:16 +00:00
};
2017-09-17 19:56:34 +00:00
const kanjiDataLoaded = async (summary, entries, total, current) => {
2016-11-05 23:44:29 +00:00
const rows = [];
2017-09-17 19:56:34 +00:00
if (summary.version === 1) {
for (const [character, onyomi, kunyomi, tags, ...meanings] of entries) {
rows.push({
character,
onyomi,
kunyomi,
tags,
meanings,
dictionary: summary.title
});
}
} else {
2017-09-18 02:57:39 +00:00
for (const [character, onyomi, kunyomi, tags, meanings, stats] of entries) {
2017-09-17 19:56:34 +00:00
rows.push({
character,
onyomi,
kunyomi,
tags,
meanings,
stats,
dictionary: summary.title
});
}
2016-08-24 05:22:09 +00:00
}
await bulkAdd('kanji', rows, total, current);
2017-09-13 03:20:03 +00:00
};
2017-09-23 15:46:34 +00:00
const kanjiMetaDataLoaded = async (summary, entries, total, current) => {
2017-09-13 03:20:03 +00:00
const rows = [];
2017-09-23 15:46:34 +00:00
for (const [character, mode, data] of entries) {
2017-09-13 03:20:03 +00:00
rows.push({
character,
2017-09-23 15:46:34 +00:00
mode,
data,
2017-09-17 19:56:34 +00:00
dictionary: summary.title
2017-09-13 03:20:03 +00:00
});
}
await bulkAdd('kanjiMeta', rows, total, current);
2016-11-05 23:44:29 +00:00
};
2016-08-24 05:22:09 +00:00
2017-09-17 19:56:34 +00:00
const tagDataLoaded = async (summary, entries, total, current) => {
2017-09-12 20:29:13 +00:00
const rows = [];
2017-10-24 09:38:05 +00:00
for (const [name, category, order, notes, score] of entries) {
2017-09-12 20:29:13 +00:00
const row = dictTagSanitize({
name,
category,
order,
notes,
2017-10-24 09:38:05 +00:00
score,
2017-09-17 19:56:34 +00:00
dictionary: summary.title
2017-09-12 20:29:13 +00:00
});
rows.push(row);
}
await bulkAdd('tagMeta', rows, total, current);
2017-09-12 20:29:13 +00:00
};
const result = await Database.importDictionaryZip(
2017-09-11 04:49:37 +00:00
archive,
indexDataLoaded,
termDataLoaded,
2017-09-23 15:46:34 +00:00
termMetaDataLoaded,
2017-09-11 04:49:37 +00:00
kanjiDataLoaded,
2017-09-23 15:46:34 +00:00
kanjiMetaDataLoaded,
tagDataLoaded,
details
2017-09-11 04:49:37 +00:00
);
return {result, errors};
2016-08-24 05:22:09 +00:00
}
2017-07-10 21:53:06 +00:00
2019-10-08 00:46:02 +00:00
validate() {
if (this.db === null) {
throw new Error('Database not initialized');
}
}
2017-09-11 04:49:37 +00:00
static async importDictionaryZip(
archive,
indexDataLoaded,
termDataLoaded,
2017-09-23 15:46:34 +00:00
termMetaDataLoaded,
2017-09-11 04:49:37 +00:00
kanjiDataLoaded,
2017-09-23 15:46:34 +00:00
kanjiMetaDataLoaded,
tagDataLoaded,
details
2017-09-11 04:49:37 +00:00
) {
2017-09-13 22:41:06 +00:00
const zip = await JSZip.loadAsync(archive);
2017-07-10 21:53:06 +00:00
2017-09-13 22:41:06 +00:00
const indexFile = zip.files['index.json'];
2017-07-10 21:53:06 +00:00
if (!indexFile) {
2019-10-08 00:46:02 +00:00
throw new Error('No dictionary index found in archive');
2017-07-10 21:53:06 +00:00
}
const index = JSON.parse(await indexFile.async('string'));
2017-09-17 19:56:34 +00:00
if (!index.title || !index.revision) {
2019-10-08 00:46:02 +00:00
throw new Error('Unrecognized dictionary format');
2017-07-10 21:53:06 +00:00
}
2017-09-17 19:56:34 +00:00
const summary = {
title: index.title,
revision: index.revision,
sequenced: index.sequenced,
version: index.format || index.version,
prefixWildcardsSupported: !!details.prefixWildcardsSupported
2017-09-17 19:56:34 +00:00
};
await indexDataLoaded(summary);
2017-07-10 21:53:06 +00:00
2019-11-27 03:01:54 +00:00
const buildTermBankName = (index) => `term_bank_${index + 1}.json`;
const buildTermMetaBankName = (index) => `term_meta_bank_${index + 1}.json`;
const buildKanjiBankName = (index) => `kanji_bank_${index + 1}.json`;
const buildKanjiMetaBankName = (index) => `kanji_meta_bank_${index + 1}.json`;
const buildTagBankName = (index) => `tag_bank_${index + 1}.json`;
2017-09-11 04:49:37 +00:00
2019-11-27 03:01:54 +00:00
const countBanks = (namer) => {
2017-09-11 04:49:37 +00:00
let count = 0;
2017-09-13 22:41:06 +00:00
while (zip.files[namer(count)]) {
2017-09-11 04:49:37 +00:00
++count;
2017-07-10 21:53:06 +00:00
}
2017-09-11 04:49:37 +00:00
return count;
};
const termBankCount = countBanks(buildTermBankName);
2017-09-23 15:46:34 +00:00
const termMetaBankCount = countBanks(buildTermMetaBankName);
2017-09-12 20:29:13 +00:00
const kanjiBankCount = countBanks(buildKanjiBankName);
2017-09-23 15:46:34 +00:00
const kanjiMetaBankCount = countBanks(buildKanjiMetaBankName);
2017-09-12 20:29:13 +00:00
const tagBankCount = countBanks(buildTagBankName);
2017-09-11 04:49:37 +00:00
let bankLoadedCount = 0;
2017-09-12 20:29:13 +00:00
let bankTotalCount =
2017-09-11 04:49:37 +00:00
termBankCount +
2017-09-23 15:46:34 +00:00
termMetaBankCount +
2017-09-12 20:29:13 +00:00
kanjiBankCount +
2017-09-23 15:46:34 +00:00
kanjiMetaBankCount +
2017-09-11 04:49:37 +00:00
tagBankCount;
2017-09-12 20:29:13 +00:00
if (tagDataLoaded && index.tagMeta) {
const bank = [];
for (const name in index.tagMeta) {
const tag = index.tagMeta[name];
2017-10-24 09:38:05 +00:00
bank.push([name, tag.category, tag.order, tag.notes, tag.score]);
2017-09-12 20:29:13 +00:00
}
2017-09-17 19:56:34 +00:00
tagDataLoaded(summary, bank, ++bankTotalCount, bankLoadedCount++);
2017-09-12 20:29:13 +00:00
}
2017-09-17 19:56:34 +00:00
const loadBank = async (summary, namer, count, callback) => {
2017-09-11 04:49:37 +00:00
if (callback) {
for (let i = 0; i < count; ++i) {
2017-09-13 22:41:06 +00:00
const bankFile = zip.files[namer(i)];
2017-09-11 04:49:37 +00:00
const bank = JSON.parse(await bankFile.async('string'));
2017-09-17 19:56:34 +00:00
await callback(summary, bank, bankTotalCount, bankLoadedCount++);
2017-09-11 04:49:37 +00:00
}
}
};
2017-09-17 19:56:34 +00:00
await loadBank(summary, buildTermBankName, termBankCount, termDataLoaded);
2017-09-23 15:46:34 +00:00
await loadBank(summary, buildTermMetaBankName, termMetaBankCount, termMetaDataLoaded);
2017-09-17 19:56:34 +00:00
await loadBank(summary, buildKanjiBankName, kanjiBankCount, kanjiDataLoaded);
2017-09-23 15:46:34 +00:00
await loadBank(summary, buildKanjiMetaBankName, kanjiMetaBankCount, kanjiMetaDataLoaded);
2017-09-17 19:56:34 +00:00
await loadBank(summary, buildTagBankName, tagBankCount, tagDataLoaded);
2017-09-11 04:49:37 +00:00
return summary;
2017-07-10 21:53:06 +00:00
}
2019-08-31 01:06:21 +00:00
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
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
};
}
static createMeta(row, index) {
2019-08-31 01:06:21 +00:00
return {
index,
mode: row.mode,
data: row.data,
dictionary: row.dictionary
};
}
static getAll(dbIndex, query, context, processRow) {
2019-08-31 01:06:21 +00:00
const fn = typeof dbIndex.getAll === 'function' ? Database.getAllFast : Database.getAllUsingCursor;
return fn(dbIndex, query, context, processRow);
2019-08-31 01:06:21 +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();
};
});
}
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();
}
};
});
}
static getCounts(targets, query) {
const countPromises = [];
const counts = {};
for (const [objectStoreName, index] of targets) {
const n = objectStoreName;
2019-11-27 03:01:54 +00:00
const countPromise = Database.getCount(index, query).then((count) => counts[n] = count);
countPromises.push(countPromise);
}
return Promise.all(countPromises).then(() => counts);
}
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);
});
}
static getAllKeys(dbIndex, query) {
const fn = typeof dbIndex.getAllKeys === 'function' ? Database.getAllKeysFast : Database.getAllKeysUsingCursor;
return fn(dbIndex, query);
}
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);
});
}
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);
}
};
});
}
static async deleteValues(dbObjectStore, dbIndex, query, onProgress, progressData, progressRate) {
const hasProgress = (typeof onProgress === 'function');
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 = [];
const primaryKeys = await Database.getAllKeys(dbIndex, query);
for (const key of primaryKeys) {
const promise = Database.deleteValue(dbObjectStore, key).then(onValueDeleted);
promises.push(promise);
}
await Promise.all(promises);
}
static deleteValue(dbObjectStore, key) {
return new Promise((resolve, reject) => {
const request = dbObjectStore.delete(key);
request.onerror = (e) => reject(e);
request.onsuccess = () => resolve();
});
}
static bulkAdd(objectStore, items, start, count) {
return new Promise((resolve, reject) => {
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;
}
});
}
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);
});
}
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];
2019-11-10 01:48:30 +00:00
const objectStoreNames = transaction.objectStoreNames || db.objectStoreNames;
const objectStore = (
2019-11-10 01:48:30 +00:00
Database.listContains(objectStoreNames, objectStoreName) ?
transaction.objectStore(objectStoreName) :
db.createObjectStore(objectStoreName, primaryKey)
);
for (const indexName of indices) {
2019-11-10 01:48:30 +00:00
if (Database.listContains(objectStore.indexNames, indexName)) { continue; }
objectStore.createIndex(indexName, indexName, {});
}
}
}
}
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
static listContains(list, value) {
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
}