DbSearcher.js 27 KB

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