|
1 | 1 | import type { CreationOptional, InferAttributes, InferCreationAttributes, ModelStatic, Sequelize } from 'sequelize'; |
| 2 | +import { QueryTypes } from 'sequelize'; |
2 | 3 | import { Op } from 'sequelize'; |
3 | 4 | import { NoteModel } from '@repository/storage/postgres/orm/sequelize/note.js'; |
4 | 5 | import type Orm from '@repository/storage/postgres/orm/sequelize/index.js'; |
5 | 6 | import type { NoteInternalId } from '@domain/entities/note.js'; |
6 | 7 | import type { Note } from '@domain/entities/note.js'; |
7 | 8 | import { Model, DataTypes } from 'sequelize'; |
8 | | -import { isEmpty, notEmpty } from '@infrastructure/utils/empty.js'; |
9 | 9 |
|
10 | 10 | /** |
11 | 11 | * Class representing a note relations in database |
@@ -216,29 +216,29 @@ export default class NoteRelationsSequelizeStorage { |
216 | 216 | * where the user has access to. |
217 | 217 | * @param noteId - the ID of the note. |
218 | 218 | */ |
219 | | - public async getAllNoteParentsIds(noteId: NoteInternalId): Promise<NoteInternalId[]> { |
220 | | - const parentNotes: NoteInternalId[] = []; |
221 | | - let currentNoteId: number | null = noteId; |
| 219 | + public async getNoteParentsIds(noteId: NoteInternalId): Promise<NoteInternalId[]> { |
| 220 | + let parentNotes: NoteInternalId[] = []; |
222 | 221 |
|
223 | 222 | // get all note ids via a singe sql query instead of many |
224 | | - while (currentNoteId !== null) { |
225 | | - const noteRelation: NoteRelationsModel | null = await this.model.findOne({ |
226 | | - where: { |
227 | | - noteId: currentNoteId, |
228 | | - }, |
229 | | - }); |
230 | | - |
231 | | - if (notEmpty(noteRelation)) { |
232 | | - parentNotes.push(noteRelation.noteId); |
233 | | - } |
234 | | - |
235 | | - if (isEmpty(noteRelation)) { |
236 | | - parentNotes.push(currentNoteId); |
237 | | - break; |
238 | | - } else { |
239 | | - currentNoteId = noteRelation.parentId ?? null; |
240 | | - } |
241 | | - } |
| 223 | + const query = ` |
| 224 | + WITH RECURSIVE note_tree AS ( |
| 225 | + SELECT noteId, parentId |
| 226 | + FROM NoteRelations |
| 227 | + WHERE noteId = :startNoteId |
| 228 | + UNION ALL |
| 229 | + SELECT nr.noteId, nr.parentId |
| 230 | + FROM NoteRelations nr |
| 231 | + INNER JOIN note_tree nt ON nt.parentId = nr.noteId |
| 232 | + ) |
| 233 | + SELECT noteId FROM note_tree; |
| 234 | + `; |
| 235 | + |
| 236 | + const result = await this.model.sequelize?.query(query, { |
| 237 | + replacements: { startNoteId: noteId }, |
| 238 | + type: QueryTypes.SELECT, |
| 239 | + }); |
| 240 | + |
| 241 | + parentNotes = (result as { noteId: number }[])?.map(note => note.noteId) ?? []; |
242 | 242 |
|
243 | 243 | parentNotes.reverse(); |
244 | 244 |
|
|
0 commit comments