DbSearcher.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  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. let 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. let 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. ${filter}
  382. return true;
  383. };
  384. let ids;
  385. if (${!ids}) {
  386. ids = @all();
  387. } else {
  388. ids = ${db.esc(ids)};
  389. }
  390. const result = new Set();
  391. for (const id of ids) {
  392. const row = @unsafeRow(id);
  393. if (row) {
  394. for (const book of row.books) {
  395. if (filterBook(book)) {
  396. result.add(id);
  397. break;
  398. }
  399. }
  400. }
  401. }
  402. return Array.from(result);
  403. `;
  404. }
  405. return where;
  406. }
  407. async selectSeriesIds(query) {
  408. const db = this.db;
  409. let seriesIds = false;
  410. let isAll = !(query.series && query.series !== '*');
  411. //серии
  412. const seriesKеy = `series-ids-series-${query.series}`;
  413. seriesIds = await this.getCached(seriesKеy);
  414. if (seriesIds === null) {
  415. if (query.series && query.series !== '*') {
  416. const where = this.getWhere(query.series);
  417. const seriesRows = await db.select({
  418. table: 'series',
  419. rawResult: true,
  420. where: `return Array.from(${where})`,
  421. });
  422. seriesIds = seriesRows[0].rawResult;
  423. } else {
  424. const seriesRows = await db.select({
  425. table: 'series',
  426. rawResult: true,
  427. where: `return Array.from(@all())`,
  428. });
  429. seriesIds = seriesRows[0].rawResult;
  430. }
  431. seriesIds.sort((a, b) => a - b);
  432. await this.putCached(seriesKеy, seriesIds);
  433. }
  434. const where = this.getWhere2(query, (isAll ? false : seriesIds), 'series');
  435. if (where) {
  436. //тяжелый запрос перебором в series_book
  437. const rows = await db.select({
  438. table: 'series_book',
  439. rawResult: true,
  440. where,
  441. });
  442. seriesIds = rows[0].rawResult;
  443. }
  444. return seriesIds;
  445. }
  446. async selectTitleIds(query) {
  447. const db = this.db;
  448. let titleIds = false;
  449. let isAll = !(query.title && query.title !== '*');
  450. //серии
  451. const titleKеy = `title-ids-title-${query.title}`;
  452. titleIds = await this.getCached(titleKеy);
  453. if (titleIds === null) {
  454. if (query.title && query.title !== '*') {
  455. const where = this.getWhere(query.title);
  456. const titleRows = await db.select({
  457. table: 'title',
  458. rawResult: true,
  459. where: `return Array.from(${where})`,
  460. });
  461. titleIds = titleRows[0].rawResult;
  462. } else {
  463. const titleRows = await db.select({
  464. table: 'title',
  465. rawResult: true,
  466. where: `return Array.from(@all())`,
  467. });
  468. titleIds = titleRows[0].rawResult;
  469. }
  470. titleIds.sort((a, b) => a - b);
  471. await this.putCached(titleKеy, titleIds);
  472. }
  473. const where = this.getWhere2(query, (isAll ? false : titleIds), 'title');
  474. if (where) {
  475. //тяжелый запрос перебором в title_book
  476. const rows = await db.select({
  477. table: 'title_book',
  478. rawResult: true,
  479. where,
  480. });
  481. titleIds = rows[0].rawResult;
  482. }
  483. return titleIds;
  484. }
  485. async getCached(key) {
  486. if (!this.config.queryCacheEnabled)
  487. return null;
  488. let result = null;
  489. const db = this.db;
  490. const memCache = this.memCache;
  491. if (memCache.has(key)) {//есть в недавних
  492. result = memCache.get(key);
  493. //изменим порядок ключей, для последующей правильной чистки старых
  494. memCache.delete(key);
  495. memCache.set(key, result);
  496. } else {//смотрим в таблице
  497. const rows = await db.select({table: 'query_cache', where: `@@id(${db.esc(key)})`});
  498. if (rows.length) {//нашли в кеше
  499. await db.insert({
  500. table: 'query_time',
  501. replace: true,
  502. rows: [{id: key, time: Date.now()}],
  503. });
  504. result = rows[0].value;
  505. memCache.set(key, result);
  506. if (memCache.size > maxMemCacheSize) {
  507. //удаляем самый старый ключ-значение
  508. for (const k of memCache.keys()) {
  509. memCache.delete(k);
  510. break;
  511. }
  512. }
  513. }
  514. }
  515. return result;
  516. }
  517. async putCached(key, value) {
  518. if (!this.config.queryCacheEnabled)
  519. return;
  520. const db = this.db;
  521. const memCache = this.memCache;
  522. memCache.set(key, value);
  523. if (memCache.size > maxMemCacheSize) {
  524. //удаляем самый старый ключ-значение
  525. for (const k of memCache.keys()) {
  526. memCache.delete(k);
  527. break;
  528. }
  529. }
  530. //кладем в таблицу
  531. await db.insert({
  532. table: 'query_cache',
  533. replace: true,
  534. rows: [{id: key, value}],
  535. });
  536. await db.insert({
  537. table: 'query_time',
  538. replace: true,
  539. rows: [{id: key, time: Date.now()}],
  540. });
  541. }
  542. async authorSearch(query) {
  543. if (this.closed)
  544. throw new Error('DbSearcher closed');
  545. this.searchFlag++;
  546. try {
  547. const db = this.db;
  548. const key = `author-ids-${this.queryKey(query)}`;
  549. //сначала попробуем найти в кеше
  550. let authorIds = await this.getCached(key);
  551. if (authorIds === null) {//не нашли в кеше, ищем в поисковых таблицах
  552. authorIds = await this.selectAuthorIds(query);
  553. await this.putCached(key, authorIds);
  554. }
  555. const totalFound = authorIds.length;
  556. let limit = (query.limit ? query.limit : 100);
  557. limit = (limit > maxLimit ? maxLimit : limit);
  558. const offset = (query.offset ? query.offset : 0);
  559. //выборка найденных авторов
  560. const result = await db.select({
  561. table: 'author',
  562. map: `(r) => ({id: r.id, author: r.author, bookCount: r.bookCount, bookDelCount: r.bookDelCount})`,
  563. where: `@@id(${db.esc(authorIds.slice(offset, offset + limit))})`
  564. });
  565. return {result, totalFound};
  566. } finally {
  567. this.searchFlag--;
  568. }
  569. }
  570. async seriesSearch(query) {
  571. if (this.closed)
  572. throw new Error('DbSearcher closed');
  573. this.searchFlag++;
  574. try {
  575. const db = this.db;
  576. const key = `series-ids-${this.queryKey(query)}`;
  577. //сначала попробуем найти в кеше
  578. let seriesIds = await this.getCached(key);
  579. if (seriesIds === null) {//не нашли в кеше, ищем в поисковых таблицах
  580. seriesIds = await this.selectSeriesIds(query);
  581. await this.putCached(key, seriesIds);
  582. }
  583. const totalFound = seriesIds.length;
  584. let limit = (query.limit ? query.limit : 100);
  585. limit = (limit > maxLimit ? maxLimit : limit);
  586. const offset = (query.offset ? query.offset : 0);
  587. //выборка найденных авторов
  588. const result = await db.select({
  589. table: 'series_book',
  590. map: `(r) => ({id: r.id, series: r.series, bookCount: r.bookCount, bookDelCount: r.bookDelCount})`,
  591. where: `@@id(${db.esc(seriesIds.slice(offset, offset + limit))})`
  592. });
  593. return {result, totalFound};
  594. } finally {
  595. this.searchFlag--;
  596. }
  597. }
  598. async titleSearch(query) {
  599. if (this.closed)
  600. throw new Error('DbSearcher closed');
  601. this.searchFlag++;
  602. try {
  603. const db = this.db;
  604. const key = `title-ids-${this.queryKey(query)}`;
  605. //сначала попробуем найти в кеше
  606. let titleIds = await this.getCached(key);
  607. if (titleIds === null) {//не нашли в кеше, ищем в поисковых таблицах
  608. titleIds = await this.selectTitleIds(query);
  609. await this.putCached(key, titleIds);
  610. }
  611. const totalFound = titleIds.length;
  612. let limit = (query.limit ? query.limit : 100);
  613. limit = (limit > maxLimit ? maxLimit : limit);
  614. const offset = (query.offset ? query.offset : 0);
  615. //выборка найденных авторов
  616. const result = await db.select({
  617. table: 'title_book',
  618. map: `(r) => ({id: r.id, title: r.title, books: r.books, bookCount: r.bookCount, bookDelCount: r.bookDelCount})`,
  619. where: `@@id(${db.esc(titleIds.slice(offset, offset + limit))})`
  620. });
  621. return {result, totalFound};
  622. } finally {
  623. this.searchFlag--;
  624. }
  625. }
  626. async getAuthorBookList(authorId) {
  627. if (this.closed)
  628. throw new Error('DbSearcher closed');
  629. if (!authorId)
  630. return {author: '', books: ''};
  631. this.searchFlag++;
  632. try {
  633. const db = this.db;
  634. //выборка книг автора по authorId
  635. const rows = await db.select({
  636. table: 'author_book',
  637. where: `@@id(${db.esc(authorId)})`
  638. });
  639. let author = '';
  640. let books = '';
  641. if (rows.length) {
  642. author = rows[0].author;
  643. books = rows[0].books;
  644. }
  645. return {author, books};
  646. } finally {
  647. this.searchFlag--;
  648. }
  649. }
  650. async getSeriesBookList(series) {
  651. if (this.closed)
  652. throw new Error('DbSearcher closed');
  653. if (!series)
  654. return {books: ''};
  655. this.searchFlag++;
  656. try {
  657. const db = this.db;
  658. series = series.toLowerCase();
  659. //выборка серии по названию серии
  660. let rows = await db.select({
  661. table: 'series',
  662. rawResult: true,
  663. where: `return Array.from(@dirtyIndexLR('value', ${db.esc(series)}, ${db.esc(series)}))`
  664. });
  665. let books;
  666. if (rows.length && rows[0].rawResult.length) {
  667. //выборка книг серии
  668. rows = await db.select({
  669. table: 'series_book',
  670. where: `@@id(${rows[0].rawResult[0]})`
  671. });
  672. if (rows.length)
  673. books = rows[0].books;
  674. }
  675. return {books: (books && books.length ? JSON.stringify(books) : '')};
  676. } finally {
  677. this.searchFlag--;
  678. }
  679. }
  680. async periodicCleanCache() {
  681. this.timer = null;
  682. const cleanInterval = this.config.cacheCleanInterval*60*1000;
  683. if (!cleanInterval)
  684. return;
  685. try {
  686. const db = this.db;
  687. const oldThres = Date.now() - cleanInterval;
  688. //выберем всех кандидатов на удаление
  689. const rows = await db.select({
  690. table: 'query_time',
  691. where: `
  692. @@iter(@all(), (r) => (r.time < ${db.esc(oldThres)}));
  693. `
  694. });
  695. const ids = [];
  696. for (const row of rows)
  697. ids.push(row.id);
  698. //удаляем
  699. await db.delete({table: 'query_cache', where: `@@id(${db.esc(ids)})`});
  700. await db.delete({table: 'query_time', where: `@@id(${db.esc(ids)})`});
  701. //console.log('Cache clean', ids);
  702. } catch(e) {
  703. console.error(e.message);
  704. } finally {
  705. if (!this.closed) {
  706. this.timer = setTimeout(() => { this.periodicCleanCache(); }, cleanInterval);
  707. }
  708. }
  709. }
  710. async close() {
  711. while (this.searchFlag > 0) {
  712. await utils.sleep(50);
  713. }
  714. this.searchCache = null;
  715. if (this.timer) {
  716. clearTimeout(this.timer);
  717. this.timer = null;
  718. }
  719. this.closed = true;
  720. }
  721. }
  722. module.exports = DbSearcher;