DbSearcher.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. //const _ = require('lodash');
  2. const utils = require('./utils');
  3. const maxMemCacheSize = 100;
  4. const maxLimit = 1000;
  5. const emptyFieldValue = '?';
  6. const maxUtf8Char = String.fromCodePoint(0xFFFFF);
  7. const ruAlphabet = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя';
  8. const enAlphabet = 'abcdefghijklmnopqrstuvwxyz';
  9. const enruArr = (ruAlphabet + enAlphabet).split('');
  10. class DbSearcher {
  11. constructor(config, db) {
  12. this.config = config;
  13. this.db = db;
  14. this.searchFlag = 0;
  15. this.timer = null;
  16. this.closed = false;
  17. this.memCache = new Map();
  18. this.bookIdMap = {};
  19. this.periodicCleanCache();//no await
  20. }
  21. queryKey(q) {
  22. return JSON.stringify([q.author, q.series, q.title, q.genre, q.lang, q.del, q.date, q.librate]);
  23. }
  24. getWhere(a) {
  25. const db = this.db;
  26. a = a.toLowerCase();
  27. let where;
  28. //особая обработка префиксов
  29. if (a[0] == '=') {
  30. a = a.substring(1);
  31. where = `@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a)})`;
  32. } else if (a[0] == '*') {
  33. a = a.substring(1);
  34. where = `@indexIter('value', (v) => (v !== ${db.esc(emptyFieldValue)} && v.indexOf(${db.esc(a)}) >= 0) )`;
  35. } else if (a[0] == '#') {
  36. a = a.substring(1);
  37. where = `@indexIter('value', (v) => {
  38. const enru = new Set(${db.esc(enruArr)});
  39. return !v || (v !== ${db.esc(emptyFieldValue)} && !enru.has(v[0]) && v.indexOf(${db.esc(a)}) >= 0);
  40. })`;
  41. } else {
  42. where = `@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a + maxUtf8Char)})`;
  43. }
  44. return where;
  45. }
  46. async selectBookIds(query) {
  47. const db = this.db;
  48. const idsArr = [];
  49. const tableBookIds = async(table, where) => {
  50. const rows = await db.select({
  51. table,
  52. rawResult: true,
  53. where: `
  54. const ids = ${where};
  55. const result = new Set();
  56. for (const id of ids) {
  57. const row = @unsafeRow(id);
  58. for (const bookId of row.bookIds)
  59. result.add(bookId);
  60. }
  61. return Array.from(result);
  62. `
  63. });
  64. return rows[0].rawResult;
  65. };
  66. //авторы
  67. if (query.author && query.author !== '*') {
  68. const key = `book-ids-author-${query.author}`;
  69. let ids = await this.getCached(key);
  70. if (ids === null) {
  71. ids = await tableBookIds('author', this.getWhere(query.author));
  72. await this.putCached(key, ids);
  73. }
  74. idsArr.push(ids);
  75. }
  76. //серии
  77. if (query.series && query.series !== '*') {
  78. const key = `book-ids-series-${query.series}`;
  79. let ids = await this.getCached(key);
  80. if (ids === null) {
  81. ids = await tableBookIds('series', this.getWhere(query.series));
  82. await this.putCached(key, ids);
  83. }
  84. idsArr.push(ids);
  85. }
  86. //названия
  87. if (query.title && query.title !== '*') {
  88. const key = `book-ids-title-${query.title}`;
  89. let ids = await this.getCached(key);
  90. if (ids === null) {
  91. ids = await tableBookIds('title', this.getWhere(query.title));
  92. await this.putCached(key, ids);
  93. }
  94. idsArr.push(ids);
  95. }
  96. //жанры
  97. if (query.genre) {
  98. const key = `book-ids-genre-${query.genre}`;
  99. let ids = await this.getCached(key);
  100. if (ids === null) {
  101. const genreRows = await db.select({
  102. table: 'genre',
  103. rawResult: true,
  104. where: `
  105. const genres = ${db.esc(query.genre.split(','))};
  106. const ids = new Set();
  107. for (const g of genres) {
  108. for (const id of @indexLR('value', g, g))
  109. ids.add(id);
  110. }
  111. const result = new Set();
  112. for (const id of ids) {
  113. const row = @unsafeRow(id);
  114. for (const bookId of row.bookIds)
  115. result.add(bookId);
  116. }
  117. return Array.from(result);
  118. `
  119. });
  120. ids = genreRows[0].rawResult;
  121. await this.putCached(key, ids);
  122. }
  123. idsArr.push(ids);
  124. }
  125. //языки
  126. if (query.lang) {
  127. const key = `book-ids-lang-${query.lang}`;
  128. let ids = await this.getCached(key);
  129. if (ids === null) {
  130. const langRows = await db.select({
  131. table: 'lang',
  132. rawResult: true,
  133. where: `
  134. const langs = ${db.esc(query.lang.split(','))};
  135. const ids = new Set();
  136. for (const l of langs) {
  137. for (const id of @indexLR('value', l, l))
  138. ids.add(id);
  139. }
  140. const result = new Set();
  141. for (const id of ids) {
  142. const row = @unsafeRow(id);
  143. for (const bookId of row.bookIds)
  144. result.add(bookId);
  145. }
  146. return Array.from(result);
  147. `
  148. });
  149. ids = langRows[0].rawResult;
  150. await this.putCached(key, ids);
  151. }
  152. idsArr.push(ids);
  153. }
  154. //удаленные
  155. if (query.del !== undefined) {
  156. const key = `book-ids-del-${query.del}`;
  157. let ids = await this.getCached(key);
  158. if (ids === null) {
  159. ids = await tableBookIds('del', `@indexLR('value', ${db.esc(query.del)}, ${db.esc(query.del)})`);
  160. await this.putCached(key, ids);
  161. }
  162. idsArr.push(ids);
  163. }
  164. //дата поступления
  165. if (query.date) {
  166. const key = `book-ids-date-${query.date}`;
  167. let ids = await this.getCached(key);
  168. if (ids === null) {
  169. let [from = '', to = ''] = query.date.split(',');
  170. ids = await tableBookIds('date', `@indexLR('value', ${db.esc(from)} || undefined, ${db.esc(to)} || undefined)`);
  171. await this.putCached(key, ids);
  172. }
  173. idsArr.push(ids);
  174. }
  175. //оценка
  176. if (query.librate) {
  177. const key = `book-ids-librate-${query.librate}`;
  178. let ids = await this.getCached(key);
  179. if (ids === null) {
  180. const dateRows = await db.select({
  181. table: 'librate',
  182. rawResult: true,
  183. where: `
  184. const rates = ${db.esc(query.librate.split(',').map(n => parseInt(n, 10)).filter(n => !isNaN(n)))};
  185. const ids = new Set();
  186. for (const rate of rates) {
  187. for (const id of @indexLR('value', rate, rate))
  188. ids.add(id);
  189. }
  190. const result = new Set();
  191. for (const id of ids) {
  192. const row = @unsafeRow(id);
  193. for (const bookId of row.bookIds)
  194. result.add(bookId);
  195. }
  196. return Array.from(result);
  197. `
  198. });
  199. ids = dateRows[0].rawResult;
  200. await this.putCached(key, ids);
  201. }
  202. idsArr.push(ids);
  203. }
  204. if (idsArr.length > 1) {
  205. //ищем пересечение множеств
  206. let proc = 0;
  207. let nextProc = 0;
  208. let inter = new Set(idsArr[0]);
  209. for (let i = 1; i < idsArr.length; i++) {
  210. const newInter = new Set();
  211. for (const id of idsArr[i]) {
  212. if (inter.has(id))
  213. newInter.add(id);
  214. //прерываемся иногда, чтобы не блокировать Event Loop
  215. proc++;
  216. if (proc >= nextProc) {
  217. nextProc += 10000;
  218. await utils.processLoop();
  219. }
  220. }
  221. inter = newInter;
  222. }
  223. return Array.from(inter);
  224. } else if (idsArr.length == 1) {
  225. return idsArr[0];
  226. } else {
  227. return false;
  228. }
  229. }
  230. async fillBookIdMap(from) {
  231. if (!this.bookIdMap[from]) {
  232. const db = this.db;
  233. const map = new Map();
  234. const table = `${from}_id`;
  235. await db.open({table});
  236. const rows = await db.select({table});
  237. await db.close({table});
  238. for (const row of rows) {
  239. if (!row.value.length)
  240. continue;
  241. if (row.value.length > 1)
  242. map.set(row.id, row.value);
  243. else
  244. map.set(row.id, row.value[0]);
  245. }
  246. this.bookIdMap[from] = map;
  247. }
  248. return this.bookIdMap[from];
  249. }
  250. async filterTableIds(tableIds, from, query) {
  251. let result = tableIds;
  252. //т.к. авторы у книги идут списком, то дополнительно фильтруем
  253. if (from == 'author' && query.author && query.author !== '*') {
  254. const key = `filter-ids-author-${query.author}`;
  255. let authorIds = await this.getCached(key);
  256. if (authorIds === null) {
  257. const rows = await this.db.select({
  258. table: 'author',
  259. rawResult: true,
  260. where: `return Array.from(${this.getWhere(query.author)})`
  261. });
  262. authorIds = rows[0].rawResult;
  263. await this.putCached(key, authorIds);
  264. }
  265. //пересечение tableIds и authorIds
  266. result = [];
  267. const authorIdsSet = new Set(authorIds);
  268. for (const id of tableIds)
  269. if (authorIdsSet.has(id))
  270. result.push(id);
  271. }
  272. return result;
  273. }
  274. async selectTableIds(from, query) {
  275. const db = this.db;
  276. const queryKey = this.queryKey(query);
  277. const tableKey = `${from}-table-ids-${queryKey}`;
  278. let tableIds = await this.getCached(tableKey);
  279. if (tableIds === null) {
  280. const bookKey = `book-ids-${queryKey}`;
  281. let bookIds = await this.getCached(bookKey);
  282. if (bookIds === null) {
  283. bookIds = await this.selectBookIds(query);
  284. await this.putCached(bookKey, bookIds);
  285. }
  286. if (bookIds) {
  287. const tableIdsSet = new Set();
  288. const bookIdMap = await this.fillBookIdMap(from);
  289. for (const bookId of bookIds) {
  290. const tableIdValue = bookIdMap.get(bookId);
  291. if (!tableIdValue)
  292. continue;
  293. if (Array.isArray(tableIdValue)) {
  294. for (const tableId of tableIdValue)
  295. tableIdsSet.add(tableId);
  296. } else
  297. tableIdsSet.add(tableIdValue);
  298. }
  299. tableIds = Array.from(tableIdsSet);
  300. } else {
  301. const rows = await db.select({
  302. table: from,
  303. rawResult: true,
  304. where: `return Array.from(@all())`
  305. });
  306. tableIds = rows[0].rawResult;
  307. }
  308. tableIds = await this.filterTableIds(tableIds, from, query);
  309. tableIds.sort((a, b) => a - b);
  310. await this.putCached(tableKey, tableIds);
  311. }
  312. return tableIds;
  313. }
  314. async restoreBooks(from, ids) {
  315. const db = this.db;
  316. const bookTable = `${from}_book`;
  317. const rows = await db.select({
  318. table: bookTable,
  319. where: `@@id(${db.esc(ids)})`
  320. });
  321. if (rows.length == ids.length)
  322. return rows;
  323. const idsSet = new Set(rows.map(r => r.id));
  324. for (const id of ids) {
  325. if (!idsSet.has(id)) {
  326. const bookIds = await db.select({
  327. table: from,
  328. where: `@@id(${db.esc(id)})`
  329. });
  330. if (!bookIds.length)
  331. continue;
  332. let books = await db.select({
  333. table: 'book',
  334. where: `@@id(${db.esc(bookIds[0].bookIds)})`
  335. });
  336. if (!books.length)
  337. continue;
  338. rows.push({id, name: bookIds[0].name, books});
  339. await db.insert({table: bookTable, ignore: true, rows});
  340. }
  341. }
  342. return rows;
  343. }
  344. async search(from, query) {
  345. if (this.closed)
  346. throw new Error('DbSearcher closed');
  347. if (!['author', 'series', 'title'].includes(from))
  348. throw new Error(`Unknown value for param 'from'`);
  349. this.searchFlag++;
  350. try {
  351. const db = this.db;
  352. const ids = await this.selectTableIds(from, query);
  353. const totalFound = ids.length;
  354. let limit = (query.limit ? query.limit : 100);
  355. limit = (limit > maxLimit ? maxLimit : limit);
  356. const offset = (query.offset ? query.offset : 0);
  357. //выборка найденных значений
  358. const found = await db.select({
  359. table: from,
  360. map: `(r) => ({id: r.id, ${from}: r.name, bookCount: r.bookCount, bookDelCount: r.bookDelCount})`,
  361. where: `@@id(${db.esc(ids.slice(offset, offset + limit))})`
  362. });
  363. //для title восстановим books
  364. if (from == 'title') {
  365. const bookIds = found.map(r => r.id);
  366. const rows = await this.restoreBooks(from, bookIds);
  367. const rowsMap = new Map();
  368. for (const row of rows)
  369. rowsMap.set(row.id, row);
  370. for (const f of found) {
  371. const b = rowsMap.get(f.id);
  372. if (b)
  373. f.books = b.books;
  374. }
  375. }
  376. return {found, totalFound};
  377. } finally {
  378. this.searchFlag--;
  379. }
  380. }
  381. async getAuthorBookList(authorId) {
  382. if (this.closed)
  383. throw new Error('DbSearcher closed');
  384. if (!authorId)
  385. return {author: '', books: ''};
  386. this.searchFlag++;
  387. try {
  388. //выборка книг автора по authorId
  389. const rows = await this.restoreBooks('author', [authorId])
  390. let author = '';
  391. let books = '';
  392. if (rows.length) {
  393. author = rows[0].name;
  394. books = rows[0].books;
  395. }
  396. return {author, books: (books && books.length ? JSON.stringify(books) : '')};
  397. } finally {
  398. this.searchFlag--;
  399. }
  400. }
  401. async getSeriesBookList(series) {
  402. if (this.closed)
  403. throw new Error('DbSearcher closed');
  404. if (!series)
  405. return {books: ''};
  406. this.searchFlag++;
  407. try {
  408. const db = this.db;
  409. series = series.toLowerCase();
  410. //выборка серии по названию серии
  411. let rows = await db.select({
  412. table: 'series',
  413. rawResult: true,
  414. where: `return Array.from(@dirtyIndexLR('value', ${db.esc(series)}, ${db.esc(series)}))`
  415. });
  416. let books;
  417. if (rows.length && rows[0].rawResult.length) {
  418. //выборка книг серии
  419. const bookRows = await this.restoreBooks('series', [rows[0].rawResult[0]])
  420. if (bookRows.length)
  421. books = bookRows[0].books;
  422. }
  423. return {books: (books && books.length ? JSON.stringify(books) : '')};
  424. } finally {
  425. this.searchFlag--;
  426. }
  427. }
  428. async getCached(key) {
  429. if (!this.config.queryCacheEnabled)
  430. return null;
  431. let result = null;
  432. const db = this.db;
  433. const memCache = this.memCache;
  434. if (memCache.has(key)) {//есть в недавних
  435. result = memCache.get(key);
  436. //изменим порядок ключей, для последующей правильной чистки старых
  437. memCache.delete(key);
  438. memCache.set(key, result);
  439. } else {//смотрим в таблице
  440. const rows = await db.select({table: 'query_cache', where: `@@id(${db.esc(key)})`});
  441. if (rows.length) {//нашли в кеше
  442. await db.insert({
  443. table: 'query_time',
  444. replace: true,
  445. rows: [{id: key, time: Date.now()}],
  446. });
  447. result = rows[0].value;
  448. memCache.set(key, result);
  449. if (memCache.size > maxMemCacheSize) {
  450. //удаляем самый старый ключ-значение
  451. for (const k of memCache.keys()) {
  452. memCache.delete(k);
  453. break;
  454. }
  455. }
  456. }
  457. }
  458. return result;
  459. }
  460. async putCached(key, value) {
  461. if (!this.config.queryCacheEnabled)
  462. return;
  463. const db = this.db;
  464. const memCache = this.memCache;
  465. memCache.set(key, value);
  466. if (memCache.size > maxMemCacheSize) {
  467. //удаляем самый старый ключ-значение
  468. for (const k of memCache.keys()) {
  469. memCache.delete(k);
  470. break;
  471. }
  472. }
  473. //кладем в таблицу асинхронно
  474. (async() => {
  475. try {
  476. await db.insert({
  477. table: 'query_cache',
  478. replace: true,
  479. rows: [{id: key, value}],
  480. });
  481. await db.insert({
  482. table: 'query_time',
  483. replace: true,
  484. rows: [{id: key, time: Date.now()}],
  485. });
  486. } catch(e) {
  487. console.error(`putCached: ${e.message}`);
  488. }
  489. })();
  490. }
  491. async periodicCleanCache() {
  492. this.timer = null;
  493. const cleanInterval = this.config.cacheCleanInterval*60*1000;
  494. if (!cleanInterval)
  495. return;
  496. try {
  497. const db = this.db;
  498. const oldThres = Date.now() - cleanInterval;
  499. //выберем всех кандидатов на удаление
  500. const rows = await db.select({
  501. table: 'query_time',
  502. where: `
  503. @@iter(@all(), (r) => (r.time < ${db.esc(oldThres)}));
  504. `
  505. });
  506. const ids = [];
  507. for (const row of rows)
  508. ids.push(row.id);
  509. //удаляем
  510. await db.delete({table: 'query_cache', where: `@@id(${db.esc(ids)})`});
  511. await db.delete({table: 'query_time', where: `@@id(${db.esc(ids)})`});
  512. //console.log('Cache clean', ids);
  513. } catch(e) {
  514. console.error(e.message);
  515. } finally {
  516. if (!this.closed) {
  517. this.timer = setTimeout(() => { this.periodicCleanCache(); }, cleanInterval);
  518. }
  519. }
  520. }
  521. async close() {
  522. while (this.searchFlag > 0) {
  523. await utils.sleep(50);
  524. }
  525. this.searchCache = null;
  526. if (this.timer) {
  527. clearTimeout(this.timer);
  528. this.timer = null;
  529. }
  530. this.closed = true;
  531. }
  532. }
  533. module.exports = DbSearcher;