Skip to content

Commit aa93ee2

Browse files
update (parent note): add sql query to retrieve all the parents note without loop
1 parent 4ccb075 commit aa93ee2

2 files changed

Lines changed: 28 additions & 23 deletions

File tree

src/repository/storage/postgres/orm/sequelize/noteRelations.ts

Lines changed: 28 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -221,26 +221,36 @@ export default class NoteRelationsSequelizeStorage {
221221

222222
// get all note ids via a singe sql query instead of many
223223
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-
});
224+
WITH RECURSIVE note_parents AS (
225+
SELECT np.note_id, np.parent_id
226+
FROM ${String(this.database.literal(this.tableName).val)} np
227+
WHERE np.note_id = :startNoteId
228+
UNION ALL
229+
SELECT nr.note_id, nr.parent_id
230+
FROM ${String(this.database.literal(this.tableName).val)} nr
231+
INNER JOIN note_parents np ON np.parent_id = nr.note_id
232+
)
233+
SELECT np.note_id, np.parent_id
234+
FROM note_parents np;`;
235+
236+
try {
237+
const result = await this.database.query(query, {
238+
replacements: { startNoteId: noteId },
239+
type: QueryTypes.SELECT,
240+
});
240241

241-
parentNotes = (result as { noteId: number }[])?.map(note => note.noteId) ?? [];
242+
// eslint-disable-next-line @typescript-eslint/naming-convention
243+
const output = (result as { note_id: number; parent_id: number }[])?.map(note => note.parent_id) ?? [];
242244

243-
parentNotes.reverse();
245+
if (output.find(note => (note == noteId)) == undefined) {
246+
parentNotes = [noteId, ...output];
247+
} else {
248+
parentNotes = output;
249+
}
250+
parentNotes.reverse();
251+
} catch {
252+
console.log(`something wrong happened with sql query`);
253+
}
244254

245255
return parentNotes;
246256
}

src/repository/storage/postgres/orm/sequelize/teams.ts

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,6 @@ export class TeamsModel extends Model<InferAttributes<TeamsModel>, InferCreation
3131
* Team member role, show what user can do with note
3232
*/
3333
public declare role: MemberRole;
34-
35-
/**
36-
* Note relation content
37-
*/
38-
public declare notes?: NoteModel | null;
3934
}
4035

4136
/**

0 commit comments

Comments
 (0)