DbSearcher.js 27 KB

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