DbSearcher.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  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.periodicCleanCache();//no await
  19. }
  20. queryKey(q) {
  21. return JSON.stringify([q.author, q.series, q.title, q.genre, q.lang, q.del]);
  22. }
  23. getWhere(a) {
  24. const db = this.db;
  25. a = a.toLowerCase();
  26. let where;
  27. //особая обработка префиксов
  28. if (a[0] == '=') {
  29. a = a.substring(1);
  30. where = `@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a)})`;
  31. } else if (a[0] == '*') {
  32. a = a.substring(1);
  33. where = `@indexIter('value', (v) => (v !== ${db.esc(emptyFieldValue)} && v.indexOf(${db.esc(a)}) >= 0) )`;
  34. } else if (a[0] == '#') {
  35. a = a.substring(1);
  36. where = `@indexIter('value', (v) => {
  37. const enru = new Set(${db.esc(enruArr)});
  38. return !v || (v !== ${db.esc(emptyFieldValue)} && !enru.has(v[0]) && v.indexOf(${db.esc(a)}) >= 0);
  39. })`;
  40. } else {
  41. where = `@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a + maxUtf8Char)})`;
  42. }
  43. return where;
  44. }
  45. async selectAuthorIds(query) {
  46. const db = this.db;
  47. const authorKеy = `author-ids-author-${query.author}`;
  48. let authorIds = await this.getCached(authorKеy);
  49. //сначала выберем все id авторов по фильтру
  50. //порядок id соответствует ASC-сортировке по author
  51. if (authorIds === null) {
  52. if (query.author && query.author !== '*') {
  53. const where = this.getWhere(query.author);
  54. const authorRows = await db.select({
  55. table: 'author',
  56. rawResult: true,
  57. where: `return Array.from(${where})`,
  58. });
  59. authorIds = authorRows[0].rawResult;
  60. } else {//все авторы
  61. const authorRows = await db.select({
  62. table: 'author',
  63. rawResult: true,
  64. where: `return Array.from(@all())`,
  65. });
  66. authorIds = authorRows[0].rawResult;
  67. }
  68. await this.putCached(authorKеy, authorIds);
  69. }
  70. const idsArr = [];
  71. //серии
  72. if (query.series && query.series !== '*') {
  73. const seriesKеy = `author-ids-series-${query.series}`;
  74. let seriesIds = await this.getCached(seriesKеy);
  75. if (seriesIds === null) {
  76. const where = this.getWhere(query.series);
  77. const seriesRows = await db.select({
  78. table: 'series',
  79. rawResult: true,
  80. where: `
  81. const ids = ${where};
  82. const result = new Set();
  83. for (const id of ids) {
  84. const row = @unsafeRow(id);
  85. for (const authorId of row.authorId)
  86. result.add(authorId);
  87. }
  88. return Array.from(result);
  89. `
  90. });
  91. seriesIds = seriesRows[0].rawResult;
  92. await this.putCached(seriesKеy, seriesIds);
  93. }
  94. idsArr.push(seriesIds);
  95. }
  96. //названия
  97. if (query.title && query.title !== '*') {
  98. const titleKey = `author-ids-title-${query.title}`;
  99. let titleIds = await this.getCached(titleKey);
  100. if (titleIds === null) {
  101. const where = this.getWhere(query.title);
  102. let titleRows = await db.select({
  103. table: 'title',
  104. rawResult: true,
  105. where: `
  106. const ids = ${where};
  107. const result = new Set();
  108. for (const id of ids) {
  109. const row = @unsafeRow(id);
  110. for (const authorId of row.authorId)
  111. result.add(authorId);
  112. }
  113. return Array.from(result);
  114. `
  115. });
  116. titleIds = titleRows[0].rawResult;
  117. await this.putCached(titleKey, titleIds);
  118. }
  119. idsArr.push(titleIds);
  120. //чистки памяти при тяжелых запросах
  121. if (this.config.lowMemoryMode && query.title[0] == '*') {
  122. utils.freeMemory();
  123. await db.freeMemory();
  124. }
  125. }
  126. //жанры
  127. if (query.genre) {
  128. const genreKey = `author-ids-genre-${query.genre}`;
  129. let genreIds = await this.getCached(genreKey);
  130. if (genreIds === null) {
  131. const genreRows = await db.select({
  132. table: 'genre',
  133. rawResult: true,
  134. where: `
  135. const genres = ${db.esc(query.genre.split(','))};
  136. const ids = new Set();
  137. for (const g of genres) {
  138. for (const id of @indexLR('value', g, g))
  139. ids.add(id);
  140. }
  141. const result = new Set();
  142. for (const id of ids) {
  143. const row = @unsafeRow(id);
  144. for (const authorId of row.authorId)
  145. result.add(authorId);
  146. }
  147. return Array.from(result);
  148. `
  149. });
  150. genreIds = genreRows[0].rawResult;
  151. await this.putCached(genreKey, genreIds);
  152. }
  153. idsArr.push(genreIds);
  154. }
  155. //языки
  156. if (query.lang) {
  157. const langKey = `author-ids-lang-${query.lang}`;
  158. let langIds = await this.getCached(langKey);
  159. if (langIds === null) {
  160. const langRows = await db.select({
  161. table: 'lang',
  162. rawResult: true,
  163. where: `
  164. const langs = ${db.esc(query.lang.split(','))};
  165. const ids = new Set();
  166. for (const l of langs) {
  167. for (const id of @indexLR('value', l, l))
  168. ids.add(id);
  169. }
  170. const result = new Set();
  171. for (const id of ids) {
  172. const row = @unsafeRow(id);
  173. for (const authorId of row.authorId)
  174. result.add(authorId);
  175. }
  176. return Array.from(result);
  177. `
  178. });
  179. langIds = langRows[0].rawResult;
  180. await this.putCached(langKey, langIds);
  181. }
  182. idsArr.push(langIds);
  183. }
  184. //удаленные
  185. if (query.del !== undefined) {
  186. const delKey = `author-ids-del-${query.del}`;
  187. let delIds = await this.getCached(delKey);
  188. if (delIds === null) {
  189. const delRows = await db.select({
  190. table: 'del',
  191. rawResult: true,
  192. where: `
  193. const ids = @indexLR('value', ${db.esc(query.del)}, ${db.esc(query.del)});
  194. const result = new Set();
  195. for (const id of ids) {
  196. const row = @unsafeRow(id);
  197. for (const authorId of row.authorId)
  198. result.add(authorId);
  199. }
  200. return Array.from(result);
  201. `
  202. });
  203. delIds = delRows[0].rawResult;
  204. await this.putCached(delKey, delIds);
  205. }
  206. idsArr.push(delIds);
  207. }
  208. /*
  209. //ищем пересечение множеств
  210. idsArr.push(authorIds);
  211. if (idsArr.length > 1) {
  212. const idsSetArr = idsArr.map(ids => new Set(ids));
  213. authorIds = Array.from(utils.intersectSet(idsSetArr));
  214. }
  215. //сортировка
  216. authorIds.sort((a, b) => a - b);
  217. */
  218. //ищем пересечение множеств, работает быстрее предыдущего
  219. if (idsArr.length) {
  220. idsArr.push(authorIds);
  221. let proc = 0;
  222. let nextProc = 0;
  223. let inter = new Set(idsArr[0]);
  224. for (let i = 1; i < idsArr.length; i++) {
  225. const newInter = new Set();
  226. for (const id of idsArr[i]) {
  227. if (inter.has(id))
  228. newInter.add(id);
  229. //прерываемся иногда, чтобы не блокировать Event Loop
  230. proc++;
  231. if (proc >= nextProc) {
  232. nextProc += 10000;
  233. await utils.processLoop();
  234. }
  235. }
  236. inter = newInter;
  237. }
  238. authorIds = Array.from(inter);
  239. }
  240. //сортировка
  241. authorIds.sort((a, b) => a - b);
  242. return authorIds;
  243. }
  244. getWhere2(query, ids, exclude = '') {
  245. const db = this.db;
  246. const filterBySearch = (searchValue) => {
  247. searchValue = searchValue.toLowerCase();
  248. //особая обработка префиксов
  249. if (searchValue[0] == '=') {
  250. searchValue = searchValue.substring(1);
  251. return `bookValue.localeCompare(${db.esc(searchValue)}) == 0`;
  252. } else if (searchValue[0] == '*') {
  253. searchValue = searchValue.substring(1);
  254. return `bookValue !== ${db.esc(emptyFieldValue)} && bookValue.indexOf(${db.esc(searchValue)}) >= 0`;
  255. } else if (searchValue[0] == '#') {
  256. searchValue = searchValue.substring(1);
  257. return `!bookValue || (bookValue !== ${db.esc(emptyFieldValue)} && !enru.has(bookValue[0]) && bookValue.indexOf(${db.esc(searchValue)}) >= 0)`;
  258. } else {
  259. return `bookValue.localeCompare(${db.esc(searchValue)}) >= 0 && bookValue.localeCompare(${db.esc(searchValue + maxUtf8Char)}) <= 0`;
  260. }
  261. };
  262. //подготовка фильтра
  263. let filter = '';
  264. let closures = '';
  265. //порядок важен, более простые проверки вперед
  266. //удаленные
  267. if (query.del !== undefined) {
  268. filter += `
  269. if (book.del !== ${db.esc(query.del)})
  270. return false;
  271. `;
  272. }
  273. //серии
  274. if (exclude !== 'series' && query.series && query.series !== '*') {
  275. closures += `
  276. const checkSeries = (bookValue) => {
  277. if (!bookValue)
  278. bookValue = ${db.esc(emptyFieldValue)};
  279. bookValue = bookValue.toLowerCase();
  280. return ${filterBySearch(query.series)};
  281. };
  282. `;
  283. filter += `
  284. if (!checkSeries(book.series))
  285. return false;
  286. `;
  287. }
  288. //названия
  289. if (exclude !== 'title' && query.title && query.title !== '*') {
  290. closures += `
  291. const checkTitle = (bookValue) => {
  292. if (!bookValue)
  293. bookValue = ${db.esc(emptyFieldValue)};
  294. bookValue = bookValue.toLowerCase();
  295. return ${filterBySearch(query.title)};
  296. };
  297. `;
  298. filter += `
  299. if (!checkTitle(book.title))
  300. return false;
  301. `;
  302. }
  303. //языки
  304. if (exclude !== 'lang' && query.lang) {
  305. const queryLangs = query.lang.split(',');
  306. closures += `
  307. const queryLangs = new Set(${db.esc(queryLangs)});
  308. const checkLang = (bookValue) => {
  309. if (!bookValue)
  310. bookValue = ${db.esc(emptyFieldValue)};
  311. return queryLangs.has(bookValue);
  312. };
  313. `;
  314. filter += `
  315. if (!checkLang(book.lang))
  316. return false;
  317. `;
  318. }
  319. //жанры
  320. if (exclude !== 'genre' && query.genre) {
  321. const queryGenres = query.genre.split(',');
  322. closures += `
  323. const queryGenres = new Set(${db.esc(queryGenres)});
  324. const checkGenre = (bookValue) => {
  325. if (!bookValue)
  326. bookValue = ${db.esc(emptyFieldValue)};
  327. return queryGenres.has(bookValue);
  328. };
  329. `;
  330. filter += `
  331. const genres = book.genre.split(',');
  332. found = false;
  333. for (const g of genres) {
  334. if (checkGenre(g)) {
  335. found = true;
  336. break;
  337. }
  338. }
  339. if (!found)
  340. return false;
  341. `;
  342. }
  343. //авторы
  344. if (exclude !== 'author' && query.author && query.author !== '*') {
  345. closures += `
  346. const splitAuthor = (author) => {
  347. if (!author)
  348. author = ${db.esc(emptyFieldValue)};
  349. const result = author.split(',');
  350. if (result.length > 1)
  351. result.push(author);
  352. return result;
  353. };
  354. const checkAuthor = (bookValue) => {
  355. if (!bookValue)
  356. bookValue = ${db.esc(emptyFieldValue)};
  357. bookValue = bookValue.toLowerCase();
  358. return ${filterBySearch(query.author)};
  359. };
  360. `;
  361. filter += `
  362. const author = splitAuthor(book.author);
  363. found = false;
  364. for (const a of author) {
  365. if (checkAuthor(a)) {
  366. found = true;
  367. break;
  368. }
  369. }
  370. if (!found)
  371. return false;
  372. `;
  373. }
  374. //формируем where
  375. let where = '';
  376. if (filter) {
  377. where = `
  378. const enru = new Set(${db.esc(enruArr)});
  379. ${closures}
  380. const filterBook = (book) => {
  381. let found = false;
  382. ${filter}
  383. return true;
  384. };
  385. let ids;
  386. if (${!ids}) {
  387. ids = @all();
  388. } else {
  389. ids = ${db.esc(ids)};
  390. }
  391. const result = new Set();
  392. for (const id of ids) {
  393. const row = @unsafeRow(id);
  394. if (row) {
  395. for (const book of row.books) {
  396. if (filterBook(book)) {
  397. result.add(id);
  398. break;
  399. }
  400. }
  401. }
  402. }
  403. return Array.from(result);
  404. `;
  405. }
  406. return where;
  407. }
  408. async selectSeriesIds(query) {
  409. const db = this.db;
  410. let seriesIds = false;
  411. let isAll = !(query.series && query.series !== '*');
  412. //серии
  413. const seriesKеy = `series-ids-series-${query.series}`;
  414. seriesIds = await this.getCached(seriesKеy);
  415. if (seriesIds === null) {
  416. if (query.series && query.series !== '*') {
  417. const where = this.getWhere(query.series);
  418. const seriesRows = await db.select({
  419. table: 'series',
  420. rawResult: true,
  421. where: `return Array.from(${where})`,
  422. });
  423. seriesIds = seriesRows[0].rawResult;
  424. } else {
  425. const seriesRows = await db.select({
  426. table: 'series',
  427. rawResult: true,
  428. where: `return Array.from(@all())`,
  429. });
  430. seriesIds = seriesRows[0].rawResult;
  431. }
  432. seriesIds.sort((a, b) => a - b);
  433. await this.putCached(seriesKеy, seriesIds);
  434. }
  435. const where = this.getWhere2(query, (isAll ? false : seriesIds), 'series');
  436. if (where) {
  437. //тяжелый запрос перебором в series_book
  438. const rows = await db.select({
  439. table: 'series_book',
  440. rawResult: true,
  441. where,
  442. });
  443. seriesIds = rows[0].rawResult;
  444. }
  445. return seriesIds;
  446. }
  447. async selectTitleIds(query) {
  448. const db = this.db;
  449. let titleIds = false;
  450. let isAll = !(query.title && query.title !== '*');
  451. //серии
  452. const titleKеy = `title-ids-title-${query.title}`;
  453. titleIds = await this.getCached(titleKеy);
  454. if (titleIds === null) {
  455. if (query.title && query.title !== '*') {
  456. const where = this.getWhere(query.title);
  457. const titleRows = await db.select({
  458. table: 'title',
  459. rawResult: true,
  460. where: `return Array.from(${where})`,
  461. });
  462. titleIds = titleRows[0].rawResult;
  463. } else {
  464. const titleRows = await db.select({
  465. table: 'title',
  466. rawResult: true,
  467. where: `return Array.from(@all())`,
  468. });
  469. titleIds = titleRows[0].rawResult;
  470. }
  471. titleIds.sort((a, b) => a - b);
  472. await this.putCached(titleKеy, titleIds);
  473. }
  474. const where = this.getWhere2(query, (isAll ? false : titleIds), 'title');
  475. if (where) {
  476. //тяжелый запрос перебором в title_book
  477. const rows = await db.select({
  478. table: 'title_book',
  479. rawResult: true,
  480. where,
  481. });
  482. titleIds = rows[0].rawResult;
  483. }
  484. return titleIds;
  485. }
  486. async getCached(key) {
  487. if (!this.config.queryCacheEnabled)
  488. return null;
  489. let result = null;
  490. const db = this.db;
  491. const memCache = this.memCache;
  492. if (memCache.has(key)) {//есть в недавних
  493. result = memCache.get(key);
  494. //изменим порядок ключей, для последующей правильной чистки старых
  495. memCache.delete(key);
  496. memCache.set(key, result);
  497. } else {//смотрим в таблице
  498. const rows = await db.select({table: 'query_cache', where: `@@id(${db.esc(key)})`});
  499. if (rows.length) {//нашли в кеше
  500. await db.insert({
  501. table: 'query_time',
  502. replace: true,
  503. rows: [{id: key, time: Date.now()}],
  504. });
  505. result = rows[0].value;
  506. memCache.set(key, result);
  507. if (memCache.size > maxMemCacheSize) {
  508. //удаляем самый старый ключ-значение
  509. for (const k of memCache.keys()) {
  510. memCache.delete(k);
  511. break;
  512. }
  513. }
  514. }
  515. }
  516. return result;
  517. }
  518. async putCached(key, value) {
  519. if (!this.config.queryCacheEnabled)
  520. return;
  521. const db = this.db;
  522. const memCache = this.memCache;
  523. memCache.set(key, value);
  524. if (memCache.size > maxMemCacheSize) {
  525. //удаляем самый старый ключ-значение
  526. for (const k of memCache.keys()) {
  527. memCache.delete(k);
  528. break;
  529. }
  530. }
  531. //кладем в таблицу
  532. await db.insert({
  533. table: 'query_cache',
  534. replace: true,
  535. rows: [{id: key, value}],
  536. });
  537. await db.insert({
  538. table: 'query_time',
  539. replace: true,
  540. rows: [{id: key, time: Date.now()}],
  541. });
  542. }
  543. async authorSearch(query) {
  544. if (this.closed)
  545. throw new Error('DbSearcher closed');
  546. this.searchFlag++;
  547. try {
  548. const db = this.db;
  549. const key = `author-ids-${this.queryKey(query)}`;
  550. //сначала попробуем найти в кеше
  551. let authorIds = await this.getCached(key);
  552. if (authorIds === null) {//не нашли в кеше, ищем в поисковых таблицах
  553. authorIds = await this.selectAuthorIds(query);
  554. await this.putCached(key, authorIds);
  555. }
  556. const totalFound = authorIds.length;
  557. let limit = (query.limit ? query.limit : 100);
  558. limit = (limit > maxLimit ? maxLimit : limit);
  559. const offset = (query.offset ? query.offset : 0);
  560. //выборка найденных авторов
  561. const result = await db.select({
  562. table: 'author',
  563. map: `(r) => ({id: r.id, author: r.author, bookCount: r.bookCount, bookDelCount: r.bookDelCount})`,
  564. where: `@@id(${db.esc(authorIds.slice(offset, offset + limit))})`
  565. });
  566. return {result, totalFound};
  567. } finally {
  568. this.searchFlag--;
  569. }
  570. }
  571. async seriesSearch(query) {
  572. if (this.closed)
  573. throw new Error('DbSearcher closed');
  574. this.searchFlag++;
  575. try {
  576. const db = this.db;
  577. const key = `series-ids-${this.queryKey(query)}`;
  578. //сначала попробуем найти в кеше
  579. let seriesIds = await this.getCached(key);
  580. if (seriesIds === null) {//не нашли в кеше, ищем в поисковых таблицах
  581. seriesIds = await this.selectSeriesIds(query);
  582. await this.putCached(key, seriesIds);
  583. }
  584. const totalFound = seriesIds.length;
  585. let limit = (query.limit ? query.limit : 100);
  586. limit = (limit > maxLimit ? maxLimit : limit);
  587. const offset = (query.offset ? query.offset : 0);
  588. //выборка найденных авторов
  589. const result = await db.select({
  590. table: 'series_book',
  591. map: `(r) => ({id: r.id, series: r.series, bookCount: r.bookCount, bookDelCount: r.bookDelCount})`,
  592. where: `@@id(${db.esc(seriesIds.slice(offset, offset + limit))})`
  593. });
  594. return {result, totalFound};
  595. } finally {
  596. this.searchFlag--;
  597. }
  598. }
  599. async titleSearch(query) {
  600. if (this.closed)
  601. throw new Error('DbSearcher closed');
  602. this.searchFlag++;
  603. try {
  604. const db = this.db;
  605. const key = `title-ids-${this.queryKey(query)}`;
  606. //сначала попробуем найти в кеше
  607. let titleIds = await this.getCached(key);
  608. if (titleIds === null) {//не нашли в кеше, ищем в поисковых таблицах
  609. titleIds = await this.selectTitleIds(query);
  610. await this.putCached(key, titleIds);
  611. }
  612. const totalFound = titleIds.length;
  613. let limit = (query.limit ? query.limit : 100);
  614. limit = (limit > maxLimit ? maxLimit : limit);
  615. const offset = (query.offset ? query.offset : 0);
  616. //выборка найденных авторов
  617. const result = await db.select({
  618. table: 'title_book',
  619. map: `(r) => ({id: r.id, title: r.title, books: r.books, bookCount: r.bookCount, bookDelCount: r.bookDelCount})`,
  620. where: `@@id(${db.esc(titleIds.slice(offset, offset + limit))})`
  621. });
  622. return {result, totalFound};
  623. } finally {
  624. this.searchFlag--;
  625. }
  626. }
  627. async getAuthorBookList(authorId) {
  628. if (this.closed)
  629. throw new Error('DbSearcher closed');
  630. if (!authorId)
  631. return {author: '', books: ''};
  632. this.searchFlag++;
  633. try {
  634. const db = this.db;
  635. //выборка книг автора по authorId
  636. const rows = await db.select({
  637. table: 'author_book',
  638. where: `@@id(${db.esc(authorId)})`
  639. });
  640. let author = '';
  641. let books = '';
  642. if (rows.length) {
  643. author = rows[0].author;
  644. books = rows[0].books;
  645. }
  646. return {author, books};
  647. } finally {
  648. this.searchFlag--;
  649. }
  650. }
  651. async getSeriesBookList(series) {
  652. if (this.closed)
  653. throw new Error('DbSearcher closed');
  654. if (!series)
  655. return {books: ''};
  656. this.searchFlag++;
  657. try {
  658. const db = this.db;
  659. series = series.toLowerCase();
  660. //выборка серии по названию серии
  661. let rows = await db.select({
  662. table: 'series',
  663. rawResult: true,
  664. where: `return Array.from(@dirtyIndexLR('value', ${db.esc(series)}, ${db.esc(series)}))`
  665. });
  666. let books;
  667. if (rows.length && rows[0].rawResult.length) {
  668. //выборка книг серии
  669. rows = await db.select({
  670. table: 'series_book',
  671. where: `@@id(${rows[0].rawResult[0]})`
  672. });
  673. if (rows.length)
  674. books = rows[0].books;
  675. }
  676. return {books: (books && books.length ? JSON.stringify(books) : '')};
  677. } finally {
  678. this.searchFlag--;
  679. }
  680. }
  681. async periodicCleanCache() {
  682. this.timer = null;
  683. const cleanInterval = this.config.cacheCleanInterval*60*1000;
  684. if (!cleanInterval)
  685. return;
  686. try {
  687. const db = this.db;
  688. const oldThres = Date.now() - cleanInterval;
  689. //выберем всех кандидатов на удаление
  690. const rows = await db.select({
  691. table: 'query_time',
  692. where: `
  693. @@iter(@all(), (r) => (r.time < ${db.esc(oldThres)}));
  694. `
  695. });
  696. const ids = [];
  697. for (const row of rows)
  698. ids.push(row.id);
  699. //удаляем
  700. await db.delete({table: 'query_cache', where: `@@id(${db.esc(ids)})`});
  701. await db.delete({table: 'query_time', where: `@@id(${db.esc(ids)})`});
  702. //console.log('Cache clean', ids);
  703. } catch(e) {
  704. console.error(e.message);
  705. } finally {
  706. if (!this.closed) {
  707. this.timer = setTimeout(() => { this.periodicCleanCache(); }, cleanInterval);
  708. }
  709. }
  710. }
  711. async close() {
  712. while (this.searchFlag > 0) {
  713. await utils.sleep(50);
  714. }
  715. this.searchCache = null;
  716. if (this.timer) {
  717. clearTimeout(this.timer);
  718. this.timer = null;
  719. }
  720. this.closed = true;
  721. }
  722. }
  723. module.exports = DbSearcher;