DbSearcher.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  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. if (exclude !== 'author' && query.author && query.author !== '*') {
  240. closures += `
  241. const splitAuthor = (author) => {
  242. if (!author)
  243. author = ${db.esc(emptyFieldValue)};
  244. const result = author.split(',');
  245. if (result.length > 1)
  246. result.push(author);
  247. return result;
  248. };
  249. const checkAuthor = (bookValue) => {
  250. if (!bookValue)
  251. bookValue = ${db.esc(emptyFieldValue)};
  252. bookValue = bookValue.toLowerCase();
  253. return ${filterBySearch(query.author)};
  254. };
  255. `;
  256. filter += `
  257. const author = splitAuthor(book.author);
  258. let found = false;
  259. for (const a of author) {
  260. if (checkAuthor(a)) {
  261. found = true;
  262. break;
  263. }
  264. }
  265. if (!found)
  266. return false;
  267. `;
  268. }
  269. //серии
  270. if (exclude !== 'series' && query.series && query.series !== '*') {
  271. closures += `
  272. const checkSeries = (bookValue) => {
  273. if (!bookValue)
  274. bookValue = ${db.esc(emptyFieldValue)};
  275. bookValue = bookValue.toLowerCase();
  276. return ${filterBySearch(query.series)};
  277. };
  278. `;
  279. filter += `
  280. if (!checkSeries(book.series))
  281. return false;
  282. `;
  283. }
  284. //названия
  285. if (exclude !== 'title' && query.title && query.title !== '*') {
  286. closures += `
  287. const checkTitle = (bookValue) => {
  288. if (!bookValue)
  289. bookValue = ${db.esc(emptyFieldValue)};
  290. bookValue = bookValue.toLowerCase();
  291. return ${filterBySearch(query.title)};
  292. };
  293. `;
  294. filter += `
  295. if (!checkTitle(book.title))
  296. return false;
  297. `;
  298. }
  299. //жанры
  300. if (exclude !== 'genre' && query.genre) {
  301. const queryGenres = query.genre.split(',');
  302. closures += `
  303. const queryGenres = new Set(${db.esc(queryGenres)});
  304. const checkGenre = (bookValue) => {
  305. if (!bookValue)
  306. bookValue = ${db.esc(emptyFieldValue)};
  307. return queryGenres.has(bookValue);
  308. };
  309. `;
  310. filter += `
  311. const genres = book.genre.split(',');
  312. let found = false;
  313. for (const g of genres) {
  314. if (checkGenre(g)) {
  315. found = true;
  316. break;
  317. }
  318. }
  319. if (!found)
  320. return false;
  321. `;
  322. }
  323. //языки
  324. if (exclude !== 'lang' && query.lang) {
  325. const queryLangs = query.lang.split(',');
  326. closures += `
  327. const queryLangs = new Set(${db.esc(queryLangs)});
  328. const checkLang = (bookValue) => {
  329. if (!bookValue)
  330. bookValue = ${db.esc(emptyFieldValue)};
  331. return queryLangs.has(bookValue);
  332. };
  333. `;
  334. filter += `
  335. if (!checkLang(book.lang))
  336. return false;
  337. `;
  338. }
  339. //формируем where
  340. let where = '';
  341. if (filter) {
  342. where = `
  343. const enru = new Set(${db.esc(enruArr)});
  344. ${closures}
  345. const filterBook = (book) => {
  346. ${filter}
  347. return true;
  348. };
  349. let ids;
  350. if (${!ids}) {
  351. ids = @all();
  352. } else {
  353. ids = ${db.esc(ids)};
  354. }
  355. const result = new Set();
  356. for (const id of ids) {
  357. const row = @unsafeRow(id);
  358. for (const book of row.books) {
  359. if (filterBook(book)) {
  360. result.add(id);
  361. break;
  362. }
  363. }
  364. }
  365. return Array.from(result);
  366. `;
  367. }
  368. return where;
  369. }
  370. async selectSeriesIds(query) {
  371. const db = this.db;
  372. let seriesIds = false;
  373. let isAll = !(query.series && query.series !== '*');
  374. //серии
  375. const seriesKеy = `series-ids-series-${query.series}`;
  376. seriesIds = await this.getCached(seriesKеy);
  377. if (seriesIds === null) {
  378. if (query.series && query.series !== '*') {
  379. const where = this.getWhere(query.series);
  380. const seriesRows = await db.select({
  381. table: 'series',
  382. rawResult: true,
  383. where: `return Array.from(${where})`,
  384. });
  385. seriesIds = seriesRows[0].rawResult;
  386. } else {
  387. const seriesRows = await db.select({
  388. table: 'series',
  389. rawResult: true,
  390. where: `return Array.from(@all())`,
  391. });
  392. seriesIds = seriesRows[0].rawResult;
  393. }
  394. seriesIds.sort((a, b) => a - b);
  395. await this.putCached(seriesKеy, seriesIds);
  396. }
  397. const where = this.getWhere2(query, (isAll ? false : seriesIds), 'series');
  398. if (where) {
  399. //тяжелый запрос перебором в series_book
  400. const rows = await db.select({
  401. table: 'series_book',
  402. rawResult: true,
  403. where,
  404. });
  405. seriesIds = rows[0].rawResult;
  406. }
  407. return seriesIds;
  408. }
  409. async selectTitleIds(query) {
  410. const db = this.db;
  411. let titleIds = false;
  412. let isAll = !(query.title && query.title !== '*');
  413. //серии
  414. const titleKеy = `title-ids-title-${query.title}`;
  415. titleIds = await this.getCached(titleKеy);
  416. if (titleIds === null) {
  417. if (query.title && query.title !== '*') {
  418. const where = this.getWhere(query.title);
  419. const seriesRows = await db.select({
  420. table: 'title',
  421. rawResult: true,
  422. where: `return Array.from(${where})`,
  423. });
  424. titleIds = seriesRows[0].rawResult;
  425. } else {
  426. const seriesRows = await db.select({
  427. table: 'title',
  428. rawResult: true,
  429. where: `return Array.from(@all())`,
  430. });
  431. titleIds = seriesRows[0].rawResult;
  432. }
  433. titleIds.sort((a, b) => a - b);
  434. await this.putCached(titleKеy, titleIds);
  435. }
  436. const where = this.getWhere2(query, (isAll ? false : titleIds), 'title');
  437. if (where) {
  438. //тяжелый запрос перебором в series_book
  439. const rows = await db.select({
  440. table: 'title_book',
  441. rawResult: true,
  442. where,
  443. });
  444. titleIds = rows[0].rawResult;
  445. }
  446. return titleIds;
  447. }
  448. queryKey(q) {
  449. return JSON.stringify([q.author, q.series, q.title, q.genre, q.lang]);
  450. }
  451. async getCached(key) {
  452. if (!this.config.queryCacheEnabled)
  453. return null;
  454. let result = null;
  455. const db = this.db;
  456. const memCache = this.memCache;
  457. if (memCache.has(key)) {//есть в недавних
  458. result = memCache.get(key);
  459. //изменим порядок ключей, для последующей правильной чистки старых
  460. memCache.delete(key);
  461. memCache.set(key, result);
  462. } else {//смотрим в таблице
  463. const rows = await db.select({table: 'query_cache', where: `@@id(${db.esc(key)})`});
  464. if (rows.length) {//нашли в кеше
  465. await db.insert({
  466. table: 'query_time',
  467. replace: true,
  468. rows: [{id: key, time: Date.now()}],
  469. });
  470. result = rows[0].value;
  471. memCache.set(key, result);
  472. if (memCache.size > maxMemCacheSize) {
  473. //удаляем самый старый ключ-значение
  474. for (const k of memCache.keys()) {
  475. memCache.delete(k);
  476. break;
  477. }
  478. }
  479. }
  480. }
  481. return result;
  482. }
  483. async putCached(key, value) {
  484. if (!this.config.queryCacheEnabled)
  485. return;
  486. const db = this.db;
  487. const memCache = this.memCache;
  488. memCache.set(key, value);
  489. if (memCache.size > maxMemCacheSize) {
  490. //удаляем самый старый ключ-значение
  491. for (const k of memCache.keys()) {
  492. memCache.delete(k);
  493. break;
  494. }
  495. }
  496. //кладем в таблицу
  497. await db.insert({
  498. table: 'query_cache',
  499. replace: true,
  500. rows: [{id: key, value}],
  501. });
  502. await db.insert({
  503. table: 'query_time',
  504. replace: true,
  505. rows: [{id: key, time: Date.now()}],
  506. });
  507. }
  508. async authorSearch(query) {
  509. if (this.closed)
  510. throw new Error('DbSearcher closed');
  511. this.searchFlag++;
  512. try {
  513. const db = this.db;
  514. const key = `author-ids-${this.queryKey(query)}`;
  515. //сначала попробуем найти в кеше
  516. let authorIds = await this.getCached(key);
  517. if (authorIds === null) {//не нашли в кеше, ищем в поисковых таблицах
  518. authorIds = await this.selectAuthorIds(query);
  519. await this.putCached(key, authorIds);
  520. }
  521. const totalFound = authorIds.length;
  522. let limit = (query.limit ? query.limit : 100);
  523. limit = (limit > maxLimit ? maxLimit : limit);
  524. const offset = (query.offset ? query.offset : 0);
  525. //выборка найденных авторов
  526. const result = await db.select({
  527. table: 'author',
  528. map: `(r) => ({id: r.id, author: r.author, bookCount: r.bookCount, bookDelCount: r.bookDelCount})`,
  529. where: `@@id(${db.esc(authorIds.slice(offset, offset + limit))})`
  530. });
  531. return {result, totalFound};
  532. } finally {
  533. this.searchFlag--;
  534. }
  535. }
  536. async seriesSearch(query) {
  537. if (this.closed)
  538. throw new Error('DbSearcher closed');
  539. this.searchFlag++;
  540. try {
  541. const db = this.db;
  542. const key = `series-ids-${this.queryKey(query)}`;
  543. //сначала попробуем найти в кеше
  544. let seriesIds = await this.getCached(key);
  545. if (seriesIds === null) {//не нашли в кеше, ищем в поисковых таблицах
  546. seriesIds = await this.selectSeriesIds(query);
  547. await this.putCached(key, seriesIds);
  548. }
  549. const totalFound = seriesIds.length;
  550. let limit = (query.limit ? query.limit : 100);
  551. limit = (limit > maxLimit ? maxLimit : limit);
  552. const offset = (query.offset ? query.offset : 0);
  553. //выборка найденных авторов
  554. const result = await db.select({
  555. table: 'series_book',
  556. map: `(r) => ({id: r.id, series: r.series, bookCount: r.bookCount, bookDelCount: r.bookDelCount})`,
  557. where: `@@id(${db.esc(seriesIds.slice(offset, offset + limit))})`
  558. });
  559. return {result, totalFound};
  560. } finally {
  561. this.searchFlag--;
  562. }
  563. }
  564. async titleSearch(query) {
  565. if (this.closed)
  566. throw new Error('DbSearcher closed');
  567. this.searchFlag++;
  568. try {
  569. const db = this.db;
  570. const key = `title-ids-${this.queryKey(query)}`;
  571. //сначала попробуем найти в кеше
  572. let seriesIds = await this.getCached(key);
  573. if (seriesIds === null) {//не нашли в кеше, ищем в поисковых таблицах
  574. seriesIds = await this.selectTitleIds(query);
  575. await this.putCached(key, seriesIds);
  576. }
  577. const totalFound = seriesIds.length;
  578. let limit = (query.limit ? query.limit : 100);
  579. limit = (limit > maxLimit ? maxLimit : limit);
  580. const offset = (query.offset ? query.offset : 0);
  581. //выборка найденных авторов
  582. const result = await db.select({
  583. table: 'title_book',
  584. map: `(r) => ({id: r.id, series: r.series, bookCount: r.bookCount, bookDelCount: r.bookDelCount})`,
  585. where: `@@id(${db.esc(seriesIds.slice(offset, offset + limit))})`
  586. });
  587. return {result, totalFound};
  588. } finally {
  589. this.searchFlag--;
  590. }
  591. }
  592. async getAuthorBookList(authorId) {
  593. if (this.closed)
  594. throw new Error('DbSearcher closed');
  595. if (!authorId)
  596. return {author: '', books: ''};
  597. this.searchFlag++;
  598. try {
  599. const db = this.db;
  600. //выборка книг автора по authorId
  601. const rows = await db.select({
  602. table: 'author_book',
  603. where: `@@id(${db.esc(authorId)})`
  604. });
  605. let author = '';
  606. let books = '';
  607. if (rows.length) {
  608. author = rows[0].author;
  609. books = rows[0].books;
  610. }
  611. return {author, books};
  612. } finally {
  613. this.searchFlag--;
  614. }
  615. }
  616. async getSeriesBookList(series) {
  617. if (this.closed)
  618. throw new Error('DbSearcher closed');
  619. if (!series)
  620. return {books: ''};
  621. this.searchFlag++;
  622. try {
  623. const db = this.db;
  624. series = series.toLowerCase();
  625. //выборка серии по названию серии
  626. let rows = await db.select({
  627. table: 'series',
  628. rawResult: true,
  629. where: `return Array.from(@dirtyIndexLR('value', ${db.esc(series)}, ${db.esc(series)}))`
  630. });
  631. let books;
  632. if (rows.length && rows[0].rawResult.length) {
  633. //выборка книг серии
  634. rows = await db.select({
  635. table: 'series_book',
  636. where: `@@id(${rows[0].rawResult[0]})`
  637. });
  638. if (rows.length)
  639. books = rows[0].books;
  640. }
  641. return {books: (books && books.length ? JSON.stringify(books) : '')};
  642. } finally {
  643. this.searchFlag--;
  644. }
  645. }
  646. async periodicCleanCache() {
  647. this.timer = null;
  648. const cleanInterval = this.config.cacheCleanInterval*60*1000;
  649. if (!cleanInterval)
  650. return;
  651. try {
  652. const db = this.db;
  653. const oldThres = Date.now() - cleanInterval;
  654. //выберем всех кандидатов на удаление
  655. const rows = await db.select({
  656. table: 'query_time',
  657. where: `
  658. @@iter(@all(), (r) => (r.time < ${db.esc(oldThres)}));
  659. `
  660. });
  661. const ids = [];
  662. for (const row of rows)
  663. ids.push(row.id);
  664. //удаляем
  665. await db.delete({table: 'query_cache', where: `@@id(${db.esc(ids)})`});
  666. await db.delete({table: 'query_time', where: `@@id(${db.esc(ids)})`});
  667. //console.log('Cache clean', ids);
  668. } catch(e) {
  669. console.error(e.message);
  670. } finally {
  671. if (!this.closed) {
  672. this.timer = setTimeout(() => { this.periodicCleanCache(); }, cleanInterval);
  673. }
  674. }
  675. }
  676. async close() {
  677. while (this.searchFlag > 0) {
  678. await utils.sleep(50);
  679. }
  680. this.searchCache = null;
  681. if (this.timer) {
  682. clearTimeout(this.timer);
  683. this.timer = null;
  684. }
  685. this.closed = true;
  686. }
  687. }
  688. module.exports = DbSearcher;