DbSearcher.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. //const _ = require('lodash');
  2. const utils = require('./utils');
  3. const maxUtf8Char = String.fromCodePoint(0xFFFFF);
  4. const ruAlphabet = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя';
  5. const enAlphabet = 'abcdefghijklmnopqrstuvwxyz';
  6. const enruArr = (ruAlphabet + enAlphabet).split('');
  7. class DbSearcher {
  8. constructor(config, db) {
  9. this.config = config;
  10. this.db = db;
  11. this.searchFlag = 0;
  12. this.timer = null;
  13. this.closed = false;
  14. this.periodicCleanCache();//no await
  15. }
  16. getWhere(a) {
  17. const db = this.db;
  18. a = a.toLowerCase();
  19. let where;
  20. //особая обработка префиксов
  21. if (a[0] == '=') {
  22. a = a.substring(1);
  23. where = `@@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a)})`;
  24. } else if (a[0] == '*') {
  25. a = a.substring(1);
  26. where = `@@indexIter('value', (v) => (v.indexOf(${db.esc(a)}) >= 0) )`;
  27. } else if (a[0] == '#') {
  28. a = a.substring(1);
  29. where = `@@indexIter('value', (v) => {
  30. const enru = new Set(${db.esc(enruArr)});
  31. return !v || (!enru.has(v[0].toLowerCase()) && v.indexOf(${db.esc(a)}) >= 0);
  32. });`;
  33. } else {
  34. where = `@@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a + maxUtf8Char)})`;
  35. }
  36. return where;
  37. }
  38. async selectAuthorIds(query) {
  39. const db = this.db;
  40. let authorIds = new Set();
  41. //сначала выберем все id авторов по фильтру
  42. //порядок id соответсвует ASC-сортировке по author
  43. if (query.author && query.author !== '*') {
  44. const where = this.getWhere(query.author);
  45. const authorRows = await db.select({
  46. table: 'author',
  47. dirtyIdsOnly: true,
  48. where
  49. });
  50. for (const row of authorRows)
  51. authorIds.add(row.id);
  52. } else {//все авторы
  53. if (!db.searchCache.authorIdsAll) {
  54. const authorRows = await db.select({
  55. table: 'author',
  56. dirtyIdsOnly: true,
  57. });
  58. db.searchCache.authorIdsAll = [];
  59. for (const row of authorRows) {
  60. authorIds.add(row.id);
  61. db.searchCache.authorIdsAll.push(row.id);
  62. }
  63. } else {//оптимизация
  64. authorIds = new Set(db.searchCache.authorIdsAll);
  65. }
  66. }
  67. const idsArr = [];
  68. idsArr.push(authorIds);
  69. //серии
  70. if (query.series && query.series !== '*') {
  71. const where = this.getWhere(query.series);
  72. const seriesRows = await db.select({
  73. table: 'series',
  74. map: `(r) => ({authorId: r.authorId})`,
  75. where
  76. });
  77. const ids = new Set();
  78. for (const row of seriesRows) {
  79. for (const id of row.authorId)
  80. ids.add(id);
  81. }
  82. idsArr.push(ids);
  83. }
  84. //названия
  85. if (query.title && query.title !== '*') {
  86. const where = this.getWhere(query.title);
  87. let titleRows = await db.select({
  88. table: 'title',
  89. map: `(r) => ({authorId: r.authorId})`,
  90. where
  91. });
  92. const ids = new Set();
  93. for (const row of titleRows) {
  94. for (const id of row.authorId)
  95. ids.add(id);
  96. }
  97. idsArr.push(ids);
  98. //чистки памяти при тяжелых запросах
  99. if (query.title[0] == '*') {
  100. titleRows = null;
  101. utils.freeMemory();
  102. await db.freeMemory();
  103. }
  104. }
  105. //жанры
  106. if (query.genre) {
  107. const genres = query.genre.split(',');
  108. const ids = new Set();
  109. for (const g of genres) {
  110. const genreRows = await db.select({
  111. table: 'genre',
  112. map: `(r) => ({authorId: r.authorId})`,
  113. where: `@@indexLR('value', ${db.esc(g)}, ${db.esc(g)})`,
  114. });
  115. for (const row of genreRows) {
  116. for (const id of row.authorId)
  117. ids.add(id);
  118. }
  119. }
  120. idsArr.push(ids);
  121. }
  122. //языки
  123. if (query.lang) {
  124. const langs = query.lang.split(',');
  125. const ids = new Set();
  126. for (const l of langs) {
  127. const langRows = await db.select({
  128. table: 'lang',
  129. map: `(r) => ({authorId: r.authorId})`,
  130. where: `@@indexLR('value', ${db.esc(l)}, ${db.esc(l)})`,
  131. });
  132. for (const row of langRows) {
  133. for (const id of row.authorId)
  134. ids.add(id);
  135. }
  136. }
  137. idsArr.push(ids);
  138. }
  139. if (idsArr.length > 1)
  140. authorIds = utils.intersectSet(idsArr);
  141. //сортировка
  142. authorIds = Array.from(authorIds);
  143. authorIds.sort((a, b) => a - b);
  144. return authorIds;
  145. }
  146. async getAuthorIds(query) {
  147. const db = this.db;
  148. if (!db.searchCache)
  149. db.searchCache = {};
  150. let result;
  151. //сначала попробуем найти в кеше
  152. const q = query;
  153. const keyArr = [q.author, q.series, q.title, q.genre, q.lang];
  154. const keyStr = `query-${keyArr.join('')}`;
  155. if (!keyStr) {//пустой запрос
  156. if (db.searchCache.authorIdsAll)
  157. result = db.searchCache.authorIdsAll;
  158. else
  159. result = await this.selectAuthorIds(query);
  160. } else {//непустой запрос
  161. if (this.config.queryCacheEnabled) {
  162. const key = JSON.stringify(keyArr);
  163. const rows = await db.select({table: 'query_cache', where: `@@id(${db.esc(key)})`});
  164. if (rows.length) {//нашли в кеше
  165. await db.insert({
  166. table: 'query_time',
  167. replace: true,
  168. rows: [{id: key, time: Date.now()}],
  169. });
  170. result = rows[0].value;
  171. } else {//не нашли в кеше, ищем в поисковых таблицах
  172. result = await this.selectAuthorIds(query);
  173. await db.insert({
  174. table: 'query_cache',
  175. replace: true,
  176. rows: [{id: key, value: result}],
  177. });
  178. await db.insert({
  179. table: 'query_time',
  180. replace: true,
  181. rows: [{id: key, time: Date.now()}],
  182. });
  183. }
  184. } else {
  185. result = await this.selectAuthorIds(query);
  186. }
  187. }
  188. return result;
  189. }
  190. async search(query) {
  191. if (this.closed)
  192. throw new Error('DbSearcher closed');
  193. this.searchFlag++;
  194. try {
  195. const db = this.db;
  196. const authorIds = await this.getAuthorIds(query);
  197. const totalFound = authorIds.length;
  198. let limit = (query.limit ? query.limit : 100);
  199. limit = (limit > 1000 ? 1000 : limit);
  200. const offset = (query.offset ? query.offset : 0);
  201. //выборка найденных авторов
  202. let result = await db.select({
  203. table: 'author',
  204. map: `(r) => ({id: r.id, author: r.author, bookCount: r.bookCount, bookDelCount: r.bookDelCount})`,
  205. where: `@@id(${db.esc(authorIds.slice(offset, offset + limit))})`
  206. });
  207. return {result, totalFound};
  208. } finally {
  209. this.searchFlag--;
  210. }
  211. }
  212. async getBookList(authorId) {
  213. if (this.closed)
  214. throw new Error('DbSearcher closed');
  215. this.searchFlag++;
  216. try {
  217. const db = this.db;
  218. //выборка автора по authorId
  219. const rows = await db.select({
  220. table: 'author_book',
  221. where: `@@id(${db.esc(authorId)})`
  222. });
  223. let author = '';
  224. let books = '';
  225. if (rows.length) {
  226. author = rows[0].author;
  227. books = rows[0].books;
  228. }
  229. return {author, books};
  230. } finally {
  231. this.searchFlag--;
  232. }
  233. }
  234. async getSeriesBookList(seriesId) {
  235. if (this.closed)
  236. throw new Error('DbSearcher closed');
  237. this.searchFlag++;
  238. try {
  239. const db = this.db;
  240. //выборка серии по seriesId
  241. const rows = await db.select({
  242. table: 'series',
  243. where: `@@id(${db.esc(seriesId)})`
  244. });
  245. return {books: (rows.length ? rows[0].books : '')};
  246. } finally {
  247. this.searchFlag--;
  248. }
  249. }
  250. async periodicCleanCache() {
  251. this.timer = null;
  252. const cleanInterval = this.config.cacheCleanInterval*60*1000;
  253. try {
  254. const db = this.db;
  255. const oldThres = Date.now() - cleanInterval;
  256. //выберем всех кандидатов на удаление
  257. const rows = await db.select({
  258. table: 'query_time',
  259. where: `
  260. @@iter(@all(), (r) => (r.time < ${db.esc(oldThres)}));
  261. `
  262. });
  263. const ids = [];
  264. for (const row of rows)
  265. ids.push(row.id);
  266. //удаляем
  267. await db.delete({table: 'query_cache', where: `@@id(${db.esc(ids)})`});
  268. await db.delete({table: 'query_time', where: `@@id(${db.esc(ids)})`});
  269. //console.log('Cache clean', ids);
  270. } catch(e) {
  271. console.error(e.message);
  272. } finally {
  273. if (!this.closed) {
  274. this.timer = setTimeout(() => { this.periodicCleanCache(); }, cleanInterval);
  275. }
  276. }
  277. }
  278. async close() {
  279. while (this.searchFlag > 0) {
  280. await utils.sleep(50);
  281. }
  282. if (this.timer) {
  283. clearTimeout(this.timer);
  284. this.timer = null;
  285. }
  286. this.closed = true;
  287. }
  288. }
  289. module.exports = DbSearcher;