DbSearcher.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  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. //далее восстановим книги из book в <from>_book
  324. const idsSet = new Set(rows.map(r => r.id));
  325. //недостающие
  326. const tableIds = [];
  327. for (const id of ids) {
  328. if (!idsSet.has(id))
  329. tableIds.push(id);
  330. }
  331. const tableRows = await db.select({
  332. table: from,
  333. where: `@@id(${db.esc(tableIds)})`
  334. });
  335. //список недостающих bookId
  336. const bookIds = [];
  337. for (const row of tableRows) {
  338. for (const bookId of row.bookIds)
  339. bookIds.push(bookId);
  340. }
  341. //выбираем книги
  342. const books = await db.select({
  343. table: 'book',
  344. where: `@@id(${db.esc(bookIds)})`
  345. });
  346. const booksMap = new Map();
  347. for (const book of books)
  348. booksMap.set(book.id, book);
  349. //распределяем
  350. for (const row of tableRows) {
  351. const books = [];
  352. for (const bookId of row.bookIds) {
  353. const book = booksMap.get(bookId);
  354. if (book)
  355. books.push(book);
  356. }
  357. rows.push({id: row.id, name: row.name, books});
  358. }
  359. await db.insert({table: bookTable, ignore: true, rows});
  360. return rows;
  361. }
  362. async search(from, query) {
  363. if (this.closed)
  364. throw new Error('DbSearcher closed');
  365. if (!['author', 'series', 'title'].includes(from))
  366. throw new Error(`Unknown value for param 'from'`);
  367. this.searchFlag++;
  368. try {
  369. const db = this.db;
  370. const ids = await this.selectTableIds(from, query);
  371. const totalFound = ids.length;
  372. let limit = (query.limit ? query.limit : 100);
  373. limit = (limit > maxLimit ? maxLimit : limit);
  374. const offset = (query.offset ? query.offset : 0);
  375. //выборка найденных значений
  376. const found = await db.select({
  377. table: from,
  378. map: `(r) => ({id: r.id, ${from}: r.name, bookCount: r.bookCount, bookDelCount: r.bookDelCount})`,
  379. where: `@@id(${db.esc(ids.slice(offset, offset + limit))})`
  380. });
  381. //для title восстановим books
  382. if (from == 'title') {
  383. const bookIds = found.map(r => r.id);
  384. const rows = await this.restoreBooks(from, bookIds);
  385. const rowsMap = new Map();
  386. for (const row of rows)
  387. rowsMap.set(row.id, row);
  388. for (const f of found) {
  389. const b = rowsMap.get(f.id);
  390. if (b)
  391. f.books = b.books;
  392. }
  393. }
  394. return {found, totalFound};
  395. } finally {
  396. this.searchFlag--;
  397. }
  398. }
  399. async getAuthorBookList(authorId) {
  400. if (this.closed)
  401. throw new Error('DbSearcher closed');
  402. if (!authorId)
  403. return {author: '', books: ''};
  404. this.searchFlag++;
  405. try {
  406. //выборка книг автора по authorId
  407. const rows = await this.restoreBooks('author', [authorId])
  408. let author = '';
  409. let books = '';
  410. if (rows.length) {
  411. author = rows[0].name;
  412. books = rows[0].books;
  413. }
  414. return {author, books: (books && books.length ? JSON.stringify(books) : '')};
  415. } finally {
  416. this.searchFlag--;
  417. }
  418. }
  419. async getSeriesBookList(series) {
  420. if (this.closed)
  421. throw new Error('DbSearcher closed');
  422. if (!series)
  423. return {books: ''};
  424. this.searchFlag++;
  425. try {
  426. const db = this.db;
  427. series = series.toLowerCase();
  428. //выборка серии по названию серии
  429. let rows = await db.select({
  430. table: 'series',
  431. rawResult: true,
  432. where: `return Array.from(@dirtyIndexLR('value', ${db.esc(series)}, ${db.esc(series)}))`
  433. });
  434. let books;
  435. if (rows.length && rows[0].rawResult.length) {
  436. //выборка книг серии
  437. const bookRows = await this.restoreBooks('series', [rows[0].rawResult[0]])
  438. if (bookRows.length)
  439. books = bookRows[0].books;
  440. }
  441. return {books: (books && books.length ? JSON.stringify(books) : '')};
  442. } finally {
  443. this.searchFlag--;
  444. }
  445. }
  446. async getCached(key) {
  447. if (!this.config.queryCacheEnabled)
  448. return null;
  449. let result = null;
  450. const db = this.db;
  451. const memCache = this.memCache;
  452. if (memCache.has(key)) {//есть в недавних
  453. result = memCache.get(key);
  454. //изменим порядок ключей, для последующей правильной чистки старых
  455. memCache.delete(key);
  456. memCache.set(key, result);
  457. } else {//смотрим в таблице
  458. const rows = await db.select({table: 'query_cache', where: `@@id(${db.esc(key)})`});
  459. if (rows.length) {//нашли в кеше
  460. await db.insert({
  461. table: 'query_time',
  462. replace: true,
  463. rows: [{id: key, time: Date.now()}],
  464. });
  465. result = rows[0].value;
  466. memCache.set(key, result);
  467. if (memCache.size > maxMemCacheSize) {
  468. //удаляем самый старый ключ-значение
  469. for (const k of memCache.keys()) {
  470. memCache.delete(k);
  471. break;
  472. }
  473. }
  474. }
  475. }
  476. return result;
  477. }
  478. async putCached(key, value) {
  479. if (!this.config.queryCacheEnabled)
  480. return;
  481. const db = this.db;
  482. const memCache = this.memCache;
  483. memCache.set(key, value);
  484. if (memCache.size > maxMemCacheSize) {
  485. //удаляем самый старый ключ-значение
  486. for (const k of memCache.keys()) {
  487. memCache.delete(k);
  488. break;
  489. }
  490. }
  491. //кладем в таблицу асинхронно
  492. (async() => {
  493. try {
  494. await db.insert({
  495. table: 'query_cache',
  496. replace: true,
  497. rows: [{id: key, value}],
  498. });
  499. await db.insert({
  500. table: 'query_time',
  501. replace: true,
  502. rows: [{id: key, time: Date.now()}],
  503. });
  504. } catch(e) {
  505. console.error(`putCached: ${e.message}`);
  506. }
  507. })();
  508. }
  509. async periodicCleanCache() {
  510. this.timer = null;
  511. const cleanInterval = this.config.cacheCleanInterval*60*1000;
  512. if (!cleanInterval)
  513. return;
  514. try {
  515. const db = this.db;
  516. const oldThres = Date.now() - cleanInterval;
  517. //выберем всех кандидатов на удаление
  518. const rows = await db.select({
  519. table: 'query_time',
  520. where: `
  521. @@iter(@all(), (r) => (r.time < ${db.esc(oldThres)}));
  522. `
  523. });
  524. const ids = [];
  525. for (const row of rows)
  526. ids.push(row.id);
  527. //удаляем
  528. await db.delete({table: 'query_cache', where: `@@id(${db.esc(ids)})`});
  529. await db.delete({table: 'query_time', where: `@@id(${db.esc(ids)})`});
  530. //console.log('Cache clean', ids);
  531. } catch(e) {
  532. console.error(e.message);
  533. } finally {
  534. if (!this.closed) {
  535. this.timer = setTimeout(() => { this.periodicCleanCache(); }, cleanInterval);
  536. }
  537. }
  538. }
  539. async close() {
  540. while (this.searchFlag > 0) {
  541. await utils.sleep(50);
  542. }
  543. this.searchCache = null;
  544. if (this.timer) {
  545. clearTimeout(this.timer);
  546. this.timer = null;
  547. }
  548. this.closed = true;
  549. }
  550. }
  551. module.exports = DbSearcher;