DbSearcher.js 35 KB

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