DbSearcher.js 32 KB

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