From be48523b86287b6f0125fcc7c8ad01ec50edd682 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 24 Jan 2024 18:39:39 -0800 Subject: [PATCH] Refactor `SearchHelper` to not use raw queries (#6426) * Removing user.documentIds usage #1 * refactor * Refactor all search queries to orm * Remove user.documentIds() * Filter deleted documents * Remove unneccessary clause, add test for draft with permission --- server/models/Team.ts | 2 +- server/models/User.ts | 14 - server/models/helpers/SearchHelper.test.ts | 42 +- server/models/helpers/SearchHelper.ts | 462 ++++++++++----------- 4 files changed, 245 insertions(+), 275 deletions(-) diff --git a/server/models/Team.ts b/server/models/Team.ts index 28a584d9b6..a438f22ecf 100644 --- a/server/models/Team.ts +++ b/server/models/Team.ts @@ -295,7 +295,7 @@ class Team extends ParanoidModel< }); }; - public collectionIds = async function (this: Team, paranoid = true) { + public collectionIds = async function (paranoid = true) { const models = await Collection.findAll({ attributes: ["id"], where: { diff --git a/server/models/User.ts b/server/models/User.ts index d98c0faee1..561e272ba6 100644 --- a/server/models/User.ts +++ b/server/models/User.ts @@ -403,20 +403,6 @@ class User extends ParanoidModel< .map((c) => c.id); }; - documentIds = async () => { - const memberships = await UserPermission.findAll({ - attributes: ["documentId"], - where: { - userId: this.id, - documentId: { - [Op.ne]: null, - }, - }, - }); - - return memberships.map((m) => m.documentId!); - }; - updateActiveAt = async (ctx: Context, force = false) => { const { ip } = ctx.request; const fiveMinutesAgo = subMinutes(new Date(), 5); diff --git a/server/models/helpers/SearchHelper.test.ts b/server/models/helpers/SearchHelper.test.ts index b0349c729d..4f5aed1e38 100644 --- a/server/models/helpers/SearchHelper.test.ts +++ b/server/models/helpers/SearchHelper.test.ts @@ -1,3 +1,4 @@ +import { DocumentPermission } from "@shared/types"; import SearchHelper from "@server/models/helpers/SearchHelper"; import { buildDocument, @@ -7,6 +8,7 @@ import { buildUser, buildShare, } from "@server/test/factories"; +import UserPermission from "../UserPermission"; beforeEach(() => { jest.resetAllMocks(); @@ -118,7 +120,7 @@ describe("SearchHelper", () => { title: "test number 2", }); const { totalCount } = await SearchHelper.searchForTeam(team, "test"); - expect(totalCount).toBe("2"); + expect(totalCount).toBe(2); }); test("should return the document when searched with their previous titles", async () => { @@ -137,7 +139,7 @@ describe("SearchHelper", () => { team, "test number" ); - expect(totalCount).toBe("1"); + expect(totalCount).toBe(1); }); test("should not return the document when searched with neither the titles nor the previous titles", async () => { @@ -156,7 +158,7 @@ describe("SearchHelper", () => { team, "title doesn't exist" ); - expect(totalCount).toBe("0"); + expect(totalCount).toBe(0); }); }); @@ -174,6 +176,13 @@ describe("SearchHelper", () => { collectionId: collection.id, title: "test", }); + await buildDocument({ + userId: user.id, + teamId: team.id, + collectionId: collection.id, + deletedAt: new Date(), + title: "test", + }); const { results } = await SearchHelper.searchForUser(user, "test"); expect(results.length).toBe(1); expect(results[0].document?.id).toBe(document.id); @@ -217,6 +226,27 @@ describe("SearchHelper", () => { expect(results.length).toBe(0); }); + test("should not include drafts with user permission", async () => { + const user = await buildUser(); + const draft = await buildDraftDocument({ + teamId: user.teamId, + userId: user.id, + createdById: user.id, + title: "test", + }); + await UserPermission.create({ + createdById: user.id, + documentId: draft.id, + userId: user.id, + permission: DocumentPermission.Read, + }); + + const { results } = await SearchHelper.searchForUser(user, "test", { + includeDrafts: false, + }); + expect(results.length).toBe(0); + }); + test("should include results from drafts as well", async () => { const user = await buildUser(); await buildDocument({ @@ -277,7 +307,7 @@ describe("SearchHelper", () => { title: "test number 2", }); const { totalCount } = await SearchHelper.searchForUser(user, "test"); - expect(totalCount).toBe("2"); + expect(totalCount).toBe(2); }); test("should return the document when searched with their previous titles", async () => { @@ -299,7 +329,7 @@ describe("SearchHelper", () => { user, "test number" ); - expect(totalCount).toBe("1"); + expect(totalCount).toBe(1); }); test("should not return the document when searched with neither the titles nor the previous titles", async () => { @@ -321,7 +351,7 @@ describe("SearchHelper", () => { user, "title doesn't exist" ); - expect(totalCount).toBe("0"); + expect(totalCount).toBe(0); }); }); diff --git a/server/models/helpers/SearchHelper.ts b/server/models/helpers/SearchHelper.ts index f0b4d2f656..48293ca4c3 100644 --- a/server/models/helpers/SearchHelper.ts +++ b/server/models/helpers/SearchHelper.ts @@ -3,7 +3,7 @@ import invariant from "invariant"; import find from "lodash/find"; import map from "lodash/map"; import queryParser from "pg-tsquery"; -import { Op, QueryTypes, WhereOptions } from "sequelize"; +import { Op, Sequelize, WhereOptions } from "sequelize"; import { DateFilter } from "@shared/types"; import Collection from "@server/models/Collection"; import Document from "@server/models/Document"; @@ -48,7 +48,7 @@ type SearchOptions = { snippetMaxWords?: number; }; -type Results = { +type RankedDocument = Document & { searchRanking: number; searchContext: string; id: string; @@ -72,25 +72,7 @@ export default class SearchHelper { offset = 0, } = options; - // restrict to specific collection if provided - // enables search in private collections if specified - let collectionIds: string[]; - if (options.collectionId) { - collectionIds = [options.collectionId]; - } else { - collectionIds = await team.collectionIds(); - } - - // short circuit if no relevant collections - if (!collectionIds.length) { - return { - results: [], - totalCount: 0, - }; - } - - // restrict to documents in the tree of a shared document when one is provided - let documentIds: string[] | undefined; + const where = await this.buildWhere(team, options); if (options.share?.includeChildDocuments) { const sharedDocument = await options.share.$get("document"); @@ -101,57 +83,57 @@ export default class SearchHelper { [Op.is]: null, }, }); - documentIds = [sharedDocument.id, ...childDocumentIds]; + + where[Op.and].push({ + id: [sharedDocument.id, ...childDocumentIds], + }); } - const documentClause = documentIds ? `"id" IN(:documentIds) AND` : ""; + where[Op.and].push( + Sequelize.fn( + `"searchVector" @@ to_tsquery`, + "english", + Sequelize.literal(":query") + ) + ); - // Build the SQL query to get result documentIds, ranking, and search term context - const whereClause = ` - "searchVector" @@ to_tsquery('english', :query) AND - "teamId" = :teamId AND - "collectionId" IN(:collectionIds) AND - ${documentClause} - "deletedAt" IS NULL AND - "publishedAt" IS NOT NULL - `; - const selectSql = ` - SELECT - id, - ts_rank(documents."searchVector", to_tsquery('english', :query)) as "searchRanking", - ts_headline('english', "text", to_tsquery('english', :query), :headlineOptions) as "searchContext" - FROM documents - WHERE ${whereClause} - ORDER BY - "searchRanking" DESC, - "updatedAt" DESC - LIMIT :limit - OFFSET :offset; - `; - const countSql = ` - SELECT COUNT(id) - FROM documents - WHERE ${whereClause} - `; const queryReplacements = { - teamId: team.id, query: this.webSearchQuery(query), - collectionIds, - documentIds, headlineOptions: `MaxFragments=1, MinWords=${snippetMinWords}, MaxWords=${snippetMaxWords}`, }; - const resultsQuery = sequelize.query(selectSql, { - type: QueryTypes.SELECT, - replacements: { ...queryReplacements, limit, offset }, - }); - const countQuery = sequelize.query<{ count: number }>(countSql, { - type: QueryTypes.SELECT, + + const resultsQuery = Document.unscoped().findAll({ + attributes: [ + "id", + [ + Sequelize.literal( + `ts_rank("searchVector", to_tsquery('english', :query))` + ), + "searchRanking", + ], + [ + Sequelize.literal( + `ts_headline('english', "text", to_tsquery('english', :query), :headlineOptions)` + ), + "searchContext", + ], + ], replacements: queryReplacements, - }); - const [results, [{ count }]] = await Promise.all([ - resultsQuery, - countQuery, - ]); + where, + order: [ + ["searchRanking", "DESC"], + ["updatedAt", "DESC"], + ], + limit, + offset, + }) as any as Promise; + + const countQuery = Document.unscoped().count({ + // @ts-expect-error Types are incorrect for count + replacements: queryReplacements, + where, + }) as any as Promise; + const [results, count] = await Promise.all([resultsQuery, countQuery]); // Final query to get associated document data const documents = await Document.findAll({ @@ -167,7 +149,7 @@ export default class SearchHelper { ], }); - return SearchHelper.buildResponse(results, documents, count); + return this.buildResponse(results, documents, count); } public static async searchTitlesForUser( @@ -176,102 +158,36 @@ export default class SearchHelper { options: SearchOptions = {} ): Promise { const { limit = 15, offset = 0 } = options; + const where = await this.buildWhere(user, options); - const where: WhereOptions = { - teamId: user.teamId, + where[Op.and].push({ title: { [Op.iLike]: `%${query}%`, }, - [Op.and]: [], - }; - - // Ensure we're filtering by the users accessible collections. If - // collectionId is passed as an option it is assumed that the authorization - // has already been done in the router - let collectionIds; - - if (options.collectionId) { - collectionIds = [options.collectionId]; - } else { - collectionIds = await user.collectionIds(); - } - - const documentIds = await user.documentIds(); - - where[Op.and].push({ - [Op.or]: [ - { - collectionId: { - [Op.in]: collectionIds, - }, - }, - { - collectionId: { - [Op.is]: null, - }, - createdById: user.id, - }, - { - id: { - [Op.in]: documentIds, - }, - }, - ], }); - if (options.dateFilter) { - where[Op.and].push({ - updatedAt: { - [Op.gt]: sequelize.literal( - `now() - interval '1 ${options.dateFilter}'` - ), + const include = [ + { + association: "memberships", + where: { + userId: user.id, }, - }); - } + required: false, + separate: false, + }, + { + model: User, + as: "createdBy", + paranoid: false, + }, + { + model: User, + as: "updatedBy", + paranoid: false, + }, + ]; - if (!options.includeArchived) { - where[Op.and].push({ - archivedAt: { - [Op.is]: null, - }, - }); - } - - if (options.includeDrafts) { - where[Op.and].push({ - [Op.or]: [ - { - publishedAt: { - [Op.ne]: null, - }, - }, - { - createdById: user.id, - }, - { - id: { - [Op.in]: documentIds, - }, - }, - ], - }); - } else { - where[Op.and].push({ - publishedAt: { - [Op.ne]: null, - }, - }); - } - - if (options.collaboratorIds) { - where[Op.and].push({ - collaboratorIds: { - [Op.contains]: options.collaboratorIds, - }, - }); - } - - return await Document.scope([ + return Document.scope([ "withoutState", "withDrafts", { @@ -285,19 +201,9 @@ export default class SearchHelper { }, ]).findAll({ where, + subQuery: false, order: [["updatedAt", "DESC"]], - include: [ - { - model: User, - as: "createdBy", - paranoid: false, - }, - { - model: User, - as: "updatedBy", - paranoid: false, - }, - ], + include, offset, limit, }); @@ -314,101 +220,69 @@ export default class SearchHelper { limit = 15, offset = 0, } = options; - // Ensure we're filtering by the users accessible collections. If - // collectionId is passed as an option it is assumed that the authorization - // has already been done in the router - let collectionIds; - if (options.collectionId) { - collectionIds = [options.collectionId]; - } else { - collectionIds = await user.collectionIds(); - } + const where = await this.buildWhere(user, options); - let dateFilter; + where[Op.and].push( + Sequelize.fn( + `"searchVector" @@ to_tsquery`, + "english", + Sequelize.literal(":query") + ) + ); - if (options.dateFilter) { - dateFilter = `1 ${options.dateFilter}`; - } - - const documentIds = await user.documentIds(); - - // Build the SQL query to get documentIds, ranking, and search term context - const whereClause = ` - "searchVector" @@ to_tsquery('english', :query) AND - "teamId" = :teamId AND - ${ - collectionIds.length - ? `( - "collectionId" IN(:collectionIds) OR - ("collectionId" IS NULL AND "createdById" = :userId) ${ - documentIds.length > 0 ? `OR id in (:documentIds)` : "" - } - ) AND` - : `( - ("collectionId" IS NULL AND "createdById" = :userId) ${ - documentIds.length > 0 ? `OR id in (:documentIds)` : "" - } - ) AND` - } - ${ - options.dateFilter ? '"updatedAt" > now() - interval :dateFilter AND' : "" - } - ${ - options.collaboratorIds - ? '"collaboratorIds" @> ARRAY[:collaboratorIds]::uuid[] AND' - : "" - } - ${options.includeArchived ? "" : '"archivedAt" IS NULL AND'} - "deletedAt" IS NULL AND - ${ - options.includeDrafts - ? `("publishedAt" IS NOT NULL OR "createdById" = :userId ${ - documentIds.length > 0 ? `OR id in (:documentIds)` : "" - })` - : '"publishedAt" IS NOT NULL' - } - `; - const selectSql = ` - SELECT - id, - ts_rank(documents."searchVector", to_tsquery('english', :query)) as "searchRanking", - ts_headline('english', "text", to_tsquery('english', :query), :headlineOptions) as "searchContext" - FROM documents - WHERE ${whereClause} - ORDER BY - "searchRanking" DESC, - "updatedAt" DESC - LIMIT :limit - OFFSET :offset; - `; - const countSql = ` - SELECT COUNT(id) - FROM documents - WHERE ${whereClause} - `; const queryReplacements = { - teamId: user.teamId, - userId: user.id, - collaboratorIds: options.collaboratorIds, query: this.webSearchQuery(query), - collectionIds, - documentIds: documentIds.length > 0 ? documentIds : undefined, - dateFilter, headlineOptions: `MaxFragments=1, MinWords=${snippetMinWords}, MaxWords=${snippetMaxWords}`, }; - const resultsQuery = sequelize.query(selectSql, { - type: QueryTypes.SELECT, - replacements: { ...queryReplacements, limit, offset }, - }); - const countQuery = sequelize.query<{ count: number }>(countSql, { - type: QueryTypes.SELECT, + + const include = [ + { + association: "memberships", + where: { + userId: user.id, + }, + required: false, + separate: false, + }, + ]; + + const resultsQuery = Document.unscoped().findAll({ + attributes: [ + "id", + [ + Sequelize.literal( + `ts_rank("searchVector", to_tsquery('english', :query))` + ), + "searchRanking", + ], + [ + Sequelize.literal( + `ts_headline('english', "text", to_tsquery('english', :query), :headlineOptions)` + ), + "searchContext", + ], + ], + subQuery: false, + include, replacements: queryReplacements, - }); - const [results, [{ count }]] = await Promise.all([ - resultsQuery, - countQuery, - ]); + where, + order: [ + ["searchRanking", "DESC"], + ["updatedAt", "DESC"], + ], + limit, + offset, + }) as any as Promise; + + const countQuery = Document.unscoped().count({ + // @ts-expect-error Types are incorrect for count + subQuery: false, + include, + replacements: queryReplacements, + where, + }) as any as Promise; + const [results, count] = await Promise.all([resultsQuery, countQuery]); // Final query to get associated document data const documents = await Document.scope([ @@ -430,11 +304,91 @@ export default class SearchHelper { }, }); - return SearchHelper.buildResponse(results, documents, count); + return this.buildResponse(results, documents, count); + } + + private static async buildWhere(model: User | Team, options: SearchOptions) { + const teamId = model instanceof Team ? model.id : model.teamId; + const where: WhereOptions = { + teamId, + [Op.or]: [], + [Op.and]: [ + { + deletedAt: { + [Op.eq]: null, + }, + }, + ], + }; + + if (model instanceof User) { + where[Op.or].push({ "$memberships.id$": { [Op.ne]: null } }); + } + + // Ensure we're filtering by the users accessible collections. If + // collectionId is passed as an option it is assumed that the authorization + // has already been done in the router + const collectionIds = options.collectionId + ? [options.collectionId] + : await model.collectionIds(); + + if (collectionIds.length) { + where[Op.or].push({ collectionId: collectionIds }); + } + + if (options.dateFilter) { + where[Op.and].push({ + updatedAt: { + [Op.gt]: sequelize.literal( + `now() - interval '1 ${options.dateFilter}'` + ), + }, + }); + } + + if (options.collaboratorIds) { + where[Op.and].push({ + collaboratorIds: { + [Op.contains]: options.collaboratorIds, + }, + }); + } + + if (!options.includeArchived) { + where[Op.and].push({ + archivedAt: { + [Op.eq]: null, + }, + }); + } + + if (options.includeDrafts && model instanceof User) { + where[Op.and].push({ + [Op.or]: [ + { + publishedAt: { + [Op.ne]: null, + }, + }, + { + createdById: model.id, + }, + { "$memberships.id$": { [Op.ne]: null } }, + ], + }); + } else { + where[Op.and].push({ + publishedAt: { + [Op.ne]: null, + }, + }); + } + + return where; } private static buildResponse( - results: Results[], + results: RankedDocument[], documents: Document[], count: number ): SearchResponse {