DbSearcher.js 31 KB

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